def drawMassRes(data,mc,output,rapidity,ptda,ptmc,trackType,funct,mcIsData,dataIsMC,year):
	style = setTDRStyle()
	print (data)
	pt_e = [0 for x in range(len(data))]
	pt_x = [0 for x in range(len(data))]
	for i,pt in enumerate(pt_x):
		pt_x[i] = ptbins[i]+(ptbins[i+1]-ptbins[i])/2.
		pt_e[i] = (ptbins[i+1]-ptbins[i])/2.
	if dataIsMC:
		(da_mean,da_meane,da_sig,da_sige, da_nChi2) = doFit(data,output,rapidity,"MC2",trackType,funct)
	else:	
		(da_mean,da_meane,da_sig,da_sige, da_nChi2) = doFit(data,output,rapidity,"DATA",trackType,funct)
	if mcIsData:	
		(mc_mean,mc_meane,mc_sig,mc_sige, mc_nChi2) = doFit(mc  ,output,rapidity,"DATA2",trackType,funct)
	else:
		(mc_mean,mc_meane,mc_sig,mc_sige, mc_nChi2) = doFit(mc  ,output,rapidity,"MC",trackType,funct)
	result = {}
	result["data_mean"] = da_mean
	result["data_meane"] = da_meane
	result["data_sig"] = da_sig
	result["data_sige"] = da_sige
	result["mc_mean"] = mc_mean
	result["mc_meane"] = mc_meane
	result["mc_sig"] = mc_sig
	result["mc_sige"] = mc_sige
	result["ptda"] = ptda
	result["ptmc"] = ptmc
	result["da_nChi2"] = da_nChi2
	result["mc_nChi2"] = mc_nChi2



	pklFile = open(output+"/MassResolutionVsPt_%s_%s.pkl" %(trackType,rapidity),"wb")
	pickle.dump(result,pklFile)
	pklFile.close()
	
	
	c2 = TCanvas("c2","c2",800,800)
	c2.cd()

	# Upper plot will be in pad1
	pad1 = TPad("pad1", "pad1", 0.01, 0.01, 0.99, 0.99)
	# ~ pad1.SetGrid()        # Vertical grid
	pad1.SetTopMargin(0.05)
	pad1.SetLeftMargin(0.13)
	pad1.SetRightMargin(0.045)
	pad1.SetBottomMargin(0.3)
	pad1.Draw()             # Draw the upper pad: pad1
	pad1.cd()               # pad1 becomes the current pad
	pad1.SetTicks()
	
	res_data  = TGraphAsymmErrors()
	res_data.SetName("res_data")
	res_mc    = TGraphAsymmErrors()
	res_mc  .SetName("res_mc")
	ratio     = TGraphErrors()
	ratio   .SetName("ratio")
	#~ print len(pt_x)
	for i,pt in enumerate(pt_x):        
		res_data.SetPoint(i,ptda[i],da_sig[i])
		res_data.SetPointError(i,ptda[i]-ptbins[i],ptbins[i+1]-ptda[i],da_sige[i],da_sige[i])
		res_mc  .SetPoint(i,ptmc[i],mc_sig[i])
		res_mc  .SetPointError(i,ptmc[i]-ptbins[i],ptbins[i+1]-ptmc[i],mc_sige[i],mc_sige[i])
		if mc_sig[i] > 0:
			ratio   .SetPoint(i,pt,da_sig[i]/mc_sig[i])
			ratio   .SetPointError(i,pt_e[i],(da_sig[i]/mc_sig[i])*math.sqrt((da_sige[i]/da_sig[i])**2+(mc_sige[i]/mc_sig[i])**2))
	res_data.SetMarkerStyle(22)
	res_data.SetMarkerSize(2)
	res_data.SetMarkerColor(kBlack)
	res_data.SetLineColor(kBlack)
	res_data.SetLineWidth(2)
	res_data.SetFillColor(0)
	res_data.SetTitle("Dimuon mass resolution vs pT for %s tracks"%trackType)
	res_data.GetYaxis().SetTitle("Mass resolution at Z peak (GeV)")
	# ~ res_data.GetXaxis().SetTitle("p_{T} (#mu^{#pm}) [GeV]")
	res_data.GetYaxis().SetTitleFont(42)
	res_data.GetYaxis().SetTitleSize(0.05)
	res_data.GetYaxis().SetTitleOffset(1.35)
	res_data.GetYaxis().SetLabelFont(42)
	res_data.GetYaxis().SetLabelSize(0.038)
	res_data.GetYaxis().SetRangeUser(0.,6.)
	res_data.GetXaxis().SetTitleSize(0.0)
	res_data.GetXaxis().SetLabelSize(0.0)
	if trackType == "Outer":
		res_data.GetYaxis().SetRangeUser(1.,20.)
	res_data.GetXaxis().SetRangeUser(ptbins[0],ptbins[len(ptda)])
	res_data.Draw("AP E0")
	res_mc.SetMarkerStyle(22)
	res_mc.SetMarkerSize(2)
	res_mc.SetMarkerColor(kRed)
	res_mc.SetLineColor(kRed)
	res_mc.SetLineWidth(2)
	res_mc.SetFillColor(0)
	res_mc.SetTitle("Dimuon mass resolution vs pT for %s tracks"%trackType)
	res_mc.GetYaxis().SetTitle("Mass resolution at Z peak (GeV)")
	res_mc.GetXaxis().SetTitle("p_{T} (#mu^{#pm}) (GeV)")
	res_mc.GetYaxis().SetTitleOffset(1.5)
	res_mc.Draw("P E0 SAME")
	if rapidity == "BB": leg = TLegend(0.5,0.65,0.95,0.90,"Both muons |#eta| < 1.2","brNDC")
	elif rapidity == "BE": leg = TLegend(0.5,0.65,0.95,0.9,"At least one muon |#eta| > 1.2","brNDC")
	else: leg = TLegend(0.2,0.65,0.9,0.9,"At least one muon |#eta| > 1.6","brNDC")
	if mcIsData:
		leg.AddEntry(res_data,"DATA 2017")
		leg.AddEntry(res_mc,"DATA 2016")
	elif dataIsMC:
		leg.AddEntry(res_data,"MC 2017")
		leg.AddEntry(res_mc,"MC 2016")		
	else:
		leg.AddEntry(res_data,"Data","p")
		leg.AddEntry(res_mc,"Simulation")
	
	leg.SetTextFont(62)
	leg.SetFillColor(10)
	leg.SetFillStyle(0)
	leg.SetLineColor(10)
	leg.SetShadowColor(0)
	leg.SetBorderSize(0)	
	leg.SetMargin(0.15)	
	leg.Draw("SAME")
	latex = TLatex()
	# ~ latex.SetTextFont(42)
	# ~ latex.SetTextAlign(31)
	# ~ latex.SetTextSize(0.04)
	# ~ latex.SetNDC(True)
	# ~ latexCMS = TLatex()
	# ~ latexCMS.SetTextFont(62)
	# ~ latexCMS.SetTextSize(0.04)
	# ~ latexCMS.SetNDC(True)
	latexCMSExtra = TLatex()
	latexCMSExtra.SetTextFont(52)
	latexCMSExtra.SetTextSize(0.03/0.7)
	latexCMSExtra.SetNDC(True)
	
	# ~ if '2016' in year:
		# ~ latex.DrawLatex(0.95, 0.96, "2016, 36.3 fb^{-1} (13 TeV)")
	# ~ elif '2017' in year:	
		# ~ latex.DrawLatex(0.95, 0.96, "2017, 42.1 fb^{-1} (13 TeV)")
	# ~ else:	
		# ~ latex.DrawLatex(0.95, 0.96, "2018, 61.3 fb^{-1} (13 TeV)")
	if '2016' in year:
		latex.DrawLatexNDC(0.50, 0.96, "#scale[0.8]{#font[42]{       2016, 36.3 fb^{-1} (13 TeV)}}")
	elif '2017' in year:	
		latex.DrawLatexNDC(0.50, 0.96, "#scale[0.8]{#font[42]{       2017, 42.1 fb^{-1} (13 TeV)}}")
	else:	
		latex.DrawLatexNDC(0.50, 0.96, "#scale[0.8]{#font[42]{       2018, 61.3 fb^{-1} (13 TeV)}}")
	
	# ~ cmsExtra = "Preliminary" 
	# ~ latexCMS.DrawLatex(0.15,0.96,"CMS")
	latex.DrawLatexNDC(0.13, 0.96, "#font[62]{CMS}")
	# ~ yLabelPos = 0.84
	# ~ latexCMSExtra.DrawLatex(0.78,yLabelPos,"%s"%(cmsExtra))
	c2.cd()          # Go back to the main canvas before defining pad2
	pad2 = TPad("pad2", "pad2",0.01, 0.01, 0.99, 0.29)    
	pad2.SetTopMargin(0)
	pad2.SetTopMargin(0.05)
	pad2.SetLeftMargin(0.13)
	pad2.SetRightMargin(0.045)
	pad2.SetBottomMargin(0.4)
	# ~ pad2.SetGrid()
	pad2.Draw()
	pad2.cd()
	pad2.SetTicks()
	ratio.SetMarkerColor(kBlue-4)
	ratio.SetFillColor(kBlue-4 )
	ratio.SetTitle("")
	ratio.GetYaxis().SetTitle("Data/MC")
	ratio.GetXaxis().SetNoExponent(0)
	ratio.GetXaxis().SetTitleFont(42)
	ratio.GetXaxis().SetTitleOffset(0.85)
	ratio.GetXaxis().SetTitleSize(0.2)
	ratio.GetXaxis().SetLabelColor(1)
	ratio.GetXaxis().SetLabelOffset(0.01)
	ratio.GetXaxis().SetLabelFont(42)
	ratio.GetXaxis().SetLabelSize(0.17)		
	if mcIsData:
		ratio.GetYaxis().SetTitle("Data 2017 / Data 2016")
	elif dataIsMC:
		ratio.GetYaxis().SetTitle("MC 2017 / MC 2016")
	ratio.GetXaxis().SetTitle("p_{T} (\mu^{\pm}) (GeV)")
	ratio.GetYaxis().SetRangeUser(0.5,1.5)
	ratio.GetXaxis().SetRangeUser(ptbins[0],ptbins[len(ptda)])
	ratio.GetYaxis().SetTitleOffset(0.55)
	ratio.GetYaxis().SetTitleSize(0.12)
	ratio.GetYaxis().SetTitleFont(42)
	ratio.GetYaxis().SetLabelSize(0.14)    
	ratio.GetYaxis().SetLabelOffset(0.007)    
	ratio.GetYaxis().SetLabelFont(42)    
	ratio.GetYaxis().SetNdivisions(505)       
	ratio.Draw("A P E2")
	pad2.Update()

	line = TLine(ptbins[0],1,ptbins[len(ptda)],1)

	line.SetLineColor(kBlue+1)
	line.SetLineWidth(2)
	line.Draw()
	pad1.RedrawAxis()

	saveas = "/MassResolutionVsPt_%s_%s" %(trackType,rapidity)
	c2.SaveAs(output+saveas+".png")
	c2.SaveAs(output+saveas+".pdf")
	c2.SaveAs(output+saveas+".root")
	c2.SaveAs(output+saveas+".C")
예제 #2
0
    def cutvariation_makeplots(self, plotname, min_cv_cut, max_cv_cut):

        self.loadstyle2()

        leg = TLegend(.15, .65, .85, .85)
        leg.SetBorderSize(0)
        leg.SetFillColor(0)
        leg.SetFillStyle(0)
        leg.SetTextFont(42)
        leg.SetTextSize(0.024)
        leg.SetNColumns(4)
        colours = [kBlack, kRed, kGreen+2, kBlue, kOrange+2, kViolet-1, \
                   kAzure+1, kOrange-7, kViolet+2, kYellow-3]

        ntrials = 2 * self.p_ncutvar + 1
        for imult in range(len(self.lvar2_binmin)):

            canv = TCanvas("%s%d" % (plotname, imult), '', 400, 400)

            diffratio = 2 * self.p_maxperccutvar
            if plotname == "histoSigmaCorr":
                diffratio = 0.2
            canv.cd(1).DrawFrame(0, 1 - diffratio, 25, 1 + diffratio, \
                                 "%s %.2f < %s < %.2f;#it{p}_{T} (GeV/#it{c});Ratio %s" % \
                                 (self.typean, self.lvar2_binmin[imult], self.v_var2_binning, \
                                  self.lvar2_binmax[imult], plotname))

            fileoutcrossmultref = self.make_file_path(self.d_results_cv, self.cross_filename, \
                                                      "root", None, [self.typean, "cutvar", \
                                                                     str(self.p_ncutvar), \
                                                                     "mult", str(imult)])

            f_fileoutcrossmultref = TFile.Open(fileoutcrossmultref)
            href = f_fileoutcrossmultref.Get(plotname)
            imk = 0
            icol = 0
            legname = "looser"
            hcutvar = []

            markers = [20, 21, 22, 23]
            for icv in range(ntrials):
                if icv == self.p_ncutvar:
                    markers = [markers[i] + 4 for i in range(len(markers))]
                    imk = 0
                    legname = "tighter"
                    continue
                if icol == len(colours) - 1:
                    imk = imk + 1
                fileoutcrossmult = self.make_file_path(self.d_results_cv, self.cross_filename, \
                                                       "root", None, [self.typean, "cutvar", str(icv), \
                                                                      "mult", str(imult)])
                f_fileoutcrossmult = TFile.Open(fileoutcrossmult)
                hcutvar.append(f_fileoutcrossmult.Get(plotname))
                hcutvar[icol].SetDirectory(0)
                hcutvar[icol].SetLineColor(colours[icol % len(colours)])
                hcutvar[icol].SetMarkerColor(colours[icol % len(colours)])
                hcutvar[icol].SetMarkerStyle(markers[imk])
                hcutvar[icol].SetMarkerSize(0.8)
                hcutvar[icol].Divide(href)
                hcutvar[icol].Draw("same")
                if imult == 0:
                    leg.AddEntry(hcutvar[icol], "Set %d (%s)" % (icv, legname), "LEP")
                icol = icol + 1
                f_fileoutcrossmult.Close()
            leg.Draw()
            canv.SaveAs("%s/Cutvar_%s_mult%d.eps" % (self.d_results_cv, plotname, imult))
            f_fileoutcrossmultref.Close()

        if plotname == "histoSigmaCorr":
            if self.p_nptfinbins < 9:
                nx = 4
                ny = 2
                canvy = 533
            elif self.p_nptfinbins < 13:
                nx = 4
                ny = 3
                canvy = 800
            else:
                nx = 5
                ny = 4
                canvy = 1200

            canv = [TCanvas("canvas_corryieldvspt%d_%d" % (icv, imult), "Data", \
                             1000, canvy) for imult in range(len(self.lvar2_binmin))]
            arrhistos = [None for ipt in range(self.p_nptfinbins)]
            for imult in range(len(self.lvar2_binmin)):
                for ipt in range(self.p_nptfinbins):
                    arrhistos[ipt] = TH1F("hcorryieldvscut%d%d" % (imult, ipt), \
                                          "%d < #it{p}_{T} < %d;cut set;Corr. Yield" % \
                                          (self.lpt_finbinmin[ipt], self.lpt_finbinmax[ipt]),
                                          ntrials, -0.5, ntrials - 0.5)
                    arrhistos[ipt].SetDirectory(0)

                for icv in range(ntrials):
                    fileoutcrossmult = self.make_file_path(self.d_results_cv, \
                                                           self.cross_filename, "root", None, \
                                                           [self.typean, "cutvar", str(icv), \
                                                            "mult", str(imult)])
                    f_fileoutcrossmult = TFile.Open(fileoutcrossmult)
                    hcutvar2 = f_fileoutcrossmult.Get(plotname)
                    for ipt in range(self.p_nptfinbins):
                        arrhistos[ipt].SetBinContent(icv + 1, hcutvar2.GetBinContent(ipt + 1))
                        arrhistos[ipt].SetBinError(icv + 1, hcutvar2.GetBinError(ipt + 1))
                    f_fileoutcrossmult.Close()

                canv[imult].Divide(nx, ny)
                for ipt in range(self.p_nptfinbins):
                    canv[imult].cd(ipt + 1)
                    arrhistos[ipt].SetLineColor(colours[ipt])
                    arrhistos[ipt].SetMarkerColor(colours[ipt])
                    arrhistos[ipt].Draw("ep")
                canv[imult].SaveAs("%s/Cutvar_CorrYieldvsSet_mult%d.eps" % (self.d_results_cv, imult))

            if min_cv_cut is not None and max_cv_cut is not None:

                probcuts = [None for ipt in range(self.p_nptfinbins)]
                probarr = [None for icv in range(2 + 2 * ntrials)]
                for ipt in range(self.p_nptfinbins):
                    bin_id = self.bin_matching[ipt]
                    stepsmin = (self.lpt_probcutfin[bin_id] - min_cv_cut[ipt]) / self.p_ncutvar
                    stepsmax = (max_cv_cut[ipt] - self.lpt_probcutfin[bin_id]) / self.p_ncutvar

                    probarr[0] = 0
                    icvmax = 1
                    for icv in range(ntrials):
                        if icv < self.p_ncutvar:
                            probarr[2 * icv + 1] = min_cv_cut[ipt] + (icv - 0.1) * stepsmin
                            probarr[2 * icv + 2] = min_cv_cut[ipt] + (icv + 0.1) * stepsmin
                        elif icv == self.p_ncutvar:
                            probarr[2 * icv + 1] = self.lpt_probcutfin[bin_id] - 0.1 * stepsmax
                            probarr[2 * icv + 2] = self.lpt_probcutfin[bin_id] + 0.1 * stepsmax
                        else:
                            probarr[2 * icv + 1] = self.lpt_probcutfin[bin_id] + (icvmax - 0.1) * stepsmax
                            probarr[2 * icv + 2] = self.lpt_probcutfin[bin_id] + (icvmax + 0.1) * stepsmax
                            icvmax = icvmax + 1
                    probarr[-1] = 1
                    probcuts[ipt] = probarr[:]

                canv2 = [TCanvas("canvas_corryieldvsprob%d_%d" % (icv, imult), "Data", \
                                 1000, canvy) for imult in range(len(self.lvar2_binmin))]
                arrhistos2 = [None for ipt in range(self.p_nptfinbins)]
                for imult in range(len(self.lvar2_binmin)):
                    for ipt in range(self.p_nptfinbins):
                        arrhistos2[ipt] = TH1F("hcorryieldvsprob%d%d" % (imult, ipt), \
                                              "%d < #it{p}_{T} < %d;Probability;Corr. Yield" % \
                                              (self.lpt_finbinmin[ipt], self.lpt_finbinmax[ipt]), \
                                               len(probcuts[ipt]) - 1, array('f', probcuts[ipt]))
                        arrhistos2[ipt].SetDirectory(0)

                    icvmax = 1
                    for icv in range(ntrials):
                        fileoutcrossmult = self.make_file_path(self.d_results_cv, \
                                                             self.cross_filename, "root", None, \
                                                             [self.typean, "cutvar", str(icv), \
                                                              "mult", str(imult)])
                        f_fileoutcrossmult = TFile.Open(fileoutcrossmult)
                        hcutvar2 = f_fileoutcrossmult.Get(plotname)

                        for ipt in range(self.p_nptfinbins):
                            bin_id = self.bin_matching[ipt]
                            stepsmin = (self.lpt_probcutfin[bin_id] - min_cv_cut[ipt]) / self.p_ncutvar
                            stepsmax = (max_cv_cut[ipt] - self.lpt_probcutfin[bin_id]) / self.p_ncutvar
                            selml_cvval = 0
                            if icv < self.p_ncutvar:
                                selml_cvval = min_cv_cut[ipt] + icv * stepsmin
                            elif icv == self.p_ncutvar:
                                selml_cvval = self.lpt_probcutfin[bin_id]
                            else:
                                selml_cvval = self.lpt_probcutfin[bin_id] + icvmax * stepsmax
                            ibin = arrhistos2[ipt].FindBin(selml_cvval)
                            arrhistos2[ipt].SetBinContent(ibin, hcutvar2.GetBinContent(ipt + 1))
                            arrhistos2[ipt].SetBinError(ibin, hcutvar2.GetBinError(ipt + 1))
                        if icv > self.p_ncutvar:
                            icvmax = icvmax + 1
                        f_fileoutcrossmult.Close()

                    canv2[imult].Divide(nx, ny)
                    for ipt in range(self.p_nptfinbins):
                        canv2[imult].cd(ipt + 1)
                        arrhistos2[ipt].SetLineColor(colours[ipt])
                        arrhistos2[ipt].SetLineWidth(1)
                        arrhistos2[ipt].SetMarkerColor(colours[ipt])
                        arrhistos2[ipt].Draw("ep")
                    canv2[imult].SaveAs("%s/Cutvar_CorrYieldvsProb_mult%d.eps" % (self.d_results_cv, imult))
