def study_cal_eff(): # Import data and MC files: f_data = TFile.Open("../trees_5gev_e/data_nn50.root", 'read') t_data = f_data.data f_mc = TFile.Open("../trees_5gev_e/lucas.root", 'read') t_mc = f_mc.lumical t_mc.AddFriend("lumical_noise=lumical", "../trees_5gev_e/lucas_geocuts_noise_cal.root") t_mc.AddFriend("lumical_eff=lumical", "../trees_5gev_e/lucas_geocuts_noise_cal_eff.root") c = TCanvas() hs = THStack("hs", "title") t_data.Draw("energy*(layer > 1)>>h_data50(200, 0, 50)", "energy*(layer > 1) > 0") h_data50 = gROOT.FindObject("h_data50") h_data50.SetTitle("Data") h_data50.SetLineWidth(2) h_data50.SetLineColor(1) hs.Add(h_data50, "histo") t_mc.Draw("cal_energy_new/0.0885>>h_mc(200, 0, 50)", "cal_energy_new/0.0885 > 0", "", 100000) h_mc = gROOT.FindObject("h_mc") h_mc.SetTitle("MC smearing and cal eff") h_mc.SetLineWidth(2) h_mc.SetLineColor(3) h_mc.Scale(t_data.GetEntries() / 100000) #t_mc.GetEntries()) hs.Add(h_mc, "histo") t_mc.Draw("cal_energy_smeared7/0.0885>>h_mc7(200, 0, 50)", "cal_energy_smeared7/0.0885 > 0", "", 100000) h_mc7 = gROOT.FindObject("h_mc7") h_mc7.SetTitle("MC smearing=0.7*#sigma") h_mc7.SetLineWidth(2) h_mc7.SetLineColor(2) h_mc7.Scale(t_data.GetEntries() / 100000) #t_mc.GetEntries()) hs.Add(h_mc7, "histo") print(h_mc7.GetEntries()) hs.Draw("nostack") hs.SetTitle( "Deposited energy in the pads of calorimeter;E, [MIP]; N_{hits}") c.SetGridx() c.SetGridy() c.BuildLegend() c.Update() input("wait")
def study_trigger(): # Import data and MC files: f_data = TFile.Open("../trees_5gev_e/.root", 'read') t_data = f_data.data f_mc = TFile.Open("../trees_5gev_e/lucas.root", 'read') t_mc = f_mc.lumical t_mc.AddFriend("lumical_tr_clusters=lumical", "../trees_5gev_e/.root") c = TCanvas() t_data.Draw("tr1_n_clusters>>h_data(6, 0, 6)") h_data = gROOT.FindObject("h_data") h_data.SetTitle("Data") h_data.SetLineWidth(2) h_data.SetLineColor(1) t_mc.Draw("tr1_n_hits>>h_mc(6, 0, 6)") h_mc = gROOT.FindObject("h_mc") h_mc.SetTitle("MC") h_mc.SetLineWidth(2) h_mc.SetLineColor(2) h_mc.Scale(t_data.GetEntries() / t_mc.GetEntries()) t_mc.Draw("tr1_n_clusters>>h_mc2(6, 0, 6)", "n_triggers == 3") h_mc2 = gROOT.FindObject("h_mc2") h_mc2.SetTitle("MC w/ trigger") h_mc2.SetLineWidth(2) h_mc2.SetLineColor(4) h_mc2.Scale(t_data.GetEntries() / t_mc.GetEntries()) hs = THStack("hs", "title") hs.Add(h_data, "histo") hs.Add(h_mc, "histo") hs.Add(h_mc2, "histo") hs.Draw("nostack") hs.SetTitle( "Number of clusters in the 1st tracker;N_{particles}; N_{events}") c.SetGridx() c.SetGridy() c.BuildLegend() c.Update() input("wait")
legend.AddEntry(errorband, "Uncertainty", "f") pad1.cd() stack.Draw('HIST') rebinnedData.Draw('E,X0,SAME') legend.Draw("same") stack.GetXaxis().SetTitle('') stack.GetXaxis().SetLabelSize(0) stack.GetYaxis().SetLabelSize(gStyle.GetLabelSize() / (1. - padRatio + padOverlap)) stack.GetYaxis().SetTitleSize(gStyle.GetTitleSize() / (1. - padRatio + padOverlap)) stack.GetYaxis().SetTitleOffset(gStyle.GetTitleYOffset() * (1. - padRatio + padOverlap)) stack.SetTitle(';;Events/%i GeV ' % rebin) CMS_lumi.channelText = channelText CMS_lumi.channelText = regionText CMS_lumi.writeChannelText = True CMS_lumi.writeExtraText = True CMS_lumi.CMS_lumi(pad1, 4, 11) if not noData: ratio = rebinnedData.Clone("temp") temp = stack.GetStack().Last().Clone("temp") for i_bin in range(1, temp.GetNbinsX() + 1): temp.SetBinError(i_bin, 0.) ratio.Divide(temp) else: ratio = rebinnedData.Clone("temp")
def plotStack(): inputfile = TFile(filename, "read") if inputfile.IsZombie(): print("inputfile is Zombie") sys.exit() # loop over features for feature, values in features.items(): file = open( "%s%s_%s_isNorm%s_wtStat%s_isBlind%s.txt" % (outputdir, feature, plotname, normalization, showStats, blind), "w") file.write( "\\begin{table}[]\n\\resizebox{!}{.33\\paperheight}{\n \\begin{tabular}{|l|l|l|}\n\\hline\nProcess & Yield & Entries \\\\ \\hline \n" ) # set up legend legend = TLegend(0.2, 0.6, 0.7, 0.88) legend.SetHeader("%i %s" % (year, region)) legend.SetNColumns(4) legend.SetBorderSize(0) c, pad1, pad2 = createCanvasPads() hstack = THStack("hstack", "hstack") hstack.SetTitle( "#scale[0.9]{#font[22]{CMS} #font[12]{Preliminary} %i at %.2f fb^{-1}(13TeV)}" % (year, luminosity[year])) histName = "TTH_" + feature # assuming TTH is always there if not inputfile.GetListOfKeys().Contains(histName): print("%s doesn't have histogram %s, please use another hist " % (inputfile, histName)) sys.exit() h0 = inputfile.Get(histName) h_totalsig = h0.Clone("h_totalsig") h_totalsig.SetDirectory(0) h_totalsig.Reset() h_totalsig.SetMarkerStyle(20) h_totalsig.Sumw2() h_totalbkg = h0.Clone("h_totalbkg") h_totalbkg.SetDirectory(0) h_totalbkg.Reset() h_totalbkg.SetMarkerStyle(20) h_totalbkg.Sumw2() h_totalmc = h0.Clone("h_totalmc") h_totalmc.SetDirectory(0) h_totalmc.Reset() h_totalmc.SetLineColor(kBlack) h_totalmc.SetFillColor(kGray + 3) h_totalmc.SetFillStyle(3001) h_totalmc.SetTitle("") #h_totalmc.SetMinimum(0.8) #h_totalmc.SetMaximum(1.35) h_totalmc.Sumw2() h_totalmc.SetStats(0) h_dataobs = h0.Clone("h_dataobs") h_dataobs.SetDirectory(0) h_dataobs.Reset() h_dataobs.SetMarkerStyle(20) # loop over samples for sample in Samples: hist = h_totalmc.Clone(sample) hist.SetDirectory(0) hist.Reset() if sample not in Process: print("sample %s is not in Process " % sample) continue # loop over data: if sample == "Data" or sample == "data": for p in Process[sample]: if p not in sampleName: print("process %s is not in sampleName " % s) continue hist_name = p + "_" + feature if not inputfile.GetListOfKeys().Contains(hist_name): print("%s doesn't have histogram %s" % (inputfile, hist_name)) continue h1 = inputfile.Get(hist_name).Clone(hist_name) h1.SetDirectory(0) h_dataobs.Add(h1) error = Double(0) h1.IntegralAndError(0, h1.GetNbinsX(), error) if not blind: file.write( "%s & %.2f +/- %.2f & %i \\\\ \\hline \n" % (p.replace('_', '\\_'), h1.Integral(), error, h1.GetEntries())) # loop over mc # loop over signal elif sample in Signals: for p in Process[sample]: if p not in sampleName: print("process %s is not in sampleName " % s) continue hist_name = p + "_" + feature if not inputfile.GetListOfKeys().Contains(hist_name): print("%s doesn't have histogram %s" % (filename, hist_name)) continue h1 = inputfile.Get(hist_name).Clone(hist_name) h1.SetDirectory(0) if p == "FakeSub" and sample == "Fakes": hist.Add(h1, -1) h_totalsig.Add(h1, -1) h_totalmc.Add(h1, -1) else: hist.Add(h1) h_totalsig.Add(h1) h_totalmc.Add(h1) error = Double(0) h1.IntegralAndError(0, h1.GetNbinsX(), error) if h1.Integral() < 0.05 or h1.GetEntries() < 100: file.write( "\\textcolor{red}{%s} & %.2f +/- %.2f & %i \\\\ \\hline \n" % (p.replace('_', '\\_'), h1.Integral(), error, h1.GetEntries())) else: file.write( "%s & %.2f +/- %.2f & %i \\\\ \\hline \n" % (p.replace('_', '\\_'), h1.Integral(), error, h1.GetEntries())) hist.SetFillColor(Color[sample]) hist.SetLineColor(kBlack) hist.SetFillStyle(Style[sample]) if sample == "TH" and tH != 1: hist.Scale(tH) hist.SetFillColor(Color[sample]) hist.SetLineColor(kBlack) hist.SetFillStyle(Style[sample]) hstack.Add(hist) legend.AddEntry(hist, "%s * %i" % (sample, tH), "f") else: hstack.Add(hist) legend.AddEntry(hist, sample, "f") # create required parts # loop over bkg else: for p in Process[sample]: if p not in sampleName: print("process %s is not in sampleName " % p) continue hist_name = p + "_" + feature if not inputfile.GetListOfKeys().Contains(hist_name): print("%s doesn't have histogram %s" % (filename, hist_name)) continue h1 = inputfile.Get(hist_name).Clone(hist_name) h1.SetDirectory(0) if p == "FakeSub" and sample == "Fakes": hist.Add(h1, -1) h_totalmc.Add(h1, -1) h_totalbkg.Add(h1, -1) else: hist.Add(h1) h_totalmc.Add(h1) h_totalbkg.Add(h1) error = Double(0) h1.IntegralAndError(0, h1.GetNbinsX(), error) if h1.Integral() < 0.05 or h1.GetEntries() < 100: file.write( "\\textcolor{red}{%s} & %.2f +/- %.2f & %i \\\\ \\hline \n" % (p.replace('_', '\\_'), h1.Integral(), error, h1.GetEntries())) else: file.write( "%s & %.2f +/- %.2f & %i \\\\ \\hline \n" % (p.replace('_', '\\_'), h1.Integral(), error, h1.GetEntries())) hist.SetFillColor(Color[sample]) hist.SetLineColor(kBlack) hist.SetFillStyle(Style[sample]) if sample == "TH" and tH != 1: hist.Scale(tH) hist.SetFillColor(Color[sample]) hist.SetLineColor(kBlack) hist.SetFillStyle(Style[sample]) hstack.Add(hist) legend.AddEntry(hist, "%s * %i" % (sample, tH), "f") else: hstack.Add(hist) legend.AddEntry(hist, sample, "f") error = Double(0) h_totalsig.IntegralAndError(0, h_totalsig.GetNbinsX(), error) file.write("signal & %.2f +/- %.2f & %i \\\\ \\hline \n" % (h_totalsig.Integral(), error, h_totalsig.GetEntries())) error = Double(0) h_totalbkg.IntegralAndError(0, h_totalbkg.GetNbinsX(), error) file.write("bkg & %.2f +/- %.2f & %i \\\\ \\hline \n" % (h_totalbkg.Integral(), error, h_totalbkg.GetEntries())) # create required parts if blind: h_sqrtB = createSqrt(h_totalbkg) h_MCerr = createTotalMCErr(h_sqrtB, values["xlabel"]) h_ratio = createRatio(h_totalsig, h_sqrtB, values["xlabel"], normalization) else: h_MCerr = createTotalMCErr(h_totalmc, feature) h_ratio = createRatio(h_dataobs, h_totalmc, values["xlabel"], normalization) legend.AddEntry(h_dataobs, "observed", "lep") legend.AddEntry(h_totalmc, "Uncertainty", "f") # draw everything pad1.cd() if values["logy"] == 1: pad1.SetLogy() maximum = h_dataobs.GetMaximum() upperbound = 2. * maximum lowerbound = -maximum / 40. if values["logy"] == 1: upperbound = 1000 * maximum lowerbound = 0.1 hstack.SetMinimum(lowerbound) hstack.SetMaximum(upperbound) hstack.Draw("HISTY") # Adjust y-axis settings y = hstack.GetYaxis() y.SetTitle("Events ") y.SetTitleSize(25) y.SetTitleFont(43) y.SetTitleOffset(1.55) y.SetLabelFont(43) y.SetLabelSize(20) nbins = h_ratio.GetNbinsX() #hstack.GetXaxis().SetRange(0, nbins+1) hstack.GetXaxis().SetRangeUser(values["min"], values["max"]) h_totalmc.Draw("e2same") if not blind: h_dataobs.Draw("same") legend.Draw("same") pad2.cd() if blind: h_ratio.SetMinimum(0.) #maximum = h_ratio.GetMaximum() #upperbound = 1.5*maximum #h_ratio.SetMaximum(upperbound) h_ratio.SetMaximum(3.) h_ratio.GetXaxis().SetRangeUser(values["min"], values["max"]) h_ratio.Draw("") else: h_MCerr.SetMinimum(0.5) h_MCerr.SetMaximum(1.8) h_MCerr.GetXaxis().SetRangeUser(values["min"], values["max"]) h_MCerr.Draw("e2") h_ratio.Draw("same") c.SaveAs( "%s%s_%s_isNorm%s_wtStat%s_isBlind%s_stack.png" % (outputdir, feature, plotname, normalization, showStats, blind)) file.write("\\end{tabular}\n}\n\\end{table}\n") file.close() inputfile.Close()
legend.AddEntry(rebinnedHist[ih], template_categoryName[ih], 'f') pad1.cd() stack.Draw('HIST') rebinnedData.Draw('E,X0,SAME') legend.Draw("same") stack.GetXaxis().SetTitle('') stack.GetXaxis().SetLabelSize(0) stack.GetYaxis().SetLabelSize(gStyle.GetLabelSize() / (1. - padRatio + padOverlap)) stack.GetYaxis().SetTitleSize(gStyle.GetTitleSize() / (1. - padRatio + padOverlap)) stack.GetYaxis().SetTitleOffset(gStyle.GetTitleYOffset() * (1. - padRatio + padOverlap)) stack.SetTitle(';;<Events/GeV>') # '%rebin) #CMS_lumi.channelText = (channelText+"\\n"+regionText) #if postfitPlots: CMS_lumi.channelText =channelText+"\\n "+regionText+"\\n "+chi2Text CMS_lumi.channelText = "#splitline{%s}{%s}" % (channelText, regionText) if postfitPlots: CMS_lumi.channelText = "#splitline{%s}{%s}" % (channelText + ";" + regionText, chi2Text) CMS_lumi.writeChannelText = True CMS_lumi.writeExtraText = True CMS_lumi.CMS_lumi(pad1, 4, 11) if not noData: ratio = rebinnedData.Clone("temp")
def readHists(): hstack = THStack("hstack", "hstack") hstack.SetTitle( "#scale[0.9]{#font[22]{CMS} #font[12]{Preliminary} 41.53 fb^{-1}(13TeV)}" ) inputfile = read_rootfile() # assuming TTH_hww is always there gROOT.cd() histName = POI + "_TTH_hww" h0 = inputfile.Get(histName) h_totalbkg = h0.Clone("h_totalbkg") h_totalbkg.SetDirectory(0) h_totalbkg.Reset() h_totalbkg.SetLineColor(kBlack) h_totalbkg.SetFillColor(kGray + 3) h_totalbkg.SetFillStyle(3001) h_totalbkg.SetTitle("") #h_totalbkg.SetMinimum(0.8) #h_totalbkg.SetMaximum(1.35) h_totalbkg.Sumw2() h_totalbkg.SetStats(0) h_totalsig = h0.Clone("h_totalsig") h_totalsig.SetDirectory(0) h_totalsig.Reset() h_totalsig.SetMarkerStyle(20) h_totalmc = h0.Clone("h_totalmc") h_totalmc.SetDirectory(0) h_totalmc.Reset() h_totalmc.SetLineColor(kBlack) h_totalmc.SetFillColor(kGray + 3) h_totalmc.SetFillStyle(3001) h_totalmc.SetTitle("") #h_totalmc.SetMinimum(0.8) #h_totalmc.SetMaximum(1.35) h_totalmc.Sumw2() h_totalmc.SetStats(0) h_dataobs = h0.Clone("h_dataobs") h_dataobs.SetDirectory(0) h_dataobs.Reset() h_dataobs.SetMarkerStyle(20) latexString = "" expString = " SM Exp" dataString = " Data Obs" latexString += ("\\begin{frame}\n\\frametitle{" + POI.replace("_", "\_") + "}\n\\begin{table}[]\n\scalebox{0.8}{\n\\begin{tabular}{" + "l" * (1 + len(Channels)) + "}\n") latexString += ("& " + SPLIT.replace("_", "\_") + " \\\\ \n") legend = TLegend(0.2, 0.6, 0.8, 0.88) #legend.SetHeader("2017 "+fit_type+", 2lss l^{#pm}l^{#pm} #mu(ttH)=#hat#mu") legend.SetHeader("2017 prefit, " + header_postfix) legend.SetNColumns(3) legend.SetBorderSize(0) Samples.reverse() for sample in Samples: isSignal = False if sample in signals: isSignal = True hist = h_totalsig.Clone(sample) hist.Reset() if not sample == "Data": latexString += sample + " &" # loop over data if sample == "Data" or sample == "data": for p in Process[sample]: rootfile = read_rootfile(p) if rootfile.IsZombie(): continue gROOT.cd() h1 = rootfile.Get(POI + "_" + p) if SMOOTH == 1: h1.Smooth() #h1.SetDirectory(0) h_dataobs.Add(h1) rootfile.Close() # loop over mc # loop over signal elif isSignal: for p in Process[sample]: rootfile = read_rootfile(p) if rootfile.IsZombie(): continue gROOT.cd() h1 = rootfile.Get(POI + "_" + p) if SMOOTH == 1: h1.Smooth() #h1.SetDirectory(0) if p == "FakeSub" and sample == "Fakes": h_totalsig.Add(h1, -1) h_totalmc.Add(h1, -1) hist.Add(h1, -1) else: h_totalsig.Add(h1) h_totalmc.Add(h1) hist.Add(h1) rootfile.Close() hist.SetFillColor(Color[sample]) hist.SetLineColor(kBlack) hist.SetFillStyle(Style[sample]) if hist.Integral() > 0.05: error = ROOT.Double(0) hist.IntegralAndError(0, hist.GetNbinsX(), error) latexString += "$ " + str( round(hist.Integral(), 2)) + " \\pm " + str(round( error, 2)) + "$ \\\\ \n" elif hist.Integral() > 0: latexString += " \\textless{}0.05 \\\\ \n" else: latexString += " - \\\\ \n " if WIDTH == 1: hist = YDivideWidth(hist) #hist.SetFillColor(Color[sample]) #hist.SetLineColor(kBlack) #hist.SetFillStyle(Style[sample]) hstack.Add(hist) legend.AddEntry(hist, sample, "f") # loop over bkg else: for p in Process[sample]: rootfile = read_rootfile(p) if rootfile.IsZombie(): continue gROOT.cd() #print " try to get histogram : " + POI+"_"+p h1 = rootfile.Get(POI + "_" + p) if SMOOTH == 1: h1.Smooth() h1.SetDirectory(0) if p == "FakeSub" and sample == "Fakes": h_totalbkg.Add(h1, -1) h_totalmc.Add(h1, -1) hist.Add(h1, -1) else: h_totalbkg.Add(h1) h_totalmc.Add(h1) hist.Add(h1) rootfile.Close() hist.SetFillColor(Color[sample]) hist.SetLineColor(kBlack) hist.SetFillStyle(Style[sample]) if hist.Integral() > 0.05: error = ROOT.Double(0) hist.IntegralAndError(0, hist.GetNbinsX(), error) latexString += "$ " + str( round(hist.Integral(), 2)) + " \\pm " + str(round( error, 2)) + "$ \\\\ \n" elif hist.Integral() > 0: latexString += " \\textless{}0.05 \\\\ \n" else: latexString += " - " if WIDTH == 1: hist = YDivideWidth(hist) #hist.SetFillColor(Color[sample]) #hist.SetLineColor(kBlack) #hist.SetFillStyle(Style[sample]) hstack.Add(hist) legend.AddEntry(hist, sample, "f") totMC_error = ROOT.Double(0) h_totalmc.IntegralAndError(0, h_totalmc.GetNbinsX(), totMC_error) expString += " & $ " + str(round(h_totalmc.Integral(), 2)) + " \\pm " + str( round(totMC_error, 2)) + "$ \\\\ \n" totbkg_error = ROOT.Double(0) h_totalbkg.IntegralAndError(0, h_totalbkg.GetNbinsX(), totbkg_error) expString += "Tot Bkg & $ " + str( round(h_totalbkg.Integral(), 2)) + " \\pm " + str( round(totbkg_error, 2)) + "$ \\\\ \n" totdata_error = ROOT.Double(0) h_dataobs.IntegralAndError(0, h_dataobs.GetNbinsX(), totdata_error) dataString += " & $ " + str(round(h_dataobs.Integral(), 2)) + " \\pm " + str( round(totdata_error, 2)) + "$ \n" if not blind == 1: latexString += (expString + dataString) else: latexString += expString latexString += ( "\\end{tabular}\n}\n\\end{table}\n\\end{frame}\n \\end{document}\n") if LATEX == 1: nameFix = "" if SMOOTH == 1: nameFix = "_smooth" latexfile = file( outputDir + "/" + POI + "_" + region + "_" + SPLIT + "_" + Expected + "_yield" + nameFix + ".tex", "w") latexfile.write( "\\documentclass{beamer}\n\\usetheme{Warsaw}\n\n\\usepackage{graphicx}\n\\useoutertheme{infolines}\n\\setbeamertemplate{headline}{}\n\n\\begin{document}\n\n" ) latexfile.write(latexString) inputfile.Close() return h_totalsig, h_totalbkg, h_totalmc, h_dataobs, hstack, legend
canvas = TCanvas("canvas", "canvas") #canvas.SetCanvasSize(600, 600) #canvas.SetLeftMargin(0.125) canvas.SetRightMargin(0.04) #canvas.SetBottomMargin(0.105) legend = ROOT.TLegend(0.6, 0.65, 0.925, 0.925) #legend.SetFillStyle(0) legend.SetBorderSize(0) #legend.SetBorderSize(1) legend.SetTextSize(0.0425) stack = THStack("stack", "stack") stack.SetTitle("#tau_{h} prompt rate (%s)" % (era)) # Loose h2_tau_pT_L = inputFile.Get(d_histName[era]["L"]).Clone() h2_tau_pT_L.Sumw2() # Tight h2_tau_pT_T = inputFile.Get(d_histName[era]["T"]).Clone() h2_tau_pT_T.Sumw2() l_h1 = [] for iDM in range(0, len(l_DM)): DM = l_DM[iDM]
def main(argv): P0DBANFFStyle = INTERFACE.GetThisStyle() INTERFACE.SetStyle(P0DBANFFStyle.GetName()) OUTPUTFILENAME = "BANFFReactionCodeStacksOfficial_Joint2018_Numode_Prefit_P0DOnly_Momentum.pdf" inputFile = TFile(sys.argv[0]) dataFile = TFile(sys.argv[1]) dummyPage = TCanvas() dummyPage.Print(OUTPUTFILENAME + "[") sampleNames = [ "P0D_Air_NuMu_CC_CC1Track", "P0D_Air_NuMu_CC_CCNTracks", "P0D_Water_NuMu_CC1Track", "P0D_Water_NuMu_CCNTracks" ] fileNameRoots = [ "P0D_Air_NuMu_CC1Track", "P0D_Air_NuMu_CCNTracks", "P0D_Water_NuMu_CC1Track", "P0D_Water_NuMu_CCNTracks" ] stackHistos = [ "#nu CCQE", "#nu CC 2p-2h", "#nu CC Res 1#pi", "#nu CC Coh 1#pi", "#nu CC Other", "#nu NC modes", "#bar{#nu} modes" ] P0DBANFFStyle.SetTitleBorderSize(0) P0DBANFFStyle.SetTitleX(0.02) P0DBANFFStyle.SetTitleY(0.95) P0DBANFFStyle.SetTitleW(0.3) P0DBANFFStyle.SetTitleH(0.07) # Align left, centered in y) P0DBANFFStyle.SetTitleAlign(11) stackColours = [1300, 1302, 1303, 1304, 1305, 1308, 1310] stackFillStyle = [1001, 1001, 1001, 1001, 1001, 1001, 1001] """ The graphs will be of the form <sampleName>_rxnPredMC_<rxnCode+100> So for each sample, we'll loop from 0-200, and if the THnD is not NULL when we try and get it, add it to a list for stacking. for sampleName in sampleNames: """ for ii in xrange(0, len(sampleNames)): sampleName = sampleNames[ii] # Total the number of events for this sample going into the histogram. # (Remember: Sand is excluded here.) mcSampleTotal = 0.0 # Now make the set of histograms to show, which combine several interaction # types. # Load in the data histogram and use it to assemble the TH2Ds for the MC, as # well as making it one of the histograms on the stack. dataHist = dataFile.Get(sampleName + "_data").Projection(1, 0) dataMomProj = dataFile.Get(sampleName + "_data").Projection( 1, 0).ProjectionX("dataratio" + sampleName + "_px", 1, dataHist.GetNbinsX()) dataMomProj.SetDirectory(0) dataMomProj.SetTitle("") prefitMomProj = inputFile.Get(sampleName + "_prefit").Projection( 1, 0).ProjectionX("prefitratio" + sampleName + "_px", 1, dataHist.GetNbinsX()) prefitMomProj.SetDirectory(0) postfitMomProj = inputFile.Get(sampleName + "_postfit_0_0").Projection( 1, 0).ProjectionX("postfitratio" + sampleName + "_px", 1, dataHist.GetNbinsX()) postfitMomProj.SetDirectory(0) for ibx in xrange(1, dataMomProj.GetNbinsX() + 1): dataMomProj.SetBinContent( ibx, dataMomProj.GetBinContent(ibx) / prefitMomProj.GetBinContent(ibx)) dataMomProj.SetBinError( ibx, ROOT.Math.sqrt(dataMomProj.GetBinContent(ibx)) / prefitMomProj.GetBinContent(ibx)) print "Data = " + str( dataMomProj.GetBinContent(ibx)) + " MC = " + str( prefitMomProj.GetBinContent(ibx)) + " Ratio = " + str( dataMomProj.GetBinContent(ibx) / prefitMomProj.GetBinContent(ibx)) dataMomProj.GetYaxis().SetRangeUser(0.75, 1.25) dataMomProj.GetXaxis().SetRangeUser(MINMOMENTUM, MAXMOMENTUM) dataMomProj.GetXaxis().SetTitle("Reconstructed muon momentum (MeV/c)") dataMomProj.GetYaxis().SetTitle("Data / Sim.") # There is only one data plot for each stack, so: # Momentum projection # Assemble them here. dataOneDimPlots = [] dataOneDimPlots.append( dataHist.ProjectionX("data" + sampleName + "_px", 1, dataHist.GetNbinsY())) dataNXBins = dataHist.GetXaxis().GetNbins() dataxarray = dataHist.GetXaxis().GetXbins().GetArray() # Now, loop through all the theta bins and add the slices in. for iby in xrange(1, dataHist.GetNbinsY() + 1): thetaLow = dataHist.GetYaxis().GetBinLowEdge(iby) thetaHigh = dataHist.GetYaxis().GetBinUpEdge(iby) thetaString = " < cos# theta < " thetaString = str(thetaLow) + thetaString + str(thetaHigh) dataOneDimPlots.append( TH1D("dataslice_" + sampleName + str(iby), thetaString, dataNXBins, dataxarray)) # Now, go through the x bins in this slice and fill the plot we # just created. for ibx in xrange(1, dataHist.GetNbinsX() + 1): # Get the bin dimensions for dividing purposes to area # normalize. dataOneDimPlots[len(dataOneDimPlots) - 1].SetBinContent( ibx, dataHist.GetBinContent(ibx, iby)) # Now that the dataOneDimPlots array is filled, loop through a area # normalize the bins. for dataOneDimHist in dataOneDimPlots: for ibx in xrange(1, dataOneDimHist.GetNbinsX() + 1): mpdim = (dataOneDimHist.GetXaxis().GetBinUpEdge(ibx) - dataOneDimHist.GetXaxis().GetBinLowEdge(ibx)) / 100.0 dataOneDimHist.SetBinError( ibx, math.sqrt(dataOneDimHist.GetBinContent(ibx)) / mpdim) dataOneDimHist.SetBinContent( ibx, dataOneDimHist.GetBinContent(ibx) / mpdim) histosToStack = [] for histo in stackHistos: histosToStack.append( TH2D(sampleName + "_" + histo, sampleName + "_" + histo, dataHist.GetXaxis().GetNbins(), dataHist.GetXaxis().GetXbins().GetArray(), dataHist.GetYaxis().GetNbins(), dataHist.GetYaxis().GetXbins().GetArray())) # Now pull the histograms from the file, and add their content to the # relevant combined histogram. for i in xrange(0, 200): if inputFile.Get(sampleName + "_rxnPredMC_" + str(i)): histosToStack[CorrespondingIndex(i)].Add( inputFile.Get(sampleName + "_rxnPredMC_" + str(i)).Projection( 1, 0)) """ # OK, so now we have an array of 2D histograms for this sample that we'd # like to stack. Need to divide it up into individual ones. Do Momentum # Projection, then momentum in theta slices. Normalize by bin area. # For storing all the one dimensional plots for this sample. """ oneDimPlots = [] # Add nothing for the momentum projection, will append the thetaStrings as # needed. stackTitles = [] for i in xrange(0, len(stackHistos)): # For storing all the one dimensional plots for this reaction code. oneDimPlotsThisReac = [] nameBase = histosToStack[i].GetTitle() oneDimPlotsThisReac.append(histosToStack[i].ProjectionX( nameBase + "_px", 1, histosToStack[i].GetNbinsY())) stackTitles.append("Momentum projection") # Area normalize this now. NXBins = histosToStack[i].GetXaxis().GetNbins() for ibx in xrange(1, NXBins + 1): mpdim = (histosToStack[i].GetXaxis().GetBinUpEdge(ibx) - histosToStack[i].GetXaxis().GetBinLowEdge(ibx)) / 100.0 oneDimPlotsThisReac[0].SetBinContent( ibx, oneDimPlotsThisReac[0].GetBinContent(ibx) / mpdim) mcSampleTotal += oneDimPlotsThisReac[0].GetSumOfWeights() # Now that the x bins are filled, loop on to the next histogram. # With all the y-slices done, oneDimPlotsThisReac is now full. Append # it to oneDimPlots. oneDimPlots.append(oneDimPlotsThisReac) """" At this point in time, oneDimPlots has a momentum projection and theta slices for each reaction code grouping in this sample. So now we just need to make TStacks for them and print them out to PDF. The stack contains the plot from the same index of each entry of oneDimPlots. They should all have the same length, so use the first one to loop through (number of slices plus 1 full momenutm projection.) """ for odi in xrange(0, len(oneDimPlots[0])): # For each one create a TStack sampleStack = THStack( "mpStack_" + sampleName + str(odi), ";Reconstructed muon momentum (MeV/c);Events/(100 MeV/c)") leg = TLegend(0.7, 0.15, 0.94, 0.93) leg.SetFillColor(0) # Make data the first entry. leg.AddEntry(dataOneDimPlots[odi], "Data", "LEP") dataOneDimPlots[odi].SetMarkerStyle(20) dataOneDimPlots[odi].SetMarkerColor(kBlack) dataOneDimPlots[odi].SetLineColor(kBlack) for odj in xrange(0, len(oneDimPlots)): # Apply the appropriate plot options from the beginning. oneDimPlots[odj][odi].SetFillColor(stackColours[odj]) oneDimPlots[odj][odi].SetFillStyle(stackFillStyle[odj]) oneDimPlots[odj][odi].SetMarkerStyle(1) # Don't want P0DBANFFStyle to interfere. sampleStack.Add(oneDimPlots[odj][odi]) print oneDimPlots[odj][odi].GetTitle() + " " + str( oneDimPlots[odj][odi].GetSumOfWeights()) leg.AddEntry(oneDimPlots[odj][odi], stackHistos[odj], "F") c1 = TCanvas() upperPad = TPad("upperPad", "upperPad", .05, .35, .96, .95) lowerPad = TPad("lowerPad", "lowerPad", .05, .1, .96, .35) upperPad.Draw() lowerPad.Draw() upperPad.cd() gPad.SetBottomMargin(1e-5) c1.SetTicks(1, 1) sampleStack.Draw("") dataOneDimPlots[odi].Draw("PEsame") sampleStack.SetMaximum( max(sampleStack.GetMaximum(), FindPlotMax(dataOneDimPlots[odi], dataOneDimPlots[odi]))) leg.Draw() sampleStack.GetXaxis().SetRangeUser(MINMOMENTUM, MAXMOMENTUM) sampleStack.GetXaxis().SetTitle("") sampleStack.GetXaxis().SetTickLength(0) sampleStack.GetXaxis().SetLabelSize(0) sampleStack.SetTitle("# nu-mode") lowerPad.cd() ROOT.gPad.SetTopMargin(1e-5) ROOT.gPad.SetBottomMargin(0.35) ROOT.gPad.SetTickx() dataMomProj.SetLineColor(2) dataMomProj.SetMarkerColor(2) dataMomProj.GetYaxis().SetNdivisions(8, 1) dataMomProj.GetYaxis().SetLabelSize( dataMomProj.GetYaxis().GetLabelSize() + 0.07) dataMomProj.GetYaxis().SetTitleSize( dataMomProj.GetYaxis().GetLabelSize() + 0.05) dataMomProj.GetYaxis().SetTitleOffset(0.335) dataMomProj.GetXaxis().SetLabelSize( dataMomProj.GetXaxis().GetLabelSize() + 0.08) dataMomProj.GetXaxis().SetTitleSize( dataMomProj.GetXaxis().GetLabelSize() + 0.04) dataMomProj.GetXaxis().SetTitleOffset(0.9) dataMomProj.GetXaxis().SetTickLength(0.04) dataMomProj.Draw("PE") line = TLine(0.0, 1.0, 5000.0, 1.0) line.SetLineWidth(2) line.SetLineColor(1) line.Draw("SAME") c1.Modified() c1.Update() c1.Print(OUTPUTFILENAME) outFileName = fileNameRoots[sampleNames.index( sampleName)] + "_mumom_rxn_postfit" c1.Print(outFileName + ".pdf") c1.Print(outFileName + ".png") c1.Print(outFileName + ".eps") dummyPage.Print(OUTPUTFILENAME + ']')
def calcAndDrawSignificance(SignalHist, BkgrHist, xtitle, legendNames, DataName, destination, year, ylog=False, customLabels=None, extraText=None, scaleSignalToBkgr=False, DivideByLine=None): GeneralSettings() #Make sure the code works for single backgrounds if not isinstance(BkgrHist, (list, )): BkgrHist = [BkgrHist] if not isinstance(SignalHist, (list, )): SignalHist = [SignalHist] BkgrHist, legendNames = orderHist(BkgrHist, legendNames, True) #Add all backgrounds totBkgr = BkgrHist[0].Clone("TotBkgr") for h in BkgrHist[1:]: totBkgr.Add(h) #Normalize signal to background if needed if scaleSignalToBkgr: for h in SignalHist: h.scale(totBkgr.GetSumOfWeights() / h.GetSumOfWeights) #Define a canvas Canv = TCanvas("Canv" + destination, "Canv" + destination, 1500, 1000) #Set Histogram Styles for h, n in zip(BkgrHist, legendNames): h.SetFillColor(TColor.GetColor(GetStackColorTauPOGbyName(n))) h.SetLineColor(TColor.GetColor(GetStackColorTauPOGbyName(n))) for i, h in enumerate(SignalHist): h.SetMarkerColor(TColor.GetColor(GetLineColor(i))) h.SetLineColor(TColor.GetColor(GetLineColor(i))) h.SetMarkerStyle(GetMarker(i)) list_of_significance_hists = [] for i, sh in enumerate(SignalHist): #Calculate significance total = totBkgr.Clone("Total") total.Add(sh) sqrt_total = total.Clone('Sqrt_Total') for xbin in xrange( 1, total.GetSize() - 1 ): #GetSize returns nbins + 2 (for overflow and underflow bin) sqrt_x = np.sqrt(total.GetBinContent(xbin)) sqrt_total.SetBinContent(xbin, sqrt_x) sqrt_total.SetBinError(xbin, 0.5 * total.GetBinError(xbin) / sqrt_x) significance = sh.Clone('Signal' + str(i)) significance.Divide(sqrt_total) list_of_significance_hists.append(significance) #First pad plotpad = TPad("plotpad", "plotpad", 0, .3, 1, 0.98) plotpad.SetBottomMargin(0.025) plotpad.Draw() plotpad.cd() #Create Stack (Change with most logical ordering) hs = THStack("hs", "hs") for h in BkgrHist: hs.Add(h) hs.Draw( "EHist" ) #Draw before using GetHistogram, see https://root-forum.cern.ch/t/thstack-gethistogram-null-pointer-error/12892/4 title = " ; ; Events" hs.SetTitle(title) # hs.GetHistogram().GetXaxis().SetTickLength(0) hs.GetHistogram().GetXaxis().SetLabelOffset(9999999) #hs.GetHistogram().SetMaximum(1) #Set range overallMin = GetOverallMinimum(BkgrHist + SignalHist, True) overallMax = GetOverallMaximum([totBkgr] + SignalHist) if ylog: if overallMin == 0.: overallMin = 0.1 ymin = 0.3 * overallMin ymax = 30 * overallMax plotpad.SetLogy() else: ymin = 0.7 * overallMin ymax = 1.3 * overallMax hs.SetMinimum(ymin) hs.SetMaximum(ymax) for h in SignalHist: h.Draw("EPSame") #Create Legend legend = TLegend(0.7, .7, .9, .9) for h, n in zip(BkgrHist, legendNames): legend.AddEntry(h, n) for h, n in zip(SignalHist, DataName): legend.AddEntry(h, n) legend.SetFillStyle(0) legend.SetBorderSize(0) legend.Draw() #Draw lines if needed if DivideByLine is not None: tdrStyle_Left_Margin = 0.16 tdrStyle_Right_Margin = 0.02 plot_size_hor = 1 - tdrStyle_Left_Margin - tdrStyle_Right_Margin #Option one, user provides the number of divisions and we divide equally if isinstance(DivideByLine[0], int): x_pos = np.linspace(totBkgr.GetXaxis().GetXmin(), totBkgr.GetXaxis().GetXmax(), DivideByLine[0] + 1) #Option two, user provides the specific boundaries if isinstance(DivideByLine[0], (list, )): x_pos = DivideByLine[0] #Draw the lines lines = [] for i, x in enumerate(x_pos[1:-1]): lines.append(TLine(x, ymin, x, ymax)) lines[i].SetLineColor(ROOT.kRed) lines[i].SetLineStyle(10) for line in lines: line.Draw('same') #Add extra text for i, name in enumerate(DivideByLine[1]): x = ((x_pos[i + 1] + x_pos[i]) / (2 * (x_pos[-1] - x_pos[0]) / plot_size_hor)) + tdrStyle_Left_Margin extraText.append(extraTextFormat(name, x, 0.1, None, 22)) #Draw extra text if needed if extraText is not None: DrawExtraText(plotpad, extraText) #Return to canvas Canv.cd() #Second pad ratiopad = TPad("ratiopad", "ratiopad", 0, 0.05, 1, .3) ratiopad.SetTopMargin(0.05) ratiopad.SetBottomMargin(0.25) ratiopad.Draw() ratiopad.cd() #print list_of_significance_hists[0].GetMaximum(), list_of_significance_hists[1].GetMaximum(), list_of_significance_hists[2].GetMaximum() overallMin = GetOverallMinimum(list_of_significance_hists) overallMax = GetOverallMaximum(list_of_significance_hists) significance = list_of_significance_hists[0] #Prepare lines before changing maximum lines_bottom = [] for i, sig in enumerate(list_of_significance_hists): lines_bottom.append( TLine(sig.GetXaxis().GetXmin(), sig.GetMaximum(), sig.GetXaxis().GetXmax(), sig.GetMaximum())) lines_bottom[i].SetLineColor(TColor.GetColor(GetLineColor(i))) lines_bottom[i].SetLineStyle(3) #Set Style for bottom plot significance.SetTitle(";" + xtitle + "; S/#sqrt{S+B}") significance.GetXaxis().SetTitleSize(.12) significance.GetYaxis().SetTitleSize(.12) significance.GetYaxis().SetTitleOffset(.6) significance.GetXaxis().SetLabelSize(.12) significance.GetYaxis().SetLabelSize(.12) significance.SetMinimum(0.) significance.SetMaximum(1.3 * overallMax) significance.Draw("EP") for sig in list_of_significance_hists[1:]: sig.Draw('EPSame') for line in lines_bottom: line.Draw("same") #Set custom x labels xaxis = significance.GetXaxis() if customLabels != None: number_of_bins = significance.GetNbinsX() if number_of_bins != len(customLabels): if DivideByLine is not None: for i in range(number_of_bins): xaxis.SetBinLabel( i + 1, customLabels[i % len(customLabels)] ) #Only works when DivideByLine[0] is an integer else: print 'Please provide ' + str( number_of_bins) + ' labels instead of ' + str( len(customLabels)) return else: for i, label in zip(range(number_of_bins), customLabels): xaxis.SetBinLabel(i + 1, label) #Throw CMs lumi at it cl.CMS_lumi(Canv, 4, 11, year, 'Simulation Preliminary', True) #Save everything savePlots(Canv, destination) ROOT.SetOwnership( Canv, False ) #https://root-forum.cern.ch/t/tlatex-crashing-in-pyroot-after-many-uses/21638/4 return
def DCRComp(run1Start,run1End,run2Start,run2End,filePath): # Setup variables firstruns = "" secondruns = ""# Used for each run in the first run range calibrationSkim1 = TChain("skimTree","skimTree") calibrationSkim2 = TChain("skimTree","skimTree") # Destination folder, trying to prevent a common formatting error if (filePath[-1] != '/'): filePath += '/' fileName = filePath + "DCRcompforRuns%d-%d_and_%d-%d.pdf" % (run1Start,run1End,run2Start,run2End) # Add functionality for multiple datasets? # NOTE: Be wary of comparing across multiple datasets. This hasn't been tested yet # So far, only datasets 5 and 6 are known by the program (see below) skimPath1 = "/global/project/projectdirs/majorana/data/mjd/surfmjd/analysis/skim/" skimPath2 = "/global/project/projectdirs/majorana/data/mjd/surfmjd/analysis/skim/" runBoundariesDS5cM1 = [24305,24318,24539,24552,24761,24775,24971,24984,25248,25261,25479,25492] runBoundariesDS5cM2 = [23960,23970,24322,24332,24556,24567,24779,24789,24988,24998,25265,25275,25496,25506] # MAKE SURE THIS HAS THE CORRECT CUTS cuts = "trapENFCal < 2635 && trapENFCal > 2605 && isGood && !wfDCBits && !muVeto && mH == 1" # If there is only one module being calibrated in DS5 cutStr5cM1 = " && C == 1" cutStr5cM2 = " && C == 2" if (run1Start <= 25507 and run1Start > 18712): # DS5c skimPath1 += "DS5ccal/GAT-v01-07-164-g8e0a877/skimDS5_" if (run1Start in runBoundariesDS5cM1): cuts += cutStr5cM1 if (run1Start in runBoundariesDS5cM2): cuts += cutStr5cM2 else: raise ValueError('First run boundary is not in either DS5c calibration range') if (run1Start > 25507): # DS6 skimPath1 += "DS6cal/GAT-v01-06/skimDS6_" if (run2Start <= 25507 and run2Start > 18712): # DS5c skimPath2 += "DS5ccal/GAT-v01-07-164-g8e0a877/skimDS5_" if (run1Start in runBoundariesDS5cM1): cuts += cutStr5cM1 if (run1Start in runBoundariesDS5cM2): cuts += cutStr5cM2 else: raise ValueError('First run boundary is not in either DS5c calibration range') if (run2Start > 25507): # DS6 skimPath2 += "DS6cal/GAT-v01-06/skimDS6_" cutStr = cuts # Build the first run range's TChain for i in range(run1Start, run1End+1): firstruns = skimPath1 + "run%d_small.root" % i calibrationSkim1.Add(firstruns,0) # Build the second run range's TChain for i in range(run2Start, run2End+1): secondruns = skimPath2 + "run%d_small.root" % i calibrationSkim2.Add(secondruns,0) # channel list from the built data in P3LTP # I don't need to use this now, but can check against it # IE check that every channel in this list has data # and that every channel with data is in this list chanList = [680,681,678,679,674,675,672,673,632,633,630,631,626,627,690,691,692,693,648,649,640,641,642,643,664,665,662,663,660,661,658,659,616,617,610,611,608,609,584,585,600,601,598,599,592,593,696,697,624,625,628,629,688,689,694,695,614,615,1122,1123,1108,1109,1106,1107,1128,1129,1204,1205,1110,1111,1126,1127,1124,1125,1202,1203,1170,1171,1172,1173,1174,1175,1176,1177,1168,1169,1120,1121,1206,1207,1208,1209,1232,1233,1236,1237,1238,1239,1234,1235,1328,1329,1298,1299,1296,1297,1302,1303,1332,1333,1268,1269,1304,1305,1330,1331] # Test case channel list #chanList = [1204,1174,1173] # Draw the whole dcr distribution vs channel # make sure there are enough bins that each channel is one bin c2 = TCanvas('c2','c2',400,400) drawStr = "dcr90:channel>>bighist1" bighist1 = TH2F("bighist1", "All Channels DCR Comparison",800,550,1350,1000,-0.001,0.001) calibrationSkim1.Draw(drawStr,cutStr,"COLZ") bighist1.SetLineColor(30) bighist1.SetStats(False) bighist1.GetXaxis().SetTitle("Channel") bighist1.GetYaxis().SetTitle("DCR99") bighist1.GetYaxis().SetTitleOffset(2.1) drawStr = "dcr90:channel>>bighist2" bighist2 = TH2F("bighist2", "All Channels DCR Comparison",800,550,1350,1000,-0.001,0.001) calibrationSkim2.Draw(drawStr,cutStr, "SAME COLZ") bighist2.SetLineColor(45) bighist2.SetStats(False) bighist2.GetXaxis().SetTitle("Channel") bighist2.GetYaxis().SetTitle("DCR99") bighist2.GetYaxis().SetTitleOffset(2.1) c2.SetLogz() gPad.SetLeftMargin(0.15) gPad.SetRightMargin(0.12) # Fix the different z scales maxz = max(bighist1.GetMaximum(),bighist2.GetMaximum()) bighist1.GetZaxis().SetRangeUser(0,maxz) bighist2.GetZaxis().SetRangeUser(0,maxz) c2.Update() # Save the big TH2F as a root file rootfileName = filePath + "DCRcomp%d-%d_and_%d-%d.root" % (run1Start, run1End, run2Start, run2End) c2.SaveAs(rootfileName) # Start the big pdf c2.Print(fileName + "(","Title: All Channels") c2.Close() # TCanvas for the individual channels c3 = TCanvas('c3','c3', 400, 400) c3.cd() # Make txt file for chanList problems txtFileTitle = "channelProblemsforRuns%d-%d_and_%d-%d.txt" % (run1Start,run1End,run2Start,run2End) chanFile = open(txtFileTitle,"w+") # Want a hist of all DCR90 efficiencies for the run range # Only do this for the second run range (so I'm not doubling the plot) # Remove entries from this if they don't have any results active_channels = [680,681,678,679,674,675,672,673,632,633,630,631,626,627,690,691,692,693,648,649,640,641,642,643,664,665,662,663,660,661,658,659,616,617,610,611,608,609,584,585,600,601,598,599,592,593,696,697,624,625,628,629,688,689,694,695,614,615,1122,1123,1108,1109,1106,1107,1128,1129,1204,1205,1110,1111,1126,1127,1124,1125,1202,1203,1170,1171,1172,1173,1174,1175,1176,1177,1168,1169,1120,1121,1206,1207,1208,1209,1232,1233,1236,1237,1238,1239,1234,1235,1328,1329,1298,1299,1296,1297,1302,1303,1332,1333,1268,1269,1304,1305,1330,1331] active_channels = sorted(active_channels) active_chan_effs = [] # Channel loop for channel in range(550,1351): # Conver channel to a bin number for slices bigX = bighist1.GetXaxis() currentbin = bigX.FindBin(channel) # Hack to get all the titles properly in the pdf canvastitle = "Channel %d" % channel bighist1.SetTitle(canvastitle) bighist2.SetTitle(canvastitle) # Get slices / bin content for each channel (the x axis of bighist) histname1 = "hist1_chan%d" % channel histname2 = "hist2_chan%d" % channel hist1 = bighist1.ProjectionY(histname1,currentbin,currentbin,"d") hist2 = bighist2.ProjectionY(histname2,currentbin,currentbin,"d") # Only proceed if the hists aren't empty if ((hist1.GetEntries() == 0 and hist2.GetEntries() == 0)): # Check that every empty channel isn't in chanList if (channel in chanList): chanFile.write("Channel %d has no output for runs %d - %d and %d - %d \n" % (channel, run1Start, run1End, run2Start, run2End)) active_channels.remove(channel) else: # Make sure every channel with output is in chanList if (channel not in chanList): chanFile.write("Channel %d is not in chanList \n" % channel) c3.Clear() c3.SetTitle(canvastitle) hstack = THStack("hstack","") hstack.SetTitle(canvastitle) hist1.SetLineColor(40) gPad.SetLogy() hstack.Add(hist1) # Get the dcr99 value by integrating the hist xaxis1 = hist1.GetXaxis() minbin = xaxis1.FindBin(-0.001) maxbin = xaxis1.FindBin(0.001) zerobin = xaxis1.FindBin(0) goodintegral1 = hist1.Integral(minbin,zerobin) totalintegral1 = hist1.Integral(minbin,maxbin) # Don't divide by zero if (goodintegral1 != 0): dcr90_1 = goodintegral1/totalintegral1 else : dcr90_1 = 0 hist2.SetLineColor(30) hstack.Add(hist2) # Get the second dcr99 value xaxis2 = hist2.GetXaxis() minbin = xaxis2.FindBin(-0.001) maxbin = xaxis2.FindBin(0.001) zerobin = xaxis2.FindBin(0) goodintegral2 = hist2.Integral(minbin,zerobin) totalintegral2 = hist2.Integral(minbin,maxbin) # Don't divide by zero if (goodintegral2 != 0): dcr90_2 = goodintegral2/totalintegral2 else: dcr90_2 = 0 active_chan_effs.append(dcr90_2) # Formatting for the THStack hstack.Draw() xaxisStack = hstack.GetXaxis() xaxisStack.SetTitle("DCR99") hstack.GetYaxis().SetTitle("Count") xaxisStack.SetLabelSize(0.02) xaxisStack.SetTitleOffset(1.2) # Draw vertical line at dcr90 = 0 for reference c3.Update() ymax = max(hist1.GetMaximum(), hist2.GetMaximum()) vert = TLine(0,0,0,ymax) vert.SetLineColor(2) vert.Draw() # Draw the legend chanlegend = TLegend(0.6,0.8,0.9,0.9) entry1 = chanlegend.AddEntry(hist1, "#splitline{Run Range %d - %d}{%f Efficiency}" % (run1Start, run1End, dcr90_1), "l") entry2 = chanlegend.AddEntry(hist2, "#splitline{Run Range %d - %d}{%f Efficiency}" % (run2Start, run2End, dcr90_2), "l") # If the Efficiencies differ by more than 1%, make their text red if (abs(dcr90_1 - dcr90_2) > 0.01): entry1.SetTextColor(2) entry2.SetTextColor(2) entry1.SetTextSize(0.02) entry2.SetTextSize(0.02) chanlegend.Draw() # Save as one big pdf file pagetitle = "Title: " + canvastitle c3.Update() c3.Print(fileName,pagetitle) # Close the pdf with a blank page c3.Clear() c3.Print(fileName + ")","I need to close the document somehow") c3.Close() # I want a spreadsheet of all the DCR90 efficiencies # Will make a file for each calibration run set, and then concatenate them later spreadsheetfilename = filePath + "eff_sheet_%d-%d.txt" % (run2Start,run2End) spreadsheet = open(spreadsheetfilename,"w+") # Make the dcr90 efficiency plot for the second run set only c_eff = TCanvas('c_eff','c_eff',800,400) c_eff.cd() # active_channels should be the x-axis labels # active_chan_effs should be the y-values num_chan = len(active_channels) eff_hist = TH1F('eff_hist',"DCR99 Efficiencies for Calibration Runs %d-%d" % (run2Start, run2End),num_chan,0,num_chan) eff_xaxis = eff_hist.GetXaxis() # Input data and write to the spreadsheet for i in range(0,num_chan): eff_xaxis.SetBinLabel(i+1, str(active_channels[i])) eff_hist.SetBinContent(i+1,active_chan_effs[i]) spreadsheet.write("%d %d %d %f \n" % (run2Start,run2End,active_channels[i],active_chan_effs[i])) c_eff.SetGridx() eff_hist.SetStats(False) eff_xaxis.SetLabelSize(0.03) eff_xaxis.SetTitle("Channel") eff_xaxis.SetTitleOffset(1.4) eff_hist.GetYaxis().SetTitle("DCR99 Efficiency") eff_hist.Draw() c_eff.Update() # Save eff_fileName = filePath + "DCR99_Efficiencies_Runs_%d-%d.pdf" % (run2Start,run2End) eff_title = "DCR99 Efficiencies for Calibration Runs %d-%d" % (run2Start, run2End) c_eff.SaveAs(eff_fileName,eff_title) c_eff.Close() spreadsheet.close()
outDir = "plots/tauIdIsoEfficiency/DYJetsToLL_mc" os.system("mkdir -p " + outDir) inputFile = TFile.Open( "DYJetsToLL_mc/output_tauIdIsoEfficiency/DYJetsToLL_M-50_TuneCUETP8M1_13TeV-madgraphMLM-pythia8_tauIdIsoEfficiency/custom_all_tauIdIsoEfficiency.root" ) process = "DYJetsToLL" #################################################################################################### canvas = TCanvas("canvas", "canvas") canvas.SetCanvasSize(800, 800) legend = TLegend(0.55, 0.5, 0.895, 0.895) stack = THStack("stack", "stack") stack.SetTitle("#tau^{gen}_{h} p_{T} fraction [%s]" % (process)) tauTemplate_pTbin = [20, 30, 50, 100] for iBin in range(0, len(tauTemplate_pTbin)): histName = "" histLabel = "" lineColor = iBin + 1 if (iBin < len(tauTemplate_pTbin) - 1): histName = "tauh_pTfraction_gen_pT-%dto%d" % ( tauTemplate_pTbin[iBin], tauTemplate_pTbin[iBin + 1]) histLabel = "%d < p^{#tau^{gen}}_{T} < %d GeV" % (
def plot(plotInfo): tdrstyle.setTDRStyle() #ROOT.gROOT.ForceStyle() canvas = TCanvas("canvas", "canvas") #canvas.SetCanvasSize(600, 600) #canvas.SetLeftMargin(0.125) canvas.SetRightMargin(0.04) #canvas.SetBottomMargin(0.105) legend = ROOT.TLegend(0.5, 0.65, 0.925, 0.925) #legend.SetFillStyle(0) legend.SetBorderSize(0) #legend.SetBorderSize(1) legend.SetTextSize(0.0425) stack = THStack("stack", "stack") stack.SetTitle("#tau_{h} fake rate (%s)" % (era)) # Loose-Loose info_str = "looseLoose_dR03_SS" #h2_LL = inputFile.Get("%s/tau_pT_vs_DM_reco_%s" %(info_str, info_str)).Clone() h2_LL = getHist(l_inputFileName, "%s/%s_%s" % (info_str, plotInfo.histName, info_str)) h2_LL.Sumw2() # Tight-Loose info_str = "tightLoose_dR03_SS" #h2_TL = inputFile.Get("%s/tau_pT_vs_DM_reco_%s" %(info_str, info_str)).Clone() h2_TL = getHist(l_inputFileName, "%s/%s_%s" % (info_str, plotInfo.histName, info_str)) h2_TL.Sumw2() # Tight-Tight info_str = "tightTight_dR03_SS" #h2_TT = inputFile.Get("%s/tau_pT_vs_DM_reco_%s" %(info_str, info_str)).Clone() h2_TT = getHist(l_inputFileName, "%s/%s_%s" % (info_str, plotInfo.histName, info_str)) h2_TT.Sumw2() l_h1_LLtoTL = [] l_h1_TLtoTT = [] for iDM in range(0, len(l_DM)): DM = l_DM[iDM] iBin = h2_LL.GetXaxis().FindBin(DM) h1_LL = h2_LL.ProjectionY("_py", iBin, iBin) h1_LL.Sumw2() h1_LL = h1_LL.Rebin( len(plotInfo.l_rebin) - 1, "", array.array("d", plotInfo.l_rebin)) #print "h1_LL %f" %(h1_LL.GetBinContent(h1_LL.GetNbinsX())) h1_TL = h2_TL.ProjectionY("_py", iBin, iBin) h1_TL.Sumw2() h1_TL = h1_TL.Rebin( len(plotInfo.l_rebin) - 1, "", array.array("d", plotInfo.l_rebin)) #print "h1_TL %f" %(h1_TL.GetBinContent(h1_TL.GetNbinsX())) h1_TT = h2_TT.ProjectionY("_py", iBin, iBin) h1_TT.Sumw2() h1_TT = h1_TT.Rebin( len(plotInfo.l_rebin) - 1, "", array.array("d", plotInfo.l_rebin)) #print "h1_TT %f" %(h1_TT.GetBinContent(h1_TT.GetNbinsX())) # LL to TL h1_temp = h1_TL.Clone() h1_temp.Divide(h1_LL) h1_temp.SetLineColor(iDM + 1) h1_temp.SetLineWidth(3) h1_temp.SetLineStyle(2) l_h1_LLtoTL.append(h1_temp.Clone()) stack.Add(l_h1_LLtoTL[-1], "hist E") legend.AddEntry(l_h1_LLtoTL[-1], "LL #rightarrow TL (DM %d)" % (DM)) # TL to TT h1_temp = h1_TT.Clone() h1_temp.Divide(h1_TL) h1_temp.SetLineColor(iDM + 1) h1_temp.SetLineWidth(3) l_h1_TLtoTT.append(h1_temp.Clone()) stack.Add(l_h1_TLtoTT[-1], "hist E") legend.AddEntry(l_h1_TLtoTT[-1], "TL #rightarrow TT (DM %d)" % (DM)) stack.Draw("nostack") legend.Draw() stack.GetXaxis().SetTitle(plotInfo.xTitle) stack.GetYaxis().SetTitle("#tau_{h} misid. probability") stack.GetXaxis().SetLabelSize(0.05) stack.GetYaxis().SetLabelSize(0.05) stack.GetXaxis().SetTitleOffset(1.05) stack.GetYaxis().SetTitleOffset(1.25) stack.GetXaxis().SetTitleSize(0.055) stack.GetYaxis().SetTitleSize(0.055) stack.GetXaxis().CenterTitle(True) stack.GetYaxis().CenterTitle(True) if (plotInfo.setXmin): stack.GetXaxis().SetRangeUser(plotInfo.xMin, plotInfo.l_rebin[-1]) if (plotInfo.centerLabelsX): stack.GetXaxis().CenterLabels() stack.SetMinimum(0) stack.SetMaximum(1.5) if (len(plotInfo.l_rebin)): if (plotInfo.isXinteger): stack.GetXaxis().SetNdivisions(len(plotInfo.l_rebin), 1, 1) else: stack.GetXaxis().SetNdivisions(len(plotInfo.l_rebin), 5, 1) #canvas.SetGridx() #canvas.SetGridy() # CMS label CMS_lumi.CMS_lumi(pad=canvas, iPeriod=0, iPosX=0, CMSextraText=Common.getCMSextraText(era), lumiText=Common.getLumitext(era)) canvas.SaveAs(outDir + "/%s%s.pdf" % (plotInfo.outFileName, suffix)) canvas.Clear() legend.Clear() stack.Clear()
def doCombination(file_list, output, debug=False): xmin = 500 xmax = 3000 hsig16 = TH1F("hsig16", ";Gen_mjj; Events ", 10, 500, 3000) hsig17 = TH1F("hsig17", ";Gen_mjj; Events ", 10, 500, 3000) hsig18 = TH1F("hsig18", ";Gen_mjj; Events ", 10, 500, 3000) hint16 = TH1F("hint16", ";Gen_mjj; Events ", 10, 500, 3000) hint17 = TH1F("hint17", ";Gen_mjj; Events ", 10, 500, 3000) hint18 = TH1F("hint18", ";Gen_mjj; Events ", 10, 500, 3000) gStyle.SetOptFit(0) gStyle.SetOptStat(0) gROOT.SetBatch(1) hs = THStack() leg = TLegend(0.58, 0.75, 0.89, 0.89) for ifile in file_list: if not os.path.exists(ifile): print '>>> This file does not exist :', ifile, " --> Check path..." continue print '>>> Opening File :', ifile inFile = TFile.Open(ifile, " READ ") c1 = inFile.Get("c1") if '2018' in ifile: hint18 = c1.GetListOfPrimitives().FindObject('hint') hsig18 = c1.GetListOfPrimitives().FindObject('hsig') print "Extract 2018" if '2017' in ifile: hint17 = c1.GetListOfPrimitives().FindObject('hint') hsig17 = c1.GetListOfPrimitives().FindObject('hsig') print "Extract 2017" if '2016' in ifile: hint16 = c1.GetListOfPrimitives().FindObject('hint') hsig16 = c1.GetListOfPrimitives().FindObject('hsig') print "Extract 2016" hsigcomb = hsig16.Clone() hsigcomb.SetName("hsigcomb") hsigcomb.Add(hsig17) hsigcomb.Add(hsig18) hintcomb = hint16.Clone() hintcomb.SetName("hintcomb") hintcomb.Add(hint17) hintcomb.Add(hint18) c = TCanvas() c.cd() hintcomb.SetLineColor(1) hsigcomb.SetLineColor(4) hs.Add(hintcomb) hs.Add(hsigcomb) leg.AddEntry(hsigcomb, "WpWmJJ_EWK_noTop") leg.AddEntry(hintcomb, "Interference") hs.SetTitle("; Gen mjj [GeV]; Events") hs.Draw("pe nostack") line1 = TLine(xmin, 0.0, xmax, 0.0) line1.SetLineWidth(2) line1.SetLineStyle(2) line1.SetLineColor(2) line1.Draw("same") #leg.SetNColumns(2) leg.SetBorderSize(0) leg.Draw("same") c.SaveAs(output + ".png") c.SaveAs(output + ".pdf") c.SaveAs(output + ".root")
def doIntPerYear(data, canvas, output, debug=False): xmin = 500 xmax = 3000 #hqcd= TH1F("hsum",";Gen_mjj; Events ",10,500,3000) #hewk= TH1F() #htot= TH1F("hsig",";Gen_mjj; Events ",10,500,3000) gStyle.SetOptFit(0) gStyle.SetOptStat(0) gROOT.SetBatch(1) hs = THStack() hqcd_hewk = THStack() leg = TLegend(0.58, 0.75, 0.89, 0.89) for isample in data: if not os.path.exists(isample['ipath']): print "Can't find this file :", isample['ipath'], " --> Skipping" sys.stdout.flush() return 0 print '>>> Opening File :', isample['ipath'] sys.stdout.flush() inFile = TFile.Open(isample['ipath'], " READ ") c1 = inFile.Get(canvas) if 'hewk_qcd' in isample['obj']: htot = c1.GetListOfPrimitives().FindObject(isample['obj']) if 'ewk' not in isample['obj']: hqcd = c1.GetListOfPrimitives().FindObject(isample['obj']) if 'qcd' not in isample['obj']: hewk = c1.GetListOfPrimitives().FindObject(isample['obj']) hsig = hewk.Clone() hsig.SetName("hsig") hsum = hewk.Clone() hsum.Add(hqcd) hint = htot.Clone() hint.SetName("hint") hint.Add(hint, hsum, 1, -1) c = TCanvas() c.SetName("c1") c.cd() hint.SetLineColor(1) hqcd.SetLineColor(2) hsig.SetLineColor(3) htot.SetLineColor(4) hs.Add(hint) hs.Add(htot) hqcd_hewk.Add(hsig) hqcd_hewk.Add(hqcd) #hsig.Draw("pe") #hint.Draw("pe, same") leg.AddEntry(hsig, "WpWmJJ_EWK_noTop") leg.AddEntry(hqcd, "WpWmJJ_QCD_noTop") leg.AddEntry(htot, "WpWmJJ_EWK_QCD_noTop") leg.AddEntry(hint, "Interference") xtitle = hewk.GetXaxis().GetTitle() ytitle = hewk.GetYaxis().GetTitle() #print xtitle #print ytitle hs.SetTitle(";" + xtitle + ";" + ytitle) hs.Draw("pe nostack") hqcd_hewk.Draw("pe same") line1 = TF1("line1", "pol0", -100, 4000) line1.FixParameter(0, 0) line1.SetLineWidth(2) line1.SetLineStyle(2) line1.SetLineColor(2) line1.Draw("same") #leg.SetNColumns(2) leg.SetBorderSize(0) leg.Draw("same") c.SaveAs(output + ".png") c.SaveAs(output + ".pdf") c.SaveAs(output + ".root")
def plotStack(canvas, pad, tree1, tree2, param, fileNum, outpath): # the name tprofname1 = tree1.GetName() + param + str(fileNum) tprofname2 = tree2.GetName() + param + str(fileNum) # they already exist in gDirectory, get them tmpCanv = TCanvas(tprofname1 + 'stack') tmpCanv.cd() tprofile1 = gDirectory.Get(tprofname1) tprofile2 = gDirectory.Get(tprofname2) # get the overall upper and lower bin limits lower1 = tprofile1.GetBinLowEdge(1) lower2 = tprofile2.GetBinLowEdge(1) # lower2 = tprofile2.GetBinCenter(1) - tprofile2.GetXAxis.GetBinWidth()/2. # upper1 = tprofile1.GetBinCenter(200) + tprofile1.GetXAxis.GetBinWidth()/2. upper1 = tprofile1.GetBinLowEdge(201) upper2 = tprofile2.GetBinLowEdge(201) newmin = min(lower1, lower2) newmax = max(upper1, upper2) # draw the plots again with new binning tprofname1new = tprofname1 + 'rebin' tprofname2new = tprofname2 + 'rebin' tree1.Draw( param + '>>' + tprofname1new + '(200,' + str(newmin) + ',' + str(newmax) + ')', '', 'prof,goff') tree2.Draw( param + '>>' + tprofname2new + '(200,' + str(newmin) + ',' + str(newmax) + ')', '', 'prof,goff') tprofile1new = gDirectory.Get(tprofname1new) tprofile2new = gDirectory.Get(tprofname2new) print '[>] In plotStack() with option :', fileNum if pad > 0: canvas.cd(pad) else: canvas.cd() # projection to TH1F for stacking h1st = tprofile1new.ProjectionX(tprofname1new + 'h1') h2st = tprofile2new.ProjectionX(tprofname2new + 'h2') ts = THStack() title = tree1.GetName().split('_')[1] + ' TOTAL' ts.SetTitle(title) print '[>] Stack:', tree1.GetName().split( '_')[1], ' newmin =', newmin, ' newmax =', newmax h1st.GetXaxis().SetTitle(param.split(':')[1]) h1st.GetYaxis().SetTitle(param.split(':')[0]) h2st.GetXaxis().SetTitle(param.split(':')[1]) h2st.GetYaxis().SetTitle(param.split(':')[0]) if fileNum: h1st.SetLineColor(fileNum) h1st.SetMarkerColor(fileNum) h1st.SetMarkerStyle(8) h1st.SetMarkerSize(0.35) h1st.Draw("p,same") h2st.SetLineColor(fileNum + 10) h2st.SetMarkerColor(fileNum + 10) h2st.SetMarkerStyle(8) h2st.SetMarkerSize(0.35) h2st.Draw("p,same") ts.Add(h1st) ts.Add(h2st) ts.Draw() else: h1st.SetLineColor(1) h1st.SetFillColor(5) h1st.Draw('hist') h2st.SetLineColor(1) h2st.SetFillColor(17) h2st.Draw('hist') ts.Add(h1st, 'hist') ts.Add(h2st, 'hist') ts.Draw() canvas.SaveAs(outpath)
tmp_histogram_sublist[-1].SetMarkerColor(flavour_color) #tmp_histogram_sublist[-1].SetStats(kTRUE) #tmp_histogram_sublist[-1].Draw() #tmp_canvas_single.Write() #tmp_canvas_single.SaveAs(histogram_name+"_"+flavour_name+'_Canvas.pdf') tmp_stack.Add(tmp_histogram_sublist[-1]) tmp_legend.AddEntry(tmp_histogram_sublist[-1],flavour_name,'f') tmp_process_sublist.append(tmp_histogram_sublist) stack_process_sublist.append(tmp_stack) tmp_canvas=TCanvas(histogram_name+'_'+process_name.split('.')[-1]+'_'+'CanvasStack','') #tmp_canvas.cd() #tmp_histogram_sublist[-1].Draw('histo') tmp_stack.Draw('histo') tmp_stack.GetXaxis().SetTitle(histogram_xaxis) tmp_stack.GetYaxis().SetTitle(histogram_yaxis) tmp_stack.SetTitle(histogram_description) tmp_legend.Draw() #tmp_canvas.BuildLegend(0.2,0.2,0.8,0.8)#tmp_legend.Draw() #autolegend=tmp_canvas.BuildLegend() stackcanvas_process_sublist.append(tmp_canvas) # outfile.Cd() if histogram_name in ["subTrackNPixelHits","subTrackMomentum","subTrackJetDistVal","subTrackDecayLenVal","subTrackSip3dVal","subTrackSip3dSig","subJetNSecondaryVertices","subCSV"]: tmp_canvas.SetLogy() tmp_canvas.Write() if histogram_name in ["subTrackNPixelHits","subTrackMomentum","subTrackJetDistVal","subTrackDecayLenVal","subTrackSip3dVal","subTrackSip3dSig","subFlightDistance3dSig","subVertexMassJTC","subJetNSecondaryVertices","subVertexNTracks","subCSV"]: tmp_canvas.SaveAs(histogram_name+'_'+process_name.split('.')[-1]+'_'+'CanvasStack.pdf') #tmp_stack.Write() input_histos.append(tmp_process_sublist) output_histos.append(stack_process_sublist) output_canvases.append(stackcanvas_process_sublist) # ttbar_histos.append()
ROOT.gPad.SetBottomMargin(0.02) #ROOT.gPad.SetTopMargin(0.01) pad2.cd() #ROOT.gPad.SetBottomMargin(0.001) ROOT.gPad.SetTopMargin(0.02) else: pad1 = TPad("pad1", "This is pad1", 0., 0., 1., 1.) pad1.Draw() pad1.cd() # copy these before the drawing settings applied data_rel = data.Clone() mc_sum_rel = mc_sum.Clone() hs.SetTitle(args.title) mc_sum.SetTitle(args.title) #data.GetYaxis().SetTitleFont(63) #data.GetYaxis().SetTitleSize(20) mc_sum.GetYaxis().SetTitleFont(63) mc_sum.GetYaxis().SetTitleSize(20) mc_sum.GetXaxis().SetTitleFont(63) mc_sum.GetXaxis().SetTitleSize(20) # axis labels #data.GetYaxis().SetLabelSize(0.02) #data.GetXaxis().SetLabelSize(0.02) mc_sum.GetYaxis().SetLabelSize(0.02) mc_sum.GetXaxis().SetLabelSize(0.02)
def plotDataVSMC(DataHist, MCHist, xtitle, legendNames, DataName, destination, year, ytitle_bottom='Data/MC', ylog=False): GeneralSettings() Canv = TCanvas("Canv" + destination, "Canv" + destination, 1000, 1000) #Set Histogram Styles for i, h in enumerate(MCHist): h.SetFillColor( TColor.GetColor(GetStackColorTauPOGbyName(legendNames[i]))) h.SetLineColor( TColor.GetColor(GetStackColorTauPOGbyName(legendNames[i]))) DataHist.SetMarkerColor(ROOT.kBlack) DataHist.SetLineColor(ROOT.kBlack) DataHist.SetMarkerStyle(20) #Add all MC samples to use in ratios totBkgr = MCHist[0].Clone("totBkgr") for h in MCHist[1:]: totBkgr.Add(h) DataOverMC = DataHist.Clone("DataOverMC") DataOverMC.Divide(totBkgr) #Errors predStatError = totBkgr.Clone("PredictedStatError") predSystError = totBkgr.Clone("PredictedSystError") predTotError = totBkgr.Clone("PredictedTotalError") for b in xrange(predSystError.GetNbinsX() + 1): predSystError.SetBinError(b, 0.3 * totBkgr.GetBinContent(b)) syst = predSystError.GetBinError(b) stat = predStatError.GetBinError(b) predTotError.SetBinError(b, np.sqrt(stat * stat + syst * syst)) #predTotError.SetFillStyle(3013) #predTotError.SetFillColor(ROOT.kGray+2) #predTotError.SetMarkerStyle(0) #predTotError.Draw("E2 Same") #First pad plotpad = TPad("plotpad", "plotpad", 0, .3, 1, 0.98) plotpad.SetBottomMargin(0.025) plotpad.Draw() plotpad.cd() #Create Stack (Change with most logical ordering) hs = THStack("hs", "hs") for h in MCHist: hs.Add(h) hs.Draw( "EHist" ) #Draw before using GetHistogram, see https://root-forum.cern.ch/t/thstack-gethistogram-null-pointer-error/12892/4 title = " ; ; Events / " + str(MCHist[0].GetBinWidth(1)) + " GeV" hs.SetTitle(title) # hs.GetHistogram().GetXaxis().SetTickLength(0) hs.GetHistogram().GetXaxis().SetLabelOffset(9999999) hs.GetHistogram().SetMaximum(1) #Set range overallMin = GetOverallMinimum(MCHist + [DataHist]) overallMax = GetOverallMaximum([totBkgr] + [DataHist]) if ylog: plotpad.SetLogy() hs.SetMinimum(0.3 * overallMin) hs.SetMaximum(10 * overallMax) else: hs.SetMinimum(0.5 * overallMin) hs.SetMaximum(1.7 * overallMax) DataHist.Draw("EPSame") predTotError.SetFillStyle(3013) predTotError.SetFillColor(ROOT.kGray + 2) predTotError.SetMarkerStyle(0) predTotError.Draw("E2 Same") #Create Legend legend = TLegend(0.7, .7, .9, .9) for h, n in zip(MCHist, legendNames): legend.AddEntry(h, n) legend.AddEntry(DataHist, DataName) legend.SetFillStyle(0) legend.SetBorderSize(0) legend.Draw() #Return to canvas Canv.cd() #Second pad ratiopad = TPad("ratiopad", "ratiopad", 0, 0.05, 1, .3) ratiopad.SetTopMargin(0.05) ratiopad.SetBottomMargin(0.25) ratiopad.Draw() ratiopad.cd() #Errors StatErrorRatio = predStatError.Clone("StatErrorRatio") StatErrorRatio.SetFillStyle(1001) StatErrorRatio.SetFillColor(TColor.GetColor('#6EF9F5')) TotErrorRatio = predTotError.Clone("SystErrorRatio") TotErrorRatio.SetFillColor(TColor.GetColor('#63E2C6')) TotErrorRatio.SetFillStyle(1001) for b in xrange(StatErrorRatio.GetNbinsX() + 1): if (StatErrorRatio.GetBinContent(b) != 0): StatErrorRatio.SetBinError( b, StatErrorRatio.GetBinError(b) / StatErrorRatio.GetBinContent(b)) TotErrorRatio.SetBinError( b, TotErrorRatio.GetBinError(b) / TotErrorRatio.GetBinContent(b)) StatErrorRatio.SetBinContent(b, 1.) TotErrorRatio.SetBinContent(b, 1.) else: StatErrorRatio.SetBinContent(b, 0) TotErrorRatio.SetBinContent(b, 0) #Set Style for bottom plot DataOverMC.SetTitle(";" + xtitle + "; " + ytitle_bottom) DataOverMC.GetXaxis().SetTitleSize(.12) DataOverMC.GetYaxis().SetTitleSize(.12) DataOverMC.GetYaxis().SetTitleOffset(.6) DataOverMC.GetXaxis().SetLabelSize(.12) DataOverMC.GetYaxis().SetLabelSize(.12) DataOverMC.SetMinimum(0.3) DataOverMC.SetMaximum(1.7) DataOverMC.Draw("EP") TotErrorRatio.Draw("E2 same") StatErrorRatio.Draw("E2 same") DataOverMC.Draw("EPsame") #Draw a guide for the eye line = TLine(DataOverMC.GetXaxis().GetXmin(), 1, DataOverMC.GetXaxis().GetXmax(), 1) line.SetLineColor(ROOT.kRed) line.SetLineWidth(1) line.SetLineStyle(1) line.Draw("Same") #Create Legend legend_bottom = TLegend(0.2, .8, .9, .9) legend_bottom.SetNColumns(3) legend_bottom.AddEntry(DataOverMC, "Obs./Pred.") legend_bottom.AddEntry(StatErrorRatio, "Stat. Unc.") legend_bottom.AddEntry(TotErrorRatio, "Tot. Unc.") legend_bottom.SetFillStyle(0) legend_bottom.SetBorderSize(0) legend_bottom.Draw() #Throw CMs lumi at it cl.CMS_lumi(Canv, 4, 11, year, 'Preliminary', True) print 'save' #Save everything savePlots(Canv, destination) print 'saved'
def readHists(postfix=""): hstack = THStack("hstack","hstack") hstack.SetTitle("#scale[0.9]{#font[22]{CMS} #font[12]{Preliminary} 41.53 fb^{-1}(13TeV)}") inputfile = read_rootfile(postfix) gROOT.cd() dirName = "ttH_"+region+"_"+Channels[0] h0 = inputfile.Get("shapes_"+fit_type+"/"+dirName+"/total") h_totalbkg = h0.Clone("h_totalbkg") h_totalbkg.SetDirectory(0) h_totalbkg.Reset() h_totalsig = h0.Clone("h_totalsig") h_totalsig.SetDirectory(0) h_totalsig.Reset() h_totalmc = h0.Clone("h_totalmc") h_totalmc.SetDirectory(0) h_totalmc.Reset() h_totalmc.SetLineColor(kBlack) h_totalmc.SetFillColor(kGray+3) h_totalmc.SetFillStyle(3001) h_totalmc.SetTitle("") h_totalmc.SetMinimum(0.8) h_totalmc.SetMaximum(1.35) h_totalmc.Sumw2() h_totalmc.SetStats(0) h_dataobs = h0.Clone("h_dataobs") h_dataobs.SetDirectory(0) h_dataobs.Reset() h_dataobs.SetMarkerStyle(20) latexString ="" expString =" SM Exp" dataString =" Data Obs" latexString += ("\\begin{frame}\n\\frametitle{"+POI.replace("_","\_")+" "+fit_type.replace("_","\_")+"}\n\\begin{table}[]\n\scalebox{0.38}{\n\\begin{tabular}{"+"l"*(2+len(Channels))+"}\n") for channel in Channels: FitDir = inputfile.Get("shapes_"+fit_type) directory = "shapes_"+fit_type+"/ttH_"+region+"_"+channel+"/" SkipChannel = False if not FitDir.GetListOfKeys().Contains("ttH_"+region+"_"+channel): print " skip " + directory SkipChannel = True else: h_bkg = inputfile.Get(directory+"total_background").Clone(directory+"total_background") h_totalbkg.Add(h_bkg) h_sig = inputfile.Get(directory+"total_signal").Clone(directory+"total_signal") h_totalsig.Add(h_sig) h_total = inputfile.Get(directory+"total").Clone(directory+"total") h_totalmc.Add(h_total) g_data = inputfile.Get(directory+"data").Clone(directory+"data") h_data = h_total.Clone("h_data") h_data.Reset() TGraphToTH1(h_data, g_data) h_dataobs.Add(h_data) if not SkipChannel: SM_error = ROOT.Double(0) h_total.IntegralAndError(0,h_total.GetNbinsX(),SM_error) expString += " & $ "+str(round(h_total.Integral(),2))+" \\pm "+str(round(SM_error,2))+"$" data_error = ROOT.Double(0) h_data.IntegralAndError(0,h_data.GetNbinsX(),data_error) dataString += " & $ "+str(round(h_data.Integral(),2))+" \\pm "+str(round(data_error,2))+"$" else: expString += " & - " dataString += " & - " latexString += ("& "+channel.replace("_","\_")+" ") totMC_error = ROOT.Double(0) h_totalmc.IntegralAndError(0,h_totalmc.GetNbinsX(),totMC_error) expString += " & $ "+str(round(h_totalmc.Integral(),2))+" \\pm "+str(round(totMC_error,2))+"$ \\\\ \n" totdata_error = ROOT.Double(0) h_dataobs.IntegralAndError(0,h_dataobs.GetNbinsX(),totdata_error) dataString += " & $ "+str(round(h_dataobs.Integral(),2))+" \\pm "+str(round(totdata_error,2))+"$ \n" latexString += "& total "+ region +" \\\\ \n" legend = TLegend(0.2,0.6,0.8,0.88) #legend.SetHeader("2017 "+fit_type+", 2lss l^{#pm}l^{#pm} #mu(ttH)=#hat#mu") legend.SetHeader("2017 "+fit_type+", "+header_postfix) legend.SetNColumns(3) legend.SetBorderSize(0) Samples.reverse() for sample in Samples: hist=h_totalsig.Clone(sample) hist.Reset() latexString += sample for channel in Channels: h_sample =hist.Clone(sample+"_sample") h_sample.Reset() latexString += " & " for p in Process[sample]: histname = "shapes_"+fit_type+"/ttH_"+region+"_"+channel+"/"+p h1 = inputfile.Get(histname) if h1: #print h1.Integral() hist.Add(h1) h_sample.Add(h1) if h_sample.Integral()>0.05: error = ROOT.Double(0) h_sample.IntegralAndError(0,h_sample.GetNbinsX(),error) latexString += "$ "+str(round(h_sample.Integral(),2))+" \\pm "+str(round(error,2))+"$" elif h_sample.Integral()>0: latexString += " \\textless{}0.05" else: latexString += " - " if hist.Integral()>0: hist.SetDirectory(0) hist.SetFillColor(Color[sample]) hist.SetLineColor(kBlack) hist.SetFillStyle(Style[sample]) hstack.Add(hist) legend.AddEntry(hist,sample,"f") if hist.Integral()>0.05: IntegralError = ROOT.Double(0) hist.IntegralAndError(0,hist.GetNbinsX(),IntegralError) latexString += " & $ "+str(round(hist.Integral(),2))+" \\pm "+str(round(IntegralError,2))+" $ \\\\ \n" else: latexString += " & \\textless{}0.05 \\\\ \n" else: latexString += " & - \\\\ \n" latexString += (expString + dataString) latexString += ("\\end{tabular}\n}\n\\end{table}\n\\end{frame}\n \\end{document}\n") if LATEX==1 : latexfile = file(DirOfRootplas+SubCat+"/"+POI+"/"+SubCat+"_"+POI+"_"+region+"_"+fit_type+"_"+SPLIT+"_"+Expected+"_yield.tex","w") latexfile.write("\\documentclass{beamer}\n\\usetheme{Warsaw}\n\n\\usepackage{graphicx}\n\\useoutertheme{infolines}\n\\setbeamertemplate{headline}{}\n\n\\begin{document}\n\n") latexfile.write(latexString) inputfile.Close() return h_totalsig, h_totalbkg, h_totalmc, h_dataobs, hstack, legend
def plotter(plotdir, plot, xTitle, logY, channels=['VV'], includeData=False, scaleSignal=0, UserRange=[None, None, None, None], initPath=''): # channelTex={'WPWP':'W^{+}W^{+}', 'WPWM':'W^{+}W^{-}','WMWM':'W^{-}W^{-}','WPZ':'W^{+}Z','WMZ':'W^{-}Z','ZZ':'ZZ'} channelTex = {'ZZ': 'ZZ'} # plotstyle=[(1,1),(1,2),(2,1),(2,2),(4,1),(4,2)] plotstyle = [(1, 1)] # 0 1 2 3 4 5 6 # Backgrounds=['QCD', 'WJetsToQQ_HT600ToInf', 'ZJetsToQQ_HT600ToInf', 'TT', 'WW', 'WZ', 'ZZ'] # BGColors= [rt.kAzure+7, rt.kRed-4, rt.kOrange-2, rt.kGreen+2, rt.kOrange+7, rt.kBlue+1, rt.kMagenta+2] # BGTeX= ['QCD', 'W+JetsToQQ', 'Z+JetsToQQ', 'TTbar'], 'WW', 'WZ', 'ZZ'] #stackOrder= [4,5,6,2,1,3,0] Backgrounds = [ 'QCD' ] # 'WJetsToQQ_HT600ToInf', 'ZJetsToQQ_HT600ToInf', 'ZZ'] 'TT', 'WW', 'WZ', 'ZZ'] BGColors = [ rt.kAzure + 7 ] #, rt.kOrange-2, rt.kGreen+2], rt.kOrange+7, rt.kBlue+1, rt.kMagenta+2] BGTeX = ['QCD'] # stackOrder = [0] PreSelection = [ 'nocuts', 'common', 'corrections', 'cleaner', 'softdropmassCorr', 'AK4pfidfilter', 'AK8pfidfilter', 'invMAk8sel', 'detaAk8sel', 'AK8N2sel' ] Selection = [ 'preselection', 'softdropAK8sel', 'tau21sel', 'deltaR48', 'VVRegion', 'AK4N2sel', 'OpSignsel', 'detaAk4sel', 'invMAk4sel_1p0', 'Kin_AK8' ] cutnames = [ 'cleaner', 'AK8N2sel', 'invMAk8sel', 'detaAk8sel', 'softdropAK8sel', 'tau21sel', 'AK4cleaner', 'AK4N2sel', 'OpSignsel', 'detaAk4sel', 'invMAk4sel_1p0' ] cuts = { 'cleaner': '#splitline{p_{T-AK8} > 200 GeV, |#eta_{AK8}| < 2.5}{p_{T-AK4} > 30 GeV, |#eta_{AK4}| < 5.0}', 'AK8N2sel': 'N_{AK8} #geq 2', 'invMAk8sel': 'M_{jj-AK8} > 1050 GeV', 'detaAk8sel': '|#Delta#eta_{jj-AK8}|<1.3', 'softdropAK8sel': '65 GeV <M_{SD}< 105 GeV', 'tau21sel': '0 #leq #tau_{2}/#tau_{1}<0.45', # 'AK4cleaner':'p_{T-AK4} > 30 GeV, |#eta_{AK4}| < 5.0', 'AK4cleaner': '', 'AK4N2sel': 'N_{AK4} #geq 2', 'OpSignsel': '#eta_{1-AK4} #eta_{2-AK4} < 0', 'detaAk4sel': '|#Delta#eta_{jj-AK4}| > 3.0', 'invMAk4sel_1p0': 'M_{jj-AK4} > 1.0 TeV' } VV = ('VV' in channels) seperate = (not VV) if VV: #channels=["WPWP","WPWM","WMWM","WPZ","WMZ","ZZ"] channels = ["ZZ"] plottitle = plotdir + '_' + plot lumi = 36.814 xLabelSize = 18. yLabelSize = 18. xTitleSize = 20. yTitleSize = 22. xTitleOffset = 4. yTitleOffset = 1.3 printout = False Portrait = True cutname = False ratio = includeData if ('highbin' in plot): binning = 'dijetbinning' else: binning = 'default' if (Portrait): canvX = 600 canvY = 600 else: canvX = 900 canvY = 675 if (plotdir in PreSelection): region = 'PreSelection' initPath = '' referenceHistPath = 'detaAk8sel/N_pv' if (PreSelection.index(plotdir) < 4 and ('softdrop' in plot)): return 'SofdropMass not filled yet!' else: region = 'SignalRegion' referenceHistPath = 'tau21sel/N_pv' referenceHistPath = plotdir + '/' + plot if (initPath == ''): path = '/nfs/dust/cms/user/loemkerj/bachelor/CMSSW_10_2_16/src/UHH2/aQGCVVjjhadronic/%s' % region else: path = initPath outputPath = path.replace( '/nfs/dust/cms/user/loemkerj/bachelor/CMSSW_10_2_16/src/UHH2/aQGCVVjjhadronic/SignalRegion', 'plots/') if (plotdir in PreSelection): CutNumber = PreSelection.index(plotdir) else: CutNumber = Selection.index(plotdir) outputPath = outputPath + '/%02i_%s' % (CutNumber, plotdir) + '/' if (printout): print('InputPath:', path) print('OutputPath:', outputPath) #check if OutputPath exists - and if not create it! if not os.path.exists(outputPath): os.makedirs(outputPath) # path='/home/albrec/Master/signal/' scaleVV = (scaleSignal != 0) VVScale = scaleSignal if (UserRange[2] == None or UserRange[3] == None): YRangeUser = False Ymin = UserRange[2] Ymax = UserRange[3] else: YRangeUser = True Ymin = UserRange[2] Ymax = UserRange[3] if (UserRange[0] == None or UserRange[1] == None): XRangeUser = False Xmin = UserRange[0] Xmax = UserRange[1] else: XRangeUser = True Xmin = UserRange[0] Xmax = UserRange[1] # YRangeUser=False # Ymin=0.11 # Ymax=9*10**3 # XRangeUser=False # Xmin=0 # Xmax=6000. gROOT.ProcessLine("gErrorIgnoreLevel = 2001;") SFiles = [] for i in range(len(channels)): SFiles.append( TFile( path + "/uhh2.AnalysisModuleRunner.MC.MC_aQGC_%sjj_hadronic_2016v3.root" % channels[i])) #uhh2.AnalysisModuleRunner.MC.MC_aQGC_ZZjj_hadronic_2016v3.root ##Open Files to get BackgroundHist: BFiles = [] for i in range(len(Backgrounds)): BFiles.append( TFile(path + "/uhh2.AnalysisModuleRunner.MC.MC_%s.root" % Backgrounds[i])) #Open File to get DataHist: # DataFile = TFile(path+"/uhh2.AnalysisModuleRunner.Data.DATA.root") #gROOT.ProcessLine( "gErrorIgnoreLevel = 0;") if (includeData == True): #calculate QCDscale with Integrals from the following Histogram: # referenceHistPath = 'tau21sel/N_AK4' # referenceHistPath = 'detaAk8sel/N_pv' # referenceHistPath = 'tau21sel/met_pt_over_sumptAK8_2' QCDscale = float(DataFile.Get(referenceHistPath).Integral()) QCDNorm = 1 for i in range(len(BFiles)): if ('QCD' in BFiles[i].GetName()): QCDNorm = float(BFiles[i].Get(referenceHistPath).Integral()) else: QCDscale -= float(BFiles[i].Get(referenceHistPath).Integral()) QCDscale /= QCDNorm else: QCDscale = 1.0 if (printout): print('using QCDscale:', QCDscale) SHists = [] for i in range(len(channels)): SHists.append(SFiles[i].Get(plotdir + '/' + plot)) BHists = [] for i in range(len(BFiles)): BHists.append(BFiles[i].Get(plotdir + '/' + plot)) if ('QCD' in BFiles[i].GetName()): BHists[-1].Scale(QCDscale) #if(includeData): # DataHist=DataFile.Get(plotdir+'/'+plot) if (binning == 'dijetbinning'): fitbinning = array('d') binwidth = 200 NBins = (14000 / binwidth) - ((1040 / binwidth) + 1) NBins = int(NBins) for i in range(NBins + 1): fitbinning.append(1050 + i * binwidth) for i in range(len(channels)): SHists[i] = SHists[i].Rebin(NBins, "new binning", fitbinning) for i in range(len(Backgrounds)): BHists[i] = BHists[i].Rebin(NBins, "new binning", fitbinning) if (includeData): DataHist = DataHist.Rebin(NBins, "new binning", fitbinning) canv = TCanvas(plottitle, plottitle, canvX, canvY) yplot = 0.7 yratio = 0.3 ymax = 1.0 xmax = 1.0 xmin = 0.0 if (ratio): plotpad = TPad("plotpad", "Plot", xmin, ymax - yplot, xmax, ymax) ratiopad = TPad("ratiopad", "Ratio", xmin, ymax - yplot - yratio, xmax, ymax - yplot) else: plotpad = TPad("plotpad", "Plot", xmin, ymax - yplot - yratio, xmax, ymax) plotpad.SetTopMargin(0.08) plotpad.SetLeftMargin(0.1) plotpad.SetRightMargin(0.05) plotpad.SetTicks() plotpad.Draw() if (ratio): plotpad.SetBottomMargin(0.016) ratiopad.SetTopMargin(0.016) ratiopad.SetBottomMargin(0.35) ratiopad.SetLeftMargin(0.1) ratiopad.SetRightMargin(0.05) ratiopad.SetTicks() ratiopad.Draw() else: plotpad.SetBottomMargin(0.1) if (logY): plotpad.SetLogy() canv.SetLogy() if ('-logX' in xTitle): plotpad.SetLogx() if (ratio): ratiopad.SetLogx() canv.SetLogx() drawOptions = "HE" stack = THStack(plottitle, plottitle) BHist = THStack(plottitle, plottitle) # for i in range(len(Backgrounds)): for i in stackOrder: # BHists[i].SetFillColor(BGColors[i]) BHists[i].SetLineColor(BGColors[i]) BHist.Add(BHists[i], 'Hist') BHist.SetTitle(plottitle) BHistErr = BHists[0].Clone() for i in range(1, len(Backgrounds)): BHistErr.Add(BHists[i]) BHistErr.SetFillStyle(3204) BHistErr.SetFillColor(rt.kGray + 2) BHistErr.SetLineColor(1) BGMax = BHist.GetMaximum() SIGMax = 0 #if(VV): #new # SIGMax=VVsum.GetMaximum() #else: for i in range(len(channels)): tmpmax = SHists[i].GetMaximum() if (tmpmax > SIGMax): SIGMax = tmpmax if (scaleVV): SIGMax = SIGMax * VVScale if (logY): MAX = 0.9 * float(10**(magnitude(max(BGMax, SIGMax)) + 1)) MIN = float(10**(magnitude(max(BGMax, SIGMax)) - 5)) MIN += float(10**(magnitude(MIN))) legendMIN = math.log(max(BGMax, SIGMax)) / math.log(MAX) else: MAX = (1.0 / 0.8) * max(BGMax, SIGMax) legendMIN = 0.7 MIN = 0. legendMIN = (legendMIN * 0.7) + 0.3 - 0.016 legend = TLegend(0.5, 0.75, 0.85, 0.89) legend.SetFillStyle(0) legend.SetTextSize(0.02) legend.SetMargin(0.4) legend.SetNColumns(2) legend.SetColumnSeparation(0.3) if (includeData): DataHist.SetMarkerStyle(8) DataHist.SetLineColor(1) DataHist.SetTitle(plottitle) if VV: for i in range(len(channels)): if (i == 0): VVsum = SHists[i].Clone() else: VVsum.Add(SHists[i]) legentry = 'VVjj' if (scaleVV): VVsum.Scale(VVScale) legentry += ' *%0.f' % VVScale VVsum.SetLineColor(1) VVsum.SetLineStyle(plotstyle[0][1]) VVsum.SetLineWidth(2) legend.AddEntry(VVsum, legentry) else: for i in range(len(channels)): SHists[i].SetLineColor(plotstyle[i][0]) SHists[i].SetLineStyle(plotstyle[i][1]) SHists[i].SetLineWidth(2) legentry = "%sjj" % channelTex[channels[i]] if (scaleVV): SHists[i].Scale(VVScale) legentry += ' *%.2E' % VVScale legend.AddEntry(SHists[i], legentry) for i in stackOrder: legend.AddEntry(BHists[i], BGTeX[i], "f") legend.AddEntry(BHistErr, "stat. Uncertainty", "f") if (includeData): legend.AddEntry(DataHist, "Data", "lep") canv.SetTitle(plottitle) BHistErr.GetYaxis().SetTitle('Events') BHistErr.GetYaxis().SetRangeUser(MIN, MAX) BHistErr.GetYaxis().SetTitleFont(43) BHistErr.GetYaxis().SetTitleSize(yTitleSize) BHistErr.GetYaxis().SetTitleOffset(yTitleOffset) BHistErr.GetYaxis().SetLabelFont(43) BHistErr.GetYaxis().SetLabelSize(yLabelSize) if (ratio): BHistErr.GetXaxis().SetTitleSize(0.0) BHistErr.GetXaxis().SetLabelSize(0.0) else: BHistErr.GetXaxis().SetTitle(xTitle) BHistErr.GetXaxis().SetTitleFont(43) BHistErr.GetXaxis().SetTitleSize(xTitleSize) # BHistErr.GetXaxis().SetTitleOffset(xTitleOffset) BHistErr.GetXaxis().SetTitleOffset(1.2) BHistErr.GetXaxis().SetLabelFont(43) BHistErr.GetXaxis().SetLabelSize(xLabelSize) # BHistErr.GetXaxis().SetTickLength(0.08) # BHistErr.GetXaxis().SetNdivisions(506) if (YRangeUser): BHistErr.GetYaxis().SetRangeUser(Ymin, Ymax) if (XRangeUser): BHistErr.GetXaxis().SetRangeUser(Xmin, Xmax) plotpad.cd() BHistErr.Draw("E2") BHist.Draw("HistSAME") BHistErr.Draw("E2SAME") if (VV): VVsum.Draw("SAME" + drawOptions) elif ('-noSig' not in xTitle): for i in range(len(channels)): SHists[i].Draw("SAME" + drawOptions) if (includeData): DataHist.Draw("APE1SAME") plotpad.RedrawAxis() if (ratio): ratiopad.cd() if (includeData): ratioHist = DataHist.Clone() else: ratioHist = BHistErr.Clone() ratioHist.SetLineColor(rt.kBlack) # ratioHist.Sumw2() ratioHist.SetStats(0) ratioHist.Divide(BHistErr) ratioHist.SetMarkerStyle(21) ratioHist.SetMarkerSize(0.7) #Yaxis ratioHist.GetYaxis().SetRangeUser(0.3, 1.7) ratioHist.GetYaxis().SetTitle("Data/BG") ratioHist.GetYaxis().CenterTitle() ratioHist.GetYaxis().SetTitleFont(43) ratioHist.GetYaxis().SetTitleSize(yTitleSize) ratioHist.GetYaxis().SetTitleOffset(yTitleOffset) ratioHist.GetYaxis().SetLabelFont(43) ratioHist.GetYaxis().SetLabelSize(yLabelSize) ratioHist.GetYaxis().SetNdivisions(506) #Xaxis ratioHist.GetXaxis().SetTitle(xTitle) ratioHist.GetXaxis().SetTitleFont(43) ratioHist.GetXaxis().SetTitleSize(xTitleSize) ratioHist.GetXaxis().SetTitleOffset(xTitleOffset) ratioHist.GetXaxis().SetLabelFont(43) ratioHist.GetXaxis().SetLabelSize(xLabelSize) ratioHist.GetXaxis().SetTickLength(0.08) ratioHist.GetXaxis().SetNdivisions(506) # if(YRangeUser): # ratioHist.GetYaxis().SetRangeUser(Ymin,Ymax) if (XRangeUser): ratioHist.GetXaxis().SetRangeUser(Xmin, Xmax) ratioXMin = Xmin ratioXMax = Xmax else: ratioXMin = ratioHist.GetXaxis().GetXmin() ratioXMax = ratioHist.GetXaxis().GetXmax() ratioHist.Draw("ep") zeropercent = TLine(ratioXMin, 1, ratioXMax, 1) zeropercent.Draw() plus10percent = TLine(ratioXMin, 1.1, ratioXMax, 1.1) plus10percent.SetLineStyle(rt.kDashed) plus10percent.Draw() minus10percent = TLine(ratioXMin, 0.9, ratioXMax, 0.9) minus10percent.SetLineStyle(rt.kDashed) minus10percent.Draw() canv.cd() gPad.RedrawAxis() legend.Draw() latex = TLatex() latex.SetNDC(kTRUE) latex.SetTextSize(20) latex.DrawLatex(0.69, 0.953, "%.2f fb^{-1} (13 TeV)" % lumi) latex.DrawLatex(0.1, 0.953, "private work") lastcut = 'nocuts' for cut in cutnames: if cut in plotdir: lastcut = cut if (not (lastcut == 'nocuts') and cutname): # latex.SetTextSize(0.03) latex.SetTextSize(15) for l in range(cutnames.index(lastcut) + 1): latex.DrawLatex(0.12, 0.8 - l * 0.04, cuts[cutnames[l]]) canv.Update() canv.Print(outputPath + '/%s_%s.pdf' % (plotdir, plot)) #prevents memory leak in Canvas Creation/Deletion #see: https://root.cern.ch/root/roottalk/roottalk04/2484.html gSystem.ProcessEvents() if (ratio): del ratiopad del plotpad, canv # gc.collect() return 'done!'
def study_smearing(): # Import data and MC files: f_data = TFile.Open("../trees_5gev_e/data_nn50.root", 'read') t_data = f_data.data t_data.AddFriend("data10=data", "../trees_5gev_e/data_nn10.root") t_data.AddFriend("data20=data", "../trees_5gev_e/data_nn20.root") t_data.AddFriend("data90=data", "../trees_5gev_e/data_nn90.root") t_data.AddFriend("data99=data", "../trees_5gev_e/data_nn99.root") f_mc = TFile.Open("../trees_5gev_e/lucas.root", 'read') t_mc = f_mc.lumical t_mc.AddFriend("lumical_noise=lumical", "../trees_5gev_e/lucas_geocuts_noise_test.root") c = TCanvas() hs = THStack("hs", "title") t_data.Draw("Sum$(data10.energy*(data10.layer == 0))>>h_data10(200, 0, 3)", "Sum$(data10.energy*(data10.layer == 0)) > 0") h_data10 = gROOT.FindObject("h_data10") h_data10.SetTitle("Data nn>0.1") h_data10.SetLineWidth(2) h_data10.SetLineColor(3) hs.Add(h_data10, "histo") t_data.Draw("Sum$(data20.energy*(data20.layer == 0))>>h_data20(200, 0, 3)", "Sum$(data20.energy*(data20.layer == 0)) > 0") h_data20 = gROOT.FindObject("h_data20") h_data20.SetTitle("Data nn>0.2") h_data20.SetLineWidth(2) h_data20.SetLineColor(4) hs.Add(h_data20, "histo") t_data.Draw("Sum$(energy*(layer == 0))>>h_data50(200, 0, 3)", "Sum$(energy*(layer == 0)) > 0") h_data50 = gROOT.FindObject("h_data50") h_data50.SetTitle("Data nn>0.5") h_data50.SetLineWidth(2) h_data50.SetLineColor(1) hs.Add(h_data50, "histo") t_data.Draw("Sum$(data90.energy*(data90.layer == 0))>>h_data90(200, 0, 3)", "Sum$(data90.energy*(data90.layer == 0)) > 0") h_data90 = gROOT.FindObject("h_data90") h_data90.SetTitle("Data nn>0.90") h_data90.SetLineWidth(2) h_data90.SetLineColor(5) hs.Add(h_data90, "histo") t_data.Draw("Sum$(data99.energy*(data99.layer == 0))>>h_data99(200, 0, 3)", "Sum$(data99.energy*(data99.layer == 0)) > 0") h_data99 = gROOT.FindObject("h_data99") h_data99.SetTitle("Data nn>0.99") h_data99.SetLineWidth(2) h_data99.SetLineColor(6) hs.Add(h_data99, "histo") # t_mc.Draw("Sum$(tr1_energy/0.0885)>>h_mc(200, 0, 3)", "Sum$(tr1_energy/0.0885) > 0") # h_mc = gROOT.FindObject("h_mc") # h_mc.SetTitle("MC no smearing") # h_mc.SetLineWidth(2) # h_mc.SetLineColor(2) # h_mc.Scale(t_data.GetEntries()/t_mc.GetEntries()) # hs.Add(h_mc, "histo") # t_mc.Draw("Sum$(tr1_energy_smeared5/0.0885)>>h_mc5(200, 0, 3)", "Sum$(tr1_energy_smeared5/0.0885) > 0") # h_mc5 = gROOT.FindObject("h_mc5") # h_mc5.SetLineWidth(2) # h_mc5.SetLineColor(3) # h_mc5.SetMarkerStyle(0) # h_mc5.Scale(t_data.GetEntries()/t_mc.GetEntries()) # hs.Add(h_mc5, "histo") # t_mc.Draw("Sum$(tr1_energy_smeared6/0.0885)>>h_mc6(200, 0, 3)", "Sum$(tr1_energy_smeared6/0.0885) > 0") # h_mc6 = gROOT.FindObject("h_mc6") # h_mc6.SetTitle("MC smearing #sigma=0.6*stdNoise") # h_mc6.SetLineWidth(2) # h_mc6.SetLineColor(2) # h_mc6.Scale(t_data.GetEntries()/t_mc.GetEntries()) # hs.Add(h_mc6, "histo") t_mc.Draw("Sum$(tr1_energy_smeared7/0.0885)>>h_mc7(200, 0, 3)", "Sum$(tr1_energy_smeared7/0.0885) > 0") h_mc7 = gROOT.FindObject("h_mc7") h_mc7.SetTitle("MC smearing #sigma=0.7*stdNoise") h_mc7.SetLineWidth(2) h_mc7.SetLineColor(2) h_mc7.Scale(t_data.GetEntries() / t_mc.GetEntries()) hs.Add(h_mc7, "histo") # t_mc.Draw("Sum$((tr1_energy_smeared10)/0.0885)>>h_mc10(200, 0, 3)", "Sum$((tr1_energy_smeared10)/0.0885) > 0") # h_mc10 = gROOT.FindObject("h_mc10") # h_mc10.SetTitle("MC smearing #sigma=stdNoise") # h_mc10.SetLineWidth(2) # h_mc10.SetLineColor(18) # h_mc10.Scale(t_data.GetEntries()/t_mc.GetEntries()) # hs.Add(h_mc10, "histo") hs.Draw("nostack") hs.SetTitle("Deposited energy in the 1st tracker;E, [MIP]; N_{events}") c.SetGridx() c.SetGridy() c.BuildLegend() c.Update() input("wait")
hs.Add(LepBDTMCDY_list[i]) #upper plot pad pad1 = TPad("pad1", "pad1", 0, 0.3, 1, 1.0) pad1.Draw() pad1.cd() hs.SetMaximum(1.6 * max(hs.GetMaximum(), LepBDTDATA_list[i].GetMaximum())) LepBDTDATA_list[i].SetMaximum( 1.6 * max(hs.GetMaximum(), LepBDTDATA_list[i].GetMaximum())) hs.SetMinimum(10) #EF for ele BDT hs.Draw("histo") LepBDTDATA_list[i].Draw("sameEP") hs.SetTitle("") hs.GetXaxis().SetTitle("BDT score") hs.GetXaxis().SetRangeUser(0.75, 1) #EF for ele BDT 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") gStyle.SetOptStat(0) pad1.SetLogy() # legend
def plotDataVSMC(DataHist, MCHist, xtitle, legendNames, DataName, destination, ytitle_bottom='Data/MC'): GeneralSettings() Canv = TCanvas("Canv" + destination, "Canv" + destination, 1000, 1000) #Set Histogram Styles for i, h in enumerate(MCHist): h.SetFillColor( TColor.GetColor(GetStackColorTauPOGbyName(legendNames[i]))) h.SetLineColor( TColor.GetColor(GetStackColorTauPOGbyName(legendNames[i]))) DataHist.SetMarkerColor(ROOT.kBlack) DataHist.SetLineColor(ROOT.kBlack) DataHist.SetMarkerStyle(20) #Add all MC samples to use in ratios totBkgr = MCHist[0].Clone("totBkgr") for h in MCHist[1:]: totBkgr.Add(h) DataOverMC = DataHist.Clone("DataOverMC") DataOverMC.Divide(totBkgr) #First pad plotpad = TPad("plotpad", "plotpad", 0, .3, 1, 0.98) plotpad.SetBottomMargin(0.025) plotpad.Draw() plotpad.cd() #Create Stack (Change with most logical ordering) hs = THStack("hs", "hs") for h in MCHist: hs.Add(h) hs.Draw( "EHist" ) #Draw before using GetHistogram, see https://root-forum.cern.ch/t/thstack-gethistogram-null-pointer-error/12892/4 title = " ; ; Events / " + str(MCHist[0].GetBinWidth(1)) + " GeV" hs.SetTitle(title) # hs.GetHistogram().GetXaxis().SetTickLength(0) hs.GetHistogram().GetXaxis().SetLabelOffset(9999999) hs.GetHistogram().SetMaximum(1) #Set range overallMin = GetOverallMinimum(MCHist + [DataHist]) overallMax = GetOverallMaximum([totBkgr] + [DataHist]) hs.SetMinimum(0.5 * overallMin) hs.SetMaximum(1.2 * overallMax) DataHist.Draw("EPSame") #Create Legend legend = TLegend(0.7, .7, .9, .9) for h, n in zip(MCHist, legendNames): legend.AddEntry(h, n) legend.AddEntry(DataHist, DataName) legend.SetFillStyle(0) legend.SetBorderSize(0) legend.Draw() #Return to canvas Canv.cd() #Second pad ratiopad = TPad("ratiopad", "ratiopad", 0, 0.05, 1, .3) ratiopad.SetTopMargin(0.05) ratiopad.SetBottomMargin(0.25) ratiopad.Draw() ratiopad.cd() #Set Style for bottom plot DataOverMC.SetTitle(";" + xtitle + "; " + ytitle_bottom) DataOverMC.GetXaxis().SetTitleSize(.12) DataOverMC.GetYaxis().SetTitleSize(.12) DataOverMC.GetYaxis().SetTitleOffset(.6) DataOverMC.GetXaxis().SetLabelSize(.12) DataOverMC.GetYaxis().SetLabelSize(.12) DataOverMC.SetMinimum(0.6) DataOverMC.SetMaximum(1.4) DataOverMC.Draw("EP") #Draw a guide for the eye line = TLine(DataOverMC.GetXaxis().GetXmin(), 1, DataOverMC.GetXaxis().GetXmax(), 1) line.SetLineColor(ROOT.kRed) line.SetLineWidth(1) line.SetLineStyle(1) line.Draw("Same") #Throw CMs lumi at it cl.CMS_lumi(Canv, 4, 11, 'Preliminary', True) print 'save' #Save everything savePlots(Canv, destination) print 'saved'