def CalibrationENC(calibration_filename):
    # Read data fron the calibration curve dataset
    C, e_C, noise_rms, d_noise_rms, fall_time, d_fall_time, amplitude, d_amplitude = LoadCalibrationFile(calibration_filename)

    noise_rms = noise_rms / 1000. # convert form \muV to mV
    d_noise_rms = d_noise_rms / 1000.

    ENC = (noise_rms/amplitude) * (C * 20.0) * pow(10,-15) / (1.602 * pow(10,-19) ) #pF * mV = 10^-12 * 10^-3 = 10^-15 C / 10^-19 C = 10^4 electrons
    d_ENC = np.zeros([len(ENC)])
    for i in range(len(ENC)):
        d_ENC[i] = sqrt( d_noise_rms[i]*d_noise_rms[i]*(C[i] * 20.0/amplitude[i])*(C[i] * 20.0/amplitude[i])  +  d_amplitude[i]*d_amplitude[i]*((noise_rms[i]/(amplitude[i]*amplitude[i])) * (C[i] * 20.0))*((noise_rms[i]/(amplitude[i]*amplitude[i])) * (C[i] * 20.0))    )
    
    d_ENC = d_ENC * pow(10,-15) / (1.602 * pow(10,-19) ) # conversted to # of electrons

    calib_curve = TGraphErrors(len(ENC), array('d', C[:-1].tolist()), array('d', ENC.tolist()), array('d', e_C.tolist()), array('d', d_ENC) )

    # Construct the fit with a 1st and 2nd order polynomial
    fit_curve = TF1('fit_curve','[1]*x + [0]',0.,110.)
    fit_curve2 = TF1('fit_curve2','[0]*x*x + [1]*x + [2]',0.,110.)

    # Fit the calibration curve
    calib_curve.Fit(fit_curve,'R')
    calib_curve.Fit(fit_curve2, 'R')

    lin_par0   = fit_curve.GetParameter(0)
    lin_e_par0 = fit_curve.GetParError(0)
    lin_par1   = fit_curve.GetParameter(1)
    lin_e_par1 = fit_curve.GetParError(1)

    xx = np.linspace(0., 105, 1000)
    yy = [fit_curve.Eval(x) for x in xx]
    yy2 = [fit_curve2.Eval(x) for x in xx]

    par = [lin_par0, lin_par1]
    l = 'fit pol1 $p_0$: {:.3g} $p_1$: {:.3g}'.format(*par)


    # Plot the calibration curve with matplotlib
    font0 = FontProperties()
    font = font0.copy()
    font.set_style('italic')
    font.set_weight('bold')
    font.set_size('x-large')

    fig, ax = plt.subplots()
    ax.set_xlabel('C [pF]')
    ax.set_ylabel('ENC [# of electrons]')
    ax.errorbar(C, ENC, d_ENC, marker='o', color='k', linestyle='None', label='Data')
    ax.plot(xx, yy, color='r', label=l)
    ax.plot(xx, yy2, color='g', label='fit pol2')
    ax.text(0.05,0.65, 'Group 1', verticalalignment='bottom', horizontalalignment='left',
                fontproperties=font, transform=ax.transAxes)
    ax.legend(loc='upper left', numpoints=1)
    plt.grid()
    #plt.show()
    fig.savefig('../graphics/calibrationENC_diode.pdf')
    plt.close(fig)
    plt.clf()

    return lin_par0, lin_e_par0, lin_par1, lin_e_par1
Ejemplo n.º 2
0
class TimeConstant(object):
    def __init__(self, file_name):
        file = open(file_name)
        out = open(output, 'w')
        for line in file:
            #calculate errors and dump the content to output file
            #skip comment lines
            if '#' in line:
                continue
            t, v = [float(x) for x in line.split()]
            te = osc_error_t(t, TIME_DIV)
            ve = osc_error_v(v, POT_DIV)
            new_line = [t, v, te, ve]
            new_line = ' '.join([str(x) for x in new_line]) + '\n'
            out.write(new_line)
        file.close()
        out.close()
        #create Graph. ROOT automatically reads columns
        self.graph = TGraphErrors(output)
        self.graph.SetMarkerStyle(7)
        self.func = TF1("exp_decay", "[0]*exp(-x/[1])")
        self.func.SetParameters(2, 20)

    def fit_graph(self):
        self.graph.Fit("exp_decay", "Q")
        self.v0 = self.func.GetParameter(0), self.func.GetParError(0)
        self.tau = self.func.GetParameter(1), self.func.GetParError(1)


#        print "%.3f \pm %.3f" %self.v0
#        print "%.3f \pm %.3f" %self.tau

    def get_capacity(self):
        c = (self.tau[0] / INTERNAL_RES, self.tau[1] / INTERNAL_RES)
        return c
Ejemplo n.º 3
0
class CauchyRelation(object):
    def __init__(self, ref_indexes, err_ref_ind, wavelengths):
        self.name = 'Cauchy Relation'
        self.init_graph(ref_indexes, err_ref_ind, wavelengths)
        self.fit_graph()

    def init_graph(self, ref_indexes, err_ref_ind, wavelengths):
        n = array('d', ref_indexes)
        errn = array('d', err_ref_ind)
        wl = array('d', wavelengths)
        errwl = array('d', [0] * len(wavelengths))
        self.pars = array('d', [0] * 3)  #fit parameters
        self.parerrs = array('d', [0] * 3)  #fit parameter errors
        self.graph = TGraphErrors(len(wavelengths), wl, n, errwl, errn)
        set_graph_style(self.graph)
        self.graph.SetTitle(self.name)

    def fit_graph(self):
        self.func = TF1('cauchy', '[0] + [1]/x**2', 400, 700)
        self.func.SetParameters(10, 1e4)
        self.graph.Fit('cauchy', 'QR')
        self.func.GetParameters(self.pars)
        self.parerrs[0] = self.func.GetParError(0)
        self.parerrs[1] = self.func.GetParError(1)
        self.r = ResGraph(self.graph, self.func)  #creates residual graph
        set_graph_style(self.r.graph)
        self.r.graph.SetTitle(self.r.name)
        return zip(self.pars, self.parerrs)

    def show_res_graph(self):
        show_graph(self.r.graph, self.r.name)

    def show_graph(self):
        show_graph(self.graph, self.name)
Ejemplo n.º 4
0
def create_resolutiongraph(n, energies, sigmasmeans, energieserrors, sigmasmeanserrors, graphname):
	"""Function to perform ROOT graphs of resolutions"""
	#How many points
	n = int(n)

	TGraphresolution = TGraphErrors(n, energies, sigmasmeans, energieserrors, sigmasmeanserrors)
	
	#Draw + DrawOptions, Fit + parameter estimation
	Style = gStyle
	Style.SetOptFit()
	XAxis = TGraphresolution.GetXaxis() #TGraphresolution
	TGraphresolution.SetMarkerColor(4)
	TGraphresolution.SetMarkerStyle(20)
	TGraphresolution.SetMarkerSize(2)
	XAxis.SetTitle("Energy (GeV)")
	YAxis = TGraphresolution.GetYaxis()
	YAxis.SetTitle("Sigma/Mean")
	resolutionfit = TF1("resolutionfit", '([0]/((x)**0.5))+[1]', 0, max(energies)) #somma non quadratura
	TGraphresolution.Fit("resolutionfit")
	a = resolutionfit.GetParameter(0)
	b = resolutionfit.GetParameter(1)             
	TGraphresolution.Draw("AP")
	gPad.SaveAs(graphname)
	gPad.Close()
	return a, b
Ejemplo n.º 5
0
class DiodeCurrent(object):
    def __init__(self, file_name):
        file = open(file_name)
        out = open(output, 'w')
        for line in file:
            #calculate errors and dump the content to output file
            if '#' in line:
                continue
            t, vin, vout = [float(x) for x in line.split()]
            te = osc_error_t(t, TIME_DIV)
            vd = vin - vout
            voute = osc_error_v(vout, POT_DIV)
            vde = osc_error_v(vd, POT_DIV)
            id = vout / R[0]
            if vout:
                ide = id * ((voute / vout) + (R[1] / R[0]))
            else:
                ide = id * (R[1] / R[0])
            new_line = [vd, id, vde, ide]
            new_line = ' '.join([str(x) for x in new_line]) + '\n'
            out.write(new_line)
        file.close()
        out.close()
        #create Graph. ROOT automatically reads columns
        self.graph = TGraphErrors(output)
        self.graph.SetMarkerStyle(7)
        self.func = TF1("shockley", "[0]*(exp(x/[1])-1)", 0.1, 1)
        self.func.SetParameters(5, 0.026)

    def fit_graph(self):
        self.graph.Fit("shockley", "QRW")
        self.v0 = self.func.GetParameter(0), self.func.GetParError(0)
        self.tau = self.func.GetParameter(1), self.func.GetParError(1)
        print("Is = %.3g \pm %.3g" % self.v0)
        print("n*Vt = %.3f \pm %.3f" % self.tau)
def CalibrationRiseTime(calibration_filename):
    # Read data fron the calibration curve dataset
    C, e_C, noise_rms, d_noise_rms, fall_time, d_fall_time, amplitude, d_amplitude = LoadCalibrationFile(calibration_filename)

    gStyle.SetOptStat(1111)

    # Construct the  curve
    calib_curve = TGraphErrors(len(C), array('d',C.tolist()), array('d', fall_time.tolist()), array('d', e_C.tolist()), array('d',d_fall_time.tolist()) )

    # Construct the fit with a 2nd order polynomial
    fit_curve = TF1('fit_curve','[0]*x*x + [1]*x + [2]',0.,110.)
    fit_curve.SetParameter(0, 0.0)
    fit_curve.SetParameter(1, 0.0)
    fit_curve.SetParameter(2, 0.0)
    fit_curve.SetLineColor(2)

    # FIt the calibration curve
    calib_curve.Fit(fit_curve,'R')

    # Extract the results fron the fit
    par0   = fit_curve.GetParameter(0)
    e_par0 = fit_curve.GetParError(0)
    par1   = fit_curve.GetParameter(1)
    e_par1 = fit_curve.GetParError(1)
    par2   = fit_curve.GetParameter(2)
    e_par2 = fit_curve.GetParError(2)

    xx = np.linspace(0., 105, 1000)
    yy = [fit_curve.Eval(x) for x in xx]
    par = [par2, par1, par0]
    l = 'fit pol2 $p_0$: {:.3g} $p_1$: {:.3g} $p_2$: {:.2f}'.format(*par)

    # Plot the calibration curve with matplotlib
    font0 = FontProperties()
    font = font0.copy()
    font.set_style('italic')
    font.set_weight('bold')
    font.set_size('x-large')

    fig, ax = plt.subplots()
    ax.set_xlabel('C [pF]')
    ax.set_xlim(0.0, 120)
    ax.set_ylabel('Rise time [ns]')
    ax.errorbar(C, fall_time, d_fall_time, marker='o', color='k', linestyle='None', label='Data')
    ax.plot(xx, yy, label=l, color='r')
    #plt.set_title('Diode calibration curve')
    ax.text(0.05,0.65, 'Group 1', verticalalignment='bottom', horizontalalignment='left',
                fontproperties=font, transform=ax.transAxes)
    ax.legend(loc='upper left', numpoints=1)
    plt.grid()
    #plt.show()
    fig.savefig('../graphics/calibration_diode.pdf')
    plt.close(fig)
    plt.clf()

    return par0, e_par0, par1, e_par1, par2, e_par2
def angresplot(energies, angrestheta, angresphi, angresthetaerror, angresphierror):

	energies_arr = array('d', energies)
	angrestheta_arr = array('d', angrestheta)
	angresphi_arr = array('d', angresphi)
	angresthetaerror_arr = array('d', angresthetaerror)
	angresphierror_arr = array('d', angresphierror)
	zeros_arr = array('d',[0.0]*len(energies))

	ThetaGraph = TGraphErrors(len(energies), energies_arr, angrestheta_arr, zeros_arr, angresthetaerror_arr)
	PhiGraph = TGraphErrors(len(energies), energies_arr, angresphi_arr, zeros_arr, angresphierror_arr)	

	resolutionfittheta = TF1("resolutionfit", '[0]/(x**0.5)+[1]', 30., 150.)
	#resolutionfittheta.SetParLimits(2, 0.5, 0.8)
	resolutionfitphi = TF1("resolutionfit", '[0]/(x**0.5)+[1]', 30., 150.)
	#resolutionfitphi.SetParLimits(2, 0.5, 0.8)	

	ThetaGraph.Fit(resolutionfittheta)
	PhiGraph.Fit(resolutionfitphi)	
	return ThetaGraph, PhiGraph
Ejemplo n.º 8
0
 def fit(self, th2, effref):
     x_points, y_points, error_points = self.get_points(th2, effref)
     import array
     from ROOT import TGraphErrors, TF1
     g = TGraphErrors(len(x_points), array.array(
         'd',
         y_points,
     ), array.array('d', x_points), array.array('d', [0.] * len(x_points)),
                      array.array('d', error_points))
     firstBinVal = th2.GetYaxis().GetBinLowEdge(th2.GetYaxis().GetFirst())
     lastBinVal = th2.GetYaxis().GetBinLowEdge(th2.GetYaxis().GetLast() + 1)
     f1 = TF1('f1', 'pol1', firstBinVal, lastBinVal)
     g.Fit(f1, "FRq")
     slope = f1.GetParameter(1)
     offset = f1.GetParameter(0)
     return slope, offset, x_points, y_points, error_points
Ejemplo n.º 9
0
class CalibrazionePotenziometro:
    def __init__(self, tabella):
        self.file_tabella = tabella
        self.gr = TGraphErrors(tabella)
        self.gr.SetTitle("calibrazione potenziometro;potenziometro;R [#Omega]")
        self.result = self.gr.Fit("pol1", "SQ")

    def disegna_grafico(self):
        self.can = TCanvas("can", "can")
        self.gr.Draw("AP")
        can.SaveAs("relazione/img/{0}.eps".format(self.file_tabella))

    def salva_calibrazione(self):
        with open("fit.{0}".format(self.file_tabella), "w") as out_file:
            a = self.result.Parameter(1)
            sigma_a = self.result.ParError(1)
            b = self.result.Parameter(0)
            sigma_b = self.result.ParError(1)
            line = [a, sigma_a, b, sigma_b]
            line = [str(x) for x in line]
            line = " ".join(line)
            out_file.write(line)

    def stampa_tabella(self):
        print("\\begin{tabular}{r@{ $\\pm$ }lr@{ $\\pm$ }l}")
        print(
            "\\multicolumn{2}{c}{$R [\\unit[]{\\ohm}]$} &\\multicolumn{2}{c}{potenziometro} \\\\ "
        )
        print("\\hline")
        with open(name_in) as file:
            for line in file:
                if "//" in line:
                    continue
                line = [float(x) for x in line.split()]
                print(
                    "{0[1]:.2f} & {0[3]:.2f} & {0[0]:.2f} & {0[2]:.2f} \\\\ ".
                    format(line))
        print("\\end{tabular}")
Ejemplo n.º 10
0
 def _FitKuriePlot(self, centralList, kurieList, errorList):
     logger.debug("Fitter private method")
     kurieGraph = TGraphErrors()
     for i, KE in enumerate(centralList):
         kurieGraph.SetPoint(i, KE, kurieList[i])
         kurieGraph.SetPointError(i, 0, errorList[i])
     self.fitFunction = TF1("kurieFit", "[0]*([1]-x)*(x<[1]) + [2]",
                            centralList[0], centralList[-1], 3)
     self.fitFunction.SetParameters(kurieList[0] / (18600 - centralList[0]),
                                    18600, kurieList[-1])
     rootResults = kurieGraph.Fit(self.fitFunction, 'MERS')
     resultsDict = {
         "amplitude": rootResults.Parameter(0),
         "err_amplitude": rootResults.ParError(0),
         "endpoint": rootResults.Parameter(1),
         "err_endpoint": rootResults.ParError(1),
         "background": rootResults.Parameter(2),
         "err_background": rootResults.ParError(2),
         "chi2": rootResults.Chi2(),
         "ndf": rootResults.Ndf(),
         "p-value": rootResults.Prob()
     }
     logger.debug("Fit done")
     return resultsDict
Ejemplo n.º 11
0
class Thickness:

    def __init__(self, name):
        self.name = name
        self.canvas = TCanvas(name, name)
        self.canvas.SetFillColor(0)
        self.name_lin = name + "_lin"
        self.linearize()
        self.make_graph()

    def linearize(self):
        with open(self.name) as file:
            with open(self.name_lin, "w") as out_file:
                for line in file:
                    x, i = [float(_) for _ in line.split()]
                    i_err = 1 / sqrt(i)
                    i = log(i)
                    output_line = [x, i, 0, i_err]
                    output_line = " ".join([str(x) for x in output_line])
                    output_line += "\n"
                    out_file.write(output_line)

    def make_graph(self):
        self.graph = TGraphErrors(self.name_lin)
        self.graph.SetTitle(self.name)
        self.graph.GetYaxis().SetTitle("log(n_events)")
        self.graph.GetXaxis().SetTitle("thickness #[]{#mu m}")
        self.graph.SetMarkerStyle(8)
        self.graph.Fit("pol1")

    def draw(self):
        self.canvas.cd()
        self.graph.Draw("ap")

    def save(self):
        self.canvas.SaveAs(self.name + ".eps")
Ejemplo n.º 12
0
    graph2.SetPointError(i, 0, zerr[i])

c2.cd()
graph1.Draw("AP")
graph1.GetYaxis().SetRangeUser(52., 62.)
graph1.GetYaxis().SetTitle("Mean value")
graph1.GetXaxis().SetTitle("Top M(GeV)")
graph1.Draw("AP")
graph1.SetTitle("Mean value of the histogram vs top mass")
graph2.SetLineColor(2)
graph2.SetMarkerColor(2)
graph2.Draw("P")

# fit

graph1.Fit("pol1")
graph2.Fit("pol1")

pol1 = TF1()
pol1 = graph1.GetFunction("pol1")
pol2 = TF1()
pol2 = graph2.GetFunction("pol1")

a0 = str(round(pol1.GetParameter(0), 2))
a1 = str(round(pol1.GetParameter(1), 2))
b0 = str(round(pol2.GetParameter(0), 2))
b1 = str(round(pol2.GetParameter(1), 2))

pol1.SetLineColor(1)
pol2.SetLineColor(2)
Ejemplo n.º 13
0
    linFunc.SetParameters(0.0, 1.0)

    for i in range(rawfitresultList.GetSize()):
        #tageffValVList[i] = rawfitresultList.At(i).getValV();
        #tageffErrorList[i] = rawfitresultList.At(i).getError();
        #etaAvgValList[i] = etaAvgValVarList.At(i).getValV();
        #etaAvgErrorList[i] = etaAvgValVarList.At(i).getError();
        tageffVsEtaGraph.SetPoint(i,
                                  etaAvgValVarList.At(i).getValV(),
                                  rawfitresultList.At(i).getValV())
        tageffVsEtaGraph.SetPointError(i,
                                       etaAvgValVarList.At(i).getError(),
                                       rawfitresultList.At(i).getError())
        tageffVsEtaGraph.SetLineColor(currentColor)
        linFunc.SetLineColor(currentColor)
        tageffVsEtaGraph.Fit(linFunc)

    graphHolder.Add(tageffVsEtaGraph)
    currentColor += 1

    #tageffVsEtaGraph = TGraph(rawfitresultList.GetSize(),etaAvgValList,tageffValVList)#,etaAvgErrorList,tageffErrorList);

    #tageffVsEtaGraph.
    #ROOT.gSystem.ProcessEvents();
    #img.FromPad(theCanvas);

os.chdir("..")