예제 #3
0
def efficiency_ctau(cutlist, labellist, setcut='', maxy=0.50):

    basecut = ""
    signame = ""
    ncuts = len(cutlist)

    file = {}
    nevt = {}
    tree = {}
    effs = {}

    for i, s in enumerate(sign_ctau):
        print "c_tau sample: ", s
        if 'BulkGravToZZToZhadZinv' in samples[s]['files'][0]:
            signame = "XZZInv"
        elif 'WprimeToWZToWhadZinv' in samples[s]['files'][0]:
            signame = "XWZInv"
        elif 'WplusH' in samples[s]['files'][0]:
            signame = "WplusH"
        elif 'WminusH' in samples[s]['files'][0]:
            signame = "WminusH"
        elif 'ZH' in samples[s]['files'][
                0] and not 'ggZH' in samples[s]['files'][0]:
            signame = "ZH"
        elif 'ggZH' in samples[s]['files'][0]:
            signame = "ggZH"
        file[s] = TFile(NTUPLEDIR + samples[s]['files'][0] + ".root",
                        "READ")  # Read TFile
        ##nevt[s] = (file[s].Get('counter/c_nEvents')).GetBinContent(1)
        tree[s] = file[s].Get("trigger/tree")  # Read TTree
        nevt[s] = file[s].Get("trigger/tree").GetEntriesFast()
        effs[s] = [0] * (ncuts + 1)
        for j, c in enumerate(cutlist):
            #print cutlist[j]

            br = 1.
            n = tree[s].GetEntries(cutlist[j])
            d = nevt[
                s]  #d = sample[samples[s]['files'][0]]['nevents']#tree[s].GetEntries(basecut)
            effs[s][j] = float(n) / (d * br)

    line_ctau = []
    outFile = TFile("Efficiency/Eff_spline.root", "UPDATE")
    outFile.cd()
    #flagLP = True
    for j, c in enumerate(cutlist):
        line_ctau.append(TGraph(ncuts))
        line_ctau[j].SetTitle(";c#tau_{#pi} (mm);Efficiency")
        print labellist[j]
        for i, s in enumerate(sign_ctau):
            #mass = int( ''.join(x for x in s if x.isdigit()) )
            ctau = float(samples[s]['ctau'])
            print i, ctau, effs[s][j]
            line_ctau[j].SetPoint(i, ctau, effs[s][j])
        line_ctau[j].SetMarkerStyle(20)
        line_ctau[j].SetMarkerColor(colors[j])
        line_ctau[j].SetLineColor(colors[j])
        line_ctau[j].SetLineWidth(3)
        line_ctau[j].GetXaxis().SetTitleOffset(
            line_ctau[j].GetXaxis().GetTitleOffset() * 1.2)
        line_ctau[j].GetYaxis().SetTitleOffset(
            line_ctau[j].GetYaxis().GetTitleOffset() * 1.2)
        line_ctau[j].Print()

    outFile.Close()
    leg = TLegend(0.2, 0.6, 0.9, 0.9)
    leg.SetBorderSize(0)
    leg.SetFillStyle(0)  #1001
    leg.SetFillColor(0)
    for i, c in enumerate(cutlist):
        leg.AddEntry(line_ctau[i], labellist[i], "lp")

    if 'BulkGravToZZToZlepZhad' in samples[s]['files'][0]:
        leg.AddEntry(line_ctau[0], 'G_{Bulk} #rightarrow Z_{had}Z_{lep}', "")
    elif 'BulkGravToZZToZlepZinv' in samples[s]['files'][0]:
        leg.AddEntry(line_ctau[0], 'G_{Bulk} #rightarrow Z_{lep}Z_{inv}', "")
    elif 'WprimeToWZToWhadZlep' in samples[s]['files'][0]:
        leg.AddEntry(line_ctau[0], 'W\' #rightarrow W_{had}Z_{lep}', "")
    elif 'BulkGravToZZToZhadZinv' in samples[s]['files'][0]:
        #signame += "XZZInv"
        leg.AddEntry(line_ctau[0], 'G_{Bulk} #rightarrow Z_{had}Z_{inv}', "")
    elif 'WprimeToWZToWhadZinv' in samples[s]['files'][0]:
        #signame += "XWZInv"
        leg.AddEntry(line_ctau[0], 'W\' #rightarrow W_{had}Z_{inv}', "")
    elif 'WplusH' in samples[s]['files'][0]:
        #signame += "XWZInv"
        leg.AddEntry(line_ctau[0],
                     'W^{+} H #rightarrow #pi #pi #rightarrow 4b', "")
    elif 'WminusH' in samples[s]['files'][0]:
        leg.AddEntry(line_ctau[0],
                     'W^{-} H #rightarrow #pi #pi #rightarrow 4b', "")
    elif 'ZH' in samples[s]['files'][
            0] and not 'ggZH' in samples[s]['files'][0]:
        leg.AddEntry(line_ctau[0], 'Z H #rightarrow #pi #pi #rightarrow 4b',
                     "")
    elif 'ggZH' in samples[s]['files'][0]:
        leg.AddEntry(line_ctau[0], 'gg Z H #rightarrow #pi #pi #rightarrow 4b',
                     "")

    c1 = TCanvas("c1", "Signals", 800, 600)
    c1.cd()
    c1.GetPad(0).SetTopMargin(0.06)
    c1.GetPad(0).SetRightMargin(0.05)
    c1.GetPad(0).SetTicks(1, 1)
    line_ctau[0].GetXaxis().SetTitle("c#tau_{#pi} (mm)")
    line_ctau[0].GetYaxis().SetTitle("Efficiency")
    line_ctau[0].GetYaxis().SetRangeUser(0., maxy)

    for i, s in enumerate(cutlist):
        line_ctau[i].Draw("APL" if i == 0 else "SAME, PL")
    leg.Draw()
    #drawCMS(-1, "Simulation")

    name = ""
    if '#mu#mu' in labellist[0]: name = "Muon"
    elif 'ee' in labellist[0]: name = "Ele"
    else: name = "Met"

    c1.Print("Efficiency/Efficiency_vs_ctau_" + signame + setcut + ".png")
    c1.Print("Efficiency/Efficiency_vs_ctau_" + signame + setcut + ".pdf")
    c1.Print("Efficiency/Efficiency_vs_ctau_" + signame + setcut + ".C")
    line_ctau = []
예제 #4
0
def binFile(rerror, filename, xtitle, backgrounds):

    file = TFile(filename)
    keys = file.GetListOfKeys()


    h_bkg = {}
    h_data = {}

    # load all the background and data histograms
    for key in keys:
        key = key.GetName()
        #print key
        info = hinfo(key)
        if not info.systematic:
            if info.process in backgrounds:
                if info.channel in h_bkg:
                    #print info.channel
                    h_bkg[info.channel] = merge(h_bkg[info.channel], file.Get(key).Clone())
                else:
                    h_bkg[info.channel] = file.Get(key).Clone()
            elif info.process == 'data' or info.process == 'DATA':
                #print info.process
                #print info.channel
                if info.channel in h_data:
                    h_data[info.channel] = merge(h_data[info.channel], file.Get(key).Clone())
                else:
                    h_data[info.channel] = file.Get(key).Clone()

    canvas = TCanvas()
#    canvas.SetLogy()

    keys = file.GetListOfKeys()

    output = TFile(filename.split('.')[0]+'_rebinned.root', 'RECREATE')

    # print all the histograms for all the channels
    for key in h_bkg:
        print h_bkg[key]
        binning = array.array('d', computeBinning(h_bkg[key], rerror))
        h_bkg[key] = h_bkg[key].Rebin(len(binning)-1, h_bkg[key].GetName(), binning)
        h_data[key] = h_data[key].Rebin(len(binning)-1, h_data[key].GetName(), binning)

        h_bkg[key].SetLineColor(ROOT.kGray+1)
        h_bkg[key].SetFillColor(ROOT.kGray+1)
        h_data[key].SetLineColor(ROOT.kBlack)
        h_data[key].SetMarkerStyle(20)

        pad = canvas.cd(1)
        pad.SetLeftMargin(0.15)
        pad.SetBottomMargin(0.15)

        maxs = [h_data[key].GetMaximum(), h_bkg[key].GetMaximum()]
        min = h_bkg[key].GetBinContent(h_bkg[key].GetMinimumBin())

        h_data[key].GetYaxis().SetRangeUser(0.5*min,max(maxs)*1.8)

        h_data[key].GetYaxis().SetLabelSize(0.05)
        h_data[key].GetYaxis().SetTitleSize(0.05)
        h_data[key].GetYaxis().SetTitle('event yield')
        h_data[key].GetXaxis().SetLabelSize(0.05)
        h_data[key].GetXaxis().SetTitleSize(0.05)
        h_data[key].GetXaxis().SetTitle(xtitle)

        h_data[key].Draw('e')
        h_bkg[key].Draw('samehist')
        h_data[key].Draw('samee')

        legend = TLegend(.67, .78, .89, .88)
        legend.SetMargin(0.12);
        legend.SetTextSize(0.03);
        legend.SetFillColor(10);
        legend.SetBorderSize(0);
        legend.AddEntry(h_bkg[key], "Background", "f")
        legend.AddEntry(h_data[key], "CMS Data 2016", "lp")
        legend.Draw()

        labelcms = TLegend(.15, .91, 1, .96)
        labelcms.SetTextSize(0.04)
        labelcms.SetMargin(0.12);
        labelcms.SetFillColor(10);
        labelcms.SetBorderSize(0);
        labelcms.SetHeader('CMS Preliminary #sqrt{s} = 13 TeV')
        labelcms.Draw()

        labellumi = TLegend(.73, .91, 1, .96)
        labellumi.SetTextSize(0.04)
        labellumi.SetMargin(0.12);
        labellumi.SetFillColor(10);
        labellumi.SetBorderSize(0);
#        labellumi.SetHeader('L = 3.99 fb^{-1}')
#        labellumi.SetHeader('L = 12.9 fb^{-1}')
        labellumi.SetHeader('L = 35.9 fb^{-1}')
        labellumi.Draw()

        labellumi2 = TLegend(.67, .70, .89, .75)
        labellumi2.SetTextSize(0.03)
        labellumi2.SetMargin(0.12);
        labellumi2.SetFillColor(10);
        labellumi2.SetBorderSize(0);
        labellumi2.SetHeader(key)
        labellumi2.Draw()

        canvas.SaveAs('h_'+filename.split('.')[0]+'_'+key+'.pdf')

        for hkey in keys:
            hkey = hkey.GetName()
            info = hinfo(hkey)
            if info.channel == key:
                histogram = file.Get(hkey).Clone()
                # #if info.systematic == 'pdf':
                # #    continue
                # if (info.systematic == 'scale' or info.systematic == 'matching') and 'light' in info.process and '1btag' in info.channel:
                #     print "Excluding : ", info.systematic, info.process, info.channel
                #     continue
                # # Hack to fix the data lowercase names
                # if 'data' in info.process:
                #     histogram.SetName(histogram.GetName().replace('data','DATA'))
                # if 'ttbar' in info.process and info.systematic == 'scale':
                #     orig = histogram.GetName()
                #     histogram.SetName(histogram.GetName().replace('scale','scale_ttbar'))
                #     print "Renaming: %s to %s" % (orig, histogram.GetName())
                # if ('wlight' in info.process or 'zlight' in info.process) and info.systematic == 'scale':
                #     orig = histogram.GetName()
                #     histogram.SetName(histogram.GetName().replace('scale','scale_vjets'))
                #     print "Renaming: %s to %s" % (orig, histogram.GetName())
                # if ('wlight' in info.process or 'zlight' in info.process) and info.systematic == 'matching':
                #     orig = histogram.GetName()
                #     histogram.SetName(histogram.GetName().replace('matching','matching_vjets'))
                #     print "Renaming: %s to %s" % (orig, histogram.GetName())
                # if info.process.startswith('zp') or info.process.startswith('rsg'):
                #     print "Scaling signal sample %s by x0.1" % histogram.GetName()
                #     histogram.Scale(0.1)
                # histogram = histogram.Rebin(len(binning)-1, histogram.GetName(), binning)
                output.cd()
                histogram.Write()
예제 #5
0
def DrawRatioPlot(name, sample, xaxis_title, yaxis_title, c, data, MC, MCUp,
                  MCDn, logscale):
    c.Divide(0, 2, 0, 0)
    pad1 = c.cd(1)

    pad1.SetBottomMargin(0.02)
    pad1.SetTopMargin(0.18)
    pad1.SetLeftMargin(0.10)

    if logscale:
        pad1.SetLogy()

    max = 0.
    for bin in range(MC.GetSize() - 2):
        if (MC.GetBinContent(bin + 1) > max):
            max = MC.GetBinContent(bin + 1)

    MC.SetMaximum(1.4 * max)

    MC.SetFillColor(kOrange + 1)
    MC.GetYaxis().SetTitle(yaxis_title)
    MC.Draw("HIST")
    MC.GetXaxis().SetLabelSize(0)
    MC.GetYaxis().SetTitleSize(0.07)
    MC.GetYaxis().SetLabelSize(0.07)
    MC.GetYaxis().SetTitleOffset(0.7)

    data.SetLineColor(ROOT.kBlack)
    data.SetMarkerStyle(20)
    data.SetMarkerSize(0.6)
    data.Draw("p E1 X0 SAME")

    pad2 = c.cd(2)

    pad2.SetBottomMargin(0.20)
    pad2.SetTopMargin(0.02)
    pad2.SetLeftMargin(0.10)

    Ratio = TH1F("Ratio", "Ratio",
                 MC.GetSize() - 2,
                 MC.GetXaxis().GetXmin(),
                 MC.GetXaxis().GetXmax())
    sigma_up = TH1F("sigma_up", "sigma_up",
                    MC.GetSize() - 2,
                    MC.GetXaxis().GetXmin(),
                    MC.GetXaxis().GetXmax())
    sigma_dn = TH1F("sigma_dn", "sigma_dn",
                    MC.GetSize() - 2,
                    MC.GetXaxis().GetXmin(),
                    MC.GetXaxis().GetXmax())

    for bin in range(MC.GetSize() - 2):
        if (MC.GetBinContent(bin + 1) == 0):
            Ratio.SetBinContent(bin + 1, 0)
            Ratio.SetBinError(bin + 1, 0)
            sigma_up.SetBinContent(bin + 1, 0)
            sigma_dn.SetBinContent(bin + 1, 0)
        else:
            Ratio.SetBinContent(
                bin + 1,
                float(data.GetBinContent(bin + 1)) / MC.GetBinContent(bin + 1))
            Ratio.SetBinError(bin + 1, 1. / (data.GetBinContent(bin + 1))**0.5)
            sigma_up.SetBinContent(
                bin + 1,
                float(MCUp.GetBinContent(bin + 1)) / MC.GetBinContent(bin + 1))
            sigma_dn.SetBinContent(
                bin + 1,
                float(MCDn.GetBinContent(bin + 1)) / MC.GetBinContent(bin + 1))

    for bin in range(Ratio.GetSize() - 2):
        temp = Ratio.GetBinContent(bin + 1)
        Ratio.SetBinContent(bin + 1, temp - 1)

    for bin in range(sigma_up.GetSize() - 2):
        temp = sigma_up.GetBinContent(bin + 1)
        sigma_up.SetBinContent(bin + 1, temp - 1)

    for bin in range(sigma_dn.GetSize() - 2):
        temp = sigma_dn.GetBinContent(bin + 1)
        sigma_dn.SetBinContent(bin + 1, temp - 1)

    sigma_up.SetFillColor(ROOT.kGray)
    sigma_up.SetLineColor(ROOT.kGray)
    sigma_up.SetMaximum(2.0)
    sigma_up.SetMinimum(-2.0)
    sigma_up.GetXaxis().SetTitle(xaxis_title)
    sigma_up.GetYaxis().SetTitle("(Data/MC)-1")
    sigma_up.GetYaxis().SetTitleOffset(0.6)
    sigma_up.Draw("HIST")
    sigma_up.GetXaxis().SetLabelSize(0.07)
    sigma_up.GetXaxis().SetTitleSize(0.07)
    sigma_up.GetYaxis().SetLabelSize(0.07)
    sigma_up.GetYaxis().SetTitleSize(0.07)

    sigma_dn.SetFillColor(ROOT.kGray)
    sigma_dn.SetLineColor(ROOT.kGray)
    sigma_dn.Draw("HIST SAME")

    gPad.RedrawAxis()

    Ratio.SetMarkerStyle(20)
    Ratio.SetMarkerSize(0.6)
    Ratio.Draw("p E1 X0 SAME")

    pad1.cd()
    leg = TLegend(.75, .45, .95, .75)
    leg.SetBorderSize(0)
    leg.SetFillColor(0)
    leg.SetFillStyle(0)
    leg.SetTextFont(42)
    leg.SetTextSize(0.07)
    leg.AddEntry(MC, sample, "f")
    leg.AddEntry(data, "Data", "p")
    leg.AddEntry(sigma_up, "JEC Uncertainty", "f")
    leg.Draw()

    #draw CMS and lumi text
    CMS_lumi.writeExtraText = True
    CMS_lumi.extraText = "Preliminary"
    CMS_lumi.lumi_sqrtS = lumiText + " (13 TeV)"
    CMS_lumi.cmsTextSize = 0.6
    CMS_lumi.lumiTextSize = 0.46
    CMS_lumi.extraOverCmsTextSize = 0.75
    CMS_lumi.relPosX = 0.12
    CMS_lumi.CMS_lumi(pad1, 0, 0)
    c.Update()

    c.SaveAs(name + ".pdf")
    c.SaveAs(name + ".png")

    c.Clear()
예제 #6
0
        last_evt = tree.evt
        last_bdtvalue = mvaValue
        last_genMatch = tree.bWj1Wj2_isGenMatched

print "No. of signal ", hist_signal.Integral(
), " No. of bkg ", hist_bkg.Integral()
hist_signal.SetLineColor(2)
hist_bkg.SetLineColor(4)
hist_signal.SetFillColor(2)
hist_bkg.SetFillColor(4)
hist_signal.SetFillStyle(3004)
hist_bkg.SetFillStyle(3005)

leg = TLegend(0.2, 0.65, 0.5, 0.9)
leg.SetBorderSize(0)
leg.SetFillColor(10)
leg.SetLineColor(0)
leg.SetFillStyle(0)
leg.SetTextSize(0.04)
leg.SetTextFont(42)

leg.AddEntry(hist_signal, "signal", "l")
leg.AddEntry(hist_bkg, "background", "l")

histogram_base.Draw("hist")
hist_signal.DrawNormalized("histsame")
hist_bkg.DrawNormalized("histsame")
leg.Draw()

c1.SaveAs("plots/bdt_score_evtLevel_hadTopTagger_" + process + "_opt1.png")
c1.SaveAs("plots/bdt_score_evtLevel_hadTopTagger_" + process + "_opt1.C")
예제 #7
0
    hs.GetXaxis().SetTitle("Mass [GeV/c^{2}]")
    hs.GetXaxis().SetLabelFont(43)
    hs.GetXaxis().SetLabelSize(15)
    hs.GetYaxis().SetTitleSize(20)
    hs.GetYaxis().SetTitleFont(43)
    hs.GetYaxis().SetTitleOffset(1.8)
    hs.GetYaxis().SetLabelFont(43)
    hs.GetYaxis().SetLabelSize(15)
    hs.GetYaxis().SetTitle("Events")

    # legend
    legend = TLegend(0.74, 0.68, 0.94, 0.87)
    legend.AddEntry(ZMass_DATA[i], "Data", "p")
    legend.AddEntry(ZMass_MC_DY[i], "Drell-Yan", "f")
    legend.AddEntry(ZMass_MC_TTJets[i], "t#bar{t}", "f")
    legend.SetFillColor(kWhite)
    legend.SetLineColor(kBlack)
    legend.SetTextFont(43)
    legend.SetTextSize(20)
    legend.Draw()

    # box with fit results
    pv = TPaveText(0.64, 0.35, 0.94, 0.65, "brNDC")
    pv.AddText("DATA:")
    pv.AddText("Z DCBmean = " + str(round(massFitDATA_dict[key], 2)) + " GeV")
    pv.AddText("Z DCBwidth = " + str(round(widthFitDATA_dict[key], 2)) +
               " GeV")
    pv.AddText("MC:")
    pv.AddText("Z DCBmean = " + str(round(massFitMC_dict[key], 2)) + " GeV")
    pv.AddText("Z DCBwidth = " + str(round(widthFitMC_dict[key], 2)) + " GeV")
    pv.SetFillColor(kWhite)
예제 #8
0
def do_plot(categories):
    #this sets how tall the canvas is
    N_cats = len(plot_categories.keys())
    #sets the number of divisions on the plot
    N_cuts = max(len(cuts) for cuts in plot_categories.itervalues())
    canv = TCanvas('theorycomp', '', 500, 500 + 200 * N_cats)
    main_pad_ylow = 1 - (500.0 / (500 + 200 * N_cats))
    rat_pad_height = main_pad_ylow / N_cats
    canv.cd()

    max_cs = get_max_cs(categories)
    min_cs = get_min_cs(categories)

    scaffold = TH1F('scaf', '', N_cuts, 0, N_cuts)
    scaffold.GetYaxis().SetLimits(10 * max_cs, min_cs / 10.0)
    scaffold.GetYaxis().SetRangeUser(min_cs / 10.0, 10 * max_cs)
    scaffold.SetNdivisions(100 * N_cuts)
    scaffold.SetStats(False)
    scaffold.GetYaxis().SetTitle(y_axis_title)
    unshitify(scaffold)

    main_pad = TPad('main_plot', '', 0, main_pad_ylow, 1, 1, 0, 0, 0)
    main_pad.SetLogy()

    main_pad.Draw()
    main_pad.cd()
    scaffold.Draw()

    cut_labels = TLatex()
    cut_labels.SetNDC()
    plot_start = 0.15
    column_width = (0.945 - plot_start) / N_cuts
    cut_labels.SetTextSize(0.045)
    cut_labels.SetTextFont(62)
    #    cut_labels.DrawLatex(0.18,0.96,
    #                         "CMS Preliminary %i, #sqrt{s} = %s"%(year,sqrts))
    #    cut_labels.DrawLatex(0.77,0.96,luminosity)
    cut_labels.DrawLatex(0.17, 0.96, "CMS Preliminary, L = 5.0 fb^{-1}")
    cut_labels.DrawLatex(0.76, 0.96, "#sqrt{s} = 7 TeV")

    labels_drawn = 0
    ratio_pads = []
    cat_meass = []
    cat_preds = []
    cat_meas_rats = []
    cat_pred_rats = []

    legend = TLegend(0.45, 0.7, 0.93, 0.93)
    legend.SetTextFont(62)
    legend.SetTextSize(0.038)
    legend.SetFillColor(0)
    legend.SetLineColor(0)
    legend.SetBorderSize(1)

    for j, (cat, cuts) in enumerate(plot_categories.iteritems()):
        canv.cd()
        ratio_pads.append(
            TPad(cat, '', 0, rat_pad_height * j + 0.075, 1,
                 rat_pad_height * (j + 1) + rat_pad_height / 4, 0, 0, 0))
        ratio_pads[-1].Draw()
        ratio_pads[-1].cd()
        rat_scaf = scaffold.DrawCopy()
        rat_scaf.GetYaxis().SetLimits(-1, 3)
        rat_scaf.GetYaxis().SetRangeUser(0, 2)
        rat_scaf.GetYaxis().SetNdivisions(105)
        rat_scaf.GetYaxis().SetTitle("#frac{Data}{%s}" % (prediction_name))
        rat_scaf.GetYaxis().SetTitleOffset(0.6)
        rat_scaf.GetYaxis().SetTitleSize(0.10)

        main_pad.cd()
        print j, cat

        cat_meass.append([])
        cat_preds.append(TGraphErrors())
        cat_meas_rats.append([])
        cat_pred_rats.append(TGraphErrors())

        cat_preds[-1].SetName("%s (%s)" % (prediction_name, cat))

        added_channels = False

        for i, cut in enumerate(cuts):
            cut_name = cut.keys()[0]
            if len(cuts) == N_cuts and labels_drawn != len(cuts):
                canv.cd()
                cut_labels.DrawLatex(plot_start + column_width * (i + 0.35),
                                     0.05, cut_name)
                labels_drawn += 1
            main_pad.cd()
            print '\t%i : %s' % (i, cut_name)

            realkeys = list(cut[cut_name].keys())
            realkeys.remove('PREDICTION')
            nchan = len(realkeys)
            divsize = 1.0 / (nchan)

            if not added_channels:
                cat_meass[-1] += [TGraphErrors() for l in range(nchan)]
                cat_meas_rats[-1] += [TGraphErrors() for l in range(nchan)]
                print cat_meass[-1]
                added_channels = True

            #graph entries for prediction
            pcs, perr = cut[cut_name]['PREDICTION']

            cat_preds[-1].SetPoint(i, i + 0.5, pcs)
            cat_preds[-1].SetPointError(i, 0.5, perr)

            cat_pred_rats[-1].SetPoint(i, i + 0.5, 1.0)
            cat_pred_rats[-1].SetPointError(i, 0.5, perr / pcs)

            #graph entries for data measurement
            for k, key in enumerate(realkeys):
                gidx = i
                print cut[cut_name][key]
                cs, stat, syst = cut[cut_name][key]
                err = hypot(stat, syst)

                cat_meass[-1][k].SetName("%s (%s)" % (key, cat))

                cat_meass[-1][k].SetPoint(gidx, i + (k + 0.5) * divsize, cs)
                cat_meass[-1][k].SetPointError(gidx, 0, err)

                cat_meas_rats[-1][k].SetPoint(gidx, i + (k + 0.5) * divsize,
                                              cs / pcs)
                cat_meas_rats[-1][k].SetPointError(gidx, 0, err / pcs)


#                                                   err/pcs)
        main_pad.cd()
        cat_preds[-1].SetFillColor(fill_colors[j] - 3)
        cat_preds[-1].Draw('2')
        legend.AddEntry(cat_preds[-1], cat_preds[-1].GetName(), 'f')
        for i, gr in enumerate(cat_meass[-1]):
            gr.SetMarkerStyle(20 + 4 * j + i)
            gr.Draw('pe1')
            legend.AddEntry(gr, gr.GetName(), 'pl')

        ratio_pads[-1].cd()
        cat_pred_rats[-1].SetFillColor(fill_colors[j] - 3)
        cat_pred_rats[-1].Draw('2')
        for i, gr in enumerate(cat_meas_rats[-1]):
            gr.SetMarkerStyle(20 + 4 * j + i)
            gr.Draw('pe1')
    main_pad.cd()
    legend.Draw()

    canv.cd()
    cut_labels.DrawLatex(0.80, 0.015, 'E_{T}^{#gamma} (GeV)')

    canv.Print('vgamma_theory_comparison_Wg_app_corr_dict.pdf')
    canv.Print('vgamma_theory_comparison_Wg_app_corr_dict.eps')
    canv.Print('vgamma_theory_comparison_Wg_app_corr_dict.png')
    canv.Print('vgamma_theory_comparison_Wg_app_corr_dict.gif')
    canv.Print('vgamma_theory_comparison_Wg_app_corr_dict.root')
예제 #9
0
def limits():

    # put real limits here: lepton+jets, dilepton, combined
    obs = np.array([0.0, 0.0, 0.0])

    expect = np.array([1, 1, 1])
    upper1sig = np.array([1.179, 0.827, 0.736])
    lower1sig = np.array([0.824, 0.578, 0.501])
    upper2sig = np.array([2.661, 1.892, 1.662])
    lower2sig = np.array([1.344, 0.9303, 0.806])

    channel = np.array([1.5, 0.5, -0.5])
    ey = np.array([0.495, 0.495, 0.495])
    zero = np.zeros(nchannels)

    xmin = 0.9
    xmax = 20

    c, h = draw_canvas_histo(
        xmin, xmax,
        "95% CL limit on #mu = #sigma/#sigma_{SM} at m_{H} = 125 GeV")
    c.SetLogx()

    gexpect1sig = TGraphAsymmErrors(nchannels, expect, channel, lower1sig,
                                    upper1sig, ey, ey)
    gexpect1sig.SetFillColor(kGreen)
    gexpect1sig.SetLineWidth(2)
    gexpect1sig.SetLineStyle(2)

    gexpect2sig = TGraphAsymmErrors(nchannels, expect, channel, lower2sig,
                                    upper2sig, ey, ey)
    gexpect2sig.SetFillColor(kYellow)
    gexpect2sig.SetLineWidth(2)
    gexpect2sig.SetLineStyle(2)

    gexpect2sig.Draw("2")
    gexpect1sig.Draw("2")

    gobs = TGraphErrors(nchannels, obs, channel, zero, ey)
    gobs.SetMarkerStyle(21)
    gobs.SetMarkerSize(1.5)
    gobs.SetLineWidth(2)
    #gobs.Draw("pz")

    # dashed line at median expected limits
    l = TLine()
    l.SetLineStyle(2)
    l.SetLineWidth(2)
    for bin in range(nchannels):
        l.DrawLine(expect[bin], channel[bin] - ey[bin], expect[bin],
                   channel[bin] + ey[bin])

    # line to separate individual and combined limits
    l.SetLineStyle(1)
    l.SetLineWidth(1)
    l.DrawLine(xmin, 0, xmax, 0)

    # legend
    leg = TLegend(0.67, 0.75, 0.95, 0.9)
    leg.SetFillColor(4000)
    leg.AddEntry(gexpect1sig, "Expected #pm1#sigma", "FL")
    leg.AddEntry(gexpect2sig, "Expected #pm2#sigma", "FL")
    #leg.AddEntry( gobs,        "Observed", "pl" )
    leg.Draw()

    #draw_disclaimer()

    c.RedrawAxis()
    c.Modified()
    c.Update()
    c.SaveAs("limits.pdf")
예제 #10
0
def DrawRatioPlot(name, xaxis_title, yaxis_title, c, data, MC, MC_NvtxWEIGHT,
                  MC_jesUp, MC_jesDn, MC_jerUp, MC_jerDn, MC_puUp, MC_puDn,
                  MC_metUp, MC_metDn):
    c.Divide(0, 2, 0, 0)
    pad1 = c.cd(1)

    pad1.SetBottomMargin(0.02)
    pad1.SetTopMargin(0.18)
    pad1.SetLeftMargin(0.10)

    max = 0.
    for bin in range(MC.GetSize() - 2):
        if (MC.GetBinContent(bin + 1) > max):
            max = MC.GetBinContent(bin + 1)

    MC.SetMaximum(1.4 * max)
    #norm = data.Integral()/MC.Integral()   # Normalize MC to data
    #MC.Scale(norm)
    MC.SetFillColor(kOrange + 1)
    MC.GetYaxis().SetTitle(yaxis_title)
    MC.Draw("HIST")
    MC.GetXaxis().SetLabelSize(0)
    MC.GetYaxis().SetTitleSize(0.07)
    MC.GetYaxis().SetLabelSize(0.07)
    MC.GetYaxis().SetTitleOffset(0.7)

    data.SetLineColor(ROOT.kBlack)
    data.SetMarkerStyle(20)
    data.SetMarkerSize(0.6)
    data.Draw("p E1 X0 SAME")

    MC_NvtxWEIGHT.SetMarkerStyle(23)
    MC_NvtxWEIGHT.SetMarkerColor(kAzure)
    MC_NvtxWEIGHT.SetMarkerSize(0.9)
    MC_NvtxWEIGHT.Draw("p E1 X0 SAME")

    pad2 = c.cd(2)

    pad2.SetBottomMargin(0.20)
    pad2.SetTopMargin(0.02)
    pad2.SetLeftMargin(0.10)
    Ratio = TH1F("Ratio", "Ratio",
                 MC.GetSize() - 2,
                 MC.GetXaxis().GetXmin(),
                 MC.GetXaxis().GetXmax())
    Ratio_W = TH1F("Ratio_W", "Ratio_W",
                   MC.GetSize() - 2,
                   MC.GetXaxis().GetXmin(),
                   MC.GetXaxis().GetXmax())
    sigma_up = TH1F("sigma_up", "sigma_up",
                    MC.GetSize() - 2,
                    MC.GetXaxis().GetXmin(),
                    MC.GetXaxis().GetXmax())
    sigma_dn = TH1F("sigma_dn", "sigma_dn",
                    MC.GetSize() - 2,
                    MC.GetXaxis().GetXmin(),
                    MC.GetXaxis().GetXmax())
    sigma_jesUp = TH1F("sigma_jesUp", "sigma_jesUp",
                       MC.GetSize() - 2,
                       MC.GetXaxis().GetXmin(),
                       MC.GetXaxis().GetXmax())
    sigma_jesDn = TH1F("sigma_jesDn", "sigma_jesDn",
                       MC.GetSize() - 2,
                       MC.GetXaxis().GetXmin(),
                       MC.GetXaxis().GetXmax())
    sigma_jerUp = TH1F("sigma_jerUp", "sigma_jerUp",
                       MC.GetSize() - 2,
                       MC.GetXaxis().GetXmin(),
                       MC.GetXaxis().GetXmax())
    sigma_jerDn = TH1F("sigma_jerDn", "sigma_jerDn",
                       MC.GetSize() - 2,
                       MC.GetXaxis().GetXmin(),
                       MC.GetXaxis().GetXmax())
    sigma_puUp = TH1F("sigma_puUp", "sigma_puUp",
                      MC.GetSize() - 2,
                      MC.GetXaxis().GetXmin(),
                      MC.GetXaxis().GetXmax())
    sigma_puDn = TH1F("sigma_puDn", "sigma_puDn",
                      MC.GetSize() - 2,
                      MC.GetXaxis().GetXmin(),
                      MC.GetXaxis().GetXmax())
    sigma_metUp = TH1F("sigma_metUp", "sigma_metUp",
                       MC.GetSize() - 2,
                       MC.GetXaxis().GetXmin(),
                       MC.GetXaxis().GetXmax())
    sigma_metDn = TH1F("sigma_metDn", "sigma_metDn",
                       MC.GetSize() - 2,
                       MC.GetXaxis().GetXmin(),
                       MC.GetXaxis().GetXmax())

    up_list = []
    dn_list = []
    for bin in range(MC.GetSize() - 2):
        temp_list = []
        if (MC.GetBinContent(bin + 1) == 0):
            Ratio.SetBinContent(bin + 1, 0)
            Ratio.SetBinError(bin + 1, 0)
            Ratio_W.SetBinContent(bin + 1, 0)
            Ratio_W.SetBinError(bin + 1, 0)
            sigma_jesUp.SetBinContent(bin + 1, 0)
            sigma_jesDn.SetBinContent(bin + 1, 0)
            sigma_jerUp.SetBinContent(bin + 1, 0)
            sigma_jerDn.SetBinContent(bin + 1, 0)
            sigma_puUp.SetBinContent(bin + 1, 0)
            sigma_puDn.SetBinContent(bin + 1, 0)
            sigma_metUp.SetBinContent(bin + 1, 0)
            sigma_metDn.SetBinContent(bin + 1, 0)
        else:
            Ratio.SetBinContent(
                bin + 1,
                float(data.GetBinContent(bin + 1)) / MC.GetBinContent(bin + 1))
            Ratio.SetBinError(bin + 1, 1. / (data.GetBinContent(bin + 1))**0.5)
            Ratio_W.SetBinContent(
                bin + 1,
                float(data.GetBinContent(bin + 1)) /
                MC_NvtxWEIGHT.GetBinContent(bin + 1))
            Ratio_W.SetBinError(bin + 1,
                                1. / (data.GetBinContent(bin + 1))**0.5)
            sigma_jesUp.SetBinContent(
                bin + 1,
                float(MC_jesUp.GetBinContent(bin + 1)) /
                MC.GetBinContent(bin + 1))
            sigma_jesDn.SetBinContent(
                bin + 1,
                float(MC_jesDn.GetBinContent(bin + 1)) /
                MC.GetBinContent(bin + 1))
            sigma_jerUp.SetBinContent(
                bin + 1,
                float(MC_jerUp.GetBinContent(bin + 1)) /
                MC.GetBinContent(bin + 1))
            sigma_jerDn.SetBinContent(
                bin + 1,
                float(MC_jerDn.GetBinContent(bin + 1)) /
                MC.GetBinContent(bin + 1))
            sigma_puUp.SetBinContent(
                bin + 1,
                float(MC_puUp.GetBinContent(bin + 1)) /
                MC.GetBinContent(bin + 1))
            sigma_puDn.SetBinContent(
                bin + 1,
                float(MC_puDn.GetBinContent(bin + 1)) /
                MC.GetBinContent(bin + 1))
            sigma_metUp.SetBinContent(
                bin + 1,
                float(MC_metUp.GetBinContent(bin + 1)) /
                MC.GetBinContent(bin + 1))
            sigma_metDn.SetBinContent(
                bin + 1,
                float(MC_metDn.GetBinContent(bin + 1)) /
                MC.GetBinContent(bin + 1))
            print '############### bin ' + str(bin + 1) + ' ##############'
            print str(sigma_jesUp.GetBinContent(bin + 1))
            print str(sigma_jerUp.GetBinContent(bin + 1))
            print str(sigma_puUp.GetBinContent(bin + 1))
            print str(sigma_metUp.GetBinContent(bin + 1))
            print str(sigma_jesDn.GetBinContent(bin + 1))
            print str(sigma_jerDn.GetBinContent(bin + 1))
            print str(sigma_puDn.GetBinContent(bin + 1))
            print str(sigma_metDn.GetBinContent(bin + 1))
            temp_jesUp = sigma_jesUp.GetBinContent(bin + 1)
            temp_jerUp = sigma_jerUp.GetBinContent(bin + 1)
            temp_puUp = sigma_puUp.GetBinContent(bin + 1)
            temp_metUp = sigma_metUp.GetBinContent(bin + 1)
            temp_jesDn = sigma_jesDn.GetBinContent(bin + 1)
            temp_jerDn = sigma_jerDn.GetBinContent(bin + 1)
            temp_puDn = sigma_puDn.GetBinContent(bin + 1)
            temp_metDn = sigma_metDn.GetBinContent(bin + 1)
            temp_list.append(temp_jesUp)
            temp_list.append(temp_jerUp)
            temp_list.append(temp_puUp)
            temp_list.append(temp_metUp)
            temp_list.append(temp_jesDn)
            temp_list.append(temp_jerDn)
            temp_list.append(temp_puDn)
            temp_list.append(temp_metDn)
            print 'temp_list size is: ' + str(len(temp_list))
            tempUp_list = []
            tempDn_list = []
            for i in range(len(temp_list)):
                print 'Elemento', i, 'is ', temp_list[i]
                if (temp_list[i] > 1.):
                    tempUp_list.append(temp_list[i])
                elif (temp_list[i] < 1.):
                    tempDn_list.append(temp_list[i])
            print 'tempUp_list size is: ' + str(len(tempUp_list))
            print 'tempDn_list size is: ' + str(len(tempDn_list))

            temp_up = 0.
            for i in tempUp_list:
                temp_up += (i - 1)**2
                #print 'Elemento up iesimo della lista: ', str(i), '; temp_up al giro i = ', temp_up
            up = math.sqrt(temp_up)
            up_list.append(up)

            temp_dn = 0.
            for i in tempDn_list:
                temp_dn += (i - 1)**2
                #print 'Elemento dn iesimo della lista: ', str(i), '; temp_dn al giro i = ', temp_dn
            dn = math.sqrt(temp_dn)
            dn_list.append(dn)

    print 'UP LIST SIZE is: ' + str(len(up_list))
    print 'DN LIST SIZE is: ' + str(len(dn_list))

    for bin in range(len(up_list)):
        sigma_up.SetBinContent(bin + 1, up_list[bin])
        print 'bin = ', bin, '   up = ', str(sigma_up.GetBinContent(bin + 1))
    for bin in range(len(dn_list)):
        sigma_dn.SetBinContent(bin + 1, -dn_list[bin])
        print 'bin = ', bin, '   down = ', str(sigma_dn.GetBinContent(bin + 1))

    print "Saving ratios for each systematic contribution bin per bin into root file ..."
    outFile_DATA = TFile.Open("RatioHisto_PROVA_" + period + ".root",
                              "RECREATE")
    outFile_DATA.cd()
    sigma_jesUp.Write()
    sigma_jesDn.Write()
    sigma_jerUp.Write()
    sigma_jerDn.Write()
    sigma_puUp.Write()
    sigma_puDn.Write()
    sigma_metUp.Write()
    sigma_metDn.Write()
    outFile_DATA.Close()

    for bin in range(Ratio.GetSize() - 2):
        temp = Ratio.GetBinContent(bin + 1)
        Ratio.SetBinContent(bin + 1, temp - 1)
    for bin in range(Ratio_W.GetSize() - 2):
        temp = Ratio_W.GetBinContent(bin + 1)
        Ratio_W.SetBinContent(bin + 1, temp - 1)

    sigma_up.SetFillColor(ROOT.kGray)
    sigma_up.SetLineColor(ROOT.kGray)
    sigma_up.SetMaximum(2.0)
    sigma_up.SetMinimum(-2.0)
    sigma_up.GetXaxis().SetTitle(xaxis_title)
    sigma_up.GetYaxis().SetTitle("(Data/MC)-1")
    sigma_up.GetYaxis().SetTitleOffset(0.6)
    sigma_up.Draw("HIST")
    sigma_up.GetXaxis().SetLabelSize(0.07)
    sigma_up.GetXaxis().SetTitleSize(0.07)
    sigma_up.GetYaxis().SetLabelSize(0.07)
    sigma_up.GetYaxis().SetTitleSize(0.07)

    sigma_dn.SetFillColor(ROOT.kGray)
    sigma_dn.SetLineColor(ROOT.kGray)
    sigma_dn.Draw("HIST SAME")

    gPad.RedrawAxis()

    Ratio.SetMarkerStyle(20)
    Ratio.SetMarkerColor(kOrange + 1)
    Ratio.SetMarkerSize(0.6)
    Ratio.Draw("p E1 X0 SAME")

    Ratio_W.SetMarkerStyle(23)
    Ratio_W.SetMarkerSize(0.9)
    Ratio_W.SetMarkerColor(kAzure)
    Ratio_W.Draw("p E1 X0 SAME")

    pad1.cd()
    leg = TLegend(.75, .3, .85, .75)
    leg.SetBorderSize(0)
    leg.SetFillColor(0)
    leg.SetFillStyle(0)
    leg.SetTextFont(42)
    leg.SetTextSize(0.07)
    #leg.AddEntry(MC, "Z/t#bar{t} + jets", "f" )
    leg.AddEntry(MC, "DY + t#bar{t}  MC", "f")
    leg.AddEntry(data, "Data", "p")
    leg.AddEntry(MC_NvtxWEIGHT, "MC reweighted", "p")
    leg.AddEntry(sigma_up, "Tot uncertainty", "f")
    leg.Draw()

    #draw CMS and lumi text
    CMS_lumi.writeExtraText = True
    CMS_lumi.extraText = "Preliminary"
    CMS_lumi.lumi_sqrtS = lumiText + " (13 TeV)"
    CMS_lumi.cmsTextSize = 0.6
    CMS_lumi.lumiTextSize = 0.46
    CMS_lumi.extraOverCmsTextSize = 0.75
    CMS_lumi.relPosX = 0.12
    CMS_lumi.CMS_lumi(pad1, 0, 0)
    c.Update()

    c.SaveAs(name + ".pdf")
    c.SaveAs(name + ".png")

    c.Clear()
예제 #11
0
leg = TLegend(.55,.2,.93,.4)
try: leg.AddEntry(hists['Low'], 'Low', "l")
except: pass
try: leg.AddEntry(hists['Med'], 'Med', "l")
except: pass
try: leg.AddEntry(hists['800'], '800', "l")
except: pass
try: leg.AddEntry(hists['1000'], '1000', "l")
except: pass
try: leg.AddEntry(hists['2000'], '2000', "l")
except: pass
try: leg.AddEntry(hists['3000'], '3000', "l")
except: pass
leg.SetShadowColor(0)
leg.SetFillColor(0)
leg.SetLineColor(0)
leg.SetNColumns(2)
leg.Draw() 

canv.SaveAs('ROCscan19vars.png')

canvrel = TCanvas("canvrel","relROCs", 1000, 800)
#canvrel.SetLogy()
canvrel.SetBottomMargin(0.15)
canvrel.SetRightMargin(0.06)
relhists['Low'].GetXaxis().LabelsOption("u")
relhists['Low'].GetXaxis().SetLabelSize(0.05)
relhists['Low'].GetYaxis().SetRangeUser(0.7,1.0)
relhists['Low'].GetXaxis().SetTitle('N_{variables}')
relhists['Low'].GetYaxis().SetTitle('relative ROC-integral')
예제 #12
0
파일: compare.py 프로젝트: zhixing1996/dhad
def kkmass1(opts, args, figname):
    parsed = parse_args(args)
    datatype = parsed[0]
    tag = parsed[1]
    modes = parsed[2]
    label = parsed[3]

    mode = modes[0]
    modekey = tools.get_modekey(mode)

    binbase = parse_opts_set(opts.set, 'binbase')
    binwidth = parse_opts_set(opts.set, 'binwidth')
    numbins = parse_opts_set(opts.set, 'numbins')
    nohtml = parse_opts_set(opts.set, 'nohtml')

    if nohtml == None:
        outputhtml = True
    else:
        outputhtml = False

    dbfile = os.path.join(attr.figpath, label, figname + '.db')

    alldata, fullrangemc = get_fullrange_data_mc(opts, dbfile, label, 'kkmass',
                                                 modekey, tag, binbase,
                                                 binwidth, numbins)

    fullrangedata = {}
    init_dict(fullrangedata)

    evtpath = os.path.join(attr.datpath, 'sel', label, 'kkmass')
    evtfilemc = tools.set_file('evt',
                               'signal',
                               modekey,
                               tag,
                               prefix='',
                               forceCombine=1,
                               extbase=evtpath)

    for i in xrange(numbins):
        lowmass = binbase + i * binwidth
        highmass = binbase + (i + 1) * binwidth
        prefix = 'dir_%s/kkmass/%s_%s' % (label, lowmass, highmass)
        datafile = tools.set_file('txt',
                                  'data',
                                  modekey,
                                  tag,
                                  prefix=prefix,
                                  extbase=attr.fitpath)

        if os.access(datafile, os.F_OK):
            parsefile(datafile, lowmass, highmass, fullrangedata)

        else:
            sys.stdout.write('Skipped %s %s ...\n' % (lowmass, highmass))

    scaledict(fullrangedata, 1 / sumdict(fullrangedata))

    scaledict(fullrangemc, 1 / sumdict(fullrangemc))

    gdata = TGraphAsymmErrors(len(fullrangedata['x']),
                              getarray('x', fullrangedata),
                              getarray('y', fullrangedata),
                              getarray('exl', fullrangedata),
                              getarray('exh', fullrangedata),
                              getarray('eyl', fullrangedata),
                              getarray('eyh', fullrangedata))

    gmc = TGraph(len(fullrangemc['x']), getarray('x', fullrangemc),
                 getarray('y', fullrangemc))

    c1 = TCanvas('c', 'kk', 600, 600)
    c1.SetLeftMargin(0.15)
    c1.SetRightMargin(0.05)
    c1.SetBottomMargin(0.15)
    c1.SetTopMargin(0.05)
    #hr = c1.DrawFrame(0.5, 0.0, 1.5, 0.04)
    hr = c1.DrawFrame(0.9, 0.0, 1.8, 0.1)
    hr.GetYaxis().SetTitle('Yield (arbitrary units)')
    hr.GetXaxis().SetTitle('M(K^{-} #pi^{+}) (GeV/#font[72]{c}^{2})')
    hr.GetYaxis().SetTitleOffset(1.4)
    hr.GetYaxis().SetTitleSize(0.05)
    hr.GetXaxis().SetTitleOffset(1.3)
    hr.GetXaxis().SetTitleSize(0.05)
    gmc.SetMarkerStyle(21)
    gmc.SetMarkerColor(kRed)
    gmc.SetMarkerSize(0.6)
    gmc.SetLineColor(kRed)
    gmc.Draw("PL")
    gdata.SetMarkerStyle(20)
    gdata.SetMarkerColor(kBlue)
    gdata.SetMarkerSize(0.6)
    gdata.Draw("P")
    leg = TLegend(0.6, 0.75, 0.92, 0.92)
    leg.AddEntry(gdata, 'Data', 'pl')
    leg.AddEntry(gmc, 'MC', 'pl')
    leg.SetFillColor(0)
    leg.SetBorderSize(0)
    leg.Draw()
    canvas_output(c1, figname, label, opts.test, outputhtml=outputhtml)