theCanvas = TCanvas()
if (graphHolder.GetListOfGraphs().GetSize() == 1):
    graphHolder.SetTitle(
Ejemplo n.º 14
0
def MeasurePSF_in_Sections(data, fitted_line, nsecs = 3, tgraph_filename = '', DEBUG = False, DEBUG_Filenum = 0):
    #get new coefficients as distance to line uses straight line of form ax + by + c = 0
    a = -1. * fitted_line.a
    b = 1
    c = -1. * fitted_line.b
    
    histmin = -1 * max(data.shape[0], data.shape[1])
    histmax = max(data.shape[0], data.shape[1])
    nbins = (histmax - histmin) * 2
    
    hists = []
    for i in range(nsecs):
       hists.append(TH1F('Track section ' + str(i), 'Track section ' + str(i), nbins, histmin, histmax))
    
    for xcoord in range(data.shape[0]):
        for ycoord in range(data.shape[1]):
            x = xcoord + 0.5 #adjust for bin centers - NB This is important!
            y = ycoord + 0.5 #adjust for bin centers - NB This is important!
            secnum = GetSecNum(data, x, y, nsecs, None) # TODO!
            
            value = float(data[xcoord,ycoord])
#            if value < 800:
            non_abs_distance = (a*x + b*y + c) / (a**2 + b**2)**0.5
            hists[secnum].Fill(non_abs_distance, value)
        
    sigmas, sigma_errors = [], []
            
    for i, hist in enumerate(hists):
        fitmin, fitmax = GetLastBinAboveX(hist, 0.1)
#        viewmin, viewmax = GetLastBinAboveX(hist, 0.1)
        viewmin, viewmax = -2,2
        hist.GetXaxis().SetRangeUser(viewmin,viewmax)
    
        fit_func = TF1("gaus", "gaus", fitmin, fitmax)
        fit_func.SetNpx(1000)
        hist.Fit(fit_func, "MEQ", "", fitmin, fitmax)
        
        legend_text = []
        
        sigma = fit_func.GetParameter(2) 
        sigma_error = fit_func.GetParError(2)
        
        sigmas.append(abs(15*sigma)) #15 for the 15um per pixel
        sigma_errors.append(abs(15*sigma_error)) #15 for the 15um per pixel
        
        mean = fit_func.GetParameter(15*1) #15 for the 15um per pixel
        mean_error = fit_func.GetParError(15*1) #10 for the 15um per pixel
        
        chisq = fit_func.GetChisquare()
        NDF = fit_func.GetNDF()
        try:
            chisqr_over_NDF = chisq/NDF
        except:
            chisqr_over_NDF = -1  
#        if chisqr_over_NDF > 500 or chisqr_over_NDF <= 1:
#            return [], [], []
        
        legend_text.append('mean = ' + str(mean) + ' #pm ' + str(mean_error) + " #mum")
        legend_text.append('#sigma = ' + str(round(sigma,4)) + ' #pm ' + str(round(sigma_error,4)) + " #mum")
    
        if DEBUG: #For showing each of n PSF *Histograms* per track
            c1 = TCanvas( 'canvas', 'canvas', CANVAS_WIDTH,CANVAS_HEIGHT)
            hist.Draw("")
            if legend_text != '':
                from ROOT import TPaveText
                textbox = TPaveText(0.0,1.0,0.2,0.8,"NDC")
                for line in legend_text:
                    textbox.AddText(line)
                textbox.SetFillColor(0)
                textbox.Draw("same")
            c1.SaveAs(OUTPUT_PATH + str(DEBUG_Filenum) + "psf_section_" + str(i) + FILE_TYPE)
            del c1

    from ROOT import TGraphErrors
    c2 = TCanvas( 'canvas', 'canvas', CANVAS_WIDTH,CANVAS_HEIGHT)
    assert nsecs == len(sigmas) == len(sigma_errors)
    xpoints = GenXPoints(nsecs, 250.)
    
    gr = TGraphErrors(nsecs, np.asarray(xpoints,dtype = float), np.asarray(sigmas,dtype = float), np.asarray([0 for i in range(nsecs)],dtype = float), np.asarray(sigma_errors,dtype = float)) #populate graph with data points
    gr.SetLineColor(2)
    gr.SetMarkerColor(2)
    gr.Draw("AP")
    
    fit_func = TF1("line","[1]*x + [0]", -1, nsecs+1)
    fit_func.SetNpx(1000)
    gr.Fit(fit_func, "MEQ", "")
    a = fit_func.GetParameter(1) 
    a_error = fit_func.GetParError(1)
    
    if DEBUG:
        if tgraph_filename == '': tgraph_filename = OUTPUT_PATH + 'psf_graph' + '.png'
        gr.SetTitle("")
        gr.GetYaxis().SetTitle('PSF #sigma (#mum)')
        gr.GetXaxis().SetTitle('Av. Si Depth (#mum)')
        c2.SaveAs(tgraph_filename)
        
#    if a_error >= a:
#        print "Inconclusive muon directionality - skipped track %s"%tgraph_filename
#        return [],[],[]

    del c2, hists, gr
    import gc
    gc.collect()
                   
    for j in range(nsecs):
        if sigma_errors[j] > sigmas[j]:
            print "bad fit skipped"
            return [],[],[]
    
    if a < 0:
        sigmas.reverse()
        sigma_errors.reverse()
        return xpoints, sigmas, sigma_errors
    else:
        return xpoints, sigmas, sigma_errors
Ejemplo n.º 15
0
class waveLength:
    """			***classe waveLength***

	legge un file formattato con tre colonne:

	ordine	nonio A	nonio B
	5	213.54	33.58
	4	212.52	32.48
	...	...	...
	(significa 213°54', 33°58' per il massimo al quinto ordine etc.)

	opera automaticamente la conversione e la media,
	per poi disporre in grafico (self.graph).

	self.fitGraph() esegue l'interpolazione lineare
	self.showGraph() mostra il grafico
	self.saveToEps() salve il grafico in formato .eps

	la lunghezza d'onda con si calcola con self.getWaveLen(),
	che restituisce una valore ed errore in una lista
	"""

    #	a = (12.65e-6, 0.05e-6) #passo del reticolo, con errore
    #	measerr = 5.*2/300 #errore (in gradi) stimato sulla misura col nonio

    def __init__(self, fileName):
        self.wavelen = [0, 0]
        self.name = fileName
        self.nData = 0
        self.deg = array('d')
        self.degerr = array('d')
        self.ord = array('d')
        self.pars = array('d', [0, 0])  #fit parameters
        self.parerrs = array('d', [0, 0])  #fit parameter errors
        self.fillDeg()  #reads data from file
        self.convertToSine()  #centers mean maximum, calculates sines
        self.initGraph()  #initialize graph, set style

    def fillDeg(self):
        file = open(self.name)
        for line in file:
            o = float(line.split()[0])
            n1 = float(line.split()[1]) - 180
            n2 = float(line.split()[2])
            self.ord.append(o)
            int1 = floor(n1)
            int2 = floor(n2)
            rem1 = 5. * (n1 - int1) / 3
            rem2 = 5. * (n2 - int2) / 3
            int1 += rem1
            int2 += rem2
            self.deg.append((int1 + int2) / 2)
            self.degerr.append(measerr / sqrt(2))
            self.nData += 1
        file.close()

    def convertToSine(self):
        j = self.ord.index(0)  #finds central maximum
        center = self.deg[j]
        for i in xrange(self.nData):
            angle = self.deg[i]
            angle -= center
            self.deg[i] = angle
            self.deg[i] = sin(pi * angle / 180)
            self.degerr[i] = cos(angle) * argerr

    def initGraph(self):
        self.graph = TGraphErrors(self.nData, self.ord, self.deg,
                                  array('d', [0] * self.nData), self.degerr)
        self.setGraphStyle()
        pass

    def fitGraph(self):
        line = TF1('line', 'pol1', -5, 5)  #funzione lineare per fit
        self.graph.Fit('line', 'QR')
        line.GetParameters(self.pars)
        self.parerrs[0] = line.GetParError(0)
        self.parerrs[1] = line.GetParError(1)
        return zip(self.pars, self.parerrs)

    def getWaveLen(self):
        self.wavelen[0] = fabs(self.pars[1] * a[0]) * 1e9
        self.wavelen[1] = self.wavelen[0] * sqrt(
            (self.parerrs[1] / self.pars[1])**2 + (a[1] / a[0])**2)
        print 'lambda %s = %.1f \pm %.1f nm' % (self.name, self.wavelen[0],
                                                self.wavelen[1])
        return self.wavelen

    def showGraph(self):
        c = TCanvas(self.name, self.name)
        self.graph.Draw('AEP')
        raw_input('Press ENTER to continue...')

    def saveToEps(self):
        if self.pars[1]:
            c = TCanvas(self.name, self.name)
            self.graph.Draw('AEP')
            c.SaveAs(self.name + '.fit.eps')
        else:
            pass

    def printData(self):
        """test per verificare la corretta lettura dei dati"""
        for o, d, e in zip(self.ord, self.deg, self.degerr):
            print '%i \t %.3f \t %.3f' % (o, d, e)

    def setGraphStyle(self):
        self.graph.SetMarkerStyle(8)
        self.graph.GetXaxis().SetTitle("order")
        self.graph.GetYaxis().SetTitle("sine")
        self.graph.GetYaxis().SetTitleOffset(1.2)
        self.graph.GetXaxis().SetTitleSize(0.03)
        self.graph.GetYaxis().SetTitleSize(0.03)
        self.graph.GetXaxis().SetLabelSize(0.03)
        self.graph.GetYaxis().SetLabelSize(0.03)
        self.graph.GetXaxis().SetDecimals()
        self.graph.GetYaxis().SetDecimals()
        #		self.graph.SetStats( kFALSE );
        self.graph.SetTitle(self.name)
Ejemplo n.º 16
0
gr2.SetMarkerColor( 2 )
gr2.SetMarkerStyle( 20 )
gr2.SetMarkerSize( makerSize )
gr2.SetTitle( '' )
gr2.GetXaxis().SetTitle( 'E_{particle} (GeV)' )
gr2.GetYaxis().SetTitle( '#sigma_{reco}/E_{reco}' )
gr2.GetXaxis().SetTitleOffset(1.2)
gr2.GetYaxis().SetTitleOffset(1.9)
gr2.GetYaxis().SetRangeUser(0, 0.1)
gPad.SetLeftMargin(0.15)
gr2.Draw( 'AP' )

funReso = TF1('detReso', 'sqrt([0]*[0]/x+[1]*[1])', 0., 100.)
funReso.SetLineStyle(9)
funReso.SetLineColor(4)
gr2.Fit('detReso', 'q')

a0 = funReso.GetParameter('p0') * 100.
a1 = funReso.GetParameter('p1') * 100.

resoFormula = '#frac{#sigma}{E} = #frac{' + str( round(a0, 1) ) + '%}{#sqrt{E}} #oplus ' + str( round(a1, 1) ) + '%'

txt = TLatex()
txt.SetTextSize(0.035)
txt.DrawLatex(35., 0.08, resoFormula)


c2.Print('resolution.eps')

print('Fitting results:', a0, a1)
gLin.GetYaxis().SetRangeUser(-0.9,0.9)

# Prepare canvas
if not calo_init.args.noLinearity:
    cRes, padRes, padLin = prepare_double_canvas("resolution","Energy resolution", factor)
    padRes.cd()
else:
    cRes = prepare_single_canvas("resolution","Energy resolution")
    cRes.cd()

# Fit energy resolution
fRes = TF1("res", "sqrt([0]*[0] + pow([1]/sqrt(x),2))",5,600)
fRes.SetParName(0,"const")
fRes.SetParName(1,"sqrt")
fRes.SetLineColor(colour)
fitResult = gRes.Fit(fRes, 'S')

# Draw graph and all labels
gRes.Draw("ape")
if calo_init.args.axisMax:
    gRes.GetYaxis().SetRangeUser(0, calo_init.args.axisMax)
formula = "#frac{#sigma_{E}}{E} = " + str(round(fitResult.Get().Parameter(0)*100,2))+"% #oplus #frac{"+str(round(fitResult.Get().Parameter(1)*100,2))+"%}{#sqrt{E}}"
if not calo_init.args.noLinearity:
    draw_text([formula], [0.55,0.8,0.95,0.95], colour, 0).SetTextSize(0.05)
else:
    draw_text([formula], [0.55,0.7,0.95,0.85], colour, 0).SetTextSize(0.05)
if calo_init.args.technical:
    constString = "const: "+str(round(fitResult.Get().Parameter(0),4))+" #pm "+str(round(fitResult.Get().Error(0),4))
    samplingString = "sampl: "+str(round(fitResult.Get().Parameter(1),4))+" #pm "+str(round(fitResult.Get().Error(1),4))
    draw_text([constString, samplingString], [0.55,0.68,0.88,0.76], colour+1, 0).SetTextSize(0.05)
draw_text(["energy resolution"], [0.2,0.88, 0.45,0.98], 1, 0).SetTextSize(0.05)
Ejemplo n.º 18
0
            legendPhi.SetTextSize(0.05)
            legendPhi.SetTextFont(42)
            canvProfile.Update()
            canvPhi.Update()
            # save canvases filled for each energy and eta
            if calo_init.output(ifile):
                canvPhi.SaveAs(
                    calo_init.output(ifile) + "_previewPhi_eta" + str(eta) +
                    ".png")
            else:
                canvPhi.SaveAs("upstremCorrection_previewPhi_eta" + str(eta) +
                               "_" + str(layer * width) + "cm.png")

    # fit energy-dependent parameters
    fitP0 = TF1("fitP0", "pol1", 0, energy)
    par0result = param0.Fit(fitP0, "SR")
    fitP1 = TF1("fitP1", "[0]+[1]/sqrt(x)", 0, energy)
    par1result = param1.Fit(fitP1, "SR")
    cEnergy = prepare_divided_canvas(
        'upstreamParams_eta' + str(eta),
        'Energy upstream E=p0+p1E for eta=' + str(eta), 2)
    cEnergy.cd(1)
    prepare_graph(param0, "param0", 'P0 (E);' + axisName + '; parameter P0')
    param0.Draw("aep")
    param0.GetYaxis().SetRangeUser(param0.GetYaxis().GetXmin(),
                                   param0.GetYaxis().GetXmax() * 1.2)
    cEnergy.cd(2)
    prepare_graph(param1, "param1", 'P1 (E);' + axisName + '; parameter P1')
    param1.Draw("aep")
    param1.GetYaxis().SetRangeUser(param1.GetYaxis().GetXmin(),
                                   param1.GetYaxis().GetXmax() * 1.2)
Ejemplo n.º 19
0
in_file = "spettro.preamp.dat"
out_file = "preamp.grafici.out"
with open(out_file, "w") as output:
    with open(in_file) as file:
        for line, tuple in zip(file, means):
            pot, tens, _ = [float(x) for x in line.split()]
            media, err_media = tuple
            new_line = [pot, tens, media, 0, 0.03 * tens, err_media]
            new_line = [str(x) for x in new_line]
            new_line = " ".join(new_line) + "\n"
            output.write(new_line)

can_pot = TCanvas(out_file, out_file)
gr_pot = TGraphErrors(out_file, "%lg %*lg %lg %lg %*g %lg")
gr_pot.SetMarkerStyle(8)
gr_pot.Draw("ap")
f_pot = TF1("retta", "pol1")
gr_pot.Fit("retta")
print(gr_pot.GetCorrelationFactor())
print(f_pot.GetChisquare(), "/", f_pot.GetNDF())

can_tens = TCanvas(out_file + "2", out_file)
gr_tens = TGraphErrors(out_file, "%*lg %lg %lg %*lg %g %lg")
gr_tens.SetMarkerStyle(8)
gr_tens.Draw("ap")
f_tens = TF1("retta", "pol1")
gr_tens.Fit("retta")
print(f_tens.GetChisquare(), "/", f_tens.GetNDF())
input()
Ejemplo n.º 20
0
class _Efficiency(object):
    def __init__(self, num_pars=0, pars=None, norm=True):
        pars = pars or []

        self._numPars = num_pars
        self.parameter = pars
        self.fCov = [[None for j in range(self._numPars)]
                     for i in range(self._numPars)
                     ]  # Simple matrix replacement
        self._dEff_dP = list()
        self.TGraph = TGraphErrors()

        # Normalization factors
        self._doNorm = norm
        self.norm = 1.0
        self.TF1.FixParameter(0, self.norm)  # Normalization
        self.TF1.SetRange(0, 10000)  # Default range for efficiency function

        self._fitInput = Pairs(lambda x: ufloat(x, 0))

        #         if self.parameter: # Parameters were given
        #             map(lambda i: self.TF1.SetParameter(i + 1, self.parameter[i]), range(1, len(pars))) # Set initial parameters
        #         else:
        #             self.parameter = [None for i in range(1, self._numPars + 1)]
        #
        self.TF1.SetParName(0, "N")  # Normalization

        for i in range(0, num_pars):
            self._dEff_dP.append(None)
            if num_pars <= len(string.ascii_lowercase):
                self.TF1.SetParName(i + 1, string.ascii_lowercase[i])

    def _getParameter(self):
        """
        Get parameter of efficiency function
        """
        pars = list()
        for i in range(self._numPars):
            pars.append(self.TF1.GetParameter(i))

        return pars

    def _setParameter(self, pars):
        """
        Set parameter for efficiency function
        """
        for i in range(self._numPars):
            try:
                self.TF1.SetParameter(i, pars[i])
            except IndexError:
                self.TF1.SetParameter(i, 0)

    parameter = property(_getParameter, _setParameter)

    def __call__(self, E):
        value = self.value(E)
        try:
            error = self.error(E)
        except TypeError:
            error = None
        return ufloat(value, error)

    def _set_fitInput(self, fitPairs):

        self._fitInput = fitPairs

        for i in range(len(self._fitInput)):
            p = self._fitInput[i]
            try:
                e_nominal_value = p[0].nominal_value
                e_std_dev = p[0].std_dev
            except AttributeError:
                e_nominal_value = float(p[0])
                e_std_dev = 0.

            try:
                eff_nominal_value = p[1].nominal_value
                eff_std_dev = p[1].std_dev
            except AttributeError:
                eff_nominal_value = float(p[1])
                eff_std_dev = 0.

            self.TGraph.SetPoint(i, e_nominal_value, eff_nominal_value)
            self.TGraph.SetPointError(i, e_std_dev, eff_std_dev)

    def _get_fitInput(self):
        return self._fitInput

    fitInput = property(_get_fitInput, _set_fitInput)

    def fit(self, fitPairs=None, quiet=True):
        """
        Fit efficiency curve to values given by 'fitPairs' which should be a list
        of energy<->efficiency pairs. (See hdtv.util.Pairs())

        'energies' and 'efficiencies' may be a list of ufloats
        """
        # TODO: Unify this with the energy calibration fitter
        if fitPairs is not None:
            #self.fitInput = fitPairs
            self._fitInput = fitPairs

        E = array.array("d")
        delta_E = array.array("d")
        eff = array.array("d")
        delta_eff = array.array("d")
        EN = array.array("d")
        effN = array.array("d")

        #        map(energies.append(self.fitInput[0]), self.fitInput)
        #        map(efficiencies.append(self.fitInput[1]), self.fitInput)
        hasXerrors = False
        # Convert energies to array needed by ROOT
        try:
            list(map(lambda x: E.append(x[0].nominal_value), self._fitInput))
            list(map(lambda x: delta_E.append(x[0].std_dev), self._fitInput))
            list(map(lambda x: EN.append(0.0), self._fitInput))
            hasXerrors = True
        except AttributeError:  # energies does not seem to be ufloat list
            list(map(lambda x: E.append(x[0]), self._fitInput))
            list(map(lambda x: delta_E.append(0.0), self._fitInput))

        # Convert efficiencies to array needed by ROOT
        try:
            list(map(lambda x: eff.append(x[1].nominal_value), self._fitInput))
            list(map(lambda x: delta_eff.append(x[1].std_dev), self._fitInput))
            list(map(lambda x: effN.append(0.0), self._fitInput))
        except AttributeError:  # energies does not seem to be ufloat list
            list(map(lambda x: eff.append(x[1]), self._fitInput))
            list(map(lambda x: delta_eff.append(0.0), self._fitInput))

        # if fit has errors we first fit without errors to get good initial values
        # if hasXerrors == True:
        # print "Fit parameter without errors included:"
        #self.TGraphWithoutErrors = TGraphErrors(len(E), E, eff, EN, effN)
        #fitWithoutErrors = self.TGraphWithoutErrors.Fit(self.id, "SF")

        hdtv.ui.msg("Fit parameter with errors included:")

        # Preliminary normalization
        #        if self._doNorm:
        #            self.norm = 1 / max(efficiencies)
        #            for i in range(len(eff)):
        #                eff[i] *= self.norm
        #                delta_eff[i] *= self.norm

        #self.TF1.SetRange(0, max(E) * 1.1)
        # self.TF1.SetParameter(0, 1) # Unset normalization for fitting

        self.TGraph = TGraphErrors(len(E), E, eff, delta_E, delta_eff)

        # Do the fit
        fitopts = "0"  # Do not plot

        if hasXerrors:
            # We must use the iterative fitter (minuit) to take x errors
            # into account.
            fitopts += "F"
            hdtv.ui.info(
                "switching to non-linear fitter (minuit) for x error weighting"
            )
        if quiet:
            fitopts += "Q"

        fitopts += "S"  # Additional fitinfo returned needed for ROOT5.26 workaround below
        fitreturn = self.TGraph.Fit(self.id, fitopts)

        try:
            # Workaround for checking the fitstatus in ROOT 5.26 (TFitResultPtr
            # does not cast properly to int)
            fitstatus = fitreturn.Get().Status()
        except AttributeError:  # This is for ROOT <= 5.24, where fit returns an int
            fitstatus = int(fitreturn)

        if fitstatus != 0:
            # raise RuntimeError, "Fit failed"
            hdtv.ui.msg("Fit failed")

#         # Final normalization
#         if self._doNorm:
#             self.normalize()

# Get parameter
        for i in range(self._numPars):
            self.parameter[i] = self.TF1.GetParameter(i)

        # Get covariance matrix
        tvf = TVirtualFitter.GetFitter()
        ##        cov = tvf.GetCovarianceMatrix()
        for i in range(0, self._numPars):
            for j in range(0, self._numPars):
                self.fCov[i][j] = tvf.GetCovarianceMatrixElement(i, j)
##                 self.fCov[i][j] = cov[i * self._numPars + j]

        return self.parameter

    def normalize(self):
        # Normalize the efficiency funtion
        try:
            self.norm = 1.0 / self.TF1.GetMaximum(0.0, 0.0)
        except ZeroDivisionError:
            self.norm = 1.0

        self.TF1.SetParameter(0, self.norm)
        normfunc = TF2("norm_" + hex(id(self)), "[0]*y")
        normfunc.SetParameter(0, self.norm)
        self.TGraph.Apply(normfunc)

    def value(self, E):
        try:
            value = E.nominal_value
        except AttributeError:
            value = E

        return self.TF1.Eval(value)

    def error(self, E):
        """
        Calculate error using the covariance matrix via:

          delta_Eff = sqrt((dEff_dP[0], dEff_dP[1], ... dEff_dP[num_pars]) x cov x (dEff_dP[0], dEff_dP[1], ... dEff_dP[num_pars]))

        """
        try:
            value = E.nominal_value
        except AttributeError:
            value = E

        if not self.fCov or (len(self.fCov) != self._numPars):
            raise ValueError("Incorrect size of covariance matrix")

        res = 0.0

        # Do matrix multiplication
        for i in range(0, self._numPars):
            tmp = 0.0
            for j in range(0, self._numPars):
                tmp += (self._dEff_dP[j](value, self.parameter) *
                        self.fCov[i][j])

            res += (self._dEff_dP[i](value, self.parameter) * tmp)

        return sqrt(res)

    def loadPar(self, parfile):
        """
        Read parameter from file
        """
        vals = []

        file = TxtFile(parfile)
        file.read()

        for line in file.lines:
            vals.append(float(line))

        if len(vals) != self._numPars:
            raise RuntimeError("Incorrect number of parameters found in file")

        self.parameter = vals
        if self._doNorm:
            self.normalize()

    def loadCov(self, covfile):
        """
        Load covariance matrix from file
        """

        vals = []

        file = TxtFile(covfile)
        file.read()

        for line in file.lines:
            val_row = [float(s) for s in line.split()]
            if len(val_row) != self._numPars:
                raise RuntimeError("Incorrect format of parameter error file")
            vals.append(val_row)

        if len(vals) != self._numPars:
            raise RuntimeError("Incorrect format of parameter error file")

        self.fCov = vals

    def load(self, parfile, covfile=None):
        """
        Read parameter and covariance matrix from file
        """
        self.loadPar(parfile)

        if covfile:
            self.loadCov(covfile)

    def savePar(self, parfile):
        """
        Save parameter to file
        """
        file = TxtFile(parfile, "w")

        for p in self.parameter:
            file.lines.append(str(p))

        file.write()

    def saveCov(self, covfile):
        """
        Save covariance matrix to file
        """
        file = TxtFile(covfile, "w")

        for i in range(0, self._numPars):
            line = ""
            for j in range(0, self._numPars):
                line += str(self.fCov[i][j]) + " "
            file.lines.append(line)

        file.write()

    def save(self, parfile, covfile=None):
        """
        Save parameter and covariance matrix to files
        """
        # Write paramter
        self.savePar(parfile)

        # Write covariance matrix
        if covfile is not None:
            self.saveCov(covfile)
Ejemplo n.º 21
0
#define some data points ...
ax = array('f',( -0.9, -0.8, -0.7, -0.6, -0.5, -0.4, -0.3, -0.2, -0.1, 0.0,  0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0) )
ay = array('f', (5.0935, 2.1777, 0.2089, -2.3949, -2.4457, -3.0430, -2.2731, -2.0706, -1.6231, -2.5605, -0.7703, -0.3055, 1.6817, 1.8728, 3.6586, 3.2353, 4.2520, 5.2550, 3.8766, 4.2890 ) ) 
ey=np.array(len(data_x)*[0.5],dtype=np.float)
ex=np.array(len(data_y)*[0],dtype=np.float)
# ... and pass to TGraphErros object
gr=TGraphErrors(nPoints,data_x,data_y,ex,ey)
gr.SetTitle("TGraphErrors mit Fit")
gr.Draw("AP");

Pol=["pol1","pol2","pol3","pol4","pol5","pol6","pol7"]

# Polifit
for i in range(len(polynom)):
  gr.Fit(polynom[i],"V")
  c1.Update()
  gr.Draw('AP')
  fitrp = TVirtualFitter.GetFitter()
  nPar = fitrp.GetNumberTotalParameters()
  covmat = TMatrixD(nPar, nPar,fitrp.GetCovarianceMatrix())
  print('The Covariance Matrix is: ')
  covmat.Print()
  cormat = TMatrixD(covmat)
  for i in range(nPar):
    for j in range(nPar):
      cormat[i][j] = cormat[i][j] / (np.sqrt(covmat[i][i]) * np.sqrt(covmat[j][j]))
  print('The Correlation Matrix is: ')
  cormat.Print()
  raw_input('Press <ret> to continue -> ')
Ejemplo n.º 22
0
def signal(category):

    interPar = True
    n = len(genPoints)

    cColor = color[category] if category in color else 4
    nBtag = category.count('b')
    isAH = False  #relict from using Alberto's more complex script

    if not os.path.exists(PLOTDIR + "MC_signal_" + YEAR):
        os.makedirs(PLOTDIR + "MC_signal_" + YEAR)

    #*******************************************************#
    #                                                       #
    #              Variables and selections                 #
    #                                                       #
    #*******************************************************#

    X_mass = RooRealVar("jj_mass_widejet", "m_{jj}", X_min, X_max, "GeV")
    j1_pt = RooRealVar("jpt_1", "jet1 pt", 0., 13000., "GeV")
    jj_deltaEta = RooRealVar("jj_deltaEta_widejet", "", 0., 5.)
    jbtag_WP_1 = RooRealVar("jbtag_WP_1", "", -1., 4.)
    jbtag_WP_2 = RooRealVar("jbtag_WP_2", "", -1., 4.)
    fatjetmass_1 = RooRealVar("fatjetmass_1", "", -1., 2500.)
    fatjetmass_2 = RooRealVar("fatjetmass_2", "", -1., 2500.)
    jid_1 = RooRealVar("jid_1", "j1 ID", -1., 8.)
    jid_2 = RooRealVar("jid_2", "j2 ID", -1., 8.)
    jnmuons_1 = RooRealVar("jnmuons_1", "j1 n_{#mu}", -1., 8.)
    jnmuons_2 = RooRealVar("jnmuons_2", "j2 n_{#mu}", -1., 8.)
    jnmuons_loose_1 = RooRealVar("jnmuons_loose_1", "jnmuons_loose_1", -1., 8.)
    jnmuons_loose_2 = RooRealVar("jnmuons_loose_2", "jnmuons_loose_2", -1., 8.)
    nmuons = RooRealVar("nmuons", "n_{#mu}", -1., 10.)
    nelectrons = RooRealVar("nelectrons", "n_{e}", -1., 10.)
    HLT_AK8PFJet500 = RooRealVar("HLT_AK8PFJet500", "", -1., 1.)
    HLT_PFJet500 = RooRealVar("HLT_PFJet500", "", -1., 1.)
    HLT_CaloJet500_NoJetID = RooRealVar("HLT_CaloJet500_NoJetID", "", -1., 1.)
    HLT_PFHT900 = RooRealVar("HLT_PFHT900", "", -1., 1.)
    HLT_AK8PFJet550 = RooRealVar("HLT_AK8PFJet550", "", -1., 1.)
    HLT_PFJet550 = RooRealVar("HLT_PFJet550", "", -1., 1.)
    HLT_CaloJet550_NoJetID = RooRealVar("HLT_CaloJet550_NoJetID", "", -1., 1.)
    HLT_PFHT1050 = RooRealVar("HLT_PFHT1050", "", -1., 1.)
    #HLT_DoublePFJets100_CaloBTagDeepCSV_p71                 =RooRealVar("HLT_DoublePFJets100_CaloBTagDeepCSV_p71"                , "", -1., 1. )
    #HLT_DoublePFJets116MaxDeta1p6_DoubleCaloBTagDeepCSV_p71 =RooRealVar("HLT_DoublePFJets116MaxDeta1p6_DoubleCaloBTagDeepCSV_p71", "", -1., 1. )
    #HLT_DoublePFJets128MaxDeta1p6_DoubleCaloBTagDeepCSV_p71 =RooRealVar("HLT_DoublePFJets128MaxDeta1p6_DoubleCaloBTagDeepCSV_p71", "", -1., 1. )
    #HLT_DoublePFJets200_CaloBTagDeepCSV_p71                 =RooRealVar("HLT_DoublePFJets200_CaloBTagDeepCSV_p71"                , "", -1., 1. )
    #HLT_DoublePFJets350_CaloBTagDeepCSV_p71                 =RooRealVar("HLT_DoublePFJets350_CaloBTagDeepCSV_p71"                , "", -1., 1. )
    #HLT_DoublePFJets40_CaloBTagDeepCSV_p71                  =RooRealVar("HLT_DoublePFJets40_CaloBTagDeepCSV_p71"                 , "", -1., 1. )

    weight = RooRealVar("eventWeightLumi", "", -1.e9, 1.e9)

    # Define the RooArgSet which will include all the variables defined before
    # there is a maximum of 9 variables in the declaration, so the others need to be added with 'add'
    variables = RooArgSet(X_mass)
    variables.add(
        RooArgSet(j1_pt, jj_deltaEta, jbtag_WP_1, jbtag_WP_2, fatjetmass_1,
                  fatjetmass_2, jnmuons_1, jnmuons_2, weight))
    variables.add(
        RooArgSet(nmuons, nelectrons, jid_1, jid_2, jnmuons_loose_1,
                  jnmuons_loose_2))
    variables.add(
        RooArgSet(HLT_AK8PFJet500, HLT_PFJet500, HLT_CaloJet500_NoJetID,
                  HLT_PFHT900, HLT_AK8PFJet550, HLT_PFJet550,
                  HLT_CaloJet550_NoJetID, HLT_PFHT1050))
    #variables.add(RooArgSet(HLT_DoublePFJets100_CaloBTagDeepCSV_p71, HLT_DoublePFJets116MaxDeta1p6_DoubleCaloBTagDeepCSV_p71, HLT_DoublePFJets128MaxDeta1p6_DoubleCaloBTagDeepCSV_p71, HLT_DoublePFJets200_CaloBTagDeepCSV_p71, HLT_DoublePFJets350_CaloBTagDeepCSV_p71, HLT_DoublePFJets40_CaloBTagDeepCSV_p71))
    X_mass.setRange("X_reasonable_range", X_mass.getMin(), X_mass.getMax())
    X_mass.setRange("X_integration_range", X_mass.getMin(), X_mass.getMax())

    if VARBINS:
        binsXmass = RooBinning(len(abins) - 1, abins)
        X_mass.setBinning(binsXmass)
        plot_binning = RooBinning(
            int((X_mass.getMax() - X_mass.getMin()) / 100.), X_mass.getMin(),
            X_mass.getMax())
    else:
        X_mass.setBins(int((X_mass.getMax() - X_mass.getMin()) / 10))
        binsXmass = RooBinning(int((X_mass.getMax() - X_mass.getMin()) / 100.),
                               X_mass.getMin(), X_mass.getMax())
        plot_binning = binsXmass

    X_mass.setBinning(plot_binning, "PLOT")

    #X_mass.setBins(int((X_mass.getMax() - X_mass.getMin())/10))
    #binsXmass = RooBinning(int((X_mass.getMax() - X_mass.getMin())/100), X_mass.getMin(), X_mass.getMax())
    #X_mass.setBinning(binsXmass, "PLOT")
    massArg = RooArgSet(X_mass)

    # Cuts
    if BTAGGING == 'semimedium':
        SRcut = aliasSM[category]
        #SRcut = aliasSM[category+"_vetoAK8"]
    else:
        SRcut = alias[category].format(WP=working_points[BTAGGING])
        #SRcut = alias[category+"_vetoAK8"].format(WP=working_points[BTAGGING])

    if ADDSELECTION: SRcut += SELECTIONS[options.selection]

    print "  Cut:\t", SRcut

    #*******************************************************#
    #                                                       #
    #                    Signal fits                        #
    #                                                       #
    #*******************************************************#

    treeSign = {}
    setSignal = {}

    vmean = {}
    vsigma = {}
    valpha1 = {}
    vslope1 = {}
    valpha2 = {}
    vslope2 = {}
    smean = {}
    ssigma = {}
    salpha1 = {}
    sslope1 = {}
    salpha2 = {}
    sslope2 = {}
    sbrwig = {}
    signal = {}
    signalExt = {}
    signalYield = {}
    signalIntegral = {}
    signalNorm = {}
    signalXS = {}
    frSignal = {}
    frSignal1 = {}
    frSignal2 = {}
    frSignal3 = {}

    # Signal shape uncertainties (common amongst all mass points)
    xmean_jes = RooRealVar(
        "CMS" + YEAR + "_sig_" + category + "_p1_scale_jes",
        "Variation of the resonance position with the jet energy scale", 0.02,
        -1., 1.)  #0.001
    smean_jes = RooRealVar(
        "CMS" + YEAR + "_sig_" + category + "_p1_jes",
        "Change of the resonance position with the jet energy scale", 0., -10,
        10)

    xsigma_jer = RooRealVar(
        "CMS" + YEAR + "_sig_" + category + "_p2_scale_jer",
        "Variation of the resonance width with the jet energy resolution",
        0.10, -1., 1.)
    ssigma_jer = RooRealVar(
        "CMS" + YEAR + "_sig_" + category + "_p2_jer",
        "Change of the resonance width with the jet energy resolution", 0.,
        -10, 10)

    xmean_jes.setConstant(True)
    smean_jes.setConstant(True)

    xsigma_jer.setConstant(True)
    ssigma_jer.setConstant(True)

    for m in massPoints:

        signalMass = "%s_M%d" % (stype, m)
        signalName = "ZpBB_{}_{}_M{}".format(YEAR, category, m)
        sampleName = "ZpBB_M{}".format(m)

        signalColor = sample[sampleName][
            'linecolor'] if signalName in sample else 1

        # define the signal PDF
        vmean[m] = RooRealVar(signalName + "_vmean", "Crystal Ball mean", m,
                              m * 0.96, m * 1.05)
        smean[m] = RooFormulaVar(signalName + "_mean", "@0*(1+@1*@2)",
                                 RooArgList(vmean[m], xmean_jes, smean_jes))

        vsigma[m] = RooRealVar(signalName + "_vsigma", "Crystal Ball sigma",
                               m * 0.0233, m * 0.019, m * 0.025)
        ssigma[m] = RooFormulaVar(
            signalName + "_sigma", "@0*(1+@1*@2)",
            RooArgList(vsigma[m], xsigma_jer, ssigma_jer))

        valpha1[m] = RooRealVar(
            signalName + "_valpha1", "Crystal Ball alpha 1", 0.2, 0.05, 0.28
        )  # number of sigmas where the exp is attached to the gaussian core. >0 left, <0 right
        salpha1[m] = RooFormulaVar(signalName + "_alpha1", "@0",
                                   RooArgList(valpha1[m]))

        #vslope1[m] = RooRealVar(signalName + "_vslope1", "Crystal Ball slope 1", 10., 0.1, 20.) # slope of the power tail
        vslope1[m] = RooRealVar(signalName + "_vslope1",
                                "Crystal Ball slope 1", 13., 10.,
                                20.)  # slope of the power tail
        sslope1[m] = RooFormulaVar(signalName + "_slope1", "@0",
                                   RooArgList(vslope1[m]))

        valpha2[m] = RooRealVar(signalName + "_valpha2",
                                "Crystal Ball alpha 2", 1.)
        valpha2[m].setConstant(True)
        salpha2[m] = RooFormulaVar(signalName + "_alpha2", "@0",
                                   RooArgList(valpha2[m]))

        #vslope2[m] = RooRealVar(signalName + "_vslope2", "Crystal Ball slope 2", 6., 2.5, 15.) # slope of the higher power tail
        ## FIXME test FIXME
        vslope2_estimation = -5.88111436852 + m * 0.00728809389442 + m * m * (
            -1.65059568762e-06) + m * m * m * (1.25128996309e-10)
        vslope2[m] = RooRealVar(signalName + "_vslope2",
                                "Crystal Ball slope 2", vslope2_estimation,
                                vslope2_estimation * 0.9, vslope2_estimation *
                                1.1)  # slope of the higher power tail
        ## FIXME end FIXME
        sslope2[m] = RooFormulaVar(
            signalName + "_slope2", "@0",
            RooArgList(vslope2[m]))  # slope of the higher power tail

        signal[m] = RooDoubleCrystalBall(signalName,
                                         "m_{%s'} = %d GeV" % ('X', m), X_mass,
                                         smean[m], ssigma[m], salpha1[m],
                                         sslope1[m], salpha2[m], sslope2[m])

        # extend the PDF with the yield to perform an extended likelihood fit
        signalYield[m] = RooRealVar(signalName + "_yield", "signalYield", 50,
                                    0., 1.e15)
        signalNorm[m] = RooRealVar(signalName + "_norm", "signalNorm", 1., 0.,
                                   1.e15)
        signalXS[m] = RooRealVar(signalName + "_xs", "signalXS", 1., 0., 1.e15)
        signalExt[m] = RooExtendPdf(signalName + "_ext", "extended p.d.f",
                                    signal[m], signalYield[m])

        # ---------- if there is no simulated signal, skip this mass point ----------
        if m in genPoints:
            if VERBOSE: print " - Mass point", m

            # define the dataset for the signal applying the SR cuts
            treeSign[m] = TChain("tree")

            if YEAR == 'run2':
                pd = sample[sampleName]['files']
                if len(pd) > 3:
                    print "multiple files given than years for a single masspoint:", pd
                    sys.exit()
                for ss in pd:
                    if not '2016' in ss and not '2017' in ss and not '2018' in ss:
                        print "unknown year given in:", ss
                        sys.exit()
            else:
                pd = [x for x in sample[sampleName]['files'] if YEAR in x]
                if len(pd) > 1:
                    print "multiple files given for a single masspoint/year:", pd
                    sys.exit()

            for ss in pd:

                if options.unskimmed:
                    j = 0
                    while True:
                        if os.path.exists(NTUPLEDIR + ss + "/" + ss +
                                          "_flatTuple_{}.root".format(j)):
                            treeSign[m].Add(NTUPLEDIR + ss + "/" + ss +
                                            "_flatTuple_{}.root".format(j))
                            j += 1
                        else:
                            print "found {} files for sample:".format(j), ss
                            break
                else:
                    if os.path.exists(NTUPLEDIR + ss + ".root"):
                        treeSign[m].Add(NTUPLEDIR + ss + ".root")
                    else:
                        print "found no file for sample:", ss

            if treeSign[m].GetEntries() <= 0.:
                if VERBOSE:
                    print " - 0 events available for mass", m, "skipping mass point..."
                signalNorm[m].setVal(-1)
                vmean[m].setConstant(True)
                vsigma[m].setConstant(True)
                salpha1[m].setConstant(True)
                sslope1[m].setConstant(True)
                salpha2[m].setConstant(True)
                sslope2[m].setConstant(True)
                signalNorm[m].setConstant(True)
                signalXS[m].setConstant(True)
                continue

            #setSignal[m] = RooDataSet("setSignal_"+signalName, "setSignal", variables, RooFit.Cut(SRcut), RooFit.WeightVar("eventWeightLumi*BTagAK4Weight_deepJet"), RooFit.Import(treeSign[m]))
            setSignal[m] = RooDataSet("setSignal_" + signalName, "setSignal",
                                      variables, RooFit.Cut(SRcut),
                                      RooFit.WeightVar(weight),
                                      RooFit.Import(treeSign[m]))
            if VERBOSE:
                print " - Dataset with", setSignal[m].sumEntries(
                ), "events loaded"

            # FIT
            entries = setSignal[m].sumEntries()
            if entries < 0. or entries != entries: entries = 0
            signalYield[m].setVal(entries)
            # Instead of eventWeightLumi
            #signalYield[m].setVal(entries * LUMI / (300000 if YEAR=='run2' else 100000) )

            if treeSign[m].GetEntries(SRcut) > 5:
                if VERBOSE: print " - Running fit"
                frSignal[m] = signalExt[m].fitTo(setSignal[m], RooFit.Save(1),
                                                 RooFit.Extended(True),
                                                 RooFit.SumW2Error(True),
                                                 RooFit.PrintLevel(-1))
                if VERBOSE:
                    print "********** Fit result [", m, "] **", category, "*" * 40, "\n", frSignal[
                        m].Print(), "\n", "*" * 80
                if VERBOSE: frSignal[m].correlationMatrix().Print()
                drawPlot(signalMass + "_" + category, stype + category, X_mass,
                         signal[m], setSignal[m], frSignal[m])

            else:
                print "  WARNING: signal", stype, "and mass point", m, "in category", category, "has 0 entries or does not exist"

            # Remove HVT cross sections
            #xs = getCrossSection(stype, channel, m)
            xs = 1.
            signalXS[m].setVal(xs * 1000.)

            signalIntegral[m] = signalExt[m].createIntegral(
                massArg, RooFit.NormSet(massArg),
                RooFit.Range("X_integration_range"))
            boundaryFactor = signalIntegral[m].getVal()
            if boundaryFactor < 0. or boundaryFactor != boundaryFactor:
                boundaryFactor = 0
            if VERBOSE:
                print " - Fit normalization vs integral:", signalYield[
                    m].getVal(), "/", boundaryFactor, "events"
            signalNorm[m].setVal(boundaryFactor * signalYield[m].getVal() /
                                 signalXS[m].getVal()
                                 )  # here normalize to sigma(X) x Br = 1 [fb]

        vmean[m].setConstant(True)
        vsigma[m].setConstant(True)
        valpha1[m].setConstant(True)
        vslope1[m].setConstant(True)
        valpha2[m].setConstant(True)
        vslope2[m].setConstant(True)
        signalNorm[m].setConstant(True)
        signalXS[m].setConstant(True)

    #*******************************************************#
    #                                                       #
    #                 Signal interpolation                  #
    #                                                       #
    #*******************************************************#

    ### FIXME FIXME just for a test FIXME FIXME

    #print
    #print
    #print "slope2 fit results:"
    #print
    #y_vals = []
    #for m in genPoints:
    #    y_vals.append(vslope2[m].getVal())
    #print "m =", genPoints
    #print "y =", y_vals
    #sys.exit()

    ### FIXME FIXME test end FIXME FIXME

    # ====== CONTROL PLOT ======
    color_scheme = [
        636, 635, 634, 633, 632, 633, 636, 635, 634, 633, 632, 633, 636, 635,
        634, 633, 632, 633, 636, 635, 634, 633, 632, 633, 636, 635, 634, 633,
        632, 633, 636, 635, 634, 633, 632, 633, 636, 635, 634, 633, 632, 633
    ]
    c_signal = TCanvas("c_signal", "c_signal", 800, 600)
    c_signal.cd()
    frame_signal = X_mass.frame()
    for j, m in enumerate(genPoints):
        if m in signalExt.keys():
            #print "color:",(j%9)+1
            #print "signalNorm[m].getVal() =", signalNorm[m].getVal()
            #print "RooAbsReal.NumEvent =", RooAbsReal.NumEvent
            signal[m].plotOn(
                frame_signal, RooFit.LineColor(color_scheme[j]),
                RooFit.Normalization(signalNorm[m].getVal(),
                                     RooAbsReal.NumEvent),
                RooFit.Range("X_reasonable_range"))
    frame_signal.GetXaxis().SetRangeUser(0, 10000)
    frame_signal.Draw()
    drawCMS(-1, "Simulation Preliminary", year=YEAR)
    #drawCMS(-1, "Work in Progress", year=YEAR, suppressCMS=True)
    #drawCMS(-1, "", year=YEAR, suppressCMS=True)
    drawAnalysis(category)
    drawRegion(category)

    c_signal.SaveAs(PLOTDIR + "MC_signal_" + YEAR + "/" + stype + "_" +
                    category + "_Signal.pdf")
    c_signal.SaveAs(PLOTDIR + "MC_signal_" + YEAR + "/" + stype + "_" +
                    category + "_Signal.png")
    #if VERBOSE: raw_input("Press Enter to continue...")
    # ====== CONTROL PLOT ======

    # Normalization
    gnorm = TGraphErrors()
    gnorm.SetTitle(";m_{X} (GeV);integral (GeV)")
    gnorm.SetMarkerStyle(20)
    gnorm.SetMarkerColor(1)
    gnorm.SetMaximum(0)
    inorm = TGraphErrors()
    inorm.SetMarkerStyle(24)
    fnorm = TF1("fnorm", "pol9", 700, 3000)
    fnorm.SetLineColor(920)
    fnorm.SetLineStyle(7)
    fnorm.SetFillColor(2)
    fnorm.SetLineColor(cColor)

    # Mean
    gmean = TGraphErrors()
    gmean.SetTitle(";m_{X} (GeV);gaussian mean (GeV)")
    gmean.SetMarkerStyle(20)
    gmean.SetMarkerColor(cColor)
    gmean.SetLineColor(cColor)
    imean = TGraphErrors()
    imean.SetMarkerStyle(24)
    fmean = TF1("fmean", "pol1", 0, 10000)
    fmean.SetLineColor(2)
    fmean.SetFillColor(2)

    # Width
    gsigma = TGraphErrors()
    gsigma.SetTitle(";m_{X} (GeV);gaussian width (GeV)")
    gsigma.SetMarkerStyle(20)
    gsigma.SetMarkerColor(cColor)
    gsigma.SetLineColor(cColor)
    isigma = TGraphErrors()
    isigma.SetMarkerStyle(24)
    fsigma = TF1("fsigma", "pol1", 0, 10000)
    fsigma.SetLineColor(2)
    fsigma.SetFillColor(2)

    # Alpha1
    galpha1 = TGraphErrors()
    galpha1.SetTitle(";m_{X} (GeV);crystal ball lower alpha")
    galpha1.SetMarkerStyle(20)
    galpha1.SetMarkerColor(cColor)
    galpha1.SetLineColor(cColor)
    ialpha1 = TGraphErrors()
    ialpha1.SetMarkerStyle(24)
    falpha1 = TF1("falpha", "pol1", 0, 10000)  #pol0
    falpha1.SetLineColor(2)
    falpha1.SetFillColor(2)

    # Slope1
    gslope1 = TGraphErrors()
    gslope1.SetTitle(";m_{X} (GeV);exponential lower slope (1/Gev)")
    gslope1.SetMarkerStyle(20)
    gslope1.SetMarkerColor(cColor)
    gslope1.SetLineColor(cColor)
    islope1 = TGraphErrors()
    islope1.SetMarkerStyle(24)
    fslope1 = TF1("fslope", "pol1", 0, 10000)  #pol0
    fslope1.SetLineColor(2)
    fslope1.SetFillColor(2)

    # Alpha2
    galpha2 = TGraphErrors()
    galpha2.SetTitle(";m_{X} (GeV);crystal ball upper alpha")
    galpha2.SetMarkerStyle(20)
    galpha2.SetMarkerColor(cColor)
    galpha2.SetLineColor(cColor)
    ialpha2 = TGraphErrors()
    ialpha2.SetMarkerStyle(24)
    falpha2 = TF1("falpha", "pol1", 0, 10000)  #pol0
    falpha2.SetLineColor(2)
    falpha2.SetFillColor(2)

    # Slope2
    gslope2 = TGraphErrors()
    gslope2.SetTitle(";m_{X} (GeV);exponential upper slope (1/Gev)")
    gslope2.SetMarkerStyle(20)
    gslope2.SetMarkerColor(cColor)
    gslope2.SetLineColor(cColor)
    islope2 = TGraphErrors()
    islope2.SetMarkerStyle(24)
    fslope2 = TF1("fslope", "pol1", 0, 10000)  #pol0
    fslope2.SetLineColor(2)
    fslope2.SetFillColor(2)

    n = 0
    for i, m in enumerate(genPoints):
        if not m in signalNorm.keys(): continue
        if signalNorm[m].getVal() < 1.e-6: continue

        if gnorm.GetMaximum() < signalNorm[m].getVal():
            gnorm.SetMaximum(signalNorm[m].getVal())
        gnorm.SetPoint(n, m, signalNorm[m].getVal())
        #gnorm.SetPointError(i, 0, signalNorm[m].getVal()/math.sqrt(treeSign[m].GetEntriesFast()))
        gmean.SetPoint(n, m, vmean[m].getVal())
        gmean.SetPointError(n, 0,
                            min(vmean[m].getError(), vmean[m].getVal() * 0.02))
        gsigma.SetPoint(n, m, vsigma[m].getVal())
        gsigma.SetPointError(
            n, 0, min(vsigma[m].getError(), vsigma[m].getVal() * 0.05))
        galpha1.SetPoint(n, m, valpha1[m].getVal())
        galpha1.SetPointError(
            n, 0, min(valpha1[m].getError(), valpha1[m].getVal() * 0.10))
        gslope1.SetPoint(n, m, vslope1[m].getVal())
        gslope1.SetPointError(
            n, 0, min(vslope1[m].getError(), vslope1[m].getVal() * 0.10))
        galpha2.SetPoint(n, m, salpha2[m].getVal())
        galpha2.SetPointError(
            n, 0, min(valpha2[m].getError(), valpha2[m].getVal() * 0.10))
        gslope2.SetPoint(n, m, sslope2[m].getVal())
        gslope2.SetPointError(
            n, 0, min(vslope2[m].getError(), vslope2[m].getVal() * 0.10))
        #tmpVar = w.var(var+"_"+signalString)
        #print m, tmpVar.getVal(), tmpVar.getError()
        n = n + 1

    gmean.Fit(fmean, "Q0", "SAME")
    gsigma.Fit(fsigma, "Q0", "SAME")
    galpha1.Fit(falpha1, "Q0", "SAME")
    gslope1.Fit(fslope1, "Q0", "SAME")
    galpha2.Fit(falpha2, "Q0", "SAME")
    gslope2.Fit(fslope2, "Q0", "SAME")
    #    gnorm.Fit(fnorm, "Q0", "", 700, 5000)
    #for m in [5000, 5500]: gnorm.SetPoint(gnorm.GetN(), m, gnorm.Eval(m, 0, "S"))
    #gnorm.Fit(fnorm, "Q", "SAME", 700, 6000)
    gnorm.Fit(fnorm, "Q", "SAME", 1800, 8000)  ## adjusted recently

    for m in massPoints:

        if vsigma[m].getVal() < 10.: vsigma[m].setVal(10.)

        # Interpolation method
        syield = gnorm.Eval(m)
        spline = gnorm.Eval(m, 0, "S")
        sfunct = fnorm.Eval(m)

        #delta = min(abs(1.-spline/sfunct), abs(1.-spline/syield))
        delta = abs(1. - spline / sfunct) if sfunct > 0 else 0
        syield = spline

        if interPar:
            #jmean = gmean.Eval(m)
            #jsigma = gsigma.Eval(m)
            #jalpha1 = galpha1.Eval(m)
            #jslope1 = gslope1.Eval(m)
            #jalpha2 = galpha2.Eval(m)
            #jslope2 = gslope2.Eval(m)
            jmean = gmean.Eval(m, 0, "S")
            jsigma = gsigma.Eval(m, 0, "S")
            jalpha1 = galpha1.Eval(m, 0, "S")
            jslope1 = gslope1.Eval(m, 0, "S")
            jalpha2 = galpha2.Eval(m, 0, "S")
            jslope2 = gslope2.Eval(m, 0, "S")

        else:
            jmean = fmean.GetParameter(
                0) + fmean.GetParameter(1) * m + fmean.GetParameter(2) * m * m
            jsigma = fsigma.GetParameter(0) + fsigma.GetParameter(
                1) * m + fsigma.GetParameter(2) * m * m
            jalpha1 = falpha1.GetParameter(0) + falpha1.GetParameter(
                1) * m + falpha1.GetParameter(2) * m * m
            jslope1 = fslope1.GetParameter(0) + fslope1.GetParameter(
                1) * m + fslope1.GetParameter(2) * m * m
            jalpha2 = falpha2.GetParameter(0) + falpha2.GetParameter(
                1) * m + falpha2.GetParameter(2) * m * m
            jslope2 = fslope2.GetParameter(0) + fslope2.GetParameter(
                1) * m + fslope2.GetParameter(2) * m * m

        inorm.SetPoint(inorm.GetN(), m, syield)
        signalNorm[m].setVal(max(0., syield))

        imean.SetPoint(imean.GetN(), m, jmean)
        if jmean > 0: vmean[m].setVal(jmean)

        isigma.SetPoint(isigma.GetN(), m, jsigma)
        if jsigma > 0: vsigma[m].setVal(jsigma)

        ialpha1.SetPoint(ialpha1.GetN(), m, jalpha1)
        if not jalpha1 == 0: valpha1[m].setVal(jalpha1)

        islope1.SetPoint(islope1.GetN(), m, jslope1)
        if jslope1 > 0: vslope1[m].setVal(jslope1)

        ialpha2.SetPoint(ialpha2.GetN(), m, jalpha2)
        if not jalpha2 == 0: valpha2[m].setVal(jalpha2)

        islope2.SetPoint(islope2.GetN(), m, jslope2)
        if jslope2 > 0: vslope2[m].setVal(jslope2)

        #### newly introduced, not yet sure if helpful:
        vmean[m].removeError()
        vsigma[m].removeError()
        valpha1[m].removeError()
        valpha2[m].removeError()
        vslope1[m].removeError()
        vslope2[m].removeError()

        #signalNorm[m].setConstant(False)  ## newly put here to ensure it's freely floating in the combine fit

    #c1 = TCanvas("c1", "Crystal Ball", 1200, 1200) #if not isAH else 1200
    #c1.Divide(2, 3)
    c1 = TCanvas("c1", "Crystal Ball", 1800, 800)
    c1.Divide(3, 2)
    c1.cd(1)
    gmean.SetMinimum(0.)
    gmean.Draw("APL")
    imean.Draw("P, SAME")
    drawRegion(category)
    drawCMS(-1, "Simulation Preliminary", year=YEAR)  ## new FIXME
    c1.cd(2)
    gsigma.SetMinimum(0.)
    gsigma.Draw("APL")
    isigma.Draw("P, SAME")
    drawRegion(category)
    drawCMS(-1, "Simulation Preliminary", year=YEAR)  ## new FIXME
    c1.cd(3)
    galpha1.Draw("APL")
    ialpha1.Draw("P, SAME")
    drawRegion(category)
    drawCMS(-1, "Simulation Preliminary", year=YEAR)  ## new FIXME
    galpha1.GetYaxis().SetRangeUser(0., 1.1)  #adjusted upper limit from 5 to 2
    c1.cd(4)
    gslope1.Draw("APL")
    islope1.Draw("P, SAME")
    drawRegion(category)
    drawCMS(-1, "Simulation Preliminary", year=YEAR)  ## new FIXME
    gslope1.GetYaxis().SetRangeUser(0.,
                                    150.)  #adjusted upper limit from 125 to 60
    if True:  #isAH:
        c1.cd(5)
        galpha2.Draw("APL")
        ialpha2.Draw("P, SAME")
        drawRegion(category)
        drawCMS(-1, "Simulation Preliminary", year=YEAR)  ## new FIXME
        galpha2.GetYaxis().SetRangeUser(0., 2.)
        c1.cd(6)
        gslope2.Draw("APL")
        islope2.Draw("P, SAME")
        drawRegion(category)
        drawCMS(-1, "Simulation Preliminary", year=YEAR)  ## new FIXME
        gslope2.GetYaxis().SetRangeUser(0., 20.)

    c1.Print(PLOTDIR + "MC_signal_" + YEAR + "/" + stype + "_" + category +
             "_SignalShape.pdf")
    c1.Print(PLOTDIR + "MC_signal_" + YEAR + "/" + stype + "_" + category +
             "_SignalShape.png")

    c2 = TCanvas("c2", "Signal Efficiency", 800, 600)
    c2.cd(1)
    gnorm.SetMarkerColor(cColor)
    gnorm.SetMarkerStyle(20)
    gnorm.SetLineColor(cColor)
    gnorm.SetLineWidth(2)
    gnorm.Draw("APL")
    inorm.Draw("P, SAME")
    gnorm.GetXaxis().SetRangeUser(genPoints[0] - 100, genPoints[-1] + 100)
    gnorm.GetYaxis().SetRangeUser(0., gnorm.GetMaximum() * 1.25)
    drawCMS(-1, "Simulation Preliminary", year=YEAR)
    #drawCMS(-1, "Work in Progress", year=YEAR, suppressCMS=True)
    #drawCMS(-1, "", year=YEAR, suppressCMS=True)
    drawAnalysis(category)
    drawRegion(category)
    c2.Print(PLOTDIR + "MC_signal_" + YEAR + "/" + stype + "_" + category +
             "_SignalNorm.pdf")
    c2.Print(PLOTDIR + "MC_signal_" + YEAR + "/" + stype + "_" + category +
             "_SignalNorm.png")

    #*******************************************************#
    #                                                       #
    #                   Generate workspace                  #
    #                                                       #
    #*******************************************************#

    # create workspace
    w = RooWorkspace("Zprime_" + YEAR, "workspace")
    for m in massPoints:
        getattr(w, "import")(signal[m], RooFit.Rename(signal[m].GetName()))
        getattr(w, "import")(signalNorm[m],
                             RooFit.Rename(signalNorm[m].GetName()))
        getattr(w, "import")(signalXS[m], RooFit.Rename(signalXS[m].GetName()))
    w.writeToFile(WORKDIR + "MC_signal_%s_%s.root" % (YEAR, category), True)
    print "Workspace", WORKDIR + "MC_signal_%s_%s.root" % (
        YEAR, category), "saved successfully"
Ejemplo n.º 23
0
def signal(channel, stype):
    if 'VBF' in channel:
        stype = 'XZHVBF'
    else:
        stype = 'XZH'
    # HVT model
    if stype.startswith('X'):
        signalType = 'HVT'
        genPoints = [800, 1000, 1200, 1400, 1600, 1800, 2000, 2500, 3000, 3500, 4000, 4500, 5000]
        massPoints = [x for x in range(800, 5000+1, 100)]
        interPar = True
    else:
        print "Signal type", stype, "not recognized"
        return
    
    n = len(genPoints)  
    
    category = channel
    cColor = color[category] if category in color else 1

    nElec = channel.count('e')
    nMuon = channel.count('m')
    nLept = nElec + nMuon
    nBtag = channel.count('b')
    if '0b' in channel:
        nBtag = 0

    X_name = "VH_mass"

    if not os.path.exists(PLOTDIR+stype+category): os.makedirs(PLOTDIR+stype+category)

    #*******************************************************#
    #                                                       #
    #              Variables and selections                 #
    #                                                       #
    #*******************************************************#
    X_mass = RooRealVar(  "X_mass",    "m_{ZH}",       XBINMIN, XBINMAX, "GeV")
    J_mass = RooRealVar(  "H_mass",   "jet mass",        LOWMIN, HIGMAX, "GeV")
    V_mass = RooRealVar(  "V_mass", "V jet mass",           -9.,  1.e6, "GeV")
    CSV1    = RooRealVar( "H_csv1",           "",         -999.,     2.     )
    CSV2    = RooRealVar( "H_csv2",           "",         -999.,     2.     )
    DeepCSV1= RooRealVar( "H_deepcsv1",       "",         -999.,     2.     )
    DeepCSV2= RooRealVar( "H_deepcsv2",       "",         -999.,     2.     )
    H_ntag  = RooRealVar( "H_ntag",           "",           -9.,     9.     )
    H_dbt   = RooRealVar( "H_dbt",            "",           -2.,     2.     )
    H_tau21 = RooRealVar( "H_tau21",          "",           -9.,     2.     )
    H_eta = RooRealVar( "H_eta",              "",           -9.,     9.     )
    H_tau21_ddt = RooRealVar( "H_ddt",  "",           -9.,     2.     )
    MaxBTag = RooRealVar( "MaxBTag",          "",          -10.,     2.     )
    H_chf   = RooRealVar( "H_chf",            "",           -1.,     2.     )
    MinDPhi = RooRealVar( "MinDPhi",          "",           -1.,    99.     )
    DPhi    = RooRealVar( "DPhi",             "",           -1.,    99.     )
    DEta    = RooRealVar( "DEta",             "",           -1.,    99.     )
    Mu1_relIso = RooRealVar( "Mu1_relIso",    "",           -1.,    99.     )
    Mu2_relIso = RooRealVar( "Mu2_relIso",    "",           -1.,    99.     )
    nTaus   = RooRealVar( "nTaus",            "",           -1.,    99.     )
    Vpt     = RooRealVar( "V.Pt()",           "",           -1.,   1.e6     )
    V_pt     = RooRealVar( "V_pt",            "",           -1.,   1.e6     )
    H_pt     = RooRealVar( "H_pt",            "",           -1.,   1.e6     )
    VH_deltaR=RooRealVar( "VH_deltaR",        "",           -1.,    99.     )
    isZtoNN = RooRealVar( "isZtoNN",          "",            0.,     2.     )
    isZtoEE = RooRealVar( "isZtoEE",          "",            0.,     2.     )
    isZtoMM = RooRealVar( "isZtoMM",          "",            0.,     2.     )
    isHtobb = RooRealVar( "isHtobb",          "",            0.,     2.     )
    isVBF   = RooRealVar( "isVBF",            "",            0.,     2.     )
    isMaxBTag_loose = RooRealVar( "isMaxBTag_loose", "",     0.,     2.     )
    weight  = RooRealVar( "eventWeightLumi",  "",         -1.e9,   1.e9     )

    Xmin = XBINMIN
    Xmax = XBINMAX

    # Define the RooArgSet which will include all the variables defined before
    # there is a maximum of 9 variables in the declaration, so the others need to be added with 'add'
    variables = RooArgSet(X_mass, J_mass, V_mass, CSV1, CSV2, H_ntag, H_dbt, H_tau21)
    variables.add(RooArgSet(DEta, DPhi, MaxBTag, MinDPhi, nTaus, Vpt))
    variables.add(RooArgSet(DeepCSV1, DeepCSV2,VH_deltaR, H_tau21_ddt))
    variables.add(RooArgSet(isZtoNN, isZtoEE, isZtoMM, isHtobb, isMaxBTag_loose, weight))
    variables.add(RooArgSet(isVBF, Mu1_relIso, Mu2_relIso, H_chf, H_pt, V_pt,H_eta))
    #X_mass.setRange("X_extended_range", X_mass.getMin(), X_mass.getMax())
    X_mass.setRange("X_reasonable_range", X_mass.getMin(), X_mass.getMax())
    X_mass.setRange("X_integration_range", Xmin, Xmax)
    X_mass.setBins(int((X_mass.getMax() - X_mass.getMin())/100))
    binsXmass = RooBinning(int((X_mass.getMax() - X_mass.getMin())/100), X_mass.getMin(), X_mass.getMax())
    X_mass.setBinning(binsXmass, "PLOT")
    massArg = RooArgSet(X_mass)

    # Cuts
    SRcut = selection[category]+selection['SR']
    print "  Cut:\t", SRcut
    #*******************************************************#
    #                                                       #
    #                    Signal fits                        #
    #                                                       #
    #*******************************************************#

    treeSign = {}
    setSignal = {}

    vmean  = {}
    vsigma = {}
    valpha1 = {}
    vslope1 = {}
    smean  = {}
    ssigma = {}
    salpha1 = {}
    sslope1 = {}
    salpha2 = {}
    sslope2 = {}
    a1 = {}
    a2 = {}
    sbrwig = {}
    signal = {}
    signalExt = {}
    signalYield = {}
    signalIntegral = {}
    signalNorm = {}
    signalXS = {}
    frSignal = {}
    frSignal1 = {}
    frSignal2 = {}
    frSignal3 = {}

    # Signal shape uncertainties (common amongst all mass points)
    xmean_fit = RooRealVar("sig_p1_fit", "Variation of the resonance position with the fit uncertainty", 0.005, -1., 1.)
    smean_fit = RooRealVar("CMSRunII_sig_p1_fit", "Change of the resonance position with the fit uncertainty", 0., -10, 10)
    xmean_jes = RooRealVar("sig_p1_scale_jes", "Variation of the resonance position with the jet energy scale", 0.010, -1., 1.) #0.001
    smean_jes = RooRealVar("CMSRunII_sig_p1_jes", "Change of the resonance position with the jet energy scale", 0., -10, 10)
    xmean_e = RooRealVar("sig_p1_scale_e", "Variation of the resonance position with the electron energy scale", 0.001, -1., 1.)
    smean_e = RooRealVar("CMSRunII_sig_p1_scale_e", "Change of the resonance position with the electron energy scale", 0., -10, 10)
    xmean_m = RooRealVar("sig_p1_scale_m", "Variation of the resonance position with the muon energy scale", 0.001, -1., 1.)
    smean_m = RooRealVar("CMSRunII_sig_p1_scale_m", "Change of the resonance position with the muon energy scale", 0., -10, 10)

    xsigma_fit = RooRealVar("sig_p2_fit", "Variation of the resonance width with the fit uncertainty", 0.02, -1., 1.)
    ssigma_fit = RooRealVar("CMSRunII_sig_p2_fit", "Change of the resonance width with the fit uncertainty", 0., -10, 10)
    xsigma_jes = RooRealVar("sig_p2_scale_jes", "Variation of the resonance width with the jet energy scale", 0.010, -1., 1.) #0.001
    ssigma_jes = RooRealVar("CMSRunII_sig_p2_jes", "Change of the resonance width with the jet energy scale", 0., -10, 10)
    xsigma_jer = RooRealVar("sig_p2_scale_jer", "Variation of the resonance width with the jet energy resolution", 0.020, -1., 1.)
    ssigma_jer = RooRealVar("CMSRunII_sig_p2_jer", "Change of the resonance width with the jet energy resolution", 0., -10, 10)
    xsigma_e = RooRealVar("sig_p2_scale_e", "Variation of the resonance width with the electron energy scale", 0.001, -1., 1.)
    ssigma_e = RooRealVar("CMSRunII_sig_p2_scale_e", "Change of the resonance width with the electron energy scale", 0., -10, 10)
    xsigma_m = RooRealVar("sig_p2_scale_m", "Variation of the resonance width with the muon energy scale", 0.040, -1., 1.)
    ssigma_m = RooRealVar("CMSRunII_sig_p2_scale_m", "Change of the resonance width with the muon energy scale", 0., -10, 10)
    
    xalpha1_fit = RooRealVar("sig_p3_fit", "Variation of the resonance alpha with the fit uncertainty", 0.03, -1., 1.)
    salpha1_fit = RooRealVar("CMSRunII_sig_p3_fit", "Change of the resonance alpha with the fit uncertainty", 0., -10, 10)
    
    xslope1_fit = RooRealVar("sig_p4_fit", "Variation of the resonance slope with the fit uncertainty", 0.10, -1., 1.)
    sslope1_fit = RooRealVar("CMSRunII_sig_p4_fit", "Change of the resonance slope with the fit uncertainty", 0., -10, 10)

    xmean_fit.setConstant(True)
    smean_fit.setConstant(True)
    xmean_jes.setConstant(True)
    smean_jes.setConstant(True)
    xmean_e.setConstant(True)
    smean_e.setConstant(True)
    xmean_m.setConstant(True)
    smean_m.setConstant(True)
    
    xsigma_fit.setConstant(True)
    ssigma_fit.setConstant(True)
    xsigma_jes.setConstant(True)
    ssigma_jes.setConstant(True)
    xsigma_jer.setConstant(True)
    ssigma_jer.setConstant(True)
    xsigma_e.setConstant(True)
    ssigma_e.setConstant(True)
    xsigma_m.setConstant(True)
    ssigma_m.setConstant(True)
    
    xalpha1_fit.setConstant(True)
    salpha1_fit.setConstant(True)
    xslope1_fit.setConstant(True)
    sslope1_fit.setConstant(True)

    # the alpha method is now done.
    for m in massPoints:
        signalString = "M%d" % m
        signalMass = "%s_M%d" % (stype, m)
        signalName = "%s%s_M%d" % (stype, category, m)
        signalColor = sample[signalMass]['linecolor'] if signalName in sample else 1

        # define the signal PDF
        vmean[m] = RooRealVar(signalName + "_vmean", "Crystal Ball mean", m, m*0.5, m*1.25)
        smean[m] = RooFormulaVar(signalName + "_mean", "@0*(1+@1*@2)*(1+@3*@4)*(1+@5*@6)*(1+@7*@8)", RooArgList(vmean[m], xmean_e, smean_e, xmean_m, smean_m, xmean_jes, smean_jes, xmean_fit, smean_fit))

        vsigma[m] = RooRealVar(signalName + "_vsigma", "Crystal Ball sigma", m*0.035, m*0.01, m*0.4)
        sigmaList = RooArgList(vsigma[m], xsigma_e, ssigma_e, xsigma_m, ssigma_m, xsigma_jes, ssigma_jes, xsigma_jer, ssigma_jer)
        sigmaList.add(RooArgList(xsigma_fit, ssigma_fit))
        ssigma[m] = RooFormulaVar(signalName + "_sigma", "@0*(1+@1*@2)*(1+@3*@4)*(1+@5*@6)*(1+@7*@8)*(1+@9*@10)", sigmaList)
        
        valpha1[m] = RooRealVar(signalName + "_valpha1", "Crystal Ball alpha", 1.,  0., 5.) # number of sigmas where the exp is attached to the gaussian core. >0 left, <0 right
        salpha1[m] = RooFormulaVar(signalName + "_alpha1", "@0*(1+@1*@2)", RooArgList(valpha1[m], xalpha1_fit, salpha1_fit))

        vslope1[m] = RooRealVar(signalName + "_vslope1", "Crystal Ball slope", 10., 1., 60.) # slope of the power tail   #10 1 60
        sslope1[m] = RooFormulaVar(signalName + "_slope1", "@0*(1+@1*@2)", RooArgList(vslope1[m], xslope1_fit, sslope1_fit))

        salpha2[m] = RooRealVar(signalName + "_alpha2", "Crystal Ball alpha", 2,  1., 5.) # number of sigmas where the exp is attached to the gaussian core. >0 left, <0 right
        sslope2[m] = RooRealVar(signalName + "_slope2", "Crystal Ball slope", 10, 1.e-1, 115.) # slope of the power tail
        #define polynomial
        #a1[m] = RooRealVar(signalName + "_a1", "par 1 for polynomial", m, 0.5*m, 2*m)
        a1[m] = RooRealVar(signalName + "_a1", "par 1 for polynomial", 0.001*m, 0.0005*m, 0.01*m)
        a2[m] = RooRealVar(signalName + "_a2", "par 2 for polynomial", 0.05, -1.,1.)
        #if channel=='nnbbVBF' or channel=='nn0bVBF':
        #    signal[m] = RooPolynomial(signalName,"m_{%s'} = %d GeV" % (stype[1], m) , X_mass, RooArgList(a1[m],a2[m]))
        #else:
        #    signal[m] = RooCBShape(signalName, "m_{%s'} = %d GeV" % (stype[1], m), X_mass, smean[m], ssigma[m], salpha1[m], sslope1[m]) # Signal name does not have the channel
        signal[m] = RooCBShape(signalName, "m_{%s'} = %d GeV" % (stype[1], m), X_mass, smean[m], ssigma[m], salpha1[m], sslope1[m]) # Signal name does not have the channel
        # extend the PDF with the yield to perform an extended likelihood fit
        signalYield[m] = RooRealVar(signalName+"_yield", "signalYield", 100, 0., 1.e6)
        signalNorm[m] = RooRealVar(signalName+"_norm", "signalNorm", 1., 0., 1.e6)
        signalXS[m] = RooRealVar(signalName+"_xs", "signalXS", 1., 0., 1.e6)
        signalExt[m] = RooExtendPdf(signalName+"_ext", "extended p.d.f", signal[m], signalYield[m])
        
        vslope1[m].setMax(50.)
        vslope1[m].setVal(20.)
        #valpha1[m].setVal(1.0)
        #valpha1[m].setConstant(True)
        
        if 'bb' in channel and 'VBF' not in channel:
            if 'nn' in channel:
                valpha1[m].setVal(0.5)
        elif '0b' in channel and 'VBF' not in channel:
            if 'nn' in channel:
                if m==800:
                    valpha1[m].setVal(2.)
                    vsigma[m].setVal(m*0.04)
            elif 'ee' in channel:
                valpha1[m].setVal(0.8)
                if m==800:
                    #valpha1[m].setVal(1.2)
                    valpha1[m].setVal(2.5)
                    vslope1[m].setVal(50.)
            elif 'mm' in channel:
                if m==800:
                    valpha1[m].setVal(2.)
                    vsigma[m].setVal(m*0.03)
                else:
                    vmean[m].setVal(m*0.9)
                    vsigma[m].setVal(m*0.08)
        elif 'bb' in channel and 'VBF' in channel:
            if 'nn' in channel:
                if m!=1800:
                    vmean[m].setVal(m*0.8)
                vsigma[m].setVal(m*0.08)
                valpha1[m].setMin(1.)
            elif 'ee' in channel:
                valpha1[m].setVal(0.7)
            elif 'mm' in channel:
                if m==800:
                    vslope1[m].setVal(50.)
                valpha1[m].setVal(0.7)
        elif '0b' in channel and 'VBF' in channel:
            if 'nn' in channel:
                valpha1[m].setVal(3.) 
                vmean[m].setVal(m*0.8)
                vsigma[m].setVal(m*0.08)
                valpha1[m].setMin(1.)
            elif 'ee' in channel:
                if m<2500:
                    valpha1[m].setVal(2.)
                if m==800:
                    vsigma[m].setVal(m*0.05)
                elif m==1000:
                    vsigma[m].setVal(m*0.03)
                elif m>1000 and m<1800:
                    vsigma[m].setVal(m*0.04)
            elif 'mm' in channel:
                if m<2000:
                    valpha1[m].setVal(2.)
                if m==1000 or m==1800:
                    vsigma[m].setVal(m*0.03)
                elif m==1200 or m==1600:
                    vsigma[m].setVal(m*0.04)

            
        #if m < 1000: vsigma[m].setVal(m*0.06)

        # If it's not the proper channel, make it a gaussian
        #if nLept==0 and 'VBF' in channel:
        #    valpha1[m].setVal(5)
        #    valpha1[m].setConstant(True)
        #    vslope1[m].setConstant(True)
        #    salpha2[m].setConstant(True)
        #    sslope2[m].setConstant(True)

        
        # ---------- if there is no simulated signal, skip this mass point ----------
        if m in genPoints:
            if VERBOSE: print " - Mass point", m

            # define the dataset for the signal applying the SR cuts
            treeSign[m] = TChain("tree")
            for j, ss in enumerate(sample[signalMass]['files']):
                treeSign[m].Add(NTUPLEDIR + ss + ".root")
            
            if treeSign[m].GetEntries() <= 0.:
                if VERBOSE: print " - 0 events available for mass", m, "skipping mass point..."
                signalNorm[m].setVal(-1)
                vmean[m].setConstant(True)
                vsigma[m].setConstant(True)
                salpha1[m].setConstant(True)
                sslope1[m].setConstant(True)
                salpha2[m].setConstant(True)
                sslope2[m].setConstant(True)
                signalNorm[m].setConstant(True)
                signalXS[m].setConstant(True)
                continue
            
            setSignal[m] = RooDataSet("setSignal_"+signalName, "setSignal", variables, RooFit.Cut(SRcut), RooFit.WeightVar(weight), RooFit.Import(treeSign[m]))
            if VERBOSE: print " - Dataset with", setSignal[m].sumEntries(), "events loaded"
            
            # FIT
            signalYield[m].setVal(setSignal[m].sumEntries())
            
            if treeSign[m].GetEntries(SRcut) > 5:
                if VERBOSE: print " - Running fit"
 
                frSignal[m] = signalExt[m].fitTo(setSignal[m], RooFit.Save(1), RooFit.Extended(True), RooFit.SumW2Error(True), RooFit.PrintLevel(-1))
                if VERBOSE: print "********** Fit result [", m, "] **", category, "*"*40, "\n", frSignal[m].Print(), "\n", "*"*80
                if VERBOSE: frSignal[m].correlationMatrix().Print()
                drawPlot(signalMass, stype+channel, X_mass, signal[m], setSignal[m], frSignal[m])
            
            else:
                print "  WARNING: signal", stype, "and mass point", m, "in channel", channel, "has 0 entries or does not exist"          
            # Remove HVT cross section (which is the same for Zlep and Zinv)
            if stype == "XZHVBF":
                sample_name = 'Zprime_VBF_Zh_Zlephinc_narrow_M-%d' % m
            else:
                sample_name = 'ZprimeToZHToZlepHinc_narrow_M%d' % m

            xs = xsection[sample_name]['xsec']
            
            signalXS[m].setVal(xs * 1000.)
            
            signalIntegral[m] = signalExt[m].createIntegral(massArg, RooFit.NormSet(massArg), RooFit.Range("X_integration_range"))
            boundaryFactor = signalIntegral[m].getVal()
            if VERBOSE: 
                print " - Fit normalization vs integral:", signalYield[m].getVal(), "/", boundaryFactor, "events"
            if channel=='nnbb' and m==5000:
                signalNorm[m].setVal(2.5)
            elif channel=='nn0b' and m==5000:
                signalNorm[m].setVal(6.7)
            else:
                signalNorm[m].setVal( boundaryFactor * signalYield[m].getVal() / signalXS[m].getVal()) # here normalize to sigma(X) x Br(X->VH) = 1 [fb]
            
            
        a1[m].setConstant(True)
        a2[m].setConstant(True)
        vmean[m].setConstant(True)
        vsigma[m].setConstant(True)
        valpha1[m].setConstant(True)
        vslope1[m].setConstant(True)
        salpha2[m].setConstant(True)
        sslope2[m].setConstant(True)
        signalNorm[m].setConstant(True)
        signalXS[m].setConstant(True)

    #*******************************************************#
    #                                                       #
    #                 Signal interpolation                  #
    #                                                       #
    #*******************************************************#


    # ====== CONTROL PLOT ======
    c_signal = TCanvas("c_signal", "c_signal", 800, 600)
    c_signal.cd()
    frame_signal = X_mass.frame()
    for m in genPoints[:-2]:
        if m in signalExt.keys():
            signal[m].plotOn(frame_signal, RooFit.LineColor(sample["%s_M%d" % (stype, m)]['linecolor']), RooFit.Normalization(signalNorm[m].getVal(), RooAbsReal.NumEvent), RooFit.Range("X_reasonable_range"))
    frame_signal.GetXaxis().SetRangeUser(0, 6500)
    frame_signal.Draw()
    drawCMS(-1, YEAR, "Simulation")
    drawAnalysis(channel)
    drawRegion(channel)
    c_signal.SaveAs(PLOTDIR+"/"+stype+category+"/"+stype+"_Signal.pdf")
    c_signal.SaveAs(PLOTDIR+"/"+stype+category+"/"+stype+"_Signal.png")
    #if VERBOSE: raw_input("Press Enter to continue...")
    # ====== CONTROL PLOT ======

    # Normalization
    gnorm = TGraphErrors()
    gnorm.SetTitle(";m_{X} (GeV);integral (GeV)")
    gnorm.SetMarkerStyle(20)
    gnorm.SetMarkerColor(1)
    gnorm.SetMaximum(0)
    inorm = TGraphErrors()
    inorm.SetMarkerStyle(24)
    fnorm = TF1("fnorm", "pol9", 800, 5000) #"pol5" if not channel=="XZHnnbb" else "pol6" #pol5*TMath::Floor(x-1800) + ([5]*x + [6]*x*x)*(1-TMath::Floor(x-1800))
    fnorm.SetLineColor(920)
    fnorm.SetLineStyle(7)
    fnorm.SetFillColor(2)
    fnorm.SetLineColor(cColor)

    # Mean
    gmean = TGraphErrors()
    gmean.SetTitle(";m_{X} (GeV);gaussian mean (GeV)")
    gmean.SetMarkerStyle(20)
    gmean.SetMarkerColor(cColor)
    gmean.SetLineColor(cColor)
    imean = TGraphErrors()
    imean.SetMarkerStyle(24)
    fmean = TF1("fmean", "pol1", 0, 5000)
    fmean.SetLineColor(2)
    fmean.SetFillColor(2)

    # Width
    gsigma = TGraphErrors()
    gsigma.SetTitle(";m_{X} (GeV);gaussian width (GeV)")
    gsigma.SetMarkerStyle(20)
    gsigma.SetMarkerColor(cColor)
    gsigma.SetLineColor(cColor)
    isigma = TGraphErrors()
    isigma.SetMarkerStyle(24)
    fsigma = TF1("fsigma", "pol1", 0, 5000)
    fsigma.SetLineColor(2)
    fsigma.SetFillColor(2)

    # Alpha1
    galpha1 = TGraphErrors()
    galpha1.SetTitle(";m_{X} (GeV);crystal ball lower alpha")
    galpha1.SetMarkerStyle(20)
    galpha1.SetMarkerColor(cColor)
    galpha1.SetLineColor(cColor)
    ialpha1 = TGraphErrors()
    ialpha1.SetMarkerStyle(24)
    falpha1 = TF1("falpha", "pol0", 0, 5000)
    falpha1.SetLineColor(2)
    falpha1.SetFillColor(2)

    # Slope1
    gslope1 = TGraphErrors()
    gslope1.SetTitle(";m_{X} (GeV);exponential lower slope (1/Gev)")
    gslope1.SetMarkerStyle(20)
    gslope1.SetMarkerColor(cColor)
    gslope1.SetLineColor(cColor)
    islope1 = TGraphErrors()
    islope1.SetMarkerStyle(24)
    fslope1 = TF1("fslope", "pol0", 0, 5000)
    fslope1.SetLineColor(2)
    fslope1.SetFillColor(2)

    # Alpha2
    galpha2 = TGraphErrors()
    galpha2.SetTitle(";m_{X} (GeV);crystal ball upper alpha")
    galpha2.SetMarkerStyle(20)
    galpha2.SetMarkerColor(cColor)
    galpha2.SetLineColor(cColor)
    ialpha2 = TGraphErrors()
    ialpha2.SetMarkerStyle(24)
    falpha2 = TF1("falpha", "pol0", 0, 5000)
    falpha2.SetLineColor(2)
    falpha2.SetFillColor(2)

    # Slope2
    gslope2 = TGraphErrors()
    gslope2.SetTitle(";m_{X} (GeV);exponential upper slope (1/Gev)")
    gslope2.SetMarkerStyle(20)
    gslope2.SetMarkerColor(cColor)
    gslope2.SetLineColor(cColor)
    islope2 = TGraphErrors()
    islope2.SetMarkerStyle(24)
    fslope2 = TF1("fslope", "pol0", 0, 5000)
    fslope2.SetLineColor(2)
    fslope2.SetFillColor(2)



    n = 0
    for i, m in enumerate(genPoints):
        if not m in signalNorm.keys(): continue
        if signalNorm[m].getVal() < 1.e-6: continue
        signalString = "M%d" % m
        signalName = "%s_M%d" % (stype, m)

        if gnorm.GetMaximum() < signalNorm[m].getVal(): gnorm.SetMaximum(signalNorm[m].getVal())
        gnorm.SetPoint(n, m, signalNorm[m].getVal())
        gmean.SetPoint(n, m, vmean[m].getVal())
        gmean.SetPointError(n, 0, min(vmean[m].getError(), vmean[m].getVal()*0.02))
        gsigma.SetPoint(n, m, vsigma[m].getVal())
        gsigma.SetPointError(n, 0, min(vsigma[m].getError(), vsigma[m].getVal()*0.05))
        galpha1.SetPoint(n, m, valpha1[m].getVal())
        galpha1.SetPointError(n, 0, min(valpha1[m].getError(), valpha1[m].getVal()*0.10))
        gslope1.SetPoint(n, m, vslope1[m].getVal())
        gslope1.SetPointError(n, 0, min(vslope1[m].getError(), vslope1[m].getVal()*0.10))
        galpha2.SetPoint(n, m, salpha2[m].getVal())
        galpha2.SetPointError(n, 0, min(salpha2[m].getError(), salpha2[m].getVal()*0.10))
        gslope2.SetPoint(n, m, sslope2[m].getVal())
        gslope2.SetPointError(n, 0, min(sslope2[m].getError(), sslope2[m].getVal()*0.10))
        n = n + 1
    print "fit on gmean:"
    gmean.Fit(fmean, "Q0", "SAME")
    print "fit on gsigma:"
    gsigma.Fit(fsigma, "Q0", "SAME")
    print "fit on galpha:"
    galpha1.Fit(falpha1, "Q0", "SAME")
    print "fit on gslope:"
    gslope1.Fit(fslope1, "Q0", "SAME")
    galpha2.Fit(falpha2, "Q0", "SAME")
    gslope2.Fit(fslope2, "Q0", "SAME")
    #for m in [5000, 5500]: gnorm.SetPoint(gnorm.GetN(), m, gnorm.Eval(m, 0, "S"))
    gnorm.Fit(fnorm, "Q", "SAME", 700, 5000)

    for m in massPoints:
        signalName = "%s_M%d" % (stype, m)
        
        if vsigma[m].getVal() < 10.: vsigma[m].setVal(10.)

        # Interpolation method
        syield = gnorm.Eval(m)
        spline = gnorm.Eval(m, 0, "S")
        sfunct = fnorm.Eval(m)
        
        #delta = min(abs(1.-spline/sfunct), abs(1.-spline/syield))
        delta = abs(1.-spline/sfunct) if sfunct > 0 else 0
        syield = spline
               
        if interPar:
            jmean = gmean.Eval(m)
            jsigma = gsigma.Eval(m)
            jalpha1 = galpha1.Eval(m)
            jslope1 = gslope1.Eval(m)
        else:
            jmean = fmean.GetParameter(0) + fmean.GetParameter(1)*m + fmean.GetParameter(2)*m*m
            jsigma = fsigma.GetParameter(0) + fsigma.GetParameter(1)*m + fsigma.GetParameter(2)*m*m
            jalpha1 = falpha1.GetParameter(0) + falpha1.GetParameter(1)*m + falpha1.GetParameter(2)*m*m
            jslope1 = fslope1.GetParameter(0) + fslope1.GetParameter(1)*m + fslope1.GetParameter(2)*m*m

        inorm.SetPoint(inorm.GetN(), m, syield)
        signalNorm[m].setVal(syield)

        imean.SetPoint(imean.GetN(), m, jmean)
        if jmean > 0: vmean[m].setVal(jmean)

        isigma.SetPoint(isigma.GetN(), m, jsigma)
        if jsigma > 0: vsigma[m].setVal(jsigma)

        ialpha1.SetPoint(ialpha1.GetN(), m, jalpha1)
        if not jalpha1==0: valpha1[m].setVal(jalpha1)

        islope1.SetPoint(islope1.GetN(), m, jslope1)
        if jslope1 > 0: vslope1[m].setVal(jslope1)
    

    c1 = TCanvas("c1", "Crystal Ball", 1200, 800)
    c1.Divide(2, 2)
    c1.cd(1)
    gmean.SetMinimum(0.)
    gmean.Draw("APL")
    imean.Draw("P, SAME")
    drawRegion(channel)
    c1.cd(2)
    gsigma.SetMinimum(0.)
    gsigma.Draw("APL")
    isigma.Draw("P, SAME")
    drawRegion(channel)
    c1.cd(3)
    galpha1.Draw("APL")
    ialpha1.Draw("P, SAME")
    drawRegion(channel)
    galpha1.GetYaxis().SetRangeUser(0., 5.)
    c1.cd(4)
    gslope1.Draw("APL")
    islope1.Draw("P, SAME")
    drawRegion(channel)
    gslope1.GetYaxis().SetRangeUser(0., 125.)
    if False:
        c1.cd(5)
        galpha2.Draw("APL")
        ialpha2.Draw("P, SAME")
        drawRegion(channel)
        c1.cd(6)
        gslope2.Draw("APL")
        islope2.Draw("P, SAME")
        drawRegion(channel)
        gslope2.GetYaxis().SetRangeUser(0., 10.)


    c1.Print(PLOTDIR+stype+category+"/"+stype+"_SignalShape.pdf")
    c1.Print(PLOTDIR+stype+category+"/"+stype+"_SignalShape.png")


    c2 = TCanvas("c2", "Signal Efficiency", 800, 600)
    c2.cd(1)
    gnorm.SetMarkerColor(cColor)
    gnorm.SetMarkerStyle(20)
    gnorm.SetLineColor(cColor)
    gnorm.SetLineWidth(2)
    gnorm.Draw("APL")
    inorm.Draw("P, SAME")
    gnorm.GetXaxis().SetRangeUser(genPoints[0]-100, genPoints[-1]+100)
    gnorm.GetYaxis().SetRangeUser(0., gnorm.GetMaximum()*1.25)
    drawCMS(-1,YEAR , "Simulation")
    drawAnalysis(channel)
    drawRegion(channel)
    c2.Print(PLOTDIR+stype+category+"/"+stype+"_SignalNorm.pdf")
    c2.Print(PLOTDIR+stype+category+"/"+stype+"_SignalNorm.png")





    #*******************************************************#
    #                                                       #
    #                   Generate workspace                  #
    #                                                       #
    #*******************************************************#

    # create workspace
    w = RooWorkspace("ZH_RunII", "workspace")
    for m in massPoints:
        getattr(w, "import")(signal[m], RooFit.Rename(signal[m].GetName()))
        getattr(w, "import")(signalNorm[m], RooFit.Rename(signalNorm[m].GetName()))
        getattr(w, "import")(signalXS[m], RooFit.Rename(signalXS[m].GetName()))
    w.writeToFile("%s%s.root" % (WORKDIR, stype+channel), True)
    print "Workspace", "%s%s.root" % (WORKDIR, stype+channel), "saved successfully"
    sys.exit()
def Model_Comparisons(Comb_Dict):

    label_size=22
    axis_size=34
    plot_power = False
    Colors = ["red","blue"]
    Markers = ["s","o"]
    fig = plt.figure(figsize=(8,8))

    fig.add_axes((0.1,0.3,0.88,0.6))
    for SYS,sys_col,marker in zip(reversed(Systems),reversed(Colors),reversed(Markers)):

        #Systematics
        Efficiency_Uncertainty = 0.056*Comb_Dict["%s_Combined_FF"%(SYS)]

        Eta_Cor = Eta_Correction #see default_value.py for value
        Eta_Cor_Uncertainty = Eta_Correction_Uncertainty*Comb_Dict["%s_Combined_FF"%(SYS)]
        if not(Apply_Eta_Correction and SYS=="p-Pb"):
            Eta_Cor_Uncertainty = 0  #2% otherwise

        FF_Central = Comb_Dict["%s_Combined_FF"%(SYS)] #Eta Correction is applied when creating Dictionary! 
        Sys_Uncertainty = np.sqrt(Efficiency_Uncertainty**2 + Comb_Dict["%s_purity_Uncertainty"%(SYS)]**2 + Eta_Cor_Uncertainty**2)
        
        if (SYS=="pp"):
            pp_sys_Error = Sys_Uncertainty
        elif (SYS=="p-Pb"):
            p_Pb_sys_Error=Sys_Uncertainty
        #Plots
        if (SYS=="pp"):
            leg_string = SYS
        if (SYS=="p-Pb"):
            leg_string = "p$-$Pb"
        plt.errorbar(zT_centers[:NzT-ZT_OFF_PLOT], Comb_Dict["%s_Combined_FF"%(SYS)][:NzT-ZT_OFF_PLOT],xerr=zT_widths[:NzT-ZT_OFF_PLOT]*0,
        yerr=Comb_Dict["%s_Combined_FF_Errors"%(SYS)][:NzT-ZT_OFF_PLOT],linewidth=1, fmt=marker,color=sys_col,capsize=0)#for lines

        plt.plot(zT_centers[:NzT-ZT_OFF_PLOT], Comb_Dict["%s_Combined_FF"%(SYS)][:NzT-ZT_OFF_PLOT],marker,linewidth=0,color=sys_col,
        label=leg_string)#for legend without lines

        if (SYS == "pp"):
            Sys_Plot_pp = plt.bar(zT_centers[:NzT-ZT_OFF_PLOT], Sys_Uncertainty[:NzT-ZT_OFF_PLOT]+Sys_Uncertainty[:NzT-ZT_OFF_PLOT],
            bottom=Comb_Dict["%s_Combined_FF"%(SYS)][:NzT-ZT_OFF_PLOT]-Sys_Uncertainty[:NzT-ZT_OFF_PLOT],width=zT_widths[:NzT-ZT_OFF_PLOT]*2, align='center',color=sys_col,alpha=0.3,edgecolor=sys_col)
        else:
            Sys_Plot_pp = plt.bar(zT_centers[:NzT-ZT_OFF_PLOT], Sys_Uncertainty[:NzT-ZT_OFF_PLOT]+Sys_Uncertainty[:NzT-ZT_OFF_PLOT],
            bottom=Comb_Dict["%s_Combined_FF"%(SYS)][:NzT-ZT_OFF_PLOT]-Sys_Uncertainty[:NzT-ZT_OFF_PLOT],width=zT_widths[:NzT-ZT_OFF_PLOT]*2,align='center',color=sys_col,fill=False,edgecolor="blue")

        if (plot_power):
            model,p,chi2dof = Fit_FF_PowerLaw(Comb_Dict,SYS)
            plt.plot(zT_centers[:NzT-ZT_OFF_PLOT], model, sys_col,label=r"%s $\alpha = %1.2f\pm 0.1 \chi^2 = %1.2f$"%(SYS,p,chi2dof))

    if (Use_MC):
        plt.plot(zT_centers[:NzT-ZT_OFF_PLOT],pythia_FF,'--',color="forestgreen",label="PYTHIA 8.2 Monash")
        plt.errorbar(zT_centers[:NzT-ZT_OFF_PLOT],pythia_FF,yerr=pythia_FF_Errors,fmt='--',color="forestgreen",capsize=0)


    plt.yscale('log')
    plt.ylabel(r"$\frac{1}{N_{\mathrm{\gamma}}}\frac{\mathrm{d}^3N}{\mathrm{d}z_{\mathrm{T}}\mathrm{d}|\Delta\varphi|\mathrm{d}\Delta\eta}$",fontsize=axis_size,y=0.76)
    plt.ylim(0.037,15)
    plt.yticks(fontsize=20)
    plt.xticks(fontsize=0)
    plt.xlim(0,0.65)
    plt.tick_params(which='both',direction='in',right=True,top=True,bottom=False,length=10)
    plt.tick_params(which='minor',length=5)

    #pp_sys_Error = (Comb_Dict["pp_Combined_FF"][:NzT-ZT_OFF_PLOT])*math.sqrt(Rel_pUncert["pp"]**2+0.056**2)
    #p_Pb_sys_Error = (Comb_Dict["p-Pb_Combined_FF"][:NzT-ZT_OFF_PLOT])*math.sqrt(Rel_pUncert["p-Pb"]**2+0.056**2+Eta_Cor**2)


    Chi2,NDF,Pval = Get_pp_pPb_List_Chi2(Comb_Dict["pp_Combined_FF"][:NzT-ZT_OFF_PLOT],
                                         Comb_Dict["pp_Combined_FF_Errors"][:NzT-ZT_OFF_PLOT],
                                         pp_sys_Error,
                                         Comb_Dict["p-Pb_Combined_FF"][:NzT-ZT_OFF_PLOT],
                                         Comb_Dict["p-Pb_Combined_FF_Errors"][:NzT-ZT_OFF_PLOT],
                                         p_Pb_sys_Error)

    leg = plt.legend(numpoints=1,frameon=True,edgecolor='white', framealpha=0.0, fontsize=label_size,handlelength=1,labelspacing=0.2,loc='lower left',bbox_to_anchor=(0.001, 0.05))


    plt.annotate(r"ALICE, $\sqrt{s_{\mathrm{_{NN}}}}=5.02$ TeV",xy=(0.115,0.008),xycoords='axes fraction', ha='left',va='bottom',fontsize=label_size)
    plt.annotate(r"%1.0f < $p_\mathrm{T}^{\gamma}$ < %1.0f GeV/$c$"%(pTbins[0],pTbins[N_pT_Bins]),xy=(0.97, 0.81), xycoords='axes fraction', ha='right', va='top', fontsize=label_size)
    plt.annotate(r"%1.1f < $p_\mathrm{T}^\mathrm{h}$ < %1.1f GeV/$c$"%(Min_Hadron_pT,Max_Hadron_pT),xy=(0.97, 0.89), xycoords='axes fraction', ha='right', va='top', fontsize=label_size)
    plt.annotate("$\chi^2/\mathrm{ndf}$ = %1.1f/%i, $p$ = %1.2f"%(Chi2*NDF,NDF,Pval), xy=(0.97, 0.97), xycoords='axes fraction', ha='right', va='top', fontsize=label_size)

    #RATIO SECOND Y_AXIS
    fig.add_axes((0.1,0.1,0.88,0.2))

    pPb_Combined = Comb_Dict["p-Pb_Combined_FF"]
    pPb_Combined_Errors = Comb_Dict["p-Pb_Combined_FF_Errors"]
    pPb_purity_Uncertainty = Comb_Dict["p-Pb_purity_Uncertainty"]

    pp_Combined = Comb_Dict["pp_Combined_FF"]
    pp_Combined_Errors = Comb_Dict["pp_Combined_FF_Errors"]
    pp_purity_Uncertainty = Comb_Dict["pp_purity_Uncertainty"]

    Ratio = pPb_Combined/pp_Combined
    Ratio_Error = np.sqrt((pPb_Combined_Errors/pPb_Combined)**2 + (pp_Combined_Errors/pp_Combined)**2)*Ratio
    Ratio_Plot = plt.errorbar(zT_centers[:NzT-ZT_OFF_PLOT], Ratio[:NzT-ZT_OFF_PLOT], yerr=Ratio_Error[:NzT-ZT_OFF_PLOT],xerr=zT_widths[:NzT-ZT_OFF_PLOT]*0, fmt='ko',capsize=0, ms=6,lw=1)

    Purity_Uncertainty = np.sqrt((pp_purity_Uncertainty/pp_Combined)**2 + (pPb_purity_Uncertainty/pPb_Combined)**2)*Ratio
    Efficiency_Uncertainty = np.ones(len(pPb_Combined))*0.056*math.sqrt(2)*Ratio
    Eta_Cor_Uncertainty = Eta_Correction_Uncertainty/Comb_Dict["p-Pb_Combined_FF"]*Ratio
    if (CorrectedP):
        Ratio_Systematic = np.sqrt(Purity_Uncertainty**2 + Efficiency_Uncertainty**2 + Eta_Cor_Uncertainty**2)

    Sys_Plot = plt.bar(zT_centers[:NzT-ZT_OFF_PLOT], Ratio_Systematic[:NzT-ZT_OFF_PLOT]+Ratio_Systematic[:NzT-ZT_OFF_PLOT],
            bottom=Ratio[:NzT-ZT_OFF_PLOT]-Ratio_Systematic[:NzT-ZT_OFF_PLOT], width=zT_widths[:NzT-ZT_OFF_PLOT]*2, align='center',color='black',alpha=0.25)

    ### ROOT LINEAR and CONSTANT FITS ### 
    Ratio_TGraph = TGraphErrors()
    for izt in range (len(Ratio)-ZT_OFF_PLOT):
        Ratio_TGraph.SetPoint(izt,zT_centers[izt],Ratio[izt])
        Ratio_TGraph.SetPointError(izt,0,Ratio_Error[izt])

    Ratio_TGraph.Fit("pol0","S")
    f = Ratio_TGraph.GetFunction("pol0")
    chi2_red  = f.GetChisquare()/f.GetNDF()
    pval = f.GetProb()
    p0 = f.GetParameter(0)
    p0e = f.GetParError(0)
    p0col = "grey"
    Show_Fits = True
    if (Show_Fits):
        sys_const = 0.19 #23% relative from purity + tracking
        plt.annotate("$c = {0:.2f} \pm {1:.2f} \pm {2:.2f}$".format(p0,p0e,sys_const), xy=(0.98, 0.9), xycoords='axes fraction', ha='right', va='top', color="black",fontsize=label_size,alpha=.9)
        plt.annotate(r"$p = %1.2f$"%(pval), xy=(0.98, 0.75), xycoords='axes fraction', ha='right', va='top', color="black",fontsize=label_size,alpha=.9)

        c_error = math.sqrt(p0e**2 + sys_const**2)
        plt.fill_between(np.arange(0,1.1,0.1), p0+c_error, p0-c_error,color=p0col,alpha=.3)

    ###LABELS/AXES###                                          
    plt.axhline(y=1, color='k', linestyle='--')

    #plt.xlabel("${z_\mathrm{T}} = p_\mathrm{T}^{\mathrm{h}}/p_\mathrm{T}^\gamma$",fontsize=axis_size-8,x=0.9)
    plt.xlabel(r"varphi = $\varphi$, phi = $\phi$",fontsize = 30)
    plt.ylabel(r"$\frac{\mathrm{p-Pb}}{\mathrm{pp}}$",fontsize=axis_size,y=0.5)
    plt.ylim((-0.0, 2.8))
    plt.xticks(fontsize=20)
    plt.yticks([0.5,1.0,1.5,2.0,2.5],fontsize=20)
    plt.xlim(0,0.65)
    plt.tick_params(which='both',direction='in',right=True,bottom=True,top=True,length=10)
    plt.tick_params(which='both',direction='in',top=True,length=5)

    plt.fill_between(QGP_zt,QGP_IpPb_LowAll,QGP_IpPb_HighAll,label="QGP Droplet",color='orange')
    plt.plot(CNM_zt,CNM_IpPb,color='red',label="CNM Model")

    plt.legend(loc='upper left')

    plt.savefig("pics/%s/%s/Model_Comparisons.pdf"%(Shower,description_string), bbox_inches = "tight")
    plt.show()
Ejemplo n.º 25
0
    if s.Get() and s.Get().IsValid() and s.Get().CovMatrixStatus() == 3:
        massArr.append(cleanhist.GetYaxis().GetBinCenter(iy))
        zeroArr.append(0)
        xintArr.append(s.Parameter(1))
        yintArr.append(s.Parameter(0))
        xintErrArr.append(s.ParError(1))
        yintErrArr.append(s.ParError(0))

xintgraph = TGraphErrors(len(massArr), massArr, xintArr, zeroArr, xintErrArr)
xintgraph.SetTitle("X-intercept;mass [GeV];D1")
xintgraph.SetName("xintgraph")
xintgraph.Write()
xintgraph.Draw("A*")
xintgraph.GetYaxis().SetRangeUser(0, 1000)
xintgraph.Fit("pol3")
c.Print(outfilename + ".pdf")

yintgraph = TGraphErrors(len(massArr), massArr, yintArr, zeroArr, yintErrArr)
yintgraph.Draw("A*")
yintgraph.GetYaxis().SetRangeUser(0.5, 1.5)
c.Print(outfilename + ".pdf")

#clean.Draw("D1>>cleanslice(10,0,500)",xfcut+" && mass>{0} && mass<{1}".format(5.0,5.2))
#cleanslice = gDirectory.Get("cleanslice")
#messyclean.Draw("D1>>messyslice(10,0,500)",xfcut+" && mass>{0} && mass<{1}".format(5.0,5.2))
#messyslice = gDirectory.Get("messyslice")

c.Print(outfilename + ".pdf]")
outfile.Close()
def Model_Ratio_Comparisons(Comb_Dict):

    label_size=24
    axis_size=34
    plot_power = False
    Colors = ["red","blue"]
    Markers = ["s","o"]
    fig = plt.figure(figsize=(8,8))
    fig.add_axes((0.1,0.3,0.88,0.6))
#    fig.add_axes((0.1,0.1,0.88,0.2))

    pPb_Combined = Comb_Dict["p-Pb_Combined_FF"]
    pPb_Combined_Errors = Comb_Dict["p-Pb_Combined_FF_Errors"]
    pPb_purity_Uncertainty = Comb_Dict["p-Pb_purity_Uncertainty"]

    pp_Combined = Comb_Dict["pp_Combined_FF"]
    pp_Combined_Errors = Comb_Dict["pp_Combined_FF_Errors"]
    pp_purity_Uncertainty = Comb_Dict["pp_purity_Uncertainty"]

    Ratio = pPb_Combined/pp_Combined
    Ratio_Error = np.sqrt((pPb_Combined_Errors/pPb_Combined)**2 + (pp_Combined_Errors/pp_Combined)**2)*Ratio
    Ratio_Plot = plt.errorbar(zT_centers[:NzT-ZT_OFF_PLOT], Ratio[:NzT-ZT_OFF_PLOT], yerr=Ratio_Error[:NzT-ZT_OFF_PLOT],xerr=zT_widths[:NzT-ZT_OFF_PLOT]*0, fmt='ko',capsize=0, ms=6,lw=1)
    Ratio_for_Legend = plt.plot(zT_centers[:NzT-ZT_OFF_PLOT], Ratio[:NzT-ZT_OFF_PLOT],'ko',label='Data')

    Purity_Uncertainty = np.sqrt((pp_purity_Uncertainty/pp_Combined)**2 + (pPb_purity_Uncertainty/pPb_Combined)**2)*Ratio
    Efficiency_Uncertainty = np.ones(len(pPb_Combined))*0.056*math.sqrt(2)*Ratio
    Eta_Cor_Uncertainty = Eta_Correction_Uncertainty/Comb_Dict["p-Pb_Combined_FF"]*Ratio
    if (CorrectedP):
        Ratio_Systematic = np.sqrt(Purity_Uncertainty**2 + Efficiency_Uncertainty**2 + Eta_Cor_Uncertainty**2)

    Sys_Plot = plt.bar(zT_centers[:NzT-ZT_OFF_PLOT], Ratio_Systematic[:NzT-ZT_OFF_PLOT]+Ratio_Systematic[:NzT-ZT_OFF_PLOT],
            bottom=Ratio[:NzT-ZT_OFF_PLOT]-Ratio_Systematic[:NzT-ZT_OFF_PLOT], width=zT_widths[:NzT-ZT_OFF_PLOT]*2, align='center',color='black',alpha=0.25)

    ### ROOT LINEAR and CONSTANT FITS ###                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                              
    Ratio_TGraph = TGraphErrors()
    for izt in range (len(Ratio)-ZT_OFF_PLOT):
        Ratio_TGraph.SetPoint(izt,zT_centers[izt],Ratio[izt])
        Ratio_TGraph.SetPointError(izt,0,Ratio_Error[izt])

    Ratio_TGraph.Fit("pol0","S")
    f = Ratio_TGraph.GetFunction("pol0")
    chi2_red  = f.GetChisquare()/f.GetNDF()
    pval = f.GetProb()
    p0 = f.GetParameter(0)
    p0e = f.GetParError(0)
    p0col = "grey"
    Show_Fits = True
    if (Show_Fits):
        sys_const = 0.19 #23% relative from purity + tracking                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                          
        plt.annotate("$c = {0:.2f} \pm {1:.2f} \pm {2:.2f}$".format(p0,p0e,sys_const), xy=(0.02, 0.15), xycoords='axes fraction', ha='left', va='top', color="black",fontsize=label_size,alpha=.9)
        plt.annotate(r"$p = %1.2f$"%(pval), xy=(0.02, 0.09), xycoords='axes fraction', ha='left', va='top', color="black",fontsize=label_size,alpha=.9)

        c_error = math.sqrt(p0e**2 + sys_const**2)
        plt.fill_between(np.arange(0,1.1,0.1), p0+c_error, p0-c_error,color=p0col,alpha=.3)

    ###LABELS/AXES###                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                  
    plt.axhline(y=1, color='k', linestyle='--')

    plt.xlabel("${z_\mathrm{T}} = p_\mathrm{T}^{\mathrm{h}}/p_\mathrm{T}^\gamma$",fontsize=axis_size-8,x=0.9)
    #plt.xlabel(r"varphi = $\varphi$, phi = $\phi$",fontsize = 30)
    plt.ylabel(r"$\frac{\mathrm{p-Pb}}{\mathrm{pp}}$",fontsize=axis_size,y=0.88)
    plt.ylim((-0.0, 2.8))
    plt.xticks(fontsize=20)
    plt.yticks([0.5,1.0,1.5,2.0,2.5],fontsize=20)
    plt.yticks(np.arange(0,3,0.25),["","","0.5","","1.0","","1.5","","2.0","","2.5"])


    #Ratio_Plot.yaxis.set_minor_locator(AutoMinorLocator(1))
    plt.xlim(0,0.65)
    plt.tick_params(which='both',direction='in',right=True,bottom=True,top=True,length=10)
    plt.tick_params(which='both',direction='in',top=True,length=5)

    plt.fill_between(QGP_zt,QGP_IpPb_LowAll,QGP_IpPb_HighAll,label="QGP Droplet",color='orange')
    plt.plot(CNM_zt,CNM_IpPb,color='red',label="CNM Model",linewidth=2)

    leg = plt.legend(loc='upper right',fontsize=20,frameon=False)
    leg.set_title("ALICE, $\sqrt{s_{\mathrm{_{NN}}}} = $ 5.02 TeV")
    plt.setp(leg.get_title(),fontsize=24)
    plt.savefig("pics/%s/%s/Model_Comparisons_Ratio.pdf"%(Shower,description_string), bbox_inches = "tight")
    plt.show()
Ejemplo n.º 27
0
def draw():
    # N = 33
    N = 8
    ecms = array('f', N * [0])
    ecms_err = array('f', N * [0])
    factor = array('f', N * [0])
    factor_err = array('f', N * [0])
    path = './txts/sys_err_width_raw.txt'

    mbc = TCanvas('mbc', 'mbc', 800, 600)
    set_canvas_style(mbc)

    f = open(path, 'r')
    lines = f.readlines()
    count = 0
    sum_mean = 0
    sum_err = 0
    for line in lines:
        fargs = map(float, line.strip('\n').strip().split())
        ecms[count] = fargs[0]
        ecms_err[count] = 0.0022
        factor[count] = fargs[1]
        factor_err[count] = fargs[2]
        sum_mean += fargs[1]
        sum_err += fargs[2]
        count += 1

    grerr = TGraphErrors(N, ecms, factor, ecms_err, factor_err)
    xtitle = 'E_{cms} (GeV)'
    ytitle = 'f^{M(K^{-}#pi^{+}#pi^{+})}'
    set_graph_style(grerr, xtitle, ytitle)
    f = TF1('f', '[0]', ecms[0], ecms[1])
    grerr.Fit(f)
    chi2 = f.GetChisquare()
    ndf = f.GetNDF()
    F = f.GetParameter(0)
    F_err = f.GetParError(0)
    grerr.Draw('ap')

    pt = TPaveText(0.25, 0.65, 0.45, 0.85, "BRNDC")
    set_pavetext(pt)
    pt.Draw()
    line = 'f#pm#sigma_{f^{M(K^{-}#pi^{+}#pi^{+})}} = ' + str(round(
        F, 3)) + '#pm' + str(round(F_err, 3))
    pt.AddText(line)
    line = '#chi^{2}/ndf = ' + str(round(chi2, 3)) + '/' + str(round(
        ndf, 3)) + ' = ' + str(round(chi2 / ndf, 3))
    pt.AddText(line)
    line = '#Delta_{f^{M(K^{-}#pi^{+}#pi^{+})}}/#sigma_{f^{M(K^{-}#pi^{+}#pi^{+})}}=' + str(
        round((1 - F) / F_err, 3))
    pt.AddText(line)
    mbc.Update()

    if not os.path.exists('./figs/'):
        os.makedirs('./figs/')
    mbc.SaveAs('./figs/sys_err_width.pdf')

    if not os.path.exists('./txts/'):
        os.makedirs('./txts/')

    with open('./txts/f_m_Kpipi.txt', 'w') as f_out:
        f_out.write(str(F) + '\n')

    ecms = [
        4190, 4200, 4210, 4220, 4230, 4237, 4245, 4246, 4260, 4270, 4280, 4290,
        4310, 4315, 4340, 4360, 4380, 4390, 4400, 4420, 4440, 4470, 4530, 4575,
        4600, 4610, 4620, 4640, 4660, 4680, 4700, 4740, 4750, 4780, 4840, 4914,
        4946
    ]
    with open('./txts/sys_err_width.txt', 'w') as f_out:
        for ecm in ecms:
            out = str(ecm / 1000.) + '\t' + str(round(F_err * 100, 1)) + '\n'
            f_out.write(out)

    raw_input('Enter anything to end...')
def pp_pPB_Avg_Ratio(Comb_Dict,pT_Start):
    
    pPb_Combined = Comb_Dict["p-Pb_Combined_FF"]
    pPb_Combined_Errors = Comb_Dict["p-Pb_Combined_FF_Errors"]
    pPb_purity_Uncertainty = Comb_Dict["p-Pb_purity_Uncertainty"]
    
    pp_Combined = Comb_Dict["pp_Combined_FF"]
    pp_Combined_Errors = Comb_Dict["pp_Combined_FF_Errors"]
    pp_purity_Uncertainty = Comb_Dict["pp_purity_Uncertainty"]
    
    #Ratio
    Ratio = pPb_Combined/pp_Combined
    
    #Stat. Error in ratio
    Ratio_Error = np.sqrt((pPb_Combined_Errors/pPb_Combined)**2 + (pp_Combined_Errors/pp_Combined)**2)*Ratio
    
    #Save
    np.save("npy_files/%s_Averaged_FF_Ratio_%s.npy"%(Shower,description_string),Ratio)
    np.save("npy_files/%s_Averaged_FF_Ratio_Errors_%s.npy"%(Shower,description_string),Ratio_Error)
    
    #Sys. Error in ratio
    Purity_Uncertainty = np.sqrt((pp_purity_Uncertainty/pPb_Combined)**2 + (pPb_purity_Uncertainty/pPb_Combined)**2)*Ratio
    Efficiency_Uncertainty = np.ones(len(pPb_Combined))*0.056*math.sqrt(2)*Ratio 
    if (CorrectedP):
        Ratio_Systematic = np.sqrt(Purity_Uncertainty**2 + Efficiency_Uncertainty**2)

    plt.figure(figsize=(10,7)) 
    plt.tick_params(which='both',direction='in',right=True,bottom=True,top=True,length=10)

    #Sys_Plot = plt.bar(zT_centers[:NzT-ZT_OFF_PLOT], Ratio_Systematic[:NzT-ZT_OFF_PLOT]+Ratio_Systematic[:NzT-ZT_OFF_PLOT],
    #        bottom=Ratio[:NzT-ZT_OFF_PLOT]-Ratio_Systematic[:NzT-ZT_OFF_PLOT], width=zt_box[:NzT-ZT_OFF_PLOT], align='center',edgecolor="k",color='w')
            #bottom=Ratio[:NzT-ZT_OFF_PLOT]-Ratio_Systematic[:NzT-ZT_OFF_PLOT], width=zt_box[:NzT-ZT_OFF_PLOT], align='center',color='black',alpha=0.2)

    Sys_Plot = plt.bar(zT_centers[:NzT-ZT_OFF_PLOT], 2*Ratio_Systematic[:NzT-ZT_OFF_PLOT], 
       bottom=1.0-Ratio_Systematic[:NzT-ZT_OFF_PLOT], width=2*zT_widths[:NzT-ZT_OFF_PLOT], align='center',color='black',alpha = 0.2)
    
    empt4, = plt.plot([], [],' ')

    Ratio_Plot = plt.errorbar(zT_centers[:NzT-ZT_OFF_PLOT], Ratio[:NzT-ZT_OFF_PLOT], yerr=Ratio_Error[:NzT-ZT_OFF_PLOT],xerr=zT_widths[:NzT-ZT_OFF_PLOT], fmt='ko',capsize=3, ms=6,lw=1)

    plt.xlabel("${z_\mathrm{T}} = p_\mathrm{T}^{\mathrm{h}}/p_\mathrm{T}^\gamma$",fontsize=20)
    plt.ylabel(r"$\frac{\mathrm{p-Pb}}{\mathrm{pp}}$",fontsize=20)
    plt.ylim((-0.49, 2.9))
    #plt.yticks(np.arange(-0, 2, step=0.2))
    
    if(NzT == 6):
        plt.xlim(xmin = 0.0,xmax=0.7)
    elif(NzT==7):
        plt.xlim(xmin = 0.0,xmax=1.0)
    #plt.xlim(xmin = 0.0,xmax=zTbins[NzT-ZT_OFF_PLOT])
    plt.xlim(xmin = 0.0,xmax=0.67)
    plt.axhline(y=1, color='k', linestyle='--')

    ### ROOT LINEAR and CONSTANT FITS ###
    Ratio_TGraph = TGraphErrors()
    for izt in range (len(Ratio)-ZT_OFF_PLOT):
        Ratio_TGraph.SetPoint(izt,zT_centers[izt],Ratio[izt])
        Ratio_TGraph.SetPointError(izt,0,Ratio_Error[izt])

    Ratio_TGraph.Fit("pol0","S")
    f = Ratio_TGraph.GetFunction("pol0")
    chi2_red  = f.GetChisquare()/f.GetNDF()
    pval = f.GetProb()
    p0 = f.GetParameter(0)
    p0e = f.GetParError(0)
    p0col = "blue"
    if (Show_Fits):
        plt.annotate("Constant Fit", xy=(0.05, 0.99), xycoords='axes fraction', ha='left', va='top', color=p0col,fontsize=20,alpha=.7)
        plt.annotate(r"$p0 = {0:.2f} \pm {1:.2f}$".format(p0,p0e), xy=(0.05, 0.94), xycoords='axes fraction', ha='left', va='top', color=p0col,fontsize=18,alpha=.7)
        plt.annotate(r"$\chi^2_{red} = %1.2f$"%(chi2_red), xy=(0.05, 0.89), xycoords='axes fraction', ha='left', va='top', color=p0col,fontsize=18,alpha=.7)
        plt.annotate(r"$p_{val} = %1.2f$"%(pval), xy=(0.05, 0.84), xycoords='axes fraction', ha='left', va='top', color=p0col,fontsize=18,alpha=.7)

        plt.fill_between(np.arange(0,1.1,0.1), p0+p0e, p0-p0e,color=p0col,alpha=.2)

    
    
    Ratio_TGraph.Fit("pol1","S")
    #zT_Points = np.linspace(0.05,zTbins[NzT-1],20)
    zT_Points = np.linspace(0.0,1,20)
    
    Fit_Band = ROOT.TGraphErrors(len(zT_Points));
    for i in range(len(zT_Points)-ZT_OFF_PLOT):
        Fit_Band.SetPoint(i, zT_Points[i], 0)
    (ROOT.TVirtualFitter.GetFitter()).GetConfidenceIntervals(Fit_Band,0.68)
    
    band_errors = np.zeros(len(zT_Points))
    for i in range (len(zT_Points)):
        band_errors[i] = Fit_Band.GetErrorY(i)
    print(band_errors)


    f2 = Ratio_TGraph.GetFunction("pol1")
    chi2_red  = f2.GetChisquare()/f2.GetNDF()
    pval = f2.GetProb()
    p0 = f2.GetParameter(0)
    p0e = f2.GetParError(0)
    p1 = f2.GetParameter(1)
    p1e = f2.GetParError(1)
    print(p1e)
    p1col = "Green"
    if (Show_Fits):
        
        plt.annotate("Linear Fit", xy=(0.4, 0.99), xycoords='axes fraction', ha='left', va='top', color=p1col,fontsize=20,alpha=.7)
        plt.annotate(r"$p0 = %1.2f \pm %1.2f$"%(p0,p0e), xy=(0.4, 0.94), xycoords='axes fraction', ha='left', va='top', color=p1col,fontsize=18,alpha=.7)
        plt.annotate(r"$p1 = %1.2f \pm %1.2f$"%(p1,p1e), xy=(0.4, 0.89), xycoords='axes fraction', ha='left', va='top', color=p1col,fontsize=18,alpha=.7)
        plt.annotate(r"$\chi^2_{red} = %1.2f$"%(chi2_red), xy=(0.4, 0.84), xycoords='axes fraction', ha='left', va='top', color=p1col,fontsize=18,alpha=.7)
        plt.annotate(r"$p_{val} = %1.2f$"%(pval), xy=(0.4, 0.79), xycoords='axes fraction', ha='left', va='top', color=p1col,fontsize=18,alpha=.7)
        
        axes = plt.gca()
        x_vals = np.array(zT_Points)
        y_vals = p0 + p1 * zT_Points
        plt.plot(zT_Points, y_vals, '--',color=p1col,linewidth=2,alpha=0.5)
        plt.fill_between(zT_Points,y_vals+band_errors,y_vals-band_errors,color=p1col,alpha=0.2)

    ### ROOT DONE ###


    leg = plt.legend([Ratio_Plot,empt4],["Statistical Error",r'%1.0f < $p_\mathrm{T}^{\mathrm{trig}}$ < %1.0f GeV/$c$'%(pTbins[pT_Start],pTbins[N_pT_Bins])],frameon=False,numpoints=1,loc="lower left",title=' ',prop={'size':18})

    leg.set_title("ALICE Work in Progress\n  $\sqrt{s_{\mathrm{_{NN}}}} = $ 5 TeV")
    plt.setp(leg.get_title(),fontsize=20)

    plt.gcf()
    plt.savefig("pics/%s/%s/Ratio_Fits.pdf"%(Shower,description_string), bbox='tight')
    plt.show()

    print("                Central Values:")
    print(Ratio[:NzT-ZT_OFF_PLOT])

    print("\n                Satistical Uncertainty Absolute:")
    print(Ratio_Error[:NzT-ZT_OFF_PLOT])
    
    print("\n               Relative Satistical Uncertainty:")
    print(Ratio_Error[:NzT-ZT_OFF_PLOT]/Ratio[:NzT-ZT_OFF_PLOT])

    print("\n                Ratio Uncertainty from Purity:")
    print(Purity_Uncertainty[:NzT-ZT_OFF_PLOT])

    print("\n                Ratio Uncertainty from Single Track Efficiency:")
    print(Efficiency_Uncertainty[:NzT-ZT_OFF_PLOT])

    print("\n                Full Systematic Uncertainty:")

    print(Ratio_Systematic[:NzT-ZT_OFF_PLOT])
    
    print("\n                 Relative Full Systematic:")
    
    print(Ratio_Systematic[:NzT-ZT_OFF_PLOT]/Ratio[:NzT-ZT_OFF_PLOT])
    
    
    print("\n                LaTeX Table:")
    
    print("$\zt$ range & pp & p--Pb & p--Pb/pp \\\\")
    for izt in range (NzT):
        print("%1.2f - %1.2f & %1.3f $\pm$ %1.3f & %1.3f $\pm$ %1.3f & %1.3f $\pm$ %1.3f \\\\"
                      %(zTbins[izt], zTbins[izt+1], pp_Combined[izt], pp_Combined_Errors[izt], pPb_Combined[izt], pPb_Combined_Errors[izt], Ratio[izt], Ratio_Error[izt]))    
Ejemplo n.º 29
0
residuals = TCanvas('malus_res', "Residuals", 1200, 800)
residuals.Divide(2, 2)
for i, r in enumerate(res):
    residuals.cd(i + 1)
    r.res_graph.Draw('AEP')
    r.res_graph.SetMarkerStyle(6)
    residuals.Update()

n = 1
current = [0] * n + [1] * n + [2] * n + [3] * n
current = array('d', current)
for tuple in zip(current, phi, phi_err):
    print "%i %.1f \pm %.1f" % tuple

zeros = array('d', [0] * n * 4)
graph = TGraphErrors(n * 4, current, phi, zeros, phi_err)
canv = TCanvas('shift', 'shift')
graph.SetMarkerStyle(8)
func = TF1('pol1', 'pol1', 0, 4)
graph.Fit('pol1', 'V')
graph.Draw('AEP')

slope = func.GetParameter(1)
slope_err = func.GetParError(1)
verdet = -(slope * ls) / (mu0 * N * lv)
verdet_err = error(verdet, (slope, slope_err))
print 'Verdet = ', verdet, verdet_err
print 'Chi2 / NDF = ', func.GetChisquare(), func.GetNDF()
raw_input()
def Plot_pp_pPb_Avg_FF_and_Ratio(Comb_Dict):
    
    label_size=22
    axis_size=34
    plot_power = False
    Colors = ["red","blue"]
    Markers = ["s","o"]
    fig = plt.figure(figsize=(8,8))
    pp_sys_Error = 0
    p_Pb_sys_Error = 0
    fig.add_axes((0.1,0.3,0.88,0.6))
    for SYS,sys_col,marker in zip(reversed(Systems),reversed(Colors),reversed(Markers)):

        #Systematics
        Efficiency_Uncertainty = 0.056*Comb_Dict["%s_Combined_FF"%(SYS)]
        
        Eta_Cor = Eta_Correction #see default_value.py for value
        Eta_Cor_Uncertainty = Eta_Correction_Uncertainty*Comb_Dict["%s_Combined_FF"%(SYS)]
        if not(Apply_Eta_Correction and SYS=="p-Pb"):
            Eta_Cor_Uncertainty = 0  #2% otherwise
        
        FF_Central = Comb_Dict["%s_Combined_FF"%(SYS)] #Eta Correction is applied when creating Dictionary!
        Sys_Uncertainty = np.sqrt(Efficiency_Uncertainty**2 + Comb_Dict["%s_purity_Uncertainty"%(SYS)]**2 + Eta_Cor_Uncertainty**2)
        
        if (SYS=="pp"):
            pp_sys_Error = Sys_Uncertainty
        elif (SYS=="p-Pb"):
            p_Pb_sys_Error=Sys_Uncertainty
        #Plots
        if (SYS=="pp"):
            leg_string = SYS
        if (SYS=="p-Pb"):
            leg_string = "p$-$Pb"
        plt.errorbar(zT_centers[:NzT-ZT_OFF_PLOT], Comb_Dict["%s_Combined_FF"%(SYS)][:NzT-ZT_OFF_PLOT],xerr=zT_widths[:NzT-ZT_OFF_PLOT]*0,
        yerr=Comb_Dict["%s_Combined_FF_Errors"%(SYS)][:NzT-ZT_OFF_PLOT],linewidth=1, fmt=marker,color=sys_col,capsize=0)#for lines

        plt.plot(zT_centers[:NzT-ZT_OFF_PLOT], Comb_Dict["%s_Combined_FF"%(SYS)][:NzT-ZT_OFF_PLOT],marker,linewidth=0,color=sys_col,
        label=leg_string)#for legend without lines
        
        if (SYS == "pp"):
            Sys_Plot_pp = plt.bar(zT_centers[:NzT-ZT_OFF_PLOT], Sys_Uncertainty[:NzT-ZT_OFF_PLOT]+Sys_Uncertainty[:NzT-ZT_OFF_PLOT],
            bottom=Comb_Dict["%s_Combined_FF"%(SYS)][:NzT-ZT_OFF_PLOT]-Sys_Uncertainty[:NzT-ZT_OFF_PLOT],width=zT_widths[:NzT-ZT_OFF_PLOT]*2, align='center',color=sys_col,alpha=0.3,edgecolor=sys_col)
        else:
            Sys_Plot_pp = plt.bar(zT_centers[:NzT-ZT_OFF_PLOT], Sys_Uncertainty[:NzT-ZT_OFF_PLOT]+Sys_Uncertainty[:NzT-ZT_OFF_PLOT],
            bottom=Comb_Dict["%s_Combined_FF"%(SYS)][:NzT-ZT_OFF_PLOT]-Sys_Uncertainty[:NzT-ZT_OFF_PLOT],width=zT_widths[:NzT-ZT_OFF_PLOT]*2,align='center',color=sys_col,fill=False,edgecolor="blue")
        
        if (plot_power):
            model,p,chi2dof = Fit_FF_PowerLaw(Comb_Dict,SYS)
            plt.plot(zT_centers[:NzT-ZT_OFF_PLOT], model, sys_col,label=r"%s $\alpha = %1.2f\pm 0.1 \chi^2 = %1.2f$"%(SYS,p,chi2dof))
    
    if (Use_MC):
        plt.plot(zT_centers[:NzT-ZT_OFF_PLOT],pythia_FF,'--',color="forestgreen",label="PYTHIA 8.2 Monash")
        plt.errorbar(zT_centers[:NzT-ZT_OFF_PLOT],pythia_FF,yerr=pythia_FF_Errors,fmt='--',color="forestgreen",capsize=0) 
    
    
    plt.yscale('log')                             
    plt.ylabel(r"$\frac{1}{N_{\mathrm{\gamma}}}\frac{\mathrm{d}^3N}{\mathrm{d}z_{\mathrm{T}}\mathrm{d}|\Delta\varphi|\mathrm{d}\Delta\eta}$",fontsize=axis_size,y=0.76)
    plt.ylim(0.037,15)
    plt.yticks(fontsize=20)
    plt.xticks(fontsize=0)
    plt.xlim(0,0.65)
    plt.tick_params(which='both',direction='in',right=True,top=True,bottom=False,length=10)
    plt.tick_params(which='minor',length=5)

    #pp_sys_Error = (Comb_Dict["pp_Combined_FF"][:NzT-ZT_OFF_PLOT])*math.sqrt(Rel_pUncert["pp"]**2+0.056**2)
    #p_Pb_sys_Error = (Comb_Dict["p-Pb_Combined_FF"][:NzT-ZT_OFF_PLOT])*math.sqrt(Rel_pUncert["p-Pb"]**2+0.056**2+Eta_Cor**2)
    
    Chi2,NDF,Pval = Get_pp_pPb_List_Chi2(Comb_Dict["pp_Combined_FF"][:NzT-ZT_OFF_PLOT],
                                         Comb_Dict["pp_Combined_FF_Errors"][:NzT-ZT_OFF_PLOT],
                                         pp_sys_Error,
                                         Comb_Dict["p-Pb_Combined_FF"][:NzT-ZT_OFF_PLOT],
                                         Comb_Dict["p-Pb_Combined_FF_Errors"][:NzT-ZT_OFF_PLOT],
                                         p_Pb_sys_Error)

    leg = plt.legend(numpoints=1,frameon=True,edgecolor='white', framealpha=0.0, fontsize=label_size,handlelength=1,labelspacing=0.2,loc='lower left',bbox_to_anchor=(0.001, 0.05))


    plt.annotate(r"ALICE, $\sqrt{s_{\mathrm{_{NN}}}}=5.02$ TeV",xy=(0.115,0.008),xycoords='axes fraction', ha='left',va='bottom',fontsize=label_size)
    plt.annotate(r"%1.0f < $p_\mathrm{T}^{\gamma}$ < %1.0f GeV/$c$"%(pTbins[0],pTbins[N_pT_Bins]),xy=(0.97, 0.81), xycoords='axes fraction', ha='right', va='top', fontsize=label_size)
    plt.annotate(r"%1.1f < $p_\mathrm{T}^\mathrm{h}$ < %1.1f GeV/$c$"%(Min_Hadron_pT,Max_Hadron_pT),xy=(0.97, 0.89), xycoords='axes fraction', ha='right', va='top', fontsize=label_size)
    plt.annotate("$\chi^2/\mathrm{ndf}$ = %1.1f/%i, $p$ = %1.2f"%(Chi2*NDF,NDF,Pval), xy=(0.97, 0.97), xycoords='axes fraction', ha='right', va='top', fontsize=label_size)



#HEP FF
    Fig5 = Table("Figure 5 Top Panel")
    Fig5.description = "$\gamma^\mathrm{iso}$-tagged fragmentation function for pp (red) and p$-$Pb data (blue) at $\sqrt{s_\mathrm{NN}}$ = 5.02 TeV as measured by the ALICE detector. The boxes represent the systematic uncertainties while the vertical bars indicate the statistical uncertainties. The dashed green line corresponds to PYTHIA 8.2 Monash Tune. The $\chi^2$ test for the comparison of pp and p$-$Pb data incorporates correlations among different $z_\mathrm{T}$ intervals. A constant that was fit to the ratio is shown as grey band, with the width indicating the uncertainty on the fit."
    Fig5.location = "Data from Figure 5 Top Panel, Page 15"
    Fig5.keywords["observables"] = ["$\frac{1}{N_{\mathrm{\gamma}}}\frac{\mathrm{d}^3N}{\mathrm{d}z_{\mathrm{T}}\mathrm{d}\Delta\varphi\mathrm{d}\Delta\eta}$"]
    Fig5.add_image("./pics/LO/zT_Rebin_8_006zT06zT13fnew/Final_FFunction_and_Ratio.pdf")
    
    # x-axis: zT
    zt = Variable(r"$z_\mathrm{T}$", is_independent=True, is_binned=True, units="")
    zt.values = zT_edges
    Fig5.add_variable(zt)

    # y-axis: p-Pb Yields
    pPb_data = Variable("p$-$Pb conditional yield of associated hadrons", is_independent=False, is_binned=False, units="")
    pPb_data.values = Comb_Dict["p-Pb_Combined_FF"]
    
    pPb_sys = Uncertainty("p-Pb Systematic", is_symmetric=True)
    pPb_sys.values = p_Pb_sys_Error
    pPb_stat = Uncertainty("p-Pb Statistical", is_symmetric=True)
    pPb_stat.values = Comb_Dict["p-Pb_Combined_FF_Errors"]
    pPb_data.add_uncertainty(pPb_sys)
    pPb_data.add_uncertainty(pPb_stat)    

    # y-axis: pp Yields
    pp_data = Variable("pp conditional yield of associated hadrons", is_independent=False, is_binned=False, units="")
    pp_data.values = Comb_Dict["pp_Combined_FF"]
    
    pp_sys = Uncertainty("pp Systematic", is_symmetric=True)
    pp_sys.values = pp_sys_Error
    pp_stat = Uncertainty("pp Statistical", is_symmetric=True)
    pp_stat.values = Comb_Dict["pp_Combined_FF_Errors"]
    pp_data.add_uncertainty(pp_sys)
    pp_data.add_uncertainty(pp_stat)

    # y-axis: PYTHIA Yields
    pythia_data = Variable("PYTHIA conditional yield of associated hadrons", is_independent=False, is_binned=False, units="")
    pythia_data.values = pythia_FF
    
    pythia_stat = Uncertainty("PYTHIA Statistical", is_symmetric=True)
    pythia_stat.values = pythia_FF_Errors
    pythia_data.add_uncertainty(pythia_stat)

    #Add everything to the HEP Table
    Fig5.add_variable(pPb_data)
    Fig5.add_variable(pp_data)
    Fig5.add_variable(pythia_data)

    submission.add_table(Fig5)

    #RATIO SECOND Y_AXIS
    fig.add_axes((0.1,0.1,0.88,0.2))

    pPb_Combined = Comb_Dict["p-Pb_Combined_FF"]
    pPb_Combined_Errors = Comb_Dict["p-Pb_Combined_FF_Errors"]
    pPb_purity_Uncertainty = Comb_Dict["p-Pb_purity_Uncertainty"]
    
    pp_Combined = Comb_Dict["pp_Combined_FF"]
    pp_Combined_Errors = Comb_Dict["pp_Combined_FF_Errors"]
    pp_purity_Uncertainty = Comb_Dict["pp_purity_Uncertainty"]
    
    Ratio = pPb_Combined/pp_Combined
    Ratio_Error = np.sqrt((pPb_Combined_Errors/pPb_Combined)**2 + (pp_Combined_Errors/pp_Combined)**2)*Ratio
    Ratio_Plot = plt.errorbar(zT_centers[:NzT-ZT_OFF_PLOT], Ratio[:NzT-ZT_OFF_PLOT], yerr=Ratio_Error[:NzT-ZT_OFF_PLOT],xerr=zT_widths[:NzT-ZT_OFF_PLOT]*0, fmt='ko',capsize=0, ms=6,lw=1)
    
        #Save
    np.save("npy_files/%s_Averaged_FF_Ratio_%s.npy"%(Shower,description_string),Ratio)
    np.save("npy_files/%s_Averaged_FF_Ratio_Errors_%s.npy"%(Shower,description_string),Ratio_Error)
    
    Purity_Uncertainty = np.sqrt((pp_purity_Uncertainty/pp_Combined)**2 + (pPb_purity_Uncertainty/pPb_Combined)**2)*Ratio
    Efficiency_Uncertainty = np.ones(len(pPb_Combined))*0.056*math.sqrt(2)*Ratio 
    Eta_Cor_Uncertainty = Eta_Correction_Uncertainty/Comb_Dict["p-Pb_Combined_FF"]*Ratio
    if (CorrectedP):
        Ratio_Systematic = np.sqrt(Purity_Uncertainty**2 + Efficiency_Uncertainty**2 + Eta_Cor_Uncertainty**2)
        
    Sys_Plot = plt.bar(zT_centers[:NzT-ZT_OFF_PLOT], Ratio_Systematic[:NzT-ZT_OFF_PLOT]+Ratio_Systematic[:NzT-ZT_OFF_PLOT],
            bottom=Ratio[:NzT-ZT_OFF_PLOT]-Ratio_Systematic[:NzT-ZT_OFF_PLOT], width=zT_widths[:NzT-ZT_OFF_PLOT]*2, align='center',color='black',alpha=0.25)
    
    ### ROOT LINEAR and CONSTANT FITS ###
    Ratio_TGraph = TGraphErrors()
    for izt in range (len(Ratio)-ZT_OFF_PLOT):
        Ratio_TGraph.SetPoint(izt,zT_centers[izt],Ratio[izt])
        Ratio_TGraph.SetPointError(izt,0,Ratio_Error[izt])

    Ratio_TGraph.Fit("pol0","S")
    f = Ratio_TGraph.GetFunction("pol0")
    chi2_red  = f.GetChisquare()/f.GetNDF()
    pval = f.GetProb()
    p0 = f.GetParameter(0)
    p0e = f.GetParError(0)
    p0col = "grey"
    Show_Fits = True
    if (Show_Fits):
        sys_const = 0.19 #23% relative from purity + tracking
        #sys_const = 0.504245 #IRC
        plt.annotate("$c = {0:.2f} \pm {1:.2f} \pm {2:.2f}$".format(p0,p0e,sys_const), xy=(0.98, 0.9), xycoords='axes fraction', ha='right', va='top', color="black",fontsize=label_size,alpha=.9)
        plt.annotate(r"$p = %1.2f$"%(pval), xy=(0.98, 0.75), xycoords='axes fraction', ha='right', va='top', color="black",fontsize=label_size,alpha=.9)

        c_error = math.sqrt(p0e**2 + sys_const**2)
        plt.fill_between(np.arange(0,1.1,0.1), p0+c_error, p0-c_error,color=p0col,alpha=.3)
    
    ###LABELS/AXES###
    plt.axhline(y=1, color='k', linestyle='--')
    
    plt.xlabel("${z_\mathrm{T}} = p_\mathrm{T}^{\mathrm{h}}/p_\mathrm{T}^\gamma$",fontsize=axis_size-8,x=0.9)
    plt.ylabel(r"$\frac{\mathrm{p-Pb}}{\mathrm{pp}}$",fontsize=axis_size,y=0.5)
    plt.ylim((-0.0, 2.8))
    plt.xticks(fontsize=20)
    plt.yticks([0.5,1.0,1.5,2.0,2.5],fontsize=20)
    plt.xlim(0,0.65)
    plt.tick_params(which='both',direction='in',right=True,bottom=True,top=True,length=10)
    plt.tick_params(which='both',direction='in',top=True,length=5)

    plt.savefig("pics/%s/%s/Final_FFunction_and_Ratio.pdf"%(Shower,description_string), bbox_inches = "tight")
    plt.show()

#RATIO HEP
    FigRatio = Table("Figure 5 Bottom Panel")
    FigRatio.description = r"$\gamma^\mathrm{iso}$-tagged fragmentation function for pp (red) and p$-$Pb data (blue) at $\sqrt{s_\mathrm{NN}}$ = 5.02 TeV as measured by the ALICE detector. The boxes represent the systematic uncertainties while the vertical bars indicate the statistical uncertainties. The dashed green line corresponds to PYTHIA 8.2 Monash Tune. The $\chi^2$ test for the comparison of pp and p$-$Pb data incorporates correlations among different $z_\mathrm{T}$ intervals. A constant that was fit to the ratio is shown as grey band, with the width indicating the uncertainty on the fit."
    FigRatio.location = "Data from Figure 5, Bottom Panel, Page 15"
    FigRatio.keywords["observables"] = [r"$\frac{1}{N_{\mathrm{\gamma}}}\frac{\mathrm{d}^3N}{\mathrm{d}z_{\mathrm{T}}\mathrm{d}\Delta\varphi\mathrm{d}\Delta\eta}$"]
    FigRatio.add_image("./pics/LO/zT_Rebin_8_006zT06zT13fnew/Final_FFunction_and_Ratio.pdf")

    # x-axis: zT     
    zt_ratio = Variable(r"$z_\mathrm{T}$", is_independent=True, is_binned=True, units="")
    zt_ratio.values = zT_edges
    FigRatio.add_variable(zt_ratio)

    # y-axis: p-Pb Yields
    Ratio_HEP = Variable("Ratio conditional yield of associated hadrons in pp and p$-$Pb", is_independent=False, is_binned=False, units="")
    Ratio_HEP.values = Ratio
    Ratio_sys = Uncertainty("Ratio Systematic", is_symmetric=True)
    Ratio_sys.values = Ratio_Systematic
    Ratio_stat = Uncertainty("Ratio Statistical", is_symmetric=True)
    Ratio_stat.values = Ratio_Error
    Ratio_HEP.add_uncertainty(Ratio_stat)
    Ratio_HEP.add_uncertainty(Ratio_sys)
    FigRatio.add_variable(Ratio_HEP)
    submission.add_table(FigRatio)