예제 #13
0
def plot_BDT(channel, var, massPoint, bin, low, high, ylabel, xlabel, save, nBtags = -1, setLog = False, finalcuts = False):

    if (channel == 'electron'):      
        cut = 'jet_0_pt_WprimeCalc >= 120 && jet_1_pt_WprimeCalc >= 40 && elec_1_pt_WprimeCalc > 32 && abs(elec_1_eta_WprimeCalc) < 2.5 && elec_1_RelIso_WprimeCalc < 0.1 && corr_met_WprimeCalc > 20' 
        #cut = 'jet_0_pt_WprimeCalc >= 100 && jet_1_pt_WprimeCalc >= 40 && elec_1_pt_WprimeCalc > 30 && abs(elec_1_eta_WprimeCalc) < 2.5 && elec_1_RelIso_WprimeCalc < 0.1 && corr_met_WprimeCalc > 35' 

    if (channel == 'muon'):      
        cut = 'jet_0_pt_WprimeCalc >= 120 && jet_1_pt_WprimeCalc >= 40 && muon_1_pt_WprimeCalc > 26 && abs(muon_1_eta_WprimeCalc) < 2.1 && muon_1_RelIso_WprimeCalc < 0.12 && corr_met_WprimeCalc > 20'
        #cut = 'jet_0_pt_WprimeCalc >= 100 && jet_1_pt_WprimeCalc >= 40 && muon_1_pt_WprimeCalc > 26 && abs(muon_1_eta_WprimeCalc) < 2.1 && muon_1_RelIso_WprimeCalc < 0.12 && corr_met_WprimeCalc > 35' 


    if finalcuts: cut+= '&& BestTop_LjetsTopoCalcNew > 130 && BestTop_LjetsTopoCalcNew < 210 &&  BestTop_Pt_LjetsTopoCalcNew > 75  && Jet1Jet2_Pt_LjetsTopoCalcNew > 100'   
    njets = ""

    if nBtags == -1:
        cutbtag = ''
        save = save     
    if nBtags == 0:
        cutbtag =  ' && ( (jet_0_tag_WprimeCalc + jet_1_tag_WprimeCalc + jet_2_tag_WprimeCalc + jet_3_tag_WprimeCalc + jet_4_tag_WprimeCalc + jet_5_tag_WprimeCalc + jet_6_tag_WprimeCalc + jet_7_tag_WprimeCalc + jet_8_tag_WprimeCalc + jet_9_tag_WprimeCalc) == 0 )'
        save = save + '_0bTags'
        njets = "N_{b tags} = 0"
    if nBtags == 1:
        cutbtag =  ' && ( (jet_0_tag_WprimeCalc + jet_1_tag_WprimeCalc) == 1)'
        save = save + '_1bTags'
        njets = "N_{b tags} = 1"
    if nBtags == 2:
        cutbtag =  ' && ( (jet_0_tag_WprimeCalc + jet_1_tag_WprimeCalc) >= 1 ) '
        save = save + '_GE1bTags'
        njets = "N_{b tags} #geq 1"


    cutwbb = ' && n_Bjets_WprimeCalc > 0' # Wb(b)
    cutwcc = ' && n_Bjets_WprimeCalc==0 && n_Cjets_WprimeCalc>0' # Wc(c)
    cutwjj = ' && n_Bjets_WprimeCalc==0 && n_Cjets_WprimeCalc==0' # W+light
    #cutwbb = ' ' # Wb(b)
    #cutwcc = ' ' # Wc(c)
    #cutwjj = ' ' # W+light
                                                                                                                   
    SFWjmu = 1.08*0.85
    SFWcmu = 1.06*0.92*1.66
    SFWbmu = 1.06*0.92*1.21
    #SFWjmu = 1.0
    #SFWcmu = 1.0
    #SFWbmu = 1.0

    WjjHist = TH1D('WjjHist', 'WjjHist', bin,low,high)
    WccHist = TH1D('WccHist', 'WccHist', bin,low,high)
    WbbHist = TH1D('WbbHist', 'WbbHist', bin,low,high)

    Variables = {}
    efficiency = {}
   
    BkgList = []

    for Type in Samples:

        #print channel,' ',Type

        if (Type.endswith('_el') and channel == 'muon'): continue
        if (Type.endswith('_mu') and channel == 'electron'): continue
        if (not Type.startswith(massPoint) ): continue

        Variables[Type] = TH1D(Type+var+channel, Type+var+channel, bin, low, high)
        histName = Type+var+channel
     
        if (channel == 'electron'): chan = '_el'
        if (channel == 'muon'): chan = '_mu'

        if (channel == 'electron'): weight = 'weight_PU_ABC_PileUpCalc*weight_ElectronEff_WprimeCalc'
        if (channel == 'muon'): weight = 'weight_PU_ABC_PileUpCalc*weight_MuonEff_WprimeCalc'
        
        if ((not Type == massPoint+massPoint+chan) and (not Type == massPoint+'_data'+chan)): BkgList.extend([Type])

        if Type.endswith('wjets'+chan):
            #print 'Filling ',Type
            Trees[Type].Draw(var + " >> " + histName, "("+weight+")*(" + str(SFWjmu) + ")*(" + cut + cutbtag + cutwjj + ")", 'goff')
            Trees[Type].Draw(var + " >> " + "WbbHist","("+weight+")*(" + str(SFWbmu) + ")*(" + cut + cutbtag + cutwbb + ")", 'goff')
            Trees[Type].Draw(var + " >> " + "WccHist","("+weight+")*(" + str(SFWcmu) + ")*(" + cut + cutbtag + cutwcc + ")", 'goff')
            #print 'Raw Wjj ',Variables['WJets'].Integral()
            Variables[Type].Add(WbbHist)
            #print 'Raw Wjj + Wbb ',Variables['WJets'].Integral()
            Variables[Type].Add(WccHist) 
            #print 'Raw Wjj + Wbb + Wcc',Variables['WJets'].Integral()

        elif Type.endswith('data'+chan):
            #print 'Filling ',Type
            Trees[Type].Draw(var + " >> " + histName, "(" + cut + cutbtag + ")", 'goff')
        else:
            #print 'Filling ',Type
            Trees[Type].Draw(var + " >> " + histName, "("+weight+")*(" + cut + cutbtag + ")", 'goff')
            
        if (not Type.endswith('data'+chan)):

            SF = 1.0
            if (channel == 'electron'):
                lumi = lumi_el
            if (channel == 'muon'):
                lumi = lumi_mu

            if (Type.startswith(massPoint+'_'+massPoint)): SF *= 20
            #print 'EVENTS Before Scaling FOR ',Type,' = ',Variables[Type].Integral()
            #print 'Pre Events before scaling for ',Type,' = ',VariablesPre[Type].Integral()
            #print str(SF),' ',str(lumi),' ',str(xsec_norm[Type]),' ',str(Nevents[Type])

            if Variables[Type].Integral() != 0:
                #print Type,' Lumi scaling: ',str(SF*lumi*xsec[Type]/Nevents[Type])
                Variables[Type].Scale ( SF*Yield[Type]/Variables[Type].Integral() ) 
                efficiency[Type] = Variables[Type].Integral()/Nevents[Type]
            else:
                efficiency[Type] = 0

    
    Variables[massPoint+'_ttbar'+chan].SetFillColor(ROOT.kRed-7)
    Variables[massPoint+'_s'+chan].SetFillColor(ROOT.kRed-7)
    Variables[massPoint+'_bs'+chan].SetFillColor(ROOT.kRed-7)
    Variables[massPoint+'_t'+chan].SetFillColor(ROOT.kRed-7)
    Variables[massPoint+'_bt'+chan].SetFillColor(ROOT.kRed-7)
    Variables[massPoint+'_tw'+chan].SetFillColor(ROOT.kRed-7)
    Variables[massPoint+'_btw'+chan].SetFillColor(ROOT.kRed-7)

    Variables[massPoint+'_s'+chan].SetLineColor(ROOT.kRed-7)
    Variables[massPoint+'_bs'+chan].SetLineColor(ROOT.kRed-7)
    Variables[massPoint+'_t'+chan].SetLineColor(ROOT.kRed-7)
    Variables[massPoint+'_bt'+chan].SetLineColor(ROOT.kRed-7)
    Variables[massPoint+'_tw'+chan].SetLineColor(ROOT.kRed-7)
    Variables[massPoint+'_btw'+chan].SetLineColor(ROOT.kRed-7)

    Variables[massPoint+'_wjets'+chan].SetFillColor(ROOT.kGreen-3)
    Variables[massPoint+'_zjets'+chan].SetFillColor(ROOT.kGreen-3)
    Variables[massPoint+'_ww'+chan].SetFillColor(ROOT.kGreen-3)

    Variables[massPoint+'_zjets'+chan].SetLineColor(ROOT.kGreen-3)
    Variables[massPoint+'_ww'+chan].SetLineColor(ROOT.kGreen-3)
    
    Variables[massPoint+'_ttbar'+chan].SetLineWidth(2)
    Variables[massPoint+'_wjets'+chan].SetLineWidth(2)

    Variables[massPoint+'_'+massPoint+chan].SetLineColor(1)
    Variables[massPoint+'_'+massPoint+chan].SetLineWidth(2)
    Variables[massPoint+'_'+massPoint+chan].SetLineStyle(6)

    stack = THStack('a', 'a')
    added = TH1D('a', 'a',bin,low,high)
    topadded  = TH1D('topadded', 'topadded', bin, low, high)
    wjetsadded = TH1D('wjetsadded', 'wjetsadded',bin,low,high)

    wjetsadded = Variables[massPoint+'_wjets'+chan].Clone()
    wjetsadded.Add(Variables[massPoint+'_ww'+chan])
    wjetsadded.Add(Variables[massPoint+'_zjets'+chan])

    topadded = Variables[massPoint+'_ttbar'+chan].Clone()
    topadded.Add(Variables[massPoint+'_s'+chan])
    topadded.Add(Variables[massPoint+'_bs'+chan])
    topadded.Add(Variables[massPoint+'_t'+chan])
    topadded.Add(Variables[massPoint+'_bt'+chan])
    topadded.Add(Variables[massPoint+'_tw'+chan])
    topadded.Add(Variables[massPoint+'_btw'+chan])

    wjetsadded.SetFillColor(ROOT.kGreen-3)
    wjetsadded.SetLineColor(1)
    wjetsadded.SetLineWidth(2)
    topadded.SetFillColor(ROOT.kRed-7)
    topadded.SetLineColor(1)
    topadded.SetLineWidth(2)

    stack.Add(wjetsadded)
    stack.Add(topadded)
    added.Add(wjetsadded)  
    added.Add(topadded)

    print 'Data: ',Variables[massPoint+'_data'+chan].Integral(),' Background: ',added.Integral(),' Data/Background: ',Variables[massPoint+'_data'+chan].Integral()/added.Integral()

    lumi_error = 0.022
    ttbar_error = 0.15
    wjets_error = 0.20
    other_error = 0.20

    uncert_list = []
    lumiband = added.Clone();
    
    for hbin in range(0,lumiband.GetNbinsX()+1): 

        uncert_lumi = 0 
        uncert_xsec = 0
        uncert_stat = 0
 
        for i in BkgList:

            error = 0
             
            if i in xsec.keys(): 
                if (i.startswith(massPoint+'_t') or i.startswith(massPoint+'_b') or i.startswith(massPoint+'_s')): 
                    error = ttbar_error
                    uncert_lumi += (efficiency[i]*xsec[i])**2 
                    uncert_xsec += (Variables[i].GetBinContent(hbin+1)*error)**2
                    uncert_stat += Variables[i].GetBinError(hbin+1)**2
                elif (i.startswith(massPoint+'_w') or i.startswith(massPoint+'_z')):
                    error = wjets_error
                    uncert_lumi += (efficiency[i]*xsec[i])**2 
                    uncert_xsec += (Variables[i].GetBinContent(hbin+1)*error)**2         
                    uncert_stat += Variables[i].GetBinError(hbin+1)**2

        #print 'uncert_lumi: ',uncert_lumi,' uncert_xsec ',uncert_xsec,' uncert_stat ',uncert_stat
        uncert = sqrt( (lumi_error**2)*uncert_lumi + uncert_xsec + uncert_stat )

        if lumiband.GetBinContent(hbin+1) != 0:
            dummy = 1.0
            #print lumiband.GetBinContent(hbin+1),'+/-',uncert,'(',100*uncert/lumiband.GetBinContent(hbin+1),'%)'
        lumiband.SetBinError(hbin+1,uncert);
        added.SetBinError(hbin+1,uncert);
        uncert_list . append(uncert)
    
    #gStyle.SetHatchesSpacing(2.0);
    gStyle.SetHatchesLineWidth(1);
            
    lumiband.SetFillStyle(3344);
    #lumiband.SetFillStyle(3001);
    lumiband.SetFillColor(1);
      
    legend = TLegend(.60,.70,.90,.90)
    legend . AddEntry( Variables[massPoint+'_data'+chan], 'Data' , "lp")
    legend . AddEntry( Variables[massPoint+'_ttbar'+chan], "t#bar{t} + Single-Top", "f")
    legend . AddEntry( Variables[massPoint+'_wjets'+chan], "W#rightarrowl#nu + Z/#gamma*#rightarrowl^{+}l^{-} + VV" , "f")
 
    if (massPoint.endswith('R')): coupling = 'R'
    if (massPoint.endswith('L')): coupling = 'L'
    if (massPoint.endswith('RL')): coupling = 'RL'

    massval = copy.copy(massPoint)
    massval = massval.lstrip('wp')
    massval = massval.rstrip('00'+coupling)
    if (len(massval)==1): massval = '0'+massval
    massval = massval[0]+'.'+massval[1]

    legend . AddEntry( Variables[massPoint+'_'+massPoint+chan], "W'_{"+coupling+"} x 20, m="+massval+" TeV", "l")
    legend . AddEntry( lumiband , "Uncertainty" , "f")

    c4 = TCanvas("c4","c4", 1000, 800)
    
    c4.SetBottomMargin(0.3)
    c4.SetRightMargin(0.06)
    stack.SetMaximum( 2*stack.GetMaximum() ) 
    if setLog:
        c4.SetLogy()
        stack.SetMaximum( stack.GetMaximum()  +  30*stack.GetMaximum() ) 

    stack.SetMinimum(0.1 )
    #stack.SetMarkerSize(0)
    stack.Draw("") 
    stack.GetYaxis().CenterTitle() 
    stack.GetYaxis().SetTitle(ylabel)
    stack.GetXaxis().SetLabelSize(0)
    #stack.GetXaxis().SetTitle(xlabel)
    lumiband.Draw("samee2")
    #lumiband.Draw("esame")
    
    legend.SetShadowColor(0);
    legend.SetFillColor(0);
    legend.SetLineColor(0);
    legend.Draw("same")    

    if (Variables[massPoint+'_data'+chan].GetBinContent(bin+1)>0):
        print "Overflow for ",massPoint+"_"+channel," data "
    Variables[massPoint+'_data'+chan].SetMarkerStyle(20)
    Variables[massPoint+'_data'+chan].Draw('SAMES:E1')
 
    Variables[massPoint+'_'+massPoint+chan].Draw("same")

    latex2 = TLatex()
    latex2.SetNDC()
    latex2.SetTextSize(0.04)
    latex2.SetTextAlign(31) # align right
    if channel == ('electron'): 
        latex2.DrawLatex(0.87, 0.95, "CMS Preliminary, "+lumiPlot_el+" fb^{-1} at #sqrt{s} = 8 TeV");
    if channel == ('muon'): 
        latex2.DrawLatex(0.87, 0.95, "CMS Preliminary, "+lumiPlot_mu+" fb^{-1} at #sqrt{s} = 8 TeV");

    latex3 = TLatex()
    latex3.SetNDC()
    latex3.SetTextSize(0.04)
    latex3.SetTextAlign(31) # align right

    if (channel == 'electron'):
        latex3.DrawLatex(0.47, 0.85, "e+jets " + njets);   
    if (channel == 'muon'):
        latex3.DrawLatex(0.47, 0.85, "#mu+jets " + njets);   
 
    latex4 = TLatex()
    latex4.SetNDC()
    latex4.SetTextSize(0.03)
    latex4.SetTextAlign(22) # align right
    latex4.SetTextAngle(90) # align right
    #latex4.DrawLatex(0.905, 0.56, "overflow")
    
    Pull  = TH1D('Pull', 'Pull', bin, low, high)  
    Pull = Variables[massPoint+'_data'+chan].Clone();
    Pull.Add(added,-1)
    Pull.Divide(added)

    for i in range(bin):
        i += 1
        #print i+1,' ',added.GetBinContent(i+1)
        if (Pull.GetBinContent(i+1) != 0 and Pull.GetBinError(i+1) != 0):
            Pull.SetBinContent(i+1,Pull.GetBinContent(i+1)/Pull.GetBinError(i+1))
        else: Pull.SetBinContent(i+1,0)

    pad = TPad("pad", "pad", 0.0, 0.0, 1.0, 1.0)
    pad.SetTopMargin(0.7)
    pad.SetFillColor(0)
    pad.SetGridy(1)
    pad.SetFillStyle(0)
    pad.Draw()
    pad.cd(0)
    pad.SetRightMargin(0.06)

    Pull.SetMarkerStyle(20)
    Pull.SetMaximum(3.0 )
    Pull.SetMinimum(-3.0)
    Pull.SetFillColor(2)
    Pull.GetXaxis().SetTitle(xlabel)
    Pull.GetYaxis().SetTitleSize(0.04)
    Pull.GetYaxis().SetTitle('#sigma(Data-MC)')
    Pull.SetMarkerSize(0.7)
    Pull.GetYaxis().SetNdivisions(5);
    Pull.Draw("HIST")
    
    c4.SaveAs('Wprime_Plots/StackedHisto_' + save + '.pdf')
      
    del c4
    #del pad
    del stack
    del Variables
예제 #14
0
def DrawOverlap(fileVec, histVec, titleVec,legendtext,pngname,logstatus=[0,0],xRange=[-99999,99999,1]):

    gStyle.SetOptTitle(0)
    gStyle.SetOptStat(0)
    gStyle.SetTitleOffset(1.1,"Y");
    gStyle.SetTitleOffset(0.9,"X");
    gStyle.SetLineWidth(3)
    gStyle.SetFrameLineWidth(3); 

    i=0

    histList_=[]
    histList=[]
    histList1=[]
    maximum=[]
    
    ## Legend    
    leg = TLegend(0.4, 0.70, 0.939, 0.89)#,NULL,"brNDC");
    leg.SetBorderSize(0)
    leg.SetNColumns(2)
    leg.SetLineColor(1)
    leg.SetLineStyle(1)
    leg.SetLineWidth(1)
    leg.SetFillColor(0)
    leg.SetFillStyle(0)
    leg.SetTextFont(22)
    leg.SetTextSize(0.045)
     
    c = TCanvas("c1", "c1",0,0,500,500)
    #c.SetBottomMargin(0.15)
    #c.SetLeftMargin(0.15)
    #c.SetLogy(0)
    #c.SetLogx(0)
    c1_2 = TPad("c1_2","newpad",0.04,0.05,1,0.994)
    c1_2.Draw()

    
    print ("you have provided "+str(len(fileVec))+" files and "+str(len(histVec))+" histograms to make a overlapping plot" )
    print "opening rootfiles"
    c.cd()
    #c1_2.SetBottomMargin(0.13)
    c1_2.SetLogy(logstatus[1])
    c1_2.SetLogx(logstatus[0])
    
    
    c1_2.cd()
    ii=0    
    inputfile={}
    print str(fileVec[(len(fileVec)-1)])

    for ifile_ in range(len(fileVec)):
        print ("opening file  "+fileVec[ifile_])
        inputfile[ifile_] = TFile( fileVec[ifile_] )
        print "fetching histograms"
        for ihisto_ in range(len(histVec)):
            print ("printing histo "+str(histVec[ihisto_]))
            histo = inputfile[ifile_].Get(histVec[ihisto_])
            #status_ = type(histo) is TGraphAsymmErrors
            histList.append(histo)
            # for ratio plot as they should nt be normalize 
            histList1.append(histo)
            print histList[ii].Integral()
            #histList[ii].Rebin(xRange[2])
            type_obj = type(histList[ii])
            if (type_obj is TH1D) or (type_obj is TH1F) or (type_obj is TH1) or (type_obj is TH1I) :
                histList[ii].Rebin(1)
                histList[ii].Scale(1.0/histList[ii].Integral())
                maximum.append(histList[ii].GetMaximum())
                maximum.sort()
            ii=ii+1

    print histList
    for ih in range(len(histList)):
        tt = type(histList[ih])
#        print "graph_status =" ,(tt is TGraphAsymmErrors)
#        print "hist status =", (tt is TH1D) or (tt is TH1F)
        if ih == 0 :      
            if (tt is TGraphAsymmErrors) | (tt is TGraph) : 
                histList[ih].Draw("A3P")
            if (tt is TH1D) or (tt is TH1F) or (tt is TH1) or (tt is TH1I) :
                histList[ih].Draw("HIST")   
        if ih > 0 :
            #histList[ih].SetLineWidth(2)
            if (tt is TGraphAsymmErrors) | (tt is TGraph) : 
                histList[ih].Draw("3P same")
            if (tt is TH1D) or (tt is TH1F) or (tt is TH1) or (tt is TH1I) :
                histList[ih].Draw("HISTsame")   

        if (tt is TGraphAsymmErrors) | (tt is TGraph) :
           # histList[ih].SetMaximum(0.06) 
           # histList[ih].SetMinimum(0.02) 

            histList[ih].SetMaximum(maximum+0.3) 
            histList[ih].SetMinimum(0) 
            histList[ih].SetMarkerColor(colors[ih])
            histList[ih].SetLineColor(colors[ih])
            histList[ih].SetLineWidth(3)
            histList[ih].SetLineStyle(linestyle[ih])
            
            histList[ih].SetMarkerStyle(markerStyle[ih])
            histList[ih].SetMarkerSize(1)
            leg.AddEntry(histList[ih],legendtext[ih],"P")
        if (tt is TH1D) or (tt is TH1F) or (tt is TH1) or (tt is TH1I) :
            histList[ih].SetLineStyle(linestyle[ih])
            histList[ih].SetLineColor(colors[ih])
            histList[ih].SetLineWidth(3)
            histList[ih].SetMaximum(maximum[0]+0.3) 
            histList[ih].SetMinimum(0) 
            leg.AddEntry(histList[ih],legendtext[ih],"L")
        histList[ih].GetYaxis().SetTitle(titleVec[1])
        histList[ih].GetYaxis().SetTitleSize(0.045)
        histList[ih].GetYaxis().SetTitleOffset(1.1000998)
        histList[ih].GetYaxis().SetTitleFont(22)
        histList[ih].GetYaxis().SetLabelFont(22)
        histList[ih].GetYaxis().SetLabelSize(.045)
        histList[ih].GetXaxis().SetRangeUser(xRange[0],xRange[1])
        histList[ih].GetXaxis().SetLabelSize(0.0000);
        histList[ih].GetXaxis().SetTitle(titleVec[0])
        histList[ih].GetXaxis().SetLabelSize(0.052)
        histList[ih].GetXaxis().SetTitleSize(0.052)
        histList[ih].GetXaxis().SetTitleOffset(1.04)
        histList[ih].GetXaxis().SetTitleFont(22)
        histList[ih].GetXaxis().SetTickLength(0.07)
        histList[ih].GetXaxis().SetLabelFont(22)
        histList[ih].GetYaxis().SetLabelFont(22) 
# histList[ih].GetXaxis().SetNdivisions(508)
#

        i=i+1
    pt = TPaveText(0.0877181,0.9,0.9580537,0.96,"brNDC")
    pt.SetBorderSize(0)
    pt.SetTextAlign(12)
    pt.SetFillStyle(0)
    pt.SetTextFont(22)
    pt.SetTextSize(0.046)
    text = pt.AddText(0.05,0.5,"CMS Preliminary")
    #text = pt.AddText(0.5,0.5,"12.9 fb^{-1} (13 TeV)")
#    text = pt.AddText(0.8,0.5," (13 TeV)")
 #   text = pt.AddText(0.65,0.5," AK8")
    pt.Draw()
   
    

#    t2a = TPaveText(0.0877181,0.81,0.9580537,0.89,"brNDC")
#    t2a.SetBorderSize(0)
#    t2a.SetFillStyle(0)
#    t2a.SetTextSize(0.040) 
#    t2a.SetTextAlign(12)
#    t2a.SetTextFont(62)
#    histolabel1= str(fileVec[(len(fileVec)-1)])
#    text1 = t2a.AddText(0.06,0.5,"CMS Internal") 
#    t2a.Draw()
    leg.Draw()
#
#    c.cd()
    outputdirname = 'HGCAL/'
    histname=outputdirname+pngname 
    c.SaveAs(histname+'.png')
    c.SaveAs(histname+'.pdf')
hist_itpulses.Draw("SAME")

hist_ittrigger.SetTitle("Triggers, IceTop and uncleaned InIce pulses")
hist_ittrigger.GetYaxis().SetTitle("For pulses: number of pulses")
hist_ittrigger.GetXaxis().SetTitle("time [ns]")

hist_ittrigger.GetYaxis().SetRangeUser(
    0,
    np.amax([hist_itpulses.GetMaximum(),
             hist_iipulses.GetMaximum()]) + 10)
leg = TLegend(0.7, 0.7, 0.89, 0.89)
leg.AddEntry(hist_ittrigger, "IT SMT", "l")
leg.AddEntry(hist_iitrigger, "II SMT", "l")
leg.AddEntry(hist_itpulses, "IT pulses", "l")
leg.AddEntry(hist_iipulses, "II pulses", "l")
leg.SetFillColor(10)
leg.SetBorderSize(0)
leg.Draw("SAME")

canv.cd(2)
gStyle.SetOptStat(0)
hist_iitrigger.Draw("")
hist_ittrigger.Draw("SAME")
hist_itpulses.Draw("SAME")
hist_coincpulses.Draw("SAME")

hist_iitrigger.SetTitle("Triggers, IceTop and selected InIce pulses")
hist_iitrigger.GetYaxis().SetTitle("For pulses: number of pulses")
hist_iitrigger.GetXaxis().SetTitle("time [ns]")
hist_iitrigger.GetYaxis().SetRangeUser(
    0,
예제 #16
0
    h2.SetLineColor(2)
    h2.SetFillColor(2)
    h2.SetLineStyle(9)
    h2.SetMarkerColor(2)

    h2.SetBarWidth(0.4)
    h2.SetBarOffset(0.55)
    h2.Draw("bar2same")
    #h2.Draw("TEXT45same");

    # Draw the legend
    infoBox = TLegend(0.65, 0.82, 0.95, 0.92, "")
    if (tree["Entries"] > 0.):
        infoBox.AddEntry(
            h1, "New LA: %.5s kB/entry" %
            str(float(tree["Size"]) / float(1024 * tree["Entries"])), "F")
        infoBox.AddEntry(
            h2, "original:  %.5s kB/entry" %
            str(float(tree2["Size"]) / float(1024 * tree2["Entries"])), "F")
    infoBox.SetShadowColor(0)
    # 0 = transparent
    infoBox.SetFillColor(0)
    infoBox.Draw("same")

    #h1.Draw("BAR")
    c1.Update()
    c1.SaveAs(tree["Name"].replace('/', '_') + ".png")
    c1.SaveAs(tree["Name"].replace('/', '_') + ".pdf")

#pprint(data)
예제 #17
0
def setPUHistogram(l):
    # https://raw.githubusercontent.com/cms-sw/cmssw/CMSSW_7_4_X/SimGeneral/MixingModule/python/mix_2015_25ns_Startup_PoissonOOTPU_cfi.py
    probValue = [
        4.8551E-07, 1.74806E-06, 3.30868E-06, 1.62972E-05, 4.95667E-05,
        0.000606966, 0.003307249, 0.010340741, 0.022852296, 0.041948781,
        0.058609363, 0.067475755, 0.072817826, 0.075931405, 0.076782504,
        0.076202319, 0.074502547, 0.072355135, 0.069642102, 0.064920999,
        0.05725576, 0.047289348, 0.036528446, 0.026376131, 0.017806872,
        0.011249422, 0.006643385, 0.003662904, 0.001899681, 0.00095614,
        0.00050028, 0.000297353, 0.000208717, 0.000165856, 0.000139974,
        0.000120481, 0.000103826, 8.88868E-05, 7.53323E-05, 6.30863E-05,
        5.21356E-05, 4.24754E-05, 3.40876E-05, 2.69282E-05, 2.09267E-05,
        1.5989E-05, 4.8551E-06, 2.42755E-06, 4.8551E-07, 2.42755E-07,
        1.21378E-07, 4.8551E-08
    ]
    mc = TH1F("mc", "nPV distribution", 50, 0, 50)
    mc.Sumw2()
    for i in range(50):
        mc.SetBinContent(i + 1, probValue[i])
    mc.SetLineWidth(3)
    mc.SetLineColor(1)
    mc.SetLineStyle(2)
    mc.Scale(1. / mc.Integral())

    puFile = TFile("./PU/PU_%s_69000.root" % l, "READ")
    data = puFile.Get("pileup")
    data.SetLineWidth(3)
    data.SetLineColor(1)
    data.Scale(1. / data.Integral())

    puUpFile = TFile("./PU/PU_%s_72450.root" % l, "READ")
    dataUp = puUpFile.Get("pileup")
    dataUp.SetLineWidth(3)
    dataUp.SetLineColor(634)
    dataUp.Scale(1. / dataUp.Integral())

    puDownFile = TFile("./PU/PU_%s_65550.root" % l, "READ")
    dataDown = puDownFile.Get("pileup")
    dataDown.SetLineWidth(3)
    dataDown.SetLineColor(598)
    dataDown.Scale(1. / dataDown.Integral())

    ratio = data.Clone("ratio")
    ratioUp = dataUp.Clone("ratioUp")
    ratioDown = dataDown.Clone("ratioDown")

    ratio.Divide(mc)
    ratioUp.Divide(mc)
    ratioDown.Divide(mc)

    outFile = TFile("./PU/PU_%s.root" % l, "RECREATE")
    outFile.cd()
    mc.Write()
    data.Write()
    dataUp.Write()
    dataDown.Write()
    ratio.Write()
    ratioUp.Write()
    ratioDown.Write()
    outFile.Close()
    print "Histograms written to ./PU/PU_%s.root file" % l

    leg = TLegend(0.65, 0.7, 0.98, 0.9)
    leg.SetBorderSize(0)
    leg.SetFillStyle(0)  #1001
    leg.SetFillColor(0)
    leg.SetHeader("pile-up reweighting")
    leg.AddEntry(dataUp, "Up", "pl")
    leg.AddEntry(data, "Central", "pl")
    leg.AddEntry(dataDown, "Down", "pl")
    leg.AddEntry(mc, "MC 25ns", "pl")

    c1 = TCanvas("c1", "PileUp reweighting", 800, 800)
    c1.cd()
    c1.GetPad(0).SetTopMargin(0.06)
    c1.GetPad(0).SetRightMargin(0.05)
    c1.GetPad(0).SetTicks(1, 1)
    dataDown.SetTitle(";number of true interactions")
    dataDown.GetXaxis().SetRangeUser(0., 30)
    dataDown.Draw("HIST")
    dataUp.Draw("SAME, HIST")
    data.Draw("SAME, HIST")
    mc.Draw("SAME, L")
    leg.Draw()
    c1.Print("PU/PU_%s.pdf" % l)
    c1.Print("PU/PU_%s.png" % l)
예제 #18
0
class DataMCPlot(object):

    '''Handles a Data vs MC plot.

    Features a list of histograms (some of them being stacked),
    and several Drawing functions.
    '''
    _f_keeper = {}
    _t_keeper = {}

    def __init__(self, name):
        self.histosDict = {}
        self.histos = []
        self.supportHist = None
        self.name = name
        self.stack = None
        self.legendOn = True
        self.legend = None
        self.legendBorders = 0.20, 0.46, 0.44, 0.89
        self.legendPos = 'left'
        # self.lastDraw = None
        # self.lastDrawArgs = None
        self.nostack = None
        self.blindminx = None
        self.blindmaxx = None
        self.groups = {}
        self.axisWasSet = False
        self.histPref = histPref

    def __contains__(self, name):
        return name in self.histosDict

    def __getitem__(self, name):
        return self.histosDict[name]

    def readTree(self, file_name, tree_name='tree', verbose=False):
        '''Cache files/trees'''
        if file_name in self.__class__._t_keeper:
            ttree = self.__class__._t_keeper[file_name]
            if verbose:
                print 'got cached tree', ttree
        else:
            tfile = self.__class__._f_keeper[file_name] = TFile.Open(file_name)
            ttree = self.__class__._t_keeper[file_name] = tfile.Get(tree_name)
            if verbose:
                print 'read tree', ttree, 'from file', file_name

        gROOT.cd()

        return ttree

    def Blind(self, minx, maxx, blindStack):
        self.blindminx = minx
        self.blindmaxx = maxx
        if self.stack and blindStack:
            self.stack.Blind(minx, maxx)
        if self.nostack:
            for hist in self.nostack:
                hist.Blind(minx, maxx)

    def AddHistogram(self, name, histo, layer=0, legendLine=None, stack=True):
        '''Add a ROOT histogram, with a given name.

        Histograms will be drawn by increasing layer.'''
        tmp = Histogram(name, histo, layer, legendLine, stack=stack)
        self.histos.append(tmp)
        self.histosDict[name] = tmp
        return tmp

    def Group(self, groupName, namesToGroup, layer=None, style=None):
        '''Group all histos with names in namesToGroup into a single
        histo with name groupName. All histogram properties are taken
        from the first histogram in namesToGroup.
        See UnGroup as well
        '''
        groupHist = None
        realNames = []
        actualNamesInGroup = []
        for name in namesToGroup:
            hist = self.histosDict.get(name, None)
            if hist is None:
                print 'warning, no histo with name', name
                continue
            if groupHist is None:
                groupHist = hist.Clone(groupName)
                self.histos.append(groupHist)
                self.histosDict[groupName] = groupHist
            else:
                groupHist.Add(hist)
            actualNamesInGroup.append(name)
            realNames.append(hist.realName)
            hist.on = False
        if groupHist:
            self.groups[groupName] = actualNamesInGroup
            groupHist.realName = ','.join(realNames)
            if style is not None:
                groupHist.SetStyle(style)
            self._ApplyPrefs()

    def UnGroup(self, groupName):
        '''Ungroup groupName, recover the histograms in the group'''
        group = self.groups.get(groupName, None)
        if group is None:
            print groupName, 'is not a group in this plot.'
            return
        for name in group:
            self.histosDict[name].on = True
        self.histosDict[groupName].on = False

    def Replace(self, name, pyhist):
        '''Not very elegant... should have a clone function in Histogram...'''
        oldh = self.histosDict.get(name, None)
        if oldh is None:
            print 'histogram', name, 'does not exist, cannot replace it.'
            return

        pythist = copy.deepcopy(pyhist)
        pythist.layer = oldh.layer
        pythist.stack = oldh.stack
        pythist.name = oldh.name
        pythist.legendLine = oldh.legendLine
        pythist.SetStyle(oldh.style)
        pythist.weighted.SetFillStyle(oldh.weighted.GetFillStyle())

        index = self.histos.index(oldh)
        self.histosDict[name] = pythist
        self.histos[index] = pythist

    def _SortedHistograms(self, reverse=False):
        '''Returns the histogram dictionary, sorted by increasing layer,
        excluding histograms which are not "on".

        This function is used in all the Draw functions.'''
        byLayer = sorted(self.histos, key=attrgetter('layer'))
        byLayerOn = [hist for hist in byLayer if (hist.on is True)]
        if reverse:
            byLayerOn.reverse()
        return byLayerOn

    def Hist(self, histName):
        '''Returns a histogram.

        Print the DataMCPlot object to see which histograms are available.'''
        return self.histosDict[histName]

    def DrawNormalized(self, opt=''):
        '''All histograms are drawn as PDFs, even the stacked ones'''
        same = ''
        for hist in self._SortedHistograms():
            hist.obj.DrawNormalized(same + opt)
            if same == '':
                same = 'same'
        self.DrawLegend()
        if TPad.Pad():
            TPad.Pad().Update()
        # self.lastDraw = 'DrawNormalized'
        # self.lastDrawArgs = [ opt ]

    def Draw(self, opt=''):
        '''All histograms are drawn.'''
        same = ''
        self.supportHist = None
        for hist in self._SortedHistograms():
            if self.supportHist is None:
                self.supportHist = hist
            hist.Draw(same + opt)
            if same == '':
                same = 'same'
        yaxis = self.supportHist.GetYaxis()
        yaxis.SetRangeUser(0.01, ymax(self._SortedHistograms()))
        self.DrawLegend()
        if TPad.Pad():
            TPad.Pad().Update()
        # self.lastDraw = 'Draw'
        # self.lastDrawArgs = [ opt ]

    def CreateLegend(self, ratio=False, print_norm=False):
        if self.legend is None:
            self.legend = TLegend(*self.legendBorders)
            self.legend.SetFillColor(0)
            self.legend.SetFillStyle(0)
            self.legend.SetLineColor(0)
        else:
            self.legend.Clear()
        hists = self._SortedHistograms(reverse=True)
        if ratio:
            hists = hists[:-1]  # removing the last histo.
        for index, hist in enumerate(hists):
            if print_norm:
                if not hist.legendLine:
                    hist.legendLine = hist.name
                hist.legendLine += ' ({norm:.1f})'.format(norm=hist.Yield())
            hist.AddEntry(self.legend)

    def DrawLegend(self, ratio=False, print_norm=False):
        '''Draw the legend.'''
        if self.legendOn:
            self.CreateLegend(ratio=ratio, print_norm=print_norm)
            self.legend.Draw('same')

    def DrawRatio(self, opt=''):
        '''Draw ratios : h_i / h_0.

        h_0 is the histogram with the smallest layer, and h_i, i>0 are the other histograms.
        if the DataMCPlot object contains N histograms, N-1 ratio plots will be drawn.
        To take another histogram as the denominator, change the layer of this histogram by doing:
        dataMCPlot.Hist("histName").layer = -99 '''
        same = ''
        denom = None
        self.ratios = []
        for hist in self._SortedHistograms():
            if denom == None:
                denom = hist
                continue
            ratio = copy.deepcopy(hist)
            ratio.obj.Divide(denom.obj)
            ratio.obj.Draw(same)
            self.ratios.append(ratio)
            if same == '':
                same = 'same'
        self.DrawLegend(ratio=True)
        if TPad.Pad():
            TPad.Pad().Update()
        # self.lastDraw = 'DrawRatio'
        # self.lastDrawArgs = [ opt ]

    def DrawDataOverMCMinus1(self, ymin=-0.5, ymax=0.5):
        stackedHists = []
        dataHist = None
        for hist in self._SortedHistograms():
            if hist.stack is False:
                dataHist = hist
                continue
            stackedHists.append(hist)
        self._BuildStack(stackedHists, ytitle='Data/MC')
        mcHist = self.stack.totalHist
        self.dataOverMCHist = copy.deepcopy(dataHist)
        # self.dataOverMCHist.Add(mcHist, -1)
        self.dataOverMCHist.Divide(mcHist)
        self.dataOverMCHist.Draw()
        yaxis = self.dataOverMCHist.GetYaxis()
        yaxis.SetRangeUser(ymin + 1., ymax + 1.)
        yaxis.SetTitle('Data/MC')
        yaxis.SetNdivisions(5)
        fraclines = 0.2
        if ymax <= 0.2 or ymin >= -0.2:
            fraclines = 0.1
        self.DrawRatioLines(self.dataOverMCHist, fraclines, 1.)
        if TPad.Pad():
            TPad.Pad().Update()

    def DrawRatioStack(self, opt='',
                       xmin=None, xmax=None, ymin=None, ymax=None):
        '''Draw ratios.

        The stack is considered as a single histogram.'''
        denom = None
        # import pdb; pdb.set_trace()
        histForRatios = []
        denom = None
        for hist in self._SortedHistograms():
            if hist.stack is False:
                # if several unstacked histograms, the highest layer is used
                denom = hist
                continue
            histForRatios.append(hist)
        self._BuildStack(histForRatios, ytitle='MC/Data')
        self.stack.Divide(denom.obj)
        if self.blindminx and self.blindmaxx:
            self.stack.Blind(self.blindminx, self.blindmaxx)
        self.stack.Draw(opt,
                        xmin=xmin, xmax=xmax,
                        ymin=ymin, ymax=ymax)
        self.ratios = []
        for hist in self.nostack:
            if hist is denom:
                continue
            ratio = copy.deepcopy(hist)
            ratio.obj.Divide(denom.obj)
            ratio.obj.Draw('same')
            self.ratios.append(ratio)
        self.DrawLegend(ratio=True)
        self.DrawRatioLines(denom, 0.2, 1)
        if TPad.Pad():
            TPad.Pad().Update()

    def DrawNormalizedRatioStack(self, opt='',
                                 xmin=None, xmax=None,
                                 ymin=None, ymax=None):
        '''Draw ratios.

        The stack is considered as a single histogram.
        All histograms are normalized before computing the ratio'''
        denom = None
        histForRatios = []
        for hist in self._SortedHistograms():
            # taking the first histogram (lowest layer)
            # as the denominator histogram.
            if denom == None:
                denom = copy.deepcopy(hist)
                continue
            # other histograms will be divided by the denominator
            histForRatios.append(hist)
        self._BuildStack(histForRatios, ytitle='MC p.d.f. / Data p.d.f.')
        self.stack.Normalize()
        denom.Normalize()
        self.stack.Divide(denom.weighted)
        self.stack.Draw(opt,
                        xmin=xmin, xmax=xmax,
                        ymin=ymin, ymax=ymax)
        self.ratios = []
        for hist in self.nostack:
            # print 'nostack ', hist
            ratio = copy.deepcopy(hist)
            ratio.Normalize()
            ratio.obj.Divide(denom.weighted)
            ratio.obj.Draw('same')
            self.ratios.append(ratio)
        self.DrawLegend(ratio=True)
        self.DrawRatioLines(denom, 0.2, 1)
        if TPad.Pad():
            TPad.Pad().Update()
        # self.lastDraw = 'DrawNormalizedRatioStack'
        # self.lastDrawArgs = [ opt ]

    def DrawRatioLines(self, hist, frac=0.2, y0=1.):
        '''Draw a line at y = 1, at 1+frac, and at 1-frac.

        hist is used to get the x axis range.'''
        xmin = hist.obj.GetXaxis().GetXmin()
        xmax = hist.obj.GetXaxis().GetXmax()
        line = TLine()
        line.DrawLine(xmin, y0, xmax, y0)
        line.SetLineStyle(2)
        line.DrawLine(xmin, y0+frac, xmax, y0+frac)
        line.DrawLine(xmin, y0-frac, xmax, y0-frac)

    def GetStack(self):
        '''Returns stack; builds stack if not there yet'''
        if not self.stack:
            self._BuildStack(self._SortedHistograms(), ytitle='Events')
        return self.stack

    def DrawStack(self, opt='',
                  xmin=None, xmax=None, ymin=None, ymax=None, print_norm=False,
                  scale_signal=''):
        '''Draw all histograms, some of them in a stack.

        if Histogram.stack is True, the histogram is put in the stack.
        scale_signal: mc_int -> scale to stack integral'''
        self._BuildStack(self._SortedHistograms(), ytitle='Events')
        same = 'same'
        if len(self.nostack) == 0:
            same = ''
        self.supportHist = None
        for hist in self.nostack:
            if hist.style.drawAsData:
                hist.Draw('SAME' if self.supportHist else '')
            else:
                if scale_signal == 'mc_int':
                    hist.Scale(hist.Yield(weighted=True)/self.stack.integral)
                hist.Draw('SAME HIST' if self.supportHist else 'HIST')
            if not self.supportHist:
                self.supportHist = hist
        self.stack.Draw(opt+same,
                        xmin=xmin, xmax=xmax,
                        ymin=ymin, ymax=ymax)
        if self.supportHist is None:
            self.supportHist = self.stack.totalHist
        if not self.axisWasSet:
            mxsup = self.supportHist.weighted.GetBinContent(
                self.supportHist.weighted.GetMaximumBin()
            )
            mxstack = self.stack.totalHist.weighted.GetBinContent(
                self.stack.totalHist.weighted.GetMaximumBin()
            )
            mx = max(mxsup, mxstack)
            if ymin is None:
                ymin = 0.01
            if ymax is None:
                ymax = mx*1.3
            self.supportHist.GetYaxis().SetRangeUser(ymin, ymax)
            self.axisWasSet = True
        for hist in self.nostack:
            if self.blindminx and hist.style.drawAsData:
                hist.Blind(self.blindminx, self.blindmaxx)
            if hist.style.drawAsData:
                hist.Draw('SAME')
            else:
                hist.Draw('SAME HIST')

        if self.supportHist.weighted.GetMaximumBin() < self.supportHist.weighted.GetNbinsX()/2:
            self.legendBorders = 0.62, 0.46, 0.88, 0.89
            self.legendPos = 'right'

        self.DrawLegend(print_norm=print_norm)
        if TPad.Pad():
            TPad.Pad().Update()

    def DrawNormalizedStack(self, opt='',
                            xmin=None, xmax=None, ymin=0.001, ymax=None):
        '''Draw all histograms, some of them in a stack.

        if Histogram.stack is True, the histogram is put in the stack.
        all histograms out of the stack, and the stack itself, are shown as PDFs.'''
        self._BuildStack(self._SortedHistograms(), ytitle='p.d.f.')
        self.stack.DrawNormalized(opt,
                                  xmin=xmin, xmax=xmax,
                                  ymin=ymin, ymax=ymax)
        for hist in self.nostack:
            hist.obj.DrawNormalized('same')
        self.DrawLegend()
        if TPad.Pad():
            TPad.Pad().Update()
        # self.lastDraw = 'DrawNormalizedStack'
        # self.lastDrawArgs = [ opt ]

    def Rebin(self, factor):
        '''Rebin, and redraw.'''
        # the dispatching technique is not too pretty,
        # but keeping a self.lastDraw function initialized to one of the Draw functions
        # when calling it creates a problem in deepcopy.
        for hist in self.histos:
            hist.Rebin(factor)
        self.axisWasSet = False

    def NormalizeToBinWidth(self):
        '''Normalize each Histograms bin to the bin width.'''
        for hist in self.histos:
            hist.NormalizeToBinWidth()

    def WriteDataCard(self, filename=None, verbose=True, 
                      mode='RECREATE', dir=None):
        '''Export current plot to datacard'''
        if not filename:
            filename = self.name+'.root'

        outf = TFile(filename, mode)
        if dir and outf.Get(dir):
            print 'Directory', dir, 'already present in output file, recreate'
            outf = TFile(filename, 'RECREATE')
        if dir:
            outf_dir = outf.mkdir(dir)
            outf_dir.cd()

        for hist in self._SortedHistograms():
            'Writing', hist, 'as', hist.name
            hist.weighted.Write(hist.name)
        outf.Write()

    def _BuildStack(self, hists, ytitle=None):
        '''build a stack from a list of Histograms.

        The histograms for which Histogram.stack is False are put in self.nostack'''
        self.stack = None
        self.stack = Stack(self.name+'_stack', ytitle=ytitle)
        self.nostack = []
        for hist in hists:
            if hist.stack:
                self.stack.Add(hist)
            else:
                self.nostack.append(hist)

    def _GetHistPref(self, name):
        '''Return the preference dictionary for a given component'''
        thePref = None
        for prefpat, pref in self.histPref.iteritems():
            if fnmatch.fnmatch(name, prefpat):
                if thePref is not None:
                    print 'several matching preferences for', name
                thePref = pref
        if thePref is None:
            print 'cannot find preference for hist', name
            thePref = {'style': Style(), 'layer': 999}
        return thePref

    def _ApplyPrefs(self):
        for hist in self.histos:
            pref = self._GetHistPref(hist.name)
            hist.layer = pref['layer']
            hist.SetStyle(pref['style'])
            hist.legendLine = pref['legend']

    def __str__(self):
        if self.stack is None:
            self._BuildStack(self._SortedHistograms(), ytitle='Events')
        tmp = [' '.join(['DataMCPlot: ', self.name])]
        tmp.append('Histograms:')
        for hist in self._SortedHistograms(reverse=True):
            tmp.append(' '.join(['\t', str(hist)]))
        tmp.append('Stack yield = {integ:7.1f}'.format(integ=self.stack.integral))
        return '\n'.join(tmp)
예제 #19
0
#h1.Sumw2()
#h1.Scale(1/h1.Integral())
#h2.Sumw2()
#h2.Scale(1/h2.Integral())
h3.Sumw2()
h3.Scale(1/h3.Integral())


a = TH1F ("a","a",10,0,100)
a.Fill(1)

c = TCanvas("c1", "c1",0,0,500,500)
gStyle.SetOptStat(0)

leg = TLegend(0.1,0.7,0.3,0.9)
leg.SetFillColor(0)
leg.SetFillStyle(0)
leg.SetTextSize(0.04)
leg.SetBorderSize(0)
leg.SetTextFont(22)
leg.Draw()

h1.SetLineColor(1)
h1.SetLineWidth(2)
h1.SetLineStyle(1)

h2.SetLineColor(2)
h2.SetLineWidth(2)
h2.SetLineStyle(1)

h3.SetLineColor(3)
def compareMassRes(trackType):

    file2016BB = open("default/MassResolutionVsMass_%s_BB.pkl" % trackType,
                      "rb")
    file2016BE = open("default/MassResolutionVsMass_%s_BE.pkl" % trackType,
                      "rb")
    file2017BB = open("cruijff/MassResolutionVsMass_%s_BB.pkl" % trackType,
                      "rb")
    file2017BE = open("cruijff/MassResolutionVsMass_%s_BE.pkl" % trackType,
                      "rb")
    fileCBB = open("crystal/MassResolutionVsMass_%s_BB.pkl" % trackType, "rb")
    fileCBE = open("crystal/MassResolutionVsMass_%s_BE.pkl" % trackType, "rb")

    results2016BB = pickle.load(file2016BB)
    results2016BE = pickle.load(file2016BE)
    results2017BB = pickle.load(file2017BB)
    results2017BE = pickle.load(file2017BE)
    resultsCBB = pickle.load(fileCBB)
    resultsCBE = pickle.load(fileCBE)

    graph2016BB = getGraph(results2016BB, "DCBBB")
    graph2016BE = getGraph(results2016BE, "DCBBE")
    graph2017BB = getGraph(results2017BB, "CruijffBB")
    graph2017BE = getGraph(results2017BE, "CruijffBE")
    graphCBB = getGraph(resultsCBB, "CBB")
    graphCBE = getGraph(resultsCBE, "CBE")

    ratioBB = getRatio(results2016BB, results2017BB, "ratioBB")
    ratioBE = getRatio(results2016BE, results2017BE, "ratioBE")
    ratioCBB = getRatio(results2016BB, resultsCBB, "ratioCBB")
    ratioCBE = getRatio(results2016BE, resultsCBE, "ratioCBE")

    canv = TCanvas("c1", "c1", 800, 1200)

    plotPad = TPad("plotPad", "plotPad", 0, 0.3, 1, 1)
    ratioPad = TPad("ratioPad", "ratioPad", 0, 0., 1, 0.3)
    style = setTDRStyle()
    gStyle.SetOptStat(0)
    plotPad.UseCurrentStyle()
    ratioPad.UseCurrentStyle()
    plotPad.Draw()
    ratioPad.Draw()
    plotPad.cd()
    plotPad.cd()
    plotPad.SetGrid()
    gStyle.SetTitleXOffset(1.45)
    gStyle.SetTitleYOffset(1.55)

    xMax = 0.08
    if trackType == "Inner":
        xMax = 0.2
    if trackType == "Outer":
        xMax = 0.4

    plotPad.DrawFrame(0, 0, 6000, xMax, ";M [GeV]; mass resolution")

    graph2016BB.Draw("samepe")
    graph2017BB.Draw("samepe")
    graphCBB.Draw("samepe")
    graph2017BB.SetLineColor(kRed)
    graph2017BB.SetMarkerColor(kRed)
    graphCBB.SetLineColor(kBlue)
    graphCBB.SetMarkerColor(kBlue)

    latex = TLatex()
    latex.SetTextFont(42)
    latex.SetTextAlign(31)
    latex.SetTextSize(0.04)
    latex.SetNDC(True)
    latexCMS = TLatex()
    latexCMS.SetTextFont(61)
    latexCMS.SetTextSize(0.055)
    latexCMS.SetNDC(True)
    latexCMSExtra = TLatex()
    latexCMSExtra.SetTextFont(52)
    latexCMSExtra.SetTextSize(0.03)
    latexCMSExtra.SetNDC(True)

    latex.DrawLatex(0.95, 0.96, "(13 TeV)")

    cmsExtra = "#splitline{Preliminary}{}"
    latexCMS.DrawLatex(0.19, 0.88, "CMS")
    if "Simulation" in cmsExtra:
        yLabelPos = 0.81
    else:
        yLabelPos = 0.84

    latexCMSExtra.DrawLatex(0.19, yLabelPos, "%s" % (cmsExtra))

    leg = TLegend(0.52, 0.76, 0.95, 0.91, "%s BB" % trackType, "brNDC")
    leg.SetFillColor(10)
    leg.SetFillStyle(0)
    leg.SetLineColor(10)
    leg.SetShadowColor(0)
    leg.SetBorderSize(1)
    leg.AddEntry(graph2016BB, "Cruijff", "l")
    leg.AddEntry(graph2017BB, "Double CB", "l")
    leg.AddEntry(graphCBB, "Crystal Ball", "l")

    leg.Draw()

    plotPad.RedrawAxis()

    ratioPad.cd()

    ratioBB.SetLineColor(kRed)
    ratioCBB.SetLineColor(kBlue)

    ratioPad.DrawFrame(0, 0.5, 6000, 1.5, ";ratio")

    ratioBB.Draw("samepe")
    ratioCBB.Draw("samepe")

    canv.Print("massResolutionCompareFunc_%s_BB.pdf" % trackType)

    canv = TCanvas("c1", "c1", 800, 1200)

    plotPad = TPad("plotPad", "plotPad", 0, 0.3, 1, 1)
    ratioPad = TPad("ratioPad", "ratioPad", 0, 0., 1, 0.3)
    style = setTDRStyle()
    gStyle.SetOptStat(0)
    plotPad.UseCurrentStyle()
    ratioPad.UseCurrentStyle()
    plotPad.Draw()
    ratioPad.Draw()
    plotPad.cd()
    plotPad.cd()
    plotPad.SetGrid()
    gStyle.SetTitleXOffset(1.45)
    gStyle.SetTitleYOffset(1.55)

    xMax = 0.08
    if trackType == "Inner":
        xMax = 0.2
    if trackType == "Outer":
        xMax = 0.4

    plotPad.DrawFrame(0, 0, 6000, xMax, ";M [GeV]; mass resolution")

    graph2016BE.Draw("samepe")
    graph2017BE.Draw("samepe")
    graphCBE.Draw("samepe")
    graph2017BE.SetLineColor(kRed)
    graph2017BE.SetMarkerColor(kRed)
    graphCBE.SetLineColor(kBlue)
    graphCBE.SetMarkerColor(kBlue)

    latex = TLatex()
    latex.SetTextFont(42)
    latex.SetTextAlign(31)
    latex.SetTextSize(0.04)
    latex.SetNDC(True)
    latexCMS = TLatex()
    latexCMS.SetTextFont(61)
    latexCMS.SetTextSize(0.055)
    latexCMS.SetNDC(True)
    latexCMSExtra = TLatex()
    latexCMSExtra.SetTextFont(52)
    latexCMSExtra.SetTextSize(0.03)
    latexCMSExtra.SetNDC(True)

    latex.DrawLatex(0.95, 0.96, "(13 TeV)")

    cmsExtra = "#splitline{Preliminary}{}"
    latexCMS.DrawLatex(0.19, 0.88, "CMS")
    if "Simulation" in cmsExtra:
        yLabelPos = 0.81
    else:
        yLabelPos = 0.84

    latexCMSExtra.DrawLatex(0.19, yLabelPos, "%s" % (cmsExtra))

    leg = TLegend(0.52, 0.76, 0.95, 0.91, "%s BE" % trackType, "brNDC")
    leg.SetFillColor(10)
    leg.SetFillStyle(0)
    leg.SetLineColor(10)
    leg.SetShadowColor(0)
    leg.SetBorderSize(1)
    leg.AddEntry(graph2016BE, "Cruijff", "l")
    leg.AddEntry(graph2017BE, "Double CB", "l")
    leg.AddEntry(graphCBE, "Crystal Ball", "l")

    leg.Draw()

    plotPad.RedrawAxis()

    ratioPad.cd()

    ratioBE.SetLineColor(kRed)
    ratioCBE.SetLineColor(kBlue)

    ratioPad.DrawFrame(0, 0.5, 6000, 1.5, ";;ratio")

    ratioBE.Draw("samepe")
    ratioCBE.Draw("samepe")

    canv.Print("massResolutionCompareFunc_%s_BE.pdf" % trackType)
예제 #21
0
gr.GetYaxis().CenterTitle()
#gr.GetXaxis().SetTitleOffset(1)
#gr.GetYaxis().SetTitleOffset(1)

#================================
gr.GetYaxis().SetTitleSize(0.04)
gr.GetXaxis().SetTitleSize(0.04)
gr.GetXaxis().SetLabelSize(0.04)
gr.GetYaxis().SetLabelSize(0.04)
gr.GetXaxis().SetLabelFont(22)
gr.GetYaxis().SetLabelFont(22)
gr.GetXaxis().SetTitleColor(1)
gr.GetYaxis().SetTitleColor(1)

leg1=TLegend(0.5,0.7,0.7,0.9)
leg1.SetFillColor(0)
leg1.SetFillStyle(0)
leg1.SetTextSize(0.05)
leg1.SetBorderSize(0)
leg1.SetTextFont(22)
leg1.AddEntry("","GeIA group","")
leg1.AddEntry("","#propto e^{-#frac{E}{2k_{B}T}}","")


line_120K =TLine(1000/120-2,0,1000/120+2,Desity_of_impurities(120,math.pow(10,10))[0])
line_77K =TLine(1000/77-2,0,1000/77+2,Desity_of_impurities(77,math.pow(10,10))[0])
line_4K =TLine(1000/4-2,0,1000/4+2,Desity_of_impurities(4,math.pow(10,10))[0])
line_120K.SetLineWidth(2)
line_77K.SetLineWidth(2)
line_4K.SetLineWidth(2)
예제 #22
0
def dijet(category):

    channel = 'bb'
    stype = channel
    isSB = True  # relict from using Alberto's more complex script
    isData = not ISMC
    nTupleDir = NTUPLEDIR

    samples = data if isData else back
    pd = []
    if options.test:
        if ISMC and YEAR == '2016':
            pd.append("MC_QCD_" + YEAR)
            nTupleDir = NTUPLEDIR.replace("weighted/", "test_for_fit/")
        else:
            print "No test sample for real data was implemented. Select '-M' if you want to test on a small MC QCD sample."
            sys.exit()
    else:
        for sample_name in samples:
            if YEAR == 'run2':
                pd += sample[sample_name]['files']
            else:
                pd += [x for x in sample[sample_name]['files'] if YEAR in x]
    print "datasets:", pd
    if not os.path.exists(PLOTDIR): os.makedirs(PLOTDIR)
    if BIAS: print "Running in BIAS mode"

    order = 0
    RSS = {}

    X_mass = RooRealVar("jj_mass_widejet", "m_{jj}", X_min, X_max, "GeV")
    j1_pt = RooRealVar("jpt_1", "jet1 pt", 0., 13000., "GeV")
    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.)
    jnmuons_1 = RooRealVar("jnmuons_1", "j1 n_{#mu}", -1., 8.)
    jnmuons_2 = RooRealVar("jnmuons_2", "j2 n_{#mu}", -1., 8.)
    jmuonpt_1 = RooRealVar("jmuonpt_1", "j1 muon pt", 0., 13000.)
    jmuonpt_2 = RooRealVar("jmuonpt_2", "j2 muon pt", 0., 13000.)
    jid_1 = RooRealVar("jid_1", "j1 ID", -1., 8.)
    jid_2 = RooRealVar("jid_2", "j2 ID", -1., 8.)
    nmuons = RooRealVar("nmuons", "n_{#mu}", -1., 10.)
    nelectrons = RooRealVar("nelectrons", "n_{e}", -1., 10.)
    jj_deltaEta = RooRealVar("jj_deltaEta_widejet", "", 0., 5.)
    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)

    variables = RooArgSet(X_mass)
    variables.add(
        RooArgSet(jbtag_WP_1, jbtag_WP_2, fatjetmass_1, fatjetmass_2,
                  jnmuons_1, jnmuons_2, nmuons, nelectrons, weight))
    variables.add(
        RooArgSet(j1_pt, jj_deltaEta, jid_1, jid_2, jmuonpt_1, jmuonpt_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))

    if VARBINS:
        binsXmass = RooBinning(len(abins) - 1, abins)
        X_mass.setBinning(RooBinning(len(abins_narrow) - 1, abins_narrow))
        #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

    if BTAGGING == 'semimedium':
        baseCut = aliasSM[category]
    else:
        baseCut = alias[category].format(WP=working_points[BTAGGING])

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

    print stype, "|", baseCut

    print " - Reading from Tree"
    treeBkg = TChain("tree")
    if options.unskimmed or options.test:
        for i, ss in enumerate(pd):
            j = 0
            while True:
                if os.path.exists(nTupleDir + ss + "/" + ss +
                                  "_flatTuple_{}.root".format(j)):
                    treeBkg.Add(nTupleDir + ss + "/" + ss +
                                "_flatTuple_{}.root".format(j))
                    j += 1
                else:
                    print "found {} files for sample:".format(j), ss
                    break
    else:
        for ss in pd:
            if os.path.exists(nTupleDir + ss + ".root"):
                treeBkg.Add(nTupleDir + ss + ".root")
            else:
                print "found no file for sample:", ss
    #setData = RooDataSet("setData", "Data" if isData else "Data (QCD MC)", variables, RooFit.Cut(baseCut), RooFit.WeightVar(weight), RooFit.Import(treeBkg))
    if isData or options.test:
        setData = RooDataSet("setData", "Data", variables, RooFit.Cut(baseCut),
                             RooFit.Import(treeBkg))
    else:
        setData = RooDataSet("setData", "Data (QCD+TTbar MC)", variables,
                             RooFit.Cut(baseCut), RooFit.WeightVar(weight),
                             RooFit.Import(treeBkg))

    nevents = setData.sumEntries()
    dataMin, dataMax = array('d', [0.]), array('d', [0.])
    setData.getRange(X_mass, dataMin, dataMax)
    xmin, xmax = dataMin[0], dataMax[0]

    lastBin = X_mass.getMax()
    if VARBINS:
        for b in narrow_bins:  # switched to narrow bins here
            if b > xmax:
                lastBin = b
                break

    print "Imported", (
        "data" if isData else "MC"
    ), "RooDataSet with", nevents, "events between [%.1f, %.1f]" % (xmin, xmax)
    #xmax = xmax+binsXmass.averageBinWidth() # start form next bin

    # 1 parameter
    print "fitting 1 parameter model"
    p1_1 = RooRealVar("CMS" + YEAR + "_" + category + "_p1_1", "p1", 7.0, 0.,
                      2000.)
    modelBkg1 = RooGenericPdf("Bkg1", "Bkg. fit (2 par.)",
                              "1./pow(@0/13000, @1)", RooArgList(X_mass, p1_1))
    normzBkg1 = RooRealVar(
        modelBkg1.GetName() + "_norm", "Number of background events", nevents,
        0., 5. * nevents)  #range dependent of actual number of events!
    modelExt1 = RooExtendPdf(modelBkg1.GetName() + "_ext",
                             modelBkg1.GetTitle(), modelBkg1, normzBkg1)
    fitRes1 = modelExt1.fitTo(setData, RooFit.Extended(True), RooFit.Save(1),
                              RooFit.SumW2Error(not isData),
                              RooFit.Strategy(2), RooFit.Minimizer("Minuit2"),
                              RooFit.PrintLevel(1 if VERBOSE else -1))
    fitRes1.Print()
    RSS[1] = drawFit("Bkg1", category, X_mass, modelBkg1, setData, binsXmass,
                     [fitRes1], normzBkg1.getVal())

    # 2 parameters
    print "fitting 2 parameter model"
    p2_1 = RooRealVar("CMS" + YEAR + "_" + category + "_p2_1", "p1", 0., -100.,
                      1000.)
    p2_2 = RooRealVar("CMS" + YEAR + "_" + category + "_p2_2", "p2",
                      p1_1.getVal(), -100., 600.)
    modelBkg2 = RooGenericPdf("Bkg2", "Bkg. fit (3 par.)",
                              "pow(1-@0/13000, @1) / pow(@0/13000, @2)",
                              RooArgList(X_mass, p2_1, p2_2))
    normzBkg2 = RooRealVar(modelBkg2.GetName() + "_norm",
                           "Number of background events", nevents, 0.,
                           5. * nevents)
    modelExt2 = RooExtendPdf(modelBkg2.GetName() + "_ext",
                             modelBkg2.GetTitle(), modelBkg2, normzBkg2)
    fitRes2 = modelExt2.fitTo(setData, RooFit.Extended(True), RooFit.Save(1),
                              RooFit.SumW2Error(not isData),
                              RooFit.Strategy(2), RooFit.Minimizer("Minuit2"),
                              RooFit.PrintLevel(1 if VERBOSE else -1))
    fitRes2.Print()
    RSS[2] = drawFit("Bkg2", category, X_mass, modelBkg2, setData, binsXmass,
                     [fitRes2], normzBkg2.getVal())

    # 3 parameters
    print "fitting 3 parameter model"
    p3_1 = RooRealVar("CMS" + YEAR + "_" + category + "_p3_1", "p1",
                      p2_1.getVal(), -2000., 2000.)
    p3_2 = RooRealVar("CMS" + YEAR + "_" + category + "_p3_2", "p2",
                      p2_2.getVal(), -400., 2000.)
    p3_3 = RooRealVar("CMS" + YEAR + "_" + category + "_p3_3", "p3", -2.5,
                      -500., 500.)
    modelBkg3 = RooGenericPdf(
        "Bkg3", "Bkg. fit (4 par.)",
        "pow(1-@0/13000, @1) / pow(@0/13000, @2+@3*log(@0/13000))",
        RooArgList(X_mass, p3_1, p3_2, p3_3))
    normzBkg3 = RooRealVar(modelBkg3.GetName() + "_norm",
                           "Number of background events", nevents, 0.,
                           5. * nevents)
    modelExt3 = RooExtendPdf(modelBkg3.GetName() + "_ext",
                             modelBkg3.GetTitle(), modelBkg3, normzBkg3)
    fitRes3 = modelExt3.fitTo(setData, RooFit.Extended(True), RooFit.Save(1),
                              RooFit.SumW2Error(not isData),
                              RooFit.Strategy(2), RooFit.Minimizer("Minuit2"),
                              RooFit.PrintLevel(1 if VERBOSE else -1))
    fitRes3.Print()
    RSS[3] = drawFit("Bkg3", category, X_mass, modelBkg3, setData, binsXmass,
                     [fitRes3], normzBkg3.getVal())

    # 4 parameters
    print "fitting 4 parameter model"
    p4_1 = RooRealVar("CMS" + YEAR + "_" + category + "_p4_1", "p1",
                      p3_1.getVal(), -2000., 2000.)
    p4_2 = RooRealVar("CMS" + YEAR + "_" + category + "_p4_2", "p2",
                      p3_2.getVal(), -2000., 2000.)
    p4_3 = RooRealVar("CMS" + YEAR + "_" + category + "_p4_3", "p3",
                      p3_3.getVal(), -50., 50.)
    p4_4 = RooRealVar("CMS" + YEAR + "_" + category + "_p4_4", "p4", 0.1, -50.,
                      50.)
    modelBkg4 = RooGenericPdf(
        "Bkg4", "Bkg. fit (5 par.)",
        "pow(1 - @0/13000, @1) / pow(@0/13000, @2+@3*log(@0/13000)+@4*pow(log(@0/13000), 2))",
        RooArgList(X_mass, p4_1, p4_2, p4_3, p4_4))
    normzBkg4 = RooRealVar(modelBkg4.GetName() + "_norm",
                           "Number of background events", nevents, 0.,
                           5. * nevents)
    modelExt4 = RooExtendPdf(modelBkg4.GetName() + "_ext",
                             modelBkg4.GetTitle(), modelBkg4, normzBkg4)
    fitRes4 = modelExt4.fitTo(setData, RooFit.Extended(True), RooFit.Save(1),
                              RooFit.SumW2Error(not isData),
                              RooFit.Strategy(2), RooFit.Minimizer("Minuit2"),
                              RooFit.PrintLevel(1 if VERBOSE else -1))
    fitRes4.Print()
    RSS[4] = drawFit("Bkg4", category, X_mass, modelBkg4, setData, binsXmass,
                     [fitRes4], normzBkg4.getVal())

    # Normalization parameters are should be set constant, but shape ones should not
    #    if BIAS:
    #        p1_1.setConstant(True)
    #        p2_1.setConstant(True)
    #        p2_2.setConstant(True)
    #        p3_1.setConstant(True)
    #        p3_2.setConstant(True)
    #        p3_3.setConstant(True)
    #        p4_1.setConstant(True)
    #        p4_2.setConstant(True)
    #        p4_3.setConstant(True)
    #        p4_4.setConstant(True)
    normzBkg1.setConstant(True)
    normzBkg2.setConstant(True)
    normzBkg3.setConstant(True)
    normzBkg4.setConstant(True)

    #*******************************************************#
    #                                                       #
    #                         Fisher                        #
    #                                                       #
    #*******************************************************#

    # Fisher test
    with open(PLOTDIR + "/Fisher_" + category + ".tex", 'w') as fout:
        fout.write(r"\begin{tabular}{c|c|c|c|c}")
        fout.write("\n")
        fout.write(r"function & $\chi^2$ & RSS & ndof & F-test \\")
        fout.write("\n")
        fout.write("\hline")
        fout.write("\n")
        CL_high = False
        for o1 in range(1, 5):
            o2 = min(o1 + 1, 5)
            if o2 > len(RSS):
                fout.write("%d par & %.2f & %.2f & %d & " %
                           (o1 + 1, RSS[o1]["chi2"], RSS[o1]["rss"],
                            RSS[o1]["nbins"] - RSS[o1]["npar"]))
                fout.write(r"\\")
                fout.write("\n")
                continue  #order==0 and

            CL = fisherTest(RSS[o1]['rss'], RSS[o2]['rss'], o1 + 1., o2 + 1.,
                            RSS[o1]["nbins"])
            if CL > 0.10:  # The function with less parameters is enough
                if not CL_high:
                    order = o1
                    fout.write("\\rowcolor{MarkerColor}\n")
                    CL_high = True
            else:
                #fout.write( "%d par are needed " % (o2+1))
                if not CL_high:
                    order = o2
            fout.write("%d par & %.2f & %.2f & %d & " %
                       (o1 + 1, RSS[o1]["chi2"], RSS[o1]["rss"],
                        RSS[o1]["nbins"] - RSS[o1]["npar"]))
            fout.write("CL=%.3f " % (CL))
            fout.write(r"\\")
            fout.write("\n")
        fout.write("\hline")
        fout.write("\n")
        fout.write(r"\end{tabular}")

    print "saved F-test table as", PLOTDIR + "/Fisher_" + category + ".tex"

    #print "-"*25
    #print "function & $\\chi^2$ & RSS & ndof & F-test & result \\\\"
    #print "\\multicolumn{6}{c}{", "Zprime_to_bb", "} \\\\"
    #print "\\hline"
    #CL_high = False
    #for o1 in range(1, 5):
    #    o2 = min(o1 + 1, 5)
    #    print "%d par & %.2f & %.2f & %d & " % (o1+1, RSS[o1]["chi2"], RSS[o1]["rss"], RSS[o1]["nbins"]-RSS[o1]["npar"]),
    #    if o2 > len(RSS):
    #        print "\\\\"
    #        continue #order==0 and
    #    CL = fisherTest(RSS[o1]['rss'], RSS[o2]['rss'], o1+1., o2+1., RSS[o1]["nbins"])
    #    print "%d par vs %d par CL=%f & " % (o1+1, o2+1, CL),
    #    if CL > 0.10: # The function with less parameters is enough
    #        if not CL_high:
    #            order = o1
    #            print "%d par are sufficient" % (o1+1),
    #            CL_high=True
    #    else:
    #        print "%d par are needed" % (o2+1),
    #        if not CL_high:
    #            order = o2
    #    print "\\\\"
    #print "\\hline"
    #print "-"*25
    #print "@ Order is", order, "("+category+")"

    #order = min(3, order)
    #order = 2
    if order == 1:
        modelBkg = modelBkg1  #.Clone("Bkg")
        modelAlt = modelBkg2  #.Clone("BkgAlt")
        normzBkg = normzBkg1  #.Clone("Bkg_norm")
        fitRes = fitRes1
    elif order == 2:
        modelBkg = modelBkg2  #.Clone("Bkg")
        modelAlt = modelBkg3  #.Clone("BkgAlt")
        normzBkg = normzBkg2  #.Clone("Bkg_norm")
        fitRes = fitRes2
    elif order == 3:
        modelBkg = modelBkg3  #.Clone("Bkg")
        modelAlt = modelBkg4  #.Clone("BkgAlt")
        normzBkg = normzBkg3  #.Clone("Bkg_norm")
        fitRes = fitRes3
    elif order == 4:
        modelBkg = modelBkg4  #.Clone("Bkg")
        modelAlt = modelBkg3  #.Clone("BkgAlt")
        normzBkg = normzBkg4  #.Clone("Bkg_norm")
        fitRes = fitRes4
    else:
        print "Functions with", order + 1, "or more parameters are needed to fit the background"
        exit()

    modelBkg.SetName("Bkg_" + YEAR + "_" + category)
    modelAlt.SetName("Alt_" + YEAR + "_" + category)
    normzBkg.SetName("Bkg_" + YEAR + "_" + category + "_norm")

    print "-" * 25

    # Generate pseudo data
    setToys = RooDataSet()
    setToys.SetName("data_toys")
    setToys.SetTitle("Data (toys)")
    if not isData:
        print " - Generating", nevents, "events for toy data"
        setToys = modelBkg.generate(RooArgSet(X_mass), nevents)
        #setToys = modelAlt.generate(RooArgSet(X_mass), nevents)
        print "toy data generated"

    if VERBOSE: raw_input("Press Enter to continue...")

    #*******************************************************#
    #                                                       #
    #                         Plot                          #
    #                                                       #
    #*******************************************************#

    print "starting to plot"
    c = TCanvas("c_" + category, category, 800, 800)
    c.Divide(1, 2)
    setTopPad(c.GetPad(1), RATIO)
    setBotPad(c.GetPad(2), RATIO)
    c.cd(1)
    frame = X_mass.frame()
    setPadStyle(frame, 1.25, True)
    if VARBINS: frame.GetXaxis().SetRangeUser(X_mass.getMin(), lastBin)
    signal = getSignal(
        category, stype,
        2000)  #replacing Alberto's getSignal by own dummy function

    graphData = setData.plotOn(frame, RooFit.Binning(plot_binning),
                               RooFit.Scaling(False), RooFit.Invisible())
    modelBkg.plotOn(frame, RooFit.VisualizeError(fitRes, 1, False),
                    RooFit.LineColor(602), RooFit.FillColor(590),
                    RooFit.FillStyle(1001), RooFit.DrawOption("FL"),
                    RooFit.Name("1sigma"))
    modelBkg.plotOn(frame, RooFit.LineColor(602), RooFit.FillColor(590),
                    RooFit.FillStyle(1001), RooFit.DrawOption("L"),
                    RooFit.Name(modelBkg.GetName()))
    modelAlt.plotOn(frame, RooFit.LineStyle(7), RooFit.LineColor(613),
                    RooFit.FillColor(609), RooFit.FillStyle(1001),
                    RooFit.DrawOption("L"), RooFit.Name(modelAlt.GetName()))
    if not isSB and signal[0] is not None:  # FIXME remove /(2./3.)
        signal[0].plotOn(
            frame,
            RooFit.Normalization(signal[1] * signal[2], RooAbsReal.NumEvent),
            RooFit.LineStyle(3), RooFit.LineWidth(6), RooFit.LineColor(629),
            RooFit.DrawOption("L"), RooFit.Name("Signal"))
    graphData = setData.plotOn(
        frame, RooFit.Binning(plot_binning), RooFit.Scaling(False),
        RooFit.XErrorSize(0 if not VARBINS else 1),
        RooFit.DataError(RooAbsData.Poisson if isData else RooAbsData.SumW2),
        RooFit.DrawOption("PE0"), RooFit.Name(setData.GetName()))
    fixData(graphData.getHist(), True, True, not isData)
    pulls = frame.pullHist(setData.GetName(), modelBkg.GetName(), True)
    chi = frame.chiSquare(setData.GetName(), modelBkg.GetName(), True)
    #setToys.plotOn(frame, RooFit.DataError(RooAbsData.Poisson), RooFit.DrawOption("PE0"), RooFit.MarkerColor(2))
    frame.GetYaxis().SetTitle("Events / ( 100 GeV )")
    frame.GetYaxis().SetTitleOffset(1.05)
    frame.Draw()
    #print "frame drawn"
    # Get Chi2
    #    chi2[1] = frame.chiSquare(modelBkg1.GetName(), setData.GetName())
    #    chi2[2] = frame.chiSquare(modelBkg2.GetName(), setData.GetName())
    #    chi2[3] = frame.chiSquare(modelBkg3.GetName(), setData.GetName())
    #    chi2[4] = frame.chiSquare(modelBkg4.GetName(), setData.GetName())

    frame.SetMaximum(frame.GetMaximum() * 10)
    frame.SetMinimum(max(frame.GetMinimum(), 1.e-1))
    c.GetPad(1).SetLogy()

    drawAnalysis(category)
    drawRegion(category, True)
    #drawCMS(LUMI, "Simulation Preliminary")
    #drawCMS(LUMI, "Work in Progress", suppressCMS=True)
    drawCMS(LUMI, "", suppressCMS=True)

    leg = TLegend(0.575, 0.6, 0.95, 0.9)
    leg.SetBorderSize(0)
    leg.SetFillStyle(0)  #1001
    leg.SetFillColor(0)
    leg.AddEntry(setData.GetName(),
                 setData.GetTitle() + " (%d events)" % nevents, "PEL")
    leg.AddEntry(modelBkg.GetName(), modelBkg.GetTitle(),
                 "FL")  #.SetTextColor(629)
    leg.AddEntry(modelAlt.GetName(), modelAlt.GetTitle(), "L")
    if not isSB and signal[0] is not None:
        leg.AddEntry("Signal", signal[0].GetTitle(), "L")
    leg.SetY1(0.9 - leg.GetNRows() * 0.05)
    leg.Draw()

    latex = TLatex()
    latex.SetNDC()
    latex.SetTextSize(0.04)
    latex.SetTextFont(42)
    if not isSB:
        latex.DrawLatex(leg.GetX1() * 1.16,
                        leg.GetY1() - 0.04, "HVT model B (g_{V}=3)")
    #    latex.DrawLatex(0.67, leg.GetY1()-0.045, "#sigma_{X} = 1.0 pb")

    c.cd(2)
    frame_res = X_mass.frame()
    setPadStyle(frame_res, 1.25)
    frame_res.addPlotable(pulls, "P")
    setBotStyle(frame_res, RATIO, False)
    if VARBINS: frame_res.GetXaxis().SetRangeUser(X_mass.getMin(), lastBin)
    frame_res.GetYaxis().SetRangeUser(-5, 5)
    frame_res.GetYaxis().SetTitle("pulls(#sigma)")
    frame_res.GetYaxis().SetTitleOffset(0.3)
    frame_res.Draw()
    fixData(pulls, False, True, False)

    drawChi2(RSS[order]["chi2"], RSS[order]["nbins"] - (order + 1), True)
    line = drawLine(X_mass.getMin(), 0, lastBin, 0)

    if VARBINS:
        c.SaveAs(PLOTDIR + "/BkgSR_" + category + ".pdf")
        c.SaveAs(PLOTDIR + "/BkgSR_" + category + ".png")
    else:
        c.SaveAs(PLOTDIR + "/BkgSR_" + category + ".pdf")
        c.SaveAs(PLOTDIR + "/BkgSR_" + category + ".png")

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

    if BIAS:
        gSystem.Load("libHiggsAnalysisCombinedLimit.so")
        from ROOT import RooMultiPdf
        cat = RooCategory("pdf_index", "Index of Pdf which is active")
        pdfs = RooArgList(modelBkg, modelAlt)
        roomultipdf = RooMultiPdf("roomultipdf", "All Pdfs", cat, pdfs)
        normulti = RooRealVar("roomultipdf_norm",
                              "Number of background events", nevents, 0., 1.e6)

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

    # create workspace
    w = RooWorkspace("Zprime_" + YEAR, "workspace")
    # Dataset
    if isData: getattr(w, "import")(setData, RooFit.Rename("data_obs"))
    else: getattr(w, "import")(setToys, RooFit.Rename("data_obs"))
    #getattr(w, "import")(setData, RooFit.Rename("data_obs"))
    if BIAS:
        getattr(w, "import")(cat, RooFit.Rename(cat.GetName()))
        getattr(w, "import")(normulti, RooFit.Rename(normulti.GetName()))
        getattr(w, "import")(roomultipdf, RooFit.Rename(roomultipdf.GetName()))
    getattr(w, "import")(modelBkg, RooFit.Rename(modelBkg.GetName()))
    getattr(w, "import")(modelAlt, RooFit.Rename(modelAlt.GetName()))
    getattr(w, "import")(normzBkg, RooFit.Rename(normzBkg.GetName()))
    w.writeToFile(
        WORKDIR + "%s_%s%s.root" %
        (DATA_TYPE + "_" + YEAR, category, "_test" if options.test else ""),
        True)
    print "Workspace", WORKDIR + "%s_%s%s.root" % (
        DATA_TYPE + "_" + YEAR, category,
        "_test" if options.test else ""), "saved successfully"
    if VERBOSE: raw_input("Press Enter to continue...")
예제 #23
0
                theory_curve_1110_2.Draw('l')

                #theory_curve_1110_3=theory_curve_1110.Clone()
                #theory_curve_1110_4=theory_curve_1110_2.Clone()

                #theory_curve_1110_3.Draw('c')
                #theory_curve_1110_4.Draw('c')

            legend = TLegend(0.335, 0.55, 0.9, 0.9)
            legend.SetTextSize(0.030)
            legend.SetBorderSize(0)
            legend.SetTextFont(42)
            legend.SetLineColor(1)
            legend.SetLineStyle(1)
            legend.SetLineWidth(1)
            legend.SetFillColor(0)
            legend.SetFillStyle(0)
            legend.SetHeader(
                '#bf{#it{#Beta}}(T#rightarrow bW, tH, tZ) = 50%, 25%, 25%')
            if triplet[0] == 0.0:
                legend.SetHeader(
                    '#bf{#it{#Beta}}(T#rightarrow tH, tZ) = 50%, 50%')
            legend.AddEntry(obslim, 'Observed', 'l')
            legend.AddEntry(explim, 'Expected', 'l')
            legend.AddEntry(exp1sigma, '#pm 1 std. deviation', 'f')
            legend.AddEntry(exp2sigma, '#pm 2 std. deviation', 'f')
            #legend.AddEntry(theory_curve,"SSM Z'#rightarrow Tt, B(Z'#rightarrow Tt) = 70%",'l')
            #legend.AddEntry(theory_curve_1110,"G*#rightarrow Tt (arXiv:1110.6058)",'l')
            if not triplet[0] == 0.0:
                legend.AddEntry(
                    theory_curve_1110,
예제 #24
0
    if len(hnames) < 2: continue
    if hnames[1] == printHistName or 'DNN' in hnames[1]:
        print hnames[2] + "_" + hnames[3]
        string_fname += "%s \n" % hnames
        string_nevt += "%s \n" % hnames

    ##if hnames[1] == printHistName :
    #print hnames[1], " ", hnames[2], " ", hnames[3]

    hs = THStack()
    #l = TLegend(0.30, 0.99 - 0.8 * N_bkgsamples / 20., 0.89, 0.85)
    l = TLegend(0.15, 0.71, 0.89, 0.87)
    l.SetNColumns(4)
    l.SetTextSize(0.05)
    l.SetLineColor(0)
    l.SetFillColor(0)

    if mode == 0 or mode == 1:
        h_data = datasamples[datasamples.keys()[mode]]["file"].Get(
            datasamples[datasamples.keys()[mode]]["hname"][i])
    elif mode == 2:
        h_data = datasamples[datasamples.keys()[0]]["file"].Get(
            datasamples[datasamples.keys()[0]]["hname"][i])
        h_data.Add(datasamples[datasamples.keys()[1]]["file"].Get(
            datasamples[datasamples.keys()[1]]["hname"][i]))
    nbins = h_data.GetNbinsX()
    h_data.AddBinContent(nbins, h_data.GetBinContent(nbins + 1))  #overflow
    h_data.Rebin(rebin)

    h_sub = h_data.Clone("h_sub")
def systematics(sys, isShape=False, antiCorr=False):
    treeRead = True
    file = {}
    hist = {}
    tree = {}
    histUp = {}
    histDown = {}
    up = {}
    down = {}
    gUp = TGraph()
    gDown = TGraph()
    gUp.SetLineWidth(3)
    gDown.SetLineWidth(3)
    gUp.SetLineColor(632)
    gDown.SetLineColor(602)
    BTagAK4deepup = False
    BTagAK4deepdown = False
    BTagAK4deep = False
    BTagAK8deepup = False
    BTagAK8deepdown = False
    BTagAK8deep = False
    #    g.SetMarkerStyle(20)
    #    g.SetMarkerColor(418)
    #    g.SetMarkerSize(1.25)
    var = sys
    cut = 'nnbbSR'
    if var == 'BTagAK4Weight_deep_up':
        var = 'X_mass'
        BTagAK4deepup = True
    elif var == 'BTagAK4Weight_deep_down':
        var = 'X_mass'
        BTagAK4deepdown = True
    elif var == 'BTagAK4Weight_deep':
        var = 'X_mass'
        BTagAK4deep = True
    elif var == 'BTagAK8Weight_deep_up':
        var = 'X_mass'
        BTagAK8deepup = True
    elif var == 'BTagAK8Weight_deep_down':
        var = 'X_mass'
        BTagAK8deepdown = True
    elif var == 'BTagAK8Weight_deep':
        var = 'X_mass'
        BTagAK8deep = True
    upAvg, downAvg, upMin, downMin, upMax, downMax = 0., 0., 2., 2., 0., 0.
    for k in sorted(selection.keys(), key=len, reverse=True):
        if k in cut:
            cut = cut.replace(k, selection[k])
    for i, s in enumerate(sign):
        if '_MZ' in s: m = int((s.split('_MZ')[1]).split('_MA')[0])
        elif '_M' in s: m = int(s.split('_M')[1])
        else: m = 0
        if treeRead:  # Project from tree
            tree[s] = TChain("tree")
            for j, ss in enumerate(sample[s]['files']):
                if not 'data' in s or ('data' in s and ss in pd):
                    tree[s].Add(NTUPLEDIR + ss + ".root")
            if variable[var]['nbins'] > 0:
                min_value = variable[var]['min']
                max_value = variable[var]['max']
                title = variable[var]['title']
                if 'isZtoNN' in cut:
                    if var == 'MET':
                        min_value = 200
                        max_value = 2000
                    elif var == 'DPhi':
                        title = "#Delta #varphi (AK8 jet-#slash{E}_{T})"
                    elif var == 'VH_deltaR':
                        title = "#Delta R (#slash{E}_{T}, AK8 jet)"
                hist[s] = TH1F(
                    s, ";" + title + ";Events;" +
                    ('log' if variable[var]['log'] else ''),
                    variable[var]['nbins'], min_value, max_value)
            else:
                hist[s] = TH1F(s, ";" + variable[var]['title'],
                               len(variable[var]['bins']) - 1,
                               array('f', variable[var]['bins']))
            hist[s].Sumw2()
            cutstring = "(eventWeightLumi)" + ("*(" + cut + ")")
            if var == 'LeptonWeightUp':
                cutstring = "(eventWeightLumi * LeptonWeightUp/LeptonWeight)" + (
                    "*(" + cut + ")")
            elif var == 'LeptonWeightDown':
                cutstring = "(eventWeightLumi * LeptonWeightDown/LeptonWeight)" + (
                    "*(" + cut + ")")
            elif var == 'TriggerWeightUp':
                cutstring = "(eventWeightLumi * TriggerWeightUp/TriggerWeight)" + (
                    "*(" + cut + ")")
            elif var == 'TriggerWeightDown':
                cutstring = "(eventWeightLumi * TriggerWeightDown/TriggerWeight)" + (
                    "*(" + cut + ")")
            #division by BTagAk4Weight_deep is because the weighted samples are used
            elif BTagAK4deepup:
                cutstring = "(eventWeightLumi * BTagAK4Weight_deep_up/BTagAK4Weight_deep)" + (
                    "*(" + cut + ")")
            elif BTagAK4deepdown:
                cutstring = "(eventWeightLumi * BTagAK4Weight_deep_down/BTagAK4Weight_deep)" + (
                    "*(" + cut + ")")
            elif BTagAK8deep:
                cutstring = "(eventWeightLumi * BTagAK8Weight_deep)" + (
                    "*(" + cut + ")")
            elif BTagAK8deepup:
                cutstring = "(eventWeightLumi * BTagAK8Weight_deep_up)" + (
                    "*(" + cut + ")")
            elif BTagAK8deepdown:
                cutstring = "(eventWeightLumi * BTagAK8Weight_deep_down)" + (
                    "*(" + cut + ")")
            tree[s].Project(s, var, cutstring)
            if not tree[s].GetTree() == None:
                hist[s].SetOption("%s" % tree[s].GetTree().GetEntriesFast())
        """
        for j, ss in enumerate(sample[s]['files']):
            file[ss] = TFile(NTUPLEDIR + ss + ".root", "READ")
            tmp = file[ss].Get("Sys/"+sys)
            if tmp == None: continue
            if not s in hist.keys(): hist[s] = tmp
            else:
                if antiCorr:
                    for x in range(1, hist[s].GetNbinsX()+1): hist[s].SetBinContent(x, hist[s].GetBinContent(x)+tmp.GetBinContent(tmp.GetNbinsX()+1-x))
                else: hist[s].Add( tmp )
            
            if isShape:
                tmp = file[ss].Get("Sys/"+sys+"_up")
                print "Sys/"+sys+"_up"
                if tmp == None: continue
                if not s in histUp.keys(): histUp[s] = tmp
                else: histUp[s].Add( tmp )
                #
                tmp = file[ss].Get("Sys/"+sys+"_down")
                if tmp == None: continue
                if not s in histDown.keys(): histDown[s] = tmp
                else: histDown[s].Add( tmp )
            
        if 'accept' in sys:
            norm = None
            for j, ss in enumerate(sample[s]['files']):
                tmp = file[ss].Get("Sys/PDF_scale")
                if tmp == None: continue
                if norm == None: norm = tmp
                else: norm.Add( tmp )
            hist[s].Divide(norm)
        """
        if (isShape):
            shape = TF1("shape", "gaus", 0, 5000)
            shapeUp = TF1("shapeUp", "gaus", 0, 5000)
            shapeDown = TF1("shapeDown", "gaus", 0, 5000)
            hist[s].Fit(shape, "Q0", "")
            histUp[s].Fit(shapeUp, "Q0", "")
            histDown[s].Fit(shapeDown, "Q0", "")
            if 'scale' in sys or 'unc' in sys:
                up[s] = histUp[s].GetMean() / hist[s].GetMean()
                down[s] = histDown[s].GetMean() / hist[s].GetMean()
#                up[s] = shapeUp.GetParameter(1)/shape.GetParameter(1)
#                down[s] = shapeDown.GetParameter(1)/shape.GetParameter(1)
            elif 'res' in sys:
                up[s] = histUp[s].GetRMS() / hist[s].GetRMS()
                down[s] = histDown[s].GetRMS() / hist[s].GetRMS()


#                up[s] = shapeUp.GetParameter(2)/shape.GetParameter(2)
#                down[s] = shapeDown.GetParameter(2)/shape.GetParameter(2)
        else:
            up[s] = hist[s].GetBinContent(
                hist[s].FindBin(+1)) / hist[s].GetBinContent(
                    hist[s].FindBin(0))
            down[s] = hist[s].GetBinContent(
                hist[s].FindBin(-1)) / hist[s].GetBinContent(
                    hist[s].FindBin(0))
        gUp.SetPoint(i, m, up[s])
        gDown.SetPoint(i, m, down[s])
        #if mass < 1000: continue
        upAvg += up[s]
        downAvg += down[s]
        if abs(up[s]) > upMax: upMax = abs(up[s])
        if abs(up[s]) < upMin: upMin = abs(up[s])
        if abs(down[s]) > downMax: downMax = abs(down[s])
        if abs(down[s]) < downMin: downMin = abs(down[s])

    upAvg /= len(sign)
    downAvg /= len(sign)

    print " ---", sys, "--- | up: %.3f, down: %.3f, average: %.3f" % (
        upAvg, downAvg, abs(upAvg - 1 + 1. - downAvg) /
        2.), "|", "^{%.1f-%.1f}_{%.1f-%.1f}" % (100. * (1. - upMin), 100. *
                                                (1. - upMax), 100. *
                                                (downMin - 1.), 100. *
                                                (downMax - 1.))

    c1 = TCanvas("c1", "Signals", 800, 600)
    c1.cd()
    c1.GetPad(0).SetTicky(2)

    gUp.Draw("AL")
    gDown.Draw("SAME, L")
    gUp.GetYaxis().SetRangeUser(0.65, 1.35)
    gUp.GetXaxis().SetTitle("m_{X} (GeV)")
    gUp.GetYaxis().SetTitle("Uncertainty")

    leg = TLegend(0.5, 0.90 - 0.20, 0.9, 0.90)
    leg.SetBorderSize(0)
    leg.SetFillStyle(0)  #1001
    leg.SetFillColor(0)
    leg.SetHeader(sys.replace('_', ' '))
    leg.AddEntry(gUp, "+1 s. d. (%.1f%%)" % (100. * (upAvg - 1.)), "l")
    leg.AddEntry(gDown, " -1 s. d. (%.1f%%)" % (100. * (1. - downAvg)), "l")
    leg.Draw()

    drawCMS(-1, "Simulation", False)
    c1.Update()

    filename = sys
    if sys.startswith('W_mass') or sys.startswith('Z_mass'):
        filename += "_" + sign[0][:3]
    #    c1.Print("plots/Systematics/"+filename+".png")
    #    c1.Print("plots/Systematics/"+filename+".pdf")
    if not gROOT.IsBatch(): raw_input("Press Enter to continue...")
    if 'doubleB' in sys or 'subjet' in sys or 'mass' in sys:
        print sys + " = {",
        for m in [
                800, 1000, 1100, 1200, 1300, 1400, 1500, 1600, 1700, 1800,
                2000, 2500, 3000, 3500, 4000, 4500
        ]:
            print "%d : [%.3f, %.3f], " % (m, gUp.Eval(m), gDown.Eval(m)),
        print "}"
    if 'extr' in sys or 'tagging' in sys:
        print sys + " = {",
        for m in [800, 1000, 1500, 2000, 2500, 3000, 3500, 4000, 4500]:
            print "%d : [%.3f, %.3f], " % (m, gUp.Eval(m), gDown.Eval(m)),
        print "}"
    if 'QCD_scale' in sys or 'PDF_scale' in sys:
        print sys + " = {",
        for m in range(800, 4500 + 1, 10):
            print "%d : [%.3f, %.3f], " % (m, gUp.Eval(m), gDown.Eval(m)),
        print "}"
예제 #26
0
    files_rate_L1[a] = TFile(outpath+"Graph_HV_scan_rate_SL1_L1_"+run_interval+"_"+a+".root", 'READ')
    graphs_rate_L1[a] = TGraphAsymmErrors(files_rate_L1[a].Get("HV_scan_rate_SL1_L1_"+run_interval))
    files_rate_L4[a] = TFile(outpath+"Graph_HV_scan_rate_SL1_L4_"+run_interval+"_"+a+".root", 'READ')
    graphs_rate_L4[a] = TGraphAsymmErrors(files_rate_L4[a].Get("HV_scan_rate_SL1_L4_"+run_interval))


##Efficiency SL1_L1    
can_HV_scan_SL1_L1 = TCanvas("can_compare_HV_scan_SL1_L1","can_compare_HV_scan_SL1_L1", 1000, 800)
can_HV_scan_SL1_L1.SetGrid()
can_HV_scan_SL1_L1.cd()

leg_L1 = TLegend(0.2, 0.7, 0.4, 0.9)
leg_L1.SetBorderSize(0)
leg_L1.SetFillStyle(0)
leg_L1.SetFillColor(0)
x_min = 3190
x_max = 3610
imin = 100
for i, j in enumerate(graphs_L1):
    if "L1" in j:
        imin = min(imin,i)
        graphs_L1[j].SetMarkerSize(1.)
        graphs_L1[j].SetMarkerStyle(21)
        graphs_L1[j].SetMarkerColor(colors[i])
        graphs_L1[j].SetFillColor(colors[i])
        graphs_L1[j].SetLineColor(colors[i])
        graphs_L1[j].SetLineWidth(3)
        leg_L1.AddEntry(graphs_L1[j],j,'PL')
        graphs_L1[j].GetXaxis().SetLimits(x_min,x_max)
        graphs_L1[j].GetXaxis().SetTitle("HV [V]")
예제 #27
0
class TriggerRate(object):
    """
	Class that will plot one or more trigger rate histograms into the TPad provided.
	
	Author Mark Grimes ([email protected])
	Date 02/Sep/2013
	"""
    instantiationCount = 0  # Need this to get around root's stupid requirement for globally unique names

    def __init__(self, pad):
        self.instantiationCount = TriggerRate.instantiationCount
        TriggerRate.instantiationCount += 1

        self.histograms = []
        self.verticalLines = []
        # Create a legend. This might not actually be plotted if drawLegend is changed to False
        self.legend = TLegend(0.59, 0.72 * 0.9, 0.99, 0.95 * 0.9)
        self.legend.SetTextSize(0.04)
        self.legend.SetFillColor(0)
        self.drawLegend = True
        self.pad = pad
        #self.pad.cd()
        self.pad.SetGrid()
        self.pad.SetLogy()
        self.maxiumumBinHeight = 0
        self.minimumBinHeight = 999999999
        self.axisLabelSize = None
        self.axisTitleSize = None
        self.axisTitleOffset = None

    def add(self, histogram, legendTitle=None):
        availableColours = [1, 2, 4, 8, 9, 11, 41, 44, 46]
        if legendTitle == None: legendTitle = histogram.GetTitle()
        self.histograms.append(histogram.Clone())
        # Make sure the copy has a globally unique name
        self.histograms[-1].SetName(self.histograms[-1].GetName() + "_hist" +
                                    str(len(self.histograms)) + "inst" +
                                    str(self.instantiationCount))
        self.histograms[-1].SetDirectory(
            0)  # Make sure the copy isn't saved to disk
        self.histograms[-1].SetLineColor(
            availableColours[(len(self.histograms) - 1) %
                             len(availableColours)])
        self.histograms[-1].SetMarkerColor(
            availableColours[(len(self.histograms) - 1) %
                             len(availableColours)])
        self.histograms[-1].SetStats(0)
        if self.axisLabelSize == None:
            self.axisLabelSize = self.histograms[-1].GetXaxis().GetLabelSize()
        if self.axisTitleSize == None:
            self.axisTitleSize = self.histograms[-1].GetXaxis().GetTitleSize()
        if self.axisTitleOffset == None:
            self.axisTitleOffset = self.histograms[-1].GetYaxis(
            ).GetTitleOffset()
        self.histograms[-1].GetYaxis().SetTitle("Rate/kHz")
        self.histograms[-1].GetXaxis().SetTitle("Offline threshold/GeV")
        self.legend.AddEntry(self.histograms[-1], legendTitle)
        # See if the histogram maximum is larger than the current maximum
        # I can have a look at histogram.GetMaximumBin() but that doesn't include
        # the error, which I want.
        for bin in range(1, self.histograms[-1].GetXaxis().GetNbins() + 1):
            #bin=self.histograms[-1].GetMaximumBin()
            try:
                max = self.histograms[-1].GetBinContent(
                    bin) + self.histograms[-1].GetBinErrorUp(bin)
            except:
                max = self.histograms[-1].GetBinContent(
                    bin) + self.histograms[-1].GetBinError(bin)
            if max > self.maxiumumBinHeight: self.maxiumumBinHeight = max
            # Minimum is not actaully used to change the plot, but I need to know it to draw any vertical lines
            try:
                min = self.histograms[-1].GetBinContent(
                    bin) - self.histograms[-1].GetBinErrorDown(bin)
            except:
                min = self.histograms[-1].GetBinContent(
                    bin) - self.histograms[-1].GetBinError(bin)
            if min < self.minimumBinHeight: self.minimumBinHeight = min

    def addVerticalLine(self, xPosition, colour=1, thickness=3):
        self.verticalLines.append(
            TLine(xPosition, 0.00001, xPosition, self.maxiumumBinHeight))
        self.verticalLines[-1].SetLineColor(colour)
        self.verticalLines[-1].SetLineWidth(thickness)

    def draw(self):
        self.pad.cd()
        for index in range(0, len(self.histograms)):
            #self.histograms[index].SetMinimum( self.minimumBinHeight*0.9 )
            self.histograms[index].SetMaximum(self.maxiumumBinHeight * 1.2)
            self.histograms[index].GetYaxis().SetTitleSize(self.axisTitleSize)
            self.histograms[index].GetYaxis().SetTitleOffset(
                self.axisTitleOffset)
            self.histograms[index].GetXaxis().SetTitleSize(self.axisTitleSize)
            if index == 0: self.histograms[index].Draw()
            else: self.histograms[index].Draw("same")
        for line in self.verticalLines:
            line.SetY1(self.minimumBinHeight * 0.9)
            line.SetY2(self.maxiumumBinHeight * 1.2)
            line.Draw()
        if self.drawLegend: self.legend.Draw()
        self.pad.Update()
예제 #28
0
    def getGraph(self):
        from array import array
        from ROOT import TMultiGraph, TLegend, TGraphAsymmErrors
        n = len(self.__x)
        if n != len(self.__y) or n != len(self.__yErrLow) or n != len(
                self.__yErrHigh):
            raise StandardError, "The length of the x(%s), y(%s) and y error(%s,%s) lists does not match" % (
                len(self.__x), len(self.__y), len(
                    self.__yErrLow), len(self.__yErrHigh))

        result = TMultiGraph()
        legendPosition = [
            float(i) for i in self.__getStyleOption("legendPosition").split()
        ]
        legend = TLegend(*legendPosition)
        legend.SetFillColor(0)
        result.SetTitle("%s;%s;%s" %
                        (self.__title, self.__xTitle, self.__yTitle))
        #(refArrays, refLabel) = self.__getRefernceGraphArrays()
        #refGraph = TGraphAsymmErrors(*refArrays)

        #refGraph.SetLineWidth(2)
        #refGraph.SetLineColor(int(self.__config.get("reference","lineColor")))
        #refGraph.SetFillColor(int(self.__config.get("reference","fillColor")))
        #result.Add(refGraph,"L3")
        #legend.AddEntry(refGraph,self.__config.get("reference","name"))

        xErr = array("d", [0 for i in range(n)])
        print "__x = ", self.__x
        print "__y = ", self.__y
        lst = []

        for inc in range(0, n):
            d = {}
            d['run'] = self.__runs[inc]
            d['x'] = self.__x[inc]
            d['y'] = self.__y[inc]
            d['yErr'] = self.__yErrLow[inc]
            d['yTitle'] = self.__yTitle
            if self.__config.has_option(self.__section,
                                        "yMin") and self.__config.has_option(
                                            self.__section, "yMax"):
                d['ymin'] = float(self.__config.get(self.__section, "yMin"))
                d['ymax'] = float(self.__config.get(self.__section, "yMax"))
            else:
                d['ymin'] = 0
                d['ymax'] = 0
            lst.append(d)

        obj = {}
        obj[self.__title] = lst
        #finalObj[self.__title]=lst
        #finalList.append(finalObj)

        # save_path = './JSON/'
        #completeName = os.path.join(save_path, self.__title+".json")
        if not os.path.exists("JSON"):
            os.makedirs("JSON")
        with open("./JSON/" + self.__title + ".json", 'w') as outfile:
            json.dump(obj, outfile, indent=4)
        print json.dumps(obj, indent=2)

        graph = TGraphAsymmErrors(n, self.__x, self.__y, xErr, xErr,
                                  self.__yErrLow, self.__yErrHigh)
        graph.SetLineWidth(2)
        graph.SetFillColor(0)
        graph.SetLineColor(int(self.__getStyleOption("lineColor")))
        graph.SetMarkerColor(int(self.__getStyleOption("markerColor")))
        graph.SetMarkerStyle(int(self.__getStyleOption("markerStyle")))
        graph.SetMarkerSize(float(self.__getStyleOption("markerSize")))

        sysGraph = TGraphAsymmErrors(n, self.__x, self.__y, xErr, xErr,
                                     self.__ySysErrLow, self.__ySysErrHigh)
        sysGraph.SetLineWidth(1)
        sysGraph.SetFillColor(0)
        sysGraph.SetLineColor(int(self.__getStyleOption("lineColor")))
        sysGraph.SetMarkerColor(int(self.__getStyleOption("markerColor")))
        sysGraph.SetMarkerStyle(int(self.__getStyleOption("markerStyle")))
        sysGraph.SetMarkerSize(float(self.__getStyleOption("markerSize")))
        #TOMAS removed sys error from the plot
        #result.Add(sysGraph,"[]")
        result.Add(graph, "P")
        #        result.SetName("MultiPlots")
        #         result.SetTitle("%s;%s;%s"%(self.__title,self.__xTitle,self.__yTitle))
        result.SetName("MG_%s" % (self.__title))
        legend.AddEntry(graph, self.__getStyleOption("name"))

        #for (x,y,yErr) in zip(self.__x, self.__y, zip(self.__yErrLow,self.__yErrHigh)):
        #    self.__addAnnotaion("hallo",x,y,yErr)

        return (result, legend)
예제 #29
0
def createPlots_(plot, geometry):
    """Cumulative material budget from simulation.
    
       Internal function that will produce a cumulative profile of the
       material budget inferred from the simulation starting from the
       single detectors that compose the tracker. It will iterate over
       all existing detectors contained in the DETECTORS
       dictionary. The function will automatically skip non-existent
       detectors.

    """

    IBs = ["InnerServices", "Phase2PixelBarrel", "TIB", "TIDF", "TIDB"]
    theDirname = "Figures"

    if plot not in plots.keys():
        print("Error: chosen plot name not known %s" % plot)
        return

    hist_X0_detectors = OrderedDict()
    hist_X0_IB = None
    hist_X0_elements = OrderedDict()

    for subDetector, color in DETECTORS.items():
        h = get1DHisto_(subDetector, plots[plot].plotNumber, geometry)
        if not h:
            print('Warning: Skipping %s' % subDetector)
            continue
        hist_X0_detectors[subDetector] = h

        # Merge together the "inner barrel detectors".
        if subDetector in IBs:
            hist_X0_IB = assignOrAddIfExists_(hist_X0_IB,
                                              hist_X0_detectors[subDetector])

        # category profiles
        for label, [num, color, leg] in hist_label_to_num.items():
            if label is 'SUM': continue
            hist_label = get1DHisto_(subDetector, num + plots[plot].plotNumber,
                                     geometry)
            hist_X0_elements[label] = assignOrAddIfExists_(
                hist_X0_elements.setdefault(label, None),
                hist_label,
            )
            hist_X0_elements[label].SetFillColor(color)

    cumulative_matbdg = TH1D("CumulativeSimulMatBdg", "CumulativeSimulMatBdg",
                             hist_X0_IB.GetNbinsX(),
                             hist_X0_IB.GetXaxis().GetXmin(),
                             hist_X0_IB.GetXaxis().GetXmax())
    cumulative_matbdg.SetDirectory(0)

    # colors
    for det, color in DETECTORS.items():
        setColorIfExists_(hist_X0_detectors, det, color)

    # First Plot: BeamPipe + Pixel + TIB/TID + TOB + TEC + Outside
    # stack
    stackTitle_SubDetectors = "Tracker Material Budget;%s;%s" % (
        plots[plot].abscissa, plots[plot].ordinate)
    stack_X0_SubDetectors = THStack("stack_X0", stackTitle_SubDetectors)
    for det, histo in hist_X0_detectors.items():
        stack_X0_SubDetectors.Add(histo)
        cumulative_matbdg.Add(histo, 1)

    # canvas
    can_SubDetectors = TCanvas("can_SubDetectors", "can_SubDetectors", 800,
                               800)
    can_SubDetectors.Range(0, 0, 25, 25)
    can_SubDetectors.SetFillColor(kWhite)

    # Draw
    stack_X0_SubDetectors.SetMinimum(plots[plot].ymin)
    stack_X0_SubDetectors.SetMaximum(plots[plot].ymax)
    stack_X0_SubDetectors.Draw("HIST")
    stack_X0_SubDetectors.GetXaxis().SetLimits(plots[plot].xmin,
                                               plots[plot].xmax)

    # Legenda
    theLegend_SubDetectors = TLegend(0.180, 0.8, 0.98, 0.92)
    theLegend_SubDetectors.SetNColumns(3)
    theLegend_SubDetectors.SetFillColor(0)
    theLegend_SubDetectors.SetFillStyle(0)
    theLegend_SubDetectors.SetBorderSize(0)

    for det, histo in hist_X0_detectors.items():
        theLegend_SubDetectors.AddEntry(histo, det, "f")

    theLegend_SubDetectors.Draw()

    # text
    text_SubDetectors = TPaveText(0.180, 0.727, 0.402, 0.787, "NDC")
    text_SubDetectors.SetFillColor(0)
    text_SubDetectors.SetBorderSize(0)
    text_SubDetectors.AddText("CMS Simulation")
    text_SubDetectors.SetTextAlign(11)
    text_SubDetectors.Draw()

    # Store
    can_SubDetectors.Update()
    if not checkFile_(theDirname):
        os.mkdir(theDirname)
    can_SubDetectors.SaveAs("%s/Tracker_SubDetectors_%s.pdf" %
                            (theDirname, plot))
    can_SubDetectors.SaveAs("%s/Tracker_SubDetectors_%s.root" %
                            (theDirname, plot))

    # Second Plot: BeamPipe + SEN + ELE + CAB + COL + SUP + OTH/AIR +
    # Outside stack
    stackTitle_Materials = "Tracker Material Budget;%s;%s" % (
        plots[plot].abscissa, plots[plot].ordinate)
    stack_X0_Materials = THStack("stack_X0", stackTitle_Materials)
    stack_X0_Materials.Add(hist_X0_detectors["BeamPipe"])
    for label, [num, color, leg] in hist_label_to_num.items():
        if label is 'SUM':
            continue
        stack_X0_Materials.Add(hist_X0_elements[label])

    # canvas
    can_Materials = TCanvas("can_Materials", "can_Materials", 800, 800)
    can_Materials.Range(0, 0, 25, 25)
    can_Materials.SetFillColor(kWhite)

    # Draw
    stack_X0_Materials.SetMinimum(plots[plot].ymin)
    stack_X0_Materials.SetMaximum(plots[plot].ymax)
    stack_X0_Materials.Draw("HIST")
    stack_X0_Materials.GetXaxis().SetLimits(plots[plot].xmin, plots[plot].xmax)

    # Legenda
    theLegend_Materials = TLegend(0.180, 0.8, 0.95, 0.92)
    theLegend_Materials.SetNColumns(3)
    theLegend_Materials.SetFillColor(0)
    theLegend_Materials.SetBorderSize(0)

    theLegend_Materials.AddEntry(hist_X0_detectors["BeamPipe"], "Beam Pipe",
                                 "f")
    for label, [num, color, leg] in hist_label_to_num.items():
        if label is 'SUM':
            continue
        theLegend_Materials.AddEntry(hist_X0_elements[label], leg, "f")
    theLegend_Materials.Draw()

    # text
    text_Materials = TPaveText(0.180, 0.727, 0.402, 0.787, "NDC")
    text_Materials.SetFillColor(0)
    text_Materials.SetBorderSize(0)
    text_Materials.AddText("CMS Simulation")
    text_Materials.SetTextAlign(11)
    text_Materials.Draw()

    # Store
    can_Materials.Update()
    can_Materials.SaveAs("%s/Tracker_Materials_%s.pdf" % (theDirname, plot))
    can_Materials.SaveAs("%s/Tracker_Materials_%s.root" % (theDirname, plot))

    return cumulative_matbdg
예제 #30
0
if "PV" in Group:
    X_axis="NPU"    
print "X_axis= ",X_axis

for obj in (1,2):
    if (obj==1):
        Prefix+="_LCT"
    if (obj==2):
        Prefix=Prefix.replace("LCT","SEG")

    c1=TCanvas("c1","c1",600,600)
    c2=TCanvas("c2","c2",600,600)
    leg=TLegend(0.45, 0.25, 0.95, 0.36)
   
    leg.SetNColumns(2) 
    leg.SetFillColor(0)
    leg.SetFillStyle(0)
    leg.SetShadowColor(0)
    leg.SetBorderSize(0)
    leg.SetTextFont(132)
    leg.SetTextSize(0.04)

    leg_ME1=TLegend(0.45, 0.25, 0.95, 0.36)
   
    leg_ME1.SetNColumns(2) 
    leg_ME1.SetFillColor(0)
    leg_ME1.SetFillStyle(0)
    leg_ME1.SetShadowColor(0)
    leg_ME1.SetBorderSize(0)
    leg_ME1.SetTextFont(132)
    leg_ME1.SetTextSize(0.04)