def get_canvas(cname): tdrstyle.setTDRStyle() iPos = 0 if( iPos==0 ): CMS_lumi.relPosX = 0.13 iPeriod=4 H_ref = 500 W_ref = 500 W = W_ref H = H_ref T = 0.08*H_ref B = 0.12*H_ref L = 0.12*W_ref R = 0.04*W_ref canvas = ROOT.TCanvas(cname,cname,50,50,W,H) canvas.SetFillColor(0) canvas.SetBorderMode(0) canvas.SetFrameFillStyle(0) canvas.SetFrameBorderMode(0) canvas.SetLeftMargin( 0.35 ) canvas.SetRightMargin( 0.02 ) canvas.SetTopMargin( 0.01 ) #/T/H canvas.SetBottomMargin( B/H ) return canvas
def get_canvas(text): tdrstyle.setTDRStyle() CMS_lumi.lumi_13TeV = "2.1 fb^{-1}," + text CMS_lumi.writeExtraText = 1 CMS_lumi.extraText = "" iPos = 0 if( iPos==0 ): CMS_lumi.relPosX = 0.12 H_ref = 600 W_ref = 800 W = W_ref H = H_ref T = 0.08*H_ref B = 0.12*H_ref L = 0.12*W_ref R = 0.04*W_ref canvas = ROOT.TCanvas("c2","c2",50,50,W,H) canvas.SetFillColor(0) canvas.SetBorderMode(0) canvas.SetFrameFillStyle(0) canvas.SetFrameBorderMode(0) canvas.SetLeftMargin( L/W+0.01 ) canvas.SetRightMargin( R/W+0.03 ) canvas.SetTopMargin( T/H ) canvas.SetBottomMargin( B/H+0.03 ) canvas.SetGrid() canvas.SetLogy() return canvas
def get_canvas(cname,lumi8,lumi13): tdrstyle.setTDRStyle() CMS_lumi.lumi_13TeV = "%s fb^{-1}"%lumi13 CMS_lumi.lumi_8TeV = "%s fb^{-1}"%lumi8 CMS_lumi.writeExtraText = 1 CMS_lumi.extraText = "Preliminary" CMS_lumi.lumi_sqrtS = "13 TeV" # used with iPeriod = 0, e.g. for simulation-only plots (default is an empty string) iPos = 0 if( iPos==0 ): CMS_lumi.relPosX = 0.13 iPeriod=4 H_ref = 630 W_ref = 600 W = W_ref H = H_ref T = 0.08*H_ref B = 0.12*H_ref L = 0.12*W_ref R = 0.04*W_ref canvas = ROOT.TCanvas(cname,cname,50,50,W,H) canvas.SetFillColor(0) canvas.SetBorderMode(0) canvas.SetFrameFillStyle(0) canvas.SetFrameBorderMode(0) canvas.SetLeftMargin( L/W+0.01 ) canvas.SetRightMargin( R/W+0.03 ) canvas.SetTopMargin( 0.07 ) #/T/H canvas.SetBottomMargin( B/H ) #canvas.SetGrid() canvas.SetLogy() return canvas
def get_canvas(cname): tdrstyle.setTDRStyle() CMS_lumi.lumi_8TeV = "19.7 fb^{-1}" CMS_lumi.writeExtraText = 1 CMS_lumi.extraText = "Preliminary" iPos = 0 if( iPos==0 ): CMS_lumi.relPosX = 0.16 H_ref = 800; W_ref = 800; W = W_ref H = H_ref T = 0.08*H_ref B = 0.12*H_ref L = 0.12*W_ref R = 0.04*W_ref canvas = ROOT.TCanvas(cname,cname,50,50,W,H) canvas.SetFillColor(0) canvas.SetBorderMode(0) canvas.SetFrameFillStyle(0) canvas.SetFrameBorderMode(0) canvas.SetLeftMargin( L/W+0.02 ) canvas.SetRightMargin( R/W ) canvas.SetTopMargin( T/H ) canvas.SetBottomMargin( B/H ) canvas.SetGrid() canvas.SetLogy() return canvas
def get_canvas(): tdrstyle.setTDRStyle() CMS_lumi.lumi_13TeV = "13 TeV" CMS_lumi.writeExtraText = 0 CMS_lumi.extraText = "Preliminary" iPos = 0 if( iPos==0 ): CMS_lumi.relPosX = 0.07 H_ref = 600; W_ref = 800; W = W_ref H = H_ref T = 0.08*H_ref B = 0.12*H_ref L = 0.12*W_ref R = 0.04*W_ref #canvas = ROOT.TCanvas("c2","c2",50,50,W,H) canvas = ROOT.TCanvas("c2","c2",W,H) canvas.SetFillColor(0) canvas.SetBorderMode(0) canvas.SetFrameFillStyle(0) canvas.SetFrameBorderMode(0) canvas.SetLeftMargin( L/W ) canvas.SetRightMargin( R/W ) canvas.SetTopMargin( T/H ) canvas.SetBottomMargin( B/H ) canvas.SetTickx() canvas.SetTicky() return canvas
def __init__(self, OutDir): self.OutDir = OutDir if not os.path.isdir(self.OutDir): try: os.makedirs(self.OutDir) except OSError: pass self.lumi = Lumi tdrstyle.setTDRStyle() self.canvas = self.CreatCanvas()
def setTDRStyle(canvas, luminosity, energy, printCMS): tdrstyle.setTDRStyle() if printCMS == "right" or printCMS == "left": if energy == 13: CMS_lumi.lumi_13TeV = "%s fb^{-1}" % luminosity if printCMS == "left": iPos = 11 else: iPos = 13 CMS_lumi.writeExtraText = 1 CMS_lumi.extraText = "Very Preliminary" CMS_lumi.CMS_lumi(canvas, 4, iPos)
def __init__(self): ''' Set up PlotStyle, set gStyle for things we always want no matter what. ''' # CMS-approved everything tdrstyle.setTDRStyle() ### Differences from TDR standard: # Big canvas (can always shrink later) gStyle.SetCanvasDefH(1200) gStyle.SetCanvasDefW(1200) # Tick marks on all sides gStyle.SetPadTickX(1) gStyle.SetPadTickY(1) # Everything has white backgrounds gStyle.SetLegendFillColor(0) # Colors that don't suck gStyle.SetPalette(1) # Make axis title and labels just a little smaller and (for Y) closer to the axis gStyle.SetTitleSize(0.048, "X") gStyle.SetTitleSize(0.044, "YZ") gStyle.SetLabelSize(0.033, "XYZ") gStyle.SetTitleYOffset(1.15) gStyle.SetTitleXOffset(0.86) gStyle.SetPadLeftMargin(0.1) gStyle.SetPadRightMargin(0.025) gStyle.SetPadBottomMargin(0.095) gStyle.SetTitleAlign(12) # Apply changes gROOT.ForceStyle() # Force exponentials when axes are over 3 digits TGaxis.SetMaxDigits(3) TGaxis.SetExponentOffset(-0.060, 0.008, "y") TGaxis.SetExponentOffset(-0.055, -0.062, "x") # will overlap with title unless title is centered
def DrawPUperFile(filedir, l1seed, key=None): global mcdf allfiles = glob.glob(filedir) if not os.path.exists("plots"): os.mkdir("plots") tdrstyle.setTDRStyle() ROOT.gStyle.SetOptStat(000000000) df = pd.DataFrame() flist = [ ] for file_ in allfiles: df_ = pd.read_csv(file_, index_col=None, header=0) flist.append(df_) df = pd.concat(flist) mcdf = GetMCDataFrame(allfiles) if l1seed == "All": for seed in pd.unique(df.L1Seed): DrawPU(df, seed) else: return DrawPU(df, l1seed, key)
def makeComparisonPlots(patTuple_list, ntuple_l1recoMuonTree, label, handle, plottingVariables): ROOT.gROOT.SetBatch() # don't pop up canvases ROOT.gStyle.SetErrorX(0) tdrstyle.setTDRStyle() muonHists_patTree = plotMuQuantities_pat(patTuple_list, label, handle, plottingVariables) muonHists_l1muRecoTree = plotMuQuantities_l1(ntuple_l1recoMuonTree, plottingVariables) for muonHist_patTree, muonHist_l1muRecoTree, plotVar in izip(muonHists_patTree, muonHists_l1muRecoTree, plottingVariables): # Draw histograms c1 = ROOT.TCanvas("", "", 1024, 786) muonHist_l1muRecoTree.SetLineColor(ROOT.kBlue) muonHist_l1muRecoTree.DrawCopy("E1HIST") muonHist_patTree.SetLineColor(ROOT.kRed) muonHist_patTree.DrawCopy("E1HISTSAME") c1.Print(plotVar.title + ".pdf")
def main(): argv = sys.argv[1:] argc = len(argv) if argc > 0: nbins = atoi(argv[0]) else: nbins = 20 gSystem.AddDynamicPath('%s/Projects/turtle/lib' % os.environ['HOME']) gSystem.Load("libturtle") files = vector('string')(1, 'bkg.root') names = vector('string')(1, 'f_pfmet') # files = list of files whose data are to be binned # names = namesd of variables in which to bin # treename # number of bins turtle = Turtle(files, names, 'HZZ4LeptonsAnalysisReduced', nbins) datfilename = 'ntuple_data.root' bkgfilename = 'ntuple_bkg.root' sigfilename = 'ntuple_ZpBary_MZp00500_MA00150.root' data, wdata = read(datfilename, 50) bkg, wbkg = read(bkgfilename) sig, wsig = read(sigfilename, 1000) dtotal = sum(wdata) btotal = sum(wbkg) stotal = sum(wsig) scale = dtotal / btotal print 'data count: %8.0f' % dtotal print 'bkg count: %10.2f' % btotal print 'sig count: %10.2f' % stotal print 'number of bins: %8d' % nbins print "\nbin data..." point = vector('double')(1) for D in data: point[0] = D turtle.Fill(point) dcount = turtle.GetBinContents() dvar = turtle.GetBinVariances() print "bin background..." turtle.Reset() for ii, D in enumerate(bkg): point[0] = D w = wbkg[ii] * scale turtle.Fill(point, w) bcount = turtle.GetBinContents() bvar = turtle.GetBinVariances() print "bin signal..." turtle.Reset() for ii, D in enumerate(sig): point[0] = D w = wsig[ii] # * scale turtle.Fill(point, w) scount = turtle.GetBinContents() svar = turtle.GetBinVariances() gof = 0.0 v = [] for ii in xrange(nbins): x = turtle.GetBinCenter(ii)[0] w = turtle.GetBinWidth(ii)[0] b = bcount[ii] berr = sqrt(bvar[ii]) d = dcount[ii] derr = sqrt(dvar[ii]) s = scount[ii] serr = sqrt(svar[ii]) gof += (d - b)**2 / dvar[ii] v.append((x, w, b, berr, d, derr, s, serr)) v.sort() gof /= nbins out = open('data_MC_MET_%3.3d.txt' % nbins, 'w') record = '%3s %10s\t%10s %10s %10s' % ('bin', 'boundary', 'pred', 'data', 'signal') print record out.write('%s\n' % record) bnd = 0.0 counts = [] for ii, (x, w, b, berr, d, derr, s, serr) in enumerate(v): bnd += w record = '%3d %10.6f\t%10.2f %10.1f %10.6f' % (ii, bnd, b, d, s) print record out.write('%s\n' % record) counts.append((ii + 1, bnd, b, berr, d, derr, s, serr)) out.close() print 'chi2 / nbins = %10.3f' % gof #------------------------------------------------------------------ # plot #------------------------------------------------------------------ xtitle = '#font[12]{f}(#font[12]{E}_{T}^{miss})' # --------------------------------------- # set up some standard graphics style # --------------------------------------- tdrstyle.setTDRStyle() gStyle.SetPadRightMargin(0.12) gStyle.SetOptStat('ei') gStyle.SetStatFont(42) gStyle.SetStatFontSize(0.03) gStyle.SetStatBorderSize(1) gStyle.SetStatH(0.2) gStyle.SetStatW(0.3) gStyle.SetStatX(0.83) gStyle.SetStatY(0.93) #change the CMS_lumi variables (see CMS_lumi.py) iPeriod = 4 iPos = 0 CMS_lumi.relPosX = 0.12 CMS_lumi.lumi_13TeV = "30.0 fb^{-1}" CMS_lumi.writeExtraText = 1 CMS_lumi.extraText = "Simulation" # DATA mcolor = kBlack hd = TH1F('hd', '', nbins, 0, 1) hd.GetXaxis().SetTitle(xtitle) hd.GetXaxis().SetNdivisions(505) hd.GetYaxis().SetNdivisions(505) hd.SetMarkerColor(mcolor) hd.SetMarkerStyle(20) hd.SetLineColor(mcolor) hd.SetLineWidth(2) # BACKGROUND mcolor = kMagenta + 1 hb = TH1F('hb', '', nbins, 0, 1) hb.GetXaxis().SetTitle(xtitle) hb.Sumw2() # needed to handle weights correctly hb.GetXaxis().SetNdivisions(505) hb.GetYaxis().SetNdivisions(505) hb.SetFillColor(mcolor) hb.SetFillStyle(3003) hb.SetLineWidth(2) # SIGNAL mcolor = kCyan + 1 hs = TH1F('hs', '', nbins, 0, 1) hs.GetXaxis().SetTitle(xtitle) hs.Sumw2() # needed to handle weights correctly hs.GetXaxis().SetNdivisions(505) hs.GetYaxis().SetNdivisions(505) hs.SetFillColor(mcolor) hs.SetFillStyle(3003) hs.SetLineWidth(2) print "\nfill histograms..." for jj, bnd, b, berr, d, derr, s, serr in counts: hb.SetBinContent(jj, b) hb.SetBinError(jj, berr) hd.SetBinContent(jj, d) hd.SetBinError(jj, derr) hs.SetBinContent(jj, s) hs.SetBinError(jj, serr) c1 = TCanvas("figures/f_data_MC_MET", 'data vs MC', 10, 10, 500, 500) c1.cd() hb.SetMinimum(0) hb.SetMaximum(1.3 * hd.GetMaximum()) hb.Draw("hist") hs.Draw("histsame") hd.Draw("epsame") CMS_lumi.CMS_lumi(c1, iPeriod, iPos) c1.Update() gSystem.ProcessEvents() c1.SaveAs('.png') clog = TCanvas("figures/f_data_MC_MET_log", 'data vs MC', 520, 10, 500, 500) clog.cd() clog.SetLogy() hbc = hb.Clone('hbc') hbc.SetMinimum(1e-4) hbc.SetMaximum(1e2 * hd.GetMaximum()) hbc.Draw("hist") hs.Draw("histsame") hd.Draw("epsame") CMS_lumi.CMS_lumi(c1, iPeriod, iPos) clog.Update() gSystem.ProcessEvents() clog.SaveAs('.png') sleep(10)
def Plot(hs_, legtitles_, savename, logy=0, norm=0, fit=0): if len(hs_) != len(legtitles_): print 'number of histograms and legends not matching!' #set the tdr style tdrstyle.setTDRStyle() H_ref = 600 W_ref = 800 W = W_ref H = H_ref # references for T, B, L, R T = 0.08 * H_ref B = 0.12 * H_ref L = 0.12 * W_ref R = 0.04 * W_ref canvas = rt.TCanvas("c2", "c2", 50, 50, W, H) canvas.SetLogy(logy) canvas.SetFillColor(0) canvas.SetBorderMode(0) canvas.SetFrameFillStyle(0) canvas.SetFrameBorderMode(0) canvas.SetLeftMargin(L / W) canvas.SetRightMargin(R / W) canvas.SetTopMargin(T / H) canvas.SetBottomMargin(B / H) canvas.SetTickx(0) canvas.SetTicky(0) xAxis = hs_[0].GetXaxis() xAxis.SetNdivisions(6, 5, 0) # xAxis.SetTitleSize(0.05) yAxis = hs_[0].GetYaxis() yAxis.SetNdivisions(6, 5, 0) yAxis.SetTitleOffset(0.8) xAxis.SetTitleOffset(1.5) yAxis.SetTitleSize(0.06) if norm: yAxis.SetTitle('Normalized Events') if fit: for i in range(len(hs_)): hs_[i].Fit('gaus') if norm == 1: for i in range(len(hs_)): if hs_[i].Integral() != 0: hs_[i].Scale(1. / hs_[i].Integral()) if logy: hs_[0].SetMaximum(10 * max(h.GetMaximum() for h in hs_)) else: hs_[0].SetMaximum(1.2 * max(h.GetMaximum() for h in hs_)) # colorind =['#7fc97f','#beaed4','#fdc086','#ffff99'] # colorind2 = ['#1b9e77','#d95f02','#7570b3','#e7298a','#66a61e','#e6ab02','#a6761d'] colorind = [ '#1de41a', '#0000ff', '#ff33ff', '#286ba6', '#b86637', '#af4a4d', '#a39d4e' ] # colorind2 = ['#a6cee3','#1f78b4','#b2df8a','#33a02c','#fb9a99','#e31a1c','#fdbf6f'] # colorind2 =['#7fc97f','#beaed4','#fdc086','#ffff99','#386cb0','#f0027f','#bf5b17'] # colorind = ['#e41a1c','#ff7f00','#ffff33','#a65628','#377eb8','#4daf4a','#984ea3'] if len(legtitles_) > 0: legend = rt.TLegend(0.65, 0.85, 0.95, 0.95) # colorind[i] for i in range(len(hs_)): color = rt.TColor.GetColorTransparent(rt.TColor.GetColor(colorind[i]), 0.8) # colorLine = rt.TColor.GetColor(colorind2[i]) hs_[i].SetFillColor(color) hs_[i].SetLineColor(1) hs_[i].SetLineWidth(3) hs_[i].Draw("histosame") if len(legtitles_) > 0: legend.AddEntry(hs_[i], legtitles_[i], 'f') if len(hs_) < 3 and len(legtitles_) > 0: legend.SetTextSize(0.03) canvas.cd() canvas.Update() canvas.Modified() canvas.RedrawAxis() if len(legtitles_) > 0: legend.Draw() ''' latex = rt.TLatex() latex.SetTextFont(42) latex.SetTextAngle(0) latex.SetTextColor(rt.kBlack) latex.SetTextSize(0.05) latex.SetTextAlign(12) latex.SetNDC(); latex.DrawLatex(0.8,0.7,"bjets: "+str(nbjets)) latex.DrawLatex(0.8,0.65,"jets: "+str(njets)) latex.SetTextSize(0.04) latex.DrawLatex(0.13,0.9,"mean: ") latex.SetTextColor(rt.kRed+1) latex.DrawLatex(0.21,0.9,str(round(h1.GetMean(),2))) latex.SetTextColor(rt.kBlue+1) latex.DrawLatex(0.30,0.9,str(round(h2.GetMean(),2))) latex.SetTextColor(rt.kBlack) latex.DrawLatex(0.13,0.85,"rms: ") latex.SetTextColor(rt.kRed+1) latex.DrawLatex(0.21,0.85,str(round(h1.GetRMS(),2))) latex.SetTextColor(rt.kBlue+1) latex.DrawLatex(0.30,0.85,str(round(h2.GetRMS(),2))) ''' #update the canvas to draw the legend canvas.Update() canvas.SaveAs(savename + '.png')
for j in range(len(cfg.etaBins)): myhistos[i][j].Write() for i in range(nHistos - 8, nHistos): myhistos[i].Write() newfile.Close() print nHistos, " histograms have been saved to ", outputFileName # running the macro # just to avoid opening windows print "Let's go!" ROOT.gROOT.SetBatch() setTDRStyle(1) frame = ROOT.TH1F("frame", "", len(xbin) - 1, xbins) frame.SetMinimum(0.01) frame.SetMaximum(1.01) # MSSM Higgs #executeCode("config_DoubleTauProng1_2012A.py") #executeCode("config_DoubleTauProng1_2012B.py") #executeCode("config_DoubleTauProng1_2012Cv3.py") #executeCode("config_DoubleTauProng1_2012Cv4.py") #executeCode("config_DoubleTauProng1_2012Dpart1.py") #executeCode("config_DoubleTauProng1_2012Dpart2.py") # ## SM Higgs executeCode("config_DoubleTauJet_2012A.py") executeCode("config_DoubleTauJet_2012B.py") executeCode("config_DoubleTauJet_2012Cv3.py")
def main(): argv = sys.argv[1:] argc = len(argv) if argc < 1: print ''' Usage: plot.py <sig-filename1> ... ''' sys.exit() print "=" * 80 os.system("mkdir -p figures") sigfilenames = argv sigfilenames.sort() bkgfilename = '../../ntuple_SM.root' BNNname = BNNNAME print 'BNN: %s' % BNNname print print 'signal file: %s' % sigfilenames print print 'background file: %s' % bkgfilename print "=" * 80 # compile bnn function gROOT.ProcessLine('.L %s.cpp' % BNNname) bnn = eval(BNNname) print "=" * 80 # --------------------------------------- # set up some standard graphics style # --------------------------------------- tdrstyle.setTDRStyle() gStyle.SetPadRightMargin(0.12) gStyle.SetOptStat('ei') gStyle.SetStatFont(42) gStyle.SetStatFontSize(0.03) gStyle.SetStatBorderSize(1) gStyle.SetStatH(0.2) gStyle.SetStatW(0.3) gStyle.SetStatX(0.83) gStyle.SetStatY(0.93) #change the CMS_lumi variables (see CMS_lumi.py) iPeriod = 4 iPos = 0 CMS_lumi.relPosX = 0.12 CMS_lumi.lumi_13TeV = "36.0 fb^{-1}" CMS_lumi.writeExtraText = 1 CMS_lumi.extraText = "Simulation" hfile = TFile("figures/h_%s.root" % BNNname, "RECREATE") hfile.cd() nbins = 100 kolors = [ kRed, kOrange, kYellow + 2, kGreen + 1, kBlue, kMagenta + 1, kCyan + 1 ] icolor = 0 h = [] # SIGNAL for ii, sigfilename in enumerate(sigfilenames): color = kolors[icolor] icolor += 1 if icolor >= len(kolors): icolor = 0 name = replace(nameonly(sigfilename), 'ntuple_', '') hs1 = TH1F(name, '', nbins, 0, 1) hs1.GetXaxis().SetTitle('D_{%s}' % name) hs1.Sumw2() # needed to handle weights correctly hs1.SetMinimum(1.e-6) hs1.GetXaxis().SetNdivisions(505) hs1.GetYaxis().SetNdivisions(505) hs1.SetFillColor(color) hs1.SetFillStyle(3001) h.append(hs1) # BACKGROUND mcolor = kMagenta + 1 hb1 = TH1F('hb1', '', nbins, 0, 1) hb1.GetXaxis().SetTitle('D_{bkg}') hb1.Sumw2() # needed to handle weights correctly hb1.SetMinimum(1.e-6) hb1.GetXaxis().SetNdivisions(505) hb1.GetYaxis().SetNdivisions(505) hb1.SetFillColor(mcolor) hb1.SetFillStyle(3003) h.append(hb1) # --------------------------------------------------------- # Fill # --------------------------------------------------------- cbnn1 = TCanvas("figures/f_%s_lin" % BNNname, BNNname, 10, 10, 500, 500) # plot for ii, sigfilename in enumerate(sigfilenames): name = h[ii].GetName() cbnn1.SetTitle(name) print name readAndFillHist(sigfilename, bnn, cbnn1, h[ii], 500) readAndFillHist(bkgfilename, bnn, cbnn1, hb1, 10000) icolor = 0 hroc = [] for ii, sigfilename in enumerate(sigfilenames): name = '%s_roc' % h[ii].GetName() color = kolors[icolor] icolor += 1 if icolor >= len(kolors): icolor = 0 hroc.append(mkroc(name, h[ii], h[-1], lcolor=color)) # --------------------------------------------------------- # Plot # --------------------------------------------------------- cbnn1.cd() h[0].SetMaximum(1.0) h[-1].SetMaximum(1.0) h[-1].Draw('hist') for hist in h: hist.Draw("histsame") cbnn1.Update() gSystem.ProcessEvents() cbnn1.SaveAs('.png') cbnn1log = TCanvas("figures/f_%s_log" % BNNname, BNNname, 520, 10, 500, 500) cbnn1log.cd() cbnn1log.SetLogy() h[-1].Draw('hist') for hist in h: hist.Draw("histsame") cbnn1log.Update() gSystem.ProcessEvents() cbnn1log.SaveAs('.png') croc = TCanvas("figures/f_%s_roc" % BNNname, BNNname, 1040, 10, 500, 500) croc.cd() hroc[0].Draw('al') for hist in hroc: hist.Draw("lsame") croc.Update() gSystem.ProcessEvents() croc.SaveAs('.png') sleep(5)
def main(): # ROOT.gROOT.SetBatch(True) sys.path.insert(0, "~/CMSstyle/") import tdrstyle tdrstyle.setTDRStyle() # ROOT.LoadMacro("~/bbH/atlasstyle-00-03-05/AtlasStyle.C") # SetAtlasStyle() gStyle.SetStatColor(0) gStyle.SetCanvasColor(0) gStyle.SetPadColor(0) gStyle.SetPadBorderMode(0) gStyle.SetCanvasBorderMode(0) gStyle.SetFrameBorderMode(0) # gStyle.SetOptStat(1110) gStyle.SetOptStat(0) gStyle.SetStatH(0.2) gStyle.SetStatW(0.2) gStyle.SetStatX(0.99) gStyle.SetTitleColor(1) gStyle.SetTitleFillColor(0) # gStyle.SetTitleY(1.) # gStyle.SetTitleX(.15) gStyle.SetTitleBorderSize(0) gStyle.SetPadTickX(1) gStyle.SetPadTickY(1) gStyle.SetPalette(1) # gStyle.SetMarkerStyle(20); # gStyle.SetMarkerSize(2); # gStyle.SetLineWidth(2); # gStyle.SetLineStyleString(2,"[12 12]"); # postscript dashes v_samples = ["7_4_6.patch1", "7_5_0.pre6"] prefix = "ExoVVAnalysis." directories = ["AK4_low", "AK4_high", "AK8_low", "AK8_high"] histNames = [ "Jet_pt", "Jet_eta", "Jet_m", "Jet_phi", "Jet_e", "Jet_muf", "Jet_phf", "Jet_emf", "Jet_nhf", "Jet_chf", "Jet_area", "Jet_cm", "Jet_nm", ] histNamesAK8 = [ "Jet_tau1", "Jet_tau2", "Jet_tau3", "Jet_tau21", "Jet_tau32", "Jet_tau31", "Jet_pruned_m", "Jet_softdrop_m", "Jet_pruned_Wwindow_m", "Jet_softdrop_Wwindow_m", ] _files = {} for sample in v_samples: inFile = "%s%s.root" % (prefix, sample) print "Opening " + inFile _files[sample] = TFile.Open(inFile, "READ") canvasList = [] for i in range(len(histNames)): for direct in directories: hists = {} for sample in v_samples: hist = _files[sample].Get("%s/%s" % (direct, histNames[i])) print "names: %s" % ("%s/%s" % (direct, histNames[i])) hists["%s_%s_%s" % (sample, direct, histNames[i])] = hist.Clone( "%s_%s_%s" % (sample, direct, histNames[i]) ) hist.Delete() # scale to unity hists["%s_%s_%s" % (sample, direct, histNames[i])].Scale( 1.0 / ( hists["%s_%s_%s" % (sample, direct, histNames[i])].Integral( 0, hists["%s_%s_%s" % (sample, direct, histNames[i])].GetNbinsX() + 1 ) ) ) MakeRatioPlot( hists["%s_%s_%s" % (v_samples[0], direct, histNames[i])], hists["%s_%s_%s" % (v_samples[1], direct, histNames[i])], "ratio_%s_%s" % (direct, histNames[i]), ) for sample in v_samples: hists["%s_%s_%s" % (sample, direct, histNames[i])].Delete() for i in range(len(histNamesAK8)): for direct in directories: if direct.find("AK8") >= 0: hists = {} for sample in v_samples: hist = _files[sample].Get("%s/%s" % (direct, histNamesAK8[i])) print "names: %s" % ("%s/%s" % (direct, histNamesAK8[i])) hists["%s_%s_%s" % (sample, direct, histNamesAK8[i])] = hist.Clone( "%s_%s_%s" % (sample, direct, histNamesAK8[i]) ) hist.Delete() # scale to unity hists["%s_%s_%s" % (sample, direct, histNamesAK8[i])].Scale( 1.0 / ( hists["%s_%s_%s" % (sample, direct, histNamesAK8[i])].Integral( 0, hists["%s_%s_%s" % (sample, direct, histNamesAK8[i])].GetNbinsX() + 1 ) ) ) canvasList.append( MakeRatioPlot( hists["%s_%s_%s" % (v_samples[0], direct, histNamesAK8[i])], hists["%s_%s_%s" % (v_samples[1], direct, histNamesAK8[i])], "ratio_%s_%s" % (direct, histNamesAK8[i]), ) ) for sample in v_samples: hists["%s_%s_%s" % (sample, direct, histNamesAK8[i])].Delete() # print "Filling summary canvas" # print canvasList # counter = 0 # for canvas in canvasList: # if (counter == 0): # canvas.Print("plots/all.pdf[") # elif (counter == len(canvasList)-1): # canvas.Print("plots/all.pdf]") # print "last" # else: # canvas.Print("plots/all.pdf") # counter += 1 c2 = TCanvas("empty", "empty", 500, 600) c2.Print("plots/all.pdf]")
def PlotOnCanvas(self, pdf_name): tdrstyle.setTDRStyle() # Canvas # canvas = TCanvas("c", "c", 600, 600) canvas.SetTopMargin(0.15) canvas.SetBottomMargin(0.15) canvas.SetRightMargin(0.05) canvas.SetLeftMargin(0.15) if self.title == '': canvas.SetTopMargin(0.05) if self.logx: canvas.SetLogx() if self.logy: canvas.SetLogy() self.list_obj[0].SetMinimum(10) # Norm # if self.norm: for obj in self.list_obj: if obj.Integral() != 0: obj.Scale(1. / obj.Integral()) # Axes # maxY = max([h.GetMaximum() for h in self.list_obj]) if self.logy: maxY *= 2 else: maxY *= 1.1 self.list_obj[0].SetMaximum(maxY) self.list_obj[0].GetXaxis().SetLabelSize(0.03) self.list_obj[0].GetXaxis().SetTitleSize(0.05) if len(self.xlabel) > 30: self.list_obj[0].GetXaxis().SetTitleSize(0.035) if len(self.xlabel) > 60: self.list_obj[0].GetXaxis().SetTitleSize(0.03) if "frac" in self.xlabel: self.list_obj[0].GetXaxis().SetTitleSize(0.03) self.list_obj[0].GetXaxis().SetTitleOffset(1.9) else: self.list_obj[0].GetXaxis().SetTitleOffset(1.6) self.list_obj[0].GetYaxis().SetTitleOffset(1.5) self.list_obj[0].GetYaxis().SetLabelSize(0.03) self.list_obj[0].GetYaxis().SetTitleSize(0.05) self.list_obj[0].GetYaxis().SetNdivisions(10) if len(self.ylabel) > 30: self.list_obj[0].GetYaxis().SetTitleSize(0.035) if len(self.ylabel) > 60: self.list_obj[0].GetYaxis().SetTitleSize(0.03) # Stacking # if self.stack: self.stack_hist = THStack( "hs", "" ) # Needs to be in self, otherwise destroyed at end of function opt = self.option for col, obj in zip(self.list_color, self.list_obj): obj.SetFillColor(col) obj.SetLineColor(col) self.stack_hist.Add(obj) obj.Draw(opt) if not "same" in opt: opt += " same" self.stack_hist.Draw(self.option + " same") maxY = self.stack_hist.GetMaximum() if self.logy: maxY *= 10 else: maxY *= 1.1 self.list_obj[0].SetMaximum(maxY) # Regular plotting else: opt = self.option for col, obj in zip(self.list_color, self.list_obj): obj.SetLineColor(col) obj.SetLineWidth(2) obj.Draw(opt) if not "same" in opt: opt += " same" # Legend # legend = TLegend(*self.legend_pos) for leg, obj in zip(self.list_legend, self.list_obj): legend.AddEntry(obj, leg, "f" if self.stack else "l") legend.SetBorderSize(0) legend.SetFillColor(0) legend.Draw() ROOT.SetOwnership(legend, 0) # Otherwise goes out of scope and not printed return canvas, self.filename
def main(): xtitle = \ '#font[12]{D}(#font[12]{m}_{4l}, '\ '#font[12]{D}^{bkg}_{kin})' MLPname = 'm4lmela' sigfilename = '../../ntuple_higgs.root' bkgfilename = '../../ntuple_bkg.root' # compile code code = open('%s.cc' % MLPname).read() gROOT.ProcessLine(code) mlp = m4lmela() # --------------------------------------- # set up some standard graphics style # --------------------------------------- tdrstyle.setTDRStyle() gStyle.SetPadRightMargin(0.12) gStyle.SetOptStat('ei') gStyle.SetStatFont(42) gStyle.SetStatFontSize(0.03) gStyle.SetStatBorderSize(1) gStyle.SetStatH(0.2) gStyle.SetStatW(0.3) gStyle.SetStatX(0.83) gStyle.SetStatY(0.93) #change the CMS_lumi variables (see CMS_lumi.py) iPeriod = 4 iPos = 0 CMS_lumi.relPosX = 0.12 CMS_lumi.lumi_13TeV = "30.0 fb^{-1}" CMS_lumi.writeExtraText = 1 CMS_lumi.extraText = "Simulation" msize = 0.15 # SIGNAL os.system('mkdir -p figures') c1 = TCanvas("figures/f_%s_lin" % MLPname, MLPname, 10, 10, 500, 500) mcolor = kCyan + 1 hs = TH1F('hs', '', 100, 0, 1) hs.GetXaxis().SetTitle(xtitle) hs.Sumw2() # needed to handle weights correctly hs.SetMinimum(0) hs.GetXaxis().SetNdivisions(505) hs.GetYaxis().SetNdivisions(505) hs.SetFillColor(mcolor) hs.SetFillStyle(3002) readAndFill(sigfilename, mlp, c1, hs) # BACKGROUND mcolor = kMagenta + 1 hb = TH1F('hb', '', 100, 0, 1) hb.GetXaxis().SetTitle(xtitle) hb.Sumw2() # needed to handle weights correctly hb.SetMinimum(0) hb.GetXaxis().SetNdivisions(505) hb.GetYaxis().SetNdivisions(505) hb.SetFillColor(mcolor) hb.SetFillStyle(3003) readAndFill(bkgfilename, mlp, c1, hb) # --------------------------------------------------------- # Plot # --------------------------------------------------------- k = int(1.05 * max(hb.GetMaximum(), hs.GetMaximum()) / 0.1) ymax = (k + 1) * 0.1 hb.SetMaximum(ymax) hs.SetMaximum(ymax) c1.cd() hs.Draw("hist") hb.Draw("hist same") c1.Update() gSystem.ProcessEvents() c1.SaveAs('.png') c2 = TCanvas("figures/f_%s_log" % MLPname, MLPname, 520, 10, 500, 500) c2.SetLogy() c2.cd() hs.Draw("hist") hb.Draw("hist same") gSystem.ProcessEvents() c2.Update() c2.SaveAs('.png') sleep(10)
def DrawPU(f, l1seed, key=None): df = f[(f.L1Seed == l1seed )] RetVar = None for i in range(0, len(pubins) -1): pumap[pubins[i]] = [] pumap[pubins[i]].append(df[np.logical_and(df.PileUp > pubins[i], df.PileUp <= pubins[i+1])].Fired.sum()) pumap[pubins[i]].append(df[np.logical_and(df.PileUp > pubins[i], df.PileUp <= pubins[i+1])].Total.sum()) # # No merging # PileUp = pd.unique(df.PileUp) # for i in PileUp: # pumap[i] = [] # pumap[i].append(df[df.PileUp == i].Fired.sum()) # pumap[i].append(df[df.PileUp == i].Total.sum()) x = [] y = [] yerr = [] for k, v in pumap.iteritems(): if v[1] != 0: x.append(k) if unit == "Hz": y.append(float(v[0])/v[1] * freq * nBunches ) yerr.append( math.sqrt(float(v[0]))/v[1] * freq * nBunches ) if unit == "kHz": y.append(float(v[0])/v[1] * freq * nBunches / 1000) yerr.append( math.sqrt(float(v[0]))/v[1] * freq * nBunches / 1000) ## Draw the plot graph = ROOT.TGraphErrors(len(x)) minx = min(x) maxx = 31 for i, (xx, yy, yee) in enumerate(zip(x, y, yerr)): graph.SetPoint(i, xx, yy) graph.SetPointError(i, 0, yee) c1 = ROOT.TCanvas("fd","Fdf", 600, 500) ROOT.gStyle.SetOptStat(000000000) tdrstyle.setTDRStyle() graph.Draw("AP") graph.SetTitle(l1seed) graph.GetXaxis().SetTitle("PileUp") graph.GetXaxis().SetLimits(0, 50) if unit == "Hz": graph.GetYaxis().SetTitle("Rate (nBunches = %d) [Hz]" % nBunches) if unit == "kHz": graph.GetYaxis().SetTitle("Rate (nBunches = %d) [kHz]" % nBunches) leg = ROOT.TLegend(0.7432886,0.1733615,0.9949664,0.3530655) leg.SetFillColor(0) leg.SetBorderSize(0) leg.SetBorderSize(0) leg.SetFillStyle(0) leg.SetTextFont(62) leg.AddEntry(graph, "Data", "p") ## Get Stage1 s1fun = GetStage1Fun(l1seed) if DrawStage1 and s1fun is not None: s1fun.SetLineColor(ROOT.kGreen+2) s1fun.SetLineWidth(2) s1fun.Draw("same") tex = ROOT.TLatex(0.19, 0.81, s1fun.GetName()) tex.SetNDC() tex.SetTextAlign(13) tex.SetTextFont(61) tex.SetTextSize(0.04) tex.SetTextColor(ROOT.kGreen+2) tex.SetLineWidth(2) tex.Draw() tex = ROOT.TLatex(0.19, 0.9, l1seed) tex.SetNDC() tex.SetTextAlign(13) tex.SetTextFont(61) tex.SetTextSize(0.05) tex.SetTextColor(ROOT.kBlack) tex.SetLineWidth(2) tex.Draw() ## Pol2 fitname = "pol2" graph.Fit("pol2", "QF", "", minx, maxx) f2 = graph.GetFunction(fitname).Clone() f2.SetLineColor(ROOT.kBlue) f2.SetLineWidth(2) fun = "f2 = %.2f + %.2f*x + %.3f*x^2" % (f2.GetParameter(0), f2.GetParameter(1), f2.GetParameter(2) ) RetVar = f2.GetParameter(2) tex = ROOT.TLatex(0.19, 0.75, fun) f2.Draw("same") tex.SetNDC() tex.SetTextAlign(13) tex.SetTextFont(61) tex.SetTextSize(0.04) tex.SetTextColor(ROOT.kBlue) tex.SetLineWidth(2) tex.Draw() ## Pol1 fitname = "pol1" graph.Fit("pol1", "QF", "", minx, maxx) f1 = graph.GetFunction(fitname) f1.SetLineColor(ROOT.kRed) f1.SetLineWidth(2) f1.Draw("same") # if l1seed == "L1APhysics": graph.GetYaxis().SetRangeUser(0, f1.Eval(50)) fun = "f1 = %.2f + %.2f*x " % (f1.GetParameter(0), f1.GetParameter(1)) tex = ROOT.TLatex(0.19, 0.69, fun) tex.SetNDC() tex.SetTextAlign(13) tex.SetTextFont(61) tex.SetTextSize(0.04) tex.SetTextColor(ROOT.kRed) tex.SetLineWidth(2) tex.Draw() if key is not None: tex = ROOT.TLatex(0.79, 0.89, key) tex.SetNDC() tex.SetTextFont(61) tex.SetTextSize(0.05) tex.SetTextColor(ROOT.kGreen+2) tex.SetLineWidth(2) tex.Draw() if mcdf is not None: DrawMCPoint(mcdf[ mcdf.L1Seed == l1seed], leg) c1.SetGridy() c1.SetGridx() leg.Draw() c1.Update() # c1.SaveAs("plots/PU_%s.root" % l1seed) if key is not None: c1.SaveAs("plots/PU_%s_%s.png" % (l1seed, key)) c1.SaveAs("plots/PU_%s_%s.root" % (l1seed, key)) else: c1.SaveAs("plots/PU_%s.png" % l1seed) c1.SaveAs("plots/PU_%s.root" % l1seed) # wait() return RetVar
ofile.write("Events after minDPhi cut : %.2f\n" %(h.GetBinContent(9)) ) if(h.GetBinContent(0)!=0):ofile.write("Selection efficiency : %.2f\n" %(h.GetBinContent(9)/h.GetBinContent(0)) ) elif(channel == "fullhadronic"): ofile.write("Events after minDPhi cut : %.2f\n" %(h.GetBinContent(7)) ) if(h.GetBinContent(0)!=0):ofile.write("Selection efficiency : %.2f\n" %(h.GetBinContent(7)/h.GetBinContent(0)) ) ROOT.gROOT.Reset(); ROOT.gROOT.SetStyle('Plain') ROOT.gStyle.SetPalette(1) ROOT.gStyle.SetOptStat(0) ROOT.gROOT.SetBatch() # don't pop up canvases ROOT.TH1.SetDefaultSumw2() ROOT.TH1.AddDirectory(False) tdrstyle.setTDRStyle(); settings = {} store = [] settings.update(plots.common_SR.settings) store += plots.common_SR.store if opt.channel == 'semileptonic': # Add semileptonic specific settings and plots to store settings.update(plots.semileptonic_SR.settings) store += plots.semileptonic_SR.store # Define sl output paths outhistos = 'output/sl/histos_SR' outpdfs = 'output/sl/pdfs_SR'
def plot(file, var='pt', rel=True): #just to avoid opening windows ROOT.gROOT.SetBatch() setTDRStyle() frame = ROOT.TH1F("frame","",100,15,50) frameEta = ROOT.TH1F("frameEta","",10,0.,2.5) frameVertex = ROOT.TH1F("frameVertex","",100,0.,50.) frame.GetXaxis().SetTitle("Offline Tau pT [GeV]") frameEta.GetXaxis().SetTitle("Offline Tau Eta ") frameVertex.GetXaxis().SetTitle("Offline # Vertices") frame.GetYaxis().SetTitle("Efficiency") frameEta.GetYaxis().SetTitle("Efficiency") frameVertex.GetYaxis().SetTitle("Efficiency") frame.SetMinimum(0.01) frame.SetMaximum(1.01) frameEta.SetMinimum(0.01) frameEta.SetMaximum(1.01) frameVertex.SetMinimum(0.01) frameVertex.SetMaximum(1.01) nHisto = 2 if var == 'eta': nHisto = 2 frame = frameEta if var == 'pt': nHisto = 4 if var == "vertex": nHisto = 6 frame = frameVertex #Eff plotting c1 = ROOT.TCanvas() c1.Divide(2,2) c1.cd(1) myhistos = histograms(file,"offlineSelectedTaus","hltPFTaus") myhistos[nHisto].Divide(myhistos[nHisto],myhistos[nHisto+1],1,1,"B") frame.DrawCopy() myhistos[nHisto].Draw("pE1same") c1.cd(2) frame.DrawCopy() myhistosLeadTrk = histograms(file,"offlineSelectedTaus","hltSelectedPFTausTrackFinding") if rel: myhistosLeadTrkRel = histograms(file,"offlineSelectedTaus","hltPFTaus") myhistosLeadTrk[nHisto].Divide(myhistosLeadTrk[nHisto],myhistosLeadTrkRel[nHisto],1,1,"B") else: myhistosLeadTrk[nHisto].Divide(myhistosLeadTrk[nHisto],myhistosLeadTrk[nHisto+1],1,1,"B") myhistosLeadTrk[nHisto].SetMarkerColor(2) myhistosLeadTrk[nHisto].Draw("pE1same") c1.cd(3) frame.DrawCopy() myhistosLeadTrkIso = histograms(file,"offlineSelectedTaus","hltSelectedPFTausTrackFindingLooseIsolation") if rel: myhistosLeadTrkIsoRel = histograms(file,"offlineSelectedTaus","hltSelectedPFTausTrackFinding") myhistosLeadTrkIso[nHisto].Divide(myhistosLeadTrkIso[nHisto],myhistosLeadTrkIsoRel[nHisto],1,1,"B") else: myhistosLeadTrkIso[nHisto].Divide(myhistosLeadTrkIso[nHisto],myhistosLeadTrkIso[nHisto+1],1,1,"B") myhistosLeadTrkIso[nHisto].SetMarkerColor(3) myhistosLeadTrkIso[nHisto].Draw("pe1same") c1.cd(4) # myhistosLeadTrkVertex = histograms(file,"offlineSelectedTaus","hltIsoMuPFTauVertexFinderRecoMuon") myhistosLeadTrkVertex = histograms(file,"offlineSelectedTaus","hltSelectedPFTausTrackFindingLooseIsolation") myhistosLeadTrkVertex[nHisto].Divide(myhistosLeadTrkVertex[nHisto],myhistosLeadTrkVertex[nHisto+1],1,1,"B") myhistosLeadTrkVertex[nHisto].SetMarkerColor(4) frame.DrawCopy() myhistosLeadTrkVertex[nHisto].Draw("pe1same") c1.SaveAs("eff_"+var+".png")
def main(): gSystem.AddDynamicPath('%s/Projects/turtle/lib' % os.environ['HOME']) gSystem.Load("libturtle") files = vector('string')(1, 'bkg.root') names = vector('string')(1, 'f_D') nbins = 25 turtle = Turtle(files, names, 'HZZ4LeptonsAnalysisReduced', nbins) MLPname = 'm4lmelamet' datfilename = 'ntuple_data.root' bkgfilename = ['ntuple_bkg.root', 'ntuple_higgs.root'] # compile code code = open('%s.cpp' % MLPname).read() gROOT.ProcessLine(code) mlp = eval(MLPname) data, wdata = read(datfilename, mlp) print bkg, wbkg = read(bkgfilename, mlp) total = sum(wdata) btotal = sum(wbkg) scale = total / btotal print 'data count: %9.0f' % total print 'bkg count: %10.1f' % btotal print "\nbinning data..." point = vector('double')(1) for D in data: point[0] = D turtle.Fill(point) count = turtle.GetBinContents() print "\nbinning background..." turtle.Reset() for ii, D in enumerate(bkg): point[0] = D w = wbkg[ii] * scale turtle.Fill(point, w) bcount = turtle.GetBinContents() v = [] for ii, c in enumerate(count): x = turtle.GetBinCenter(ii)[0] w = turtle.GetBinWidth(ii)[0] b = bcount[ii] v.append((x, w, b, c)) v.sort() out = open('data_MC.txt', 'w') record = '%3s %10s\t%10s %10s' % ('bin', 'boundary', 'pred', 'data') print record out.write('%s\n' % record) from array import array ibins = array('d') jj = 0 bnd = 0.0 ibins.append(0) for ii, (x, w, b, c) in enumerate(v): bnd += w record = '%3d %10.6f\t%10.2f %10.1f' % (ii, bnd, b, c) print record out.write('%s\n' % record) ibins.append(bnd) out.close() #------------------------------------------------------------------ # plot #------------------------------------------------------------------ xtitle = \ '#font[12]{D}(#font[12]{m}_{4l}, '\ '#font[12]{D}^{bkg}_{kin}, ' \ '#font[12]{E}_{T}^{miss})' MLPname = 'm4lmelamet' bkgfilename = ['ntuple_bkg.root', 'ntuple_higgs.root'] datfilename = 'ntuple_data.root' # --------------------------------------- # set up some standard graphics style # --------------------------------------- tdrstyle.setTDRStyle() gStyle.SetPadRightMargin(0.12) gStyle.SetOptStat('ei') gStyle.SetStatFont(42) gStyle.SetStatFontSize(0.03) gStyle.SetStatBorderSize(1) gStyle.SetStatH(0.2) gStyle.SetStatW(0.3) gStyle.SetStatX(0.83) gStyle.SetStatY(0.93) #change the CMS_lumi variables (see CMS_lumi.py) iPeriod = 4 iPos = 0 CMS_lumi.relPosX = 0.12 CMS_lumi.lumi_13TeV = "30.0 fb^{-1}" CMS_lumi.writeExtraText = 1 CMS_lumi.extraText = "Simulation" nbins = len(ibins) - 1 # DATA mcolor = kBlack hd = TH1F('hd', '', nbins, ibins) hd.GetXaxis().SetTitle(xtitle) hd.Sumw2() # needed to handle weights correctly hd.GetXaxis().SetNdivisions(505) hd.GetYaxis().SetNdivisions(505) hd.SetMarkerColor(mcolor) hd.SetMarkerStyle(20) hd.SetLineColor(mcolor) hd.SetLineWidth(2) # BACKGROUND mcolor = kMagenta + 1 hb = TH1F('hb', '', nbins, ibins) hb.GetXaxis().SetTitle(xtitle) hb.Sumw2() # needed to handle weights correctly hb.GetXaxis().SetNdivisions(505) hb.GetYaxis().SetNdivisions(505) hb.SetFillColor(mcolor) hb.SetFillStyle(3003) hb.SetLineWidth(2) print "\nbinning data..." point = vector('double')(1) for D in data: hd.Fill(D) print "binning background..." for ii, D in enumerate(bkg): hb.Fill(D, wbkg[ii]) c1 = TCanvas("figures/f_data_MC", 'data vs MC', 10, 10, 500, 500) c1.cd() c1.SetLogx() hb.Scale(hd.Integral() / hb.Integral()) hb.SetMaximum(1.3 * hd.GetMaximum()) hb.Draw("hist") hd.Draw("ep same") CMS_lumi.CMS_lumi(c1, iPeriod, iPos) c1.Update() gSystem.ProcessEvents() c1.SaveAs('.png') sleep(10)
def main(): # --------------------------------------- # set up some standard graphics style # --------------------------------------- tdrstyle.setTDRStyle() gStyle.SetPadRightMargin(0.12) #change the CMS_lumi variables (see CMS_lumi.py) iPeriod = 4 iPos = 0 CMS_lumi.relPosX = 0.12 CMS_lumi.lumi_13TeV = "30 fb^{-1}" CMS_lumi.writeExtraText = 1 CMS_lumi.extraText = "Simulation" tfile = [] hbnn = [] hmet = [] hpt4l = [] colorbase = 39 for filename in FILES: source = getsrc.findall(filename)[0] print source f = TFile(filename); if not f.IsOpen(): sys.exit("can't open %s" % filename) # get BNN histogram hbnn.append(f.Get('hbnn').Clone('hbnn_%s' % source)) # get signal region (SR) missing-ET (MET) hmet.append(f.Get('hpfmets').Clone('hmet_%s' % source)) hpt4l.append(f.Get('hpt4ls').Clone('hpt4l_%s' % source)) tfile.append(f) colorbase += 1 plotname = 'fig_%s_met' % source cmet = TCanvas(plotname, plotname, 10, 10, 500, 500) cmet.cd() hmet[-1].SetFillColor(colorbase) hmet[-1].SetFillStyle(3001) hmet[-1].Draw('hist') if source == 'data': hmet[-1].SetMarkerColor(kBlack) hmet[-1].Draw('epsame') CMS_lumi.CMS_lumi(cmet, iPeriod, iPos) cmet.Update() gSystem.ProcessEvents() cmet.SaveAs('.png') plotname = 'fig_%s_pt4l' % source cpt4l = TCanvas(plotname, plotname, 520, 10, 500, 500) cpt4l.cd() hpt4l[-1].SetFillColor(colorbase) hpt4l[-1].SetFillStyle(3001) hpt4l[-1].Draw('hist') if source == 'data': hpt4l[-1].SetMarkerColor(kBlack) hpt4l[-1].Draw('epsame') CMS_lumi.CMS_lumi(cpt4l, iPeriod, iPos) cpt4l.Update() gSystem.ProcessEvents() cpt4l.SaveAs('.png') plotname = 'fig_%s_bnn' % source cbnn = TCanvas(plotname, plotname, 520, 510, 500, 500) cbnn.cd() hbnn[-1].SetFillColor(colorbase) hbnn[-1].SetFillStyle(3001) hbnn[-1].Draw('hist') if source == 'data': hbnn[-1].SetMarkerColor(kBlack) hbnn[-1].Draw('epsame') CMS_lumi.CMS_lumi(cbnn, iPeriod, iPos) cbnn.Update() gSystem.ProcessEvents() cbnn.SaveAs('.png') sleep(5)
def BDT_output(): tdrstyle.setTDRStyle() iPeriod = 4 iPos = 11 CMS_lumi.lumiTextSize = 0.9 CMS_lumi.cmsTextSize = 1. CMS_lumi.lumi_13TeV = "137 fb^{-1}" f_Data = TFile( "../histos/latest_production/mergedYearsSelection/WPiGammaHistos_Data_201620172018.root" ) if isMuon: f = TFile("outputs/Nominal_training_mu_firstPart.root") f1 = TFile("outputs/Nominal_training_mu_secondPart.root") h_BDT_data = f_Data.Get("h_BDT_out_mu") else: f = TFile("outputs/Nominal_training_ele_firstPart.root") f1 = TFile("outputs/Nominal_training_ele_secondPart.root") h_BDT_data = f_Data.Get("h_BDT_out_ele") h_BDT_sig = f.Get("default/Method_BDT/BDT/MVA_BDT_Train_S") h_BDT_bkg = f.Get("default/Method_BDT/BDT/MVA_BDT_Train_B") h_BDT_Train_sig = f1.Get("default/Method_BDT/BDT/MVA_BDT_S") h_BDT_Train_bkg = f1.Get("default/Method_BDT/BDT/MVA_BDT_B") data_normalization = h_BDT_bkg.Integral() / h_BDT_data.Integral() #print data_normalization h_BDT_data.Scale(data_normalization) leg1 = TLegend(0.40, 0.62, 0.65, 0.87) leg1.SetHeader("") leg1.SetFillColor(0) leg1.SetBorderSize(0) leg1.SetLineColor(1) leg1.SetLineStyle(1) leg1.SetLineWidth(1) leg1.SetFillStyle(0) leg1.AddEntry(h_BDT_sig, "Signal", "f") leg1.AddEntry(h_BDT_bkg, "Background", "f") #leg1.AddEntry(h_BDT_data,"Data","ep") channel_text = TPaveText(0.30, 0.84, 0.65, 0.86, "NB,NDC") if isMuon: channel_text.AddText("#mu channel") arrow_SR = TArrow( 0.292, 2.6, 0.59, 2.6, 0.02, "<|>" ) #The starting point in x should be 0.285, but then the two arrows overlap arrow_CR = TArrow(0.216, 2.6, 0.285, 2.6, 0.02, "<|>") SR_text = TPaveText(0.412, 2.75, 0.454, 2.77, "NB") CR_text = TPaveText(0.230, 2.75, 0.272, 2.77, "NB") else: channel_text.AddText("e channel") arrow_SR = TArrow( 0.284, 2.6, 0.6, 2.6, 0.02, "<|>" ) #The starting point in x should be 0.277, but then the two arrows overlap arrow_CR = TArrow(0.212, 2.6, 0.277, 2.6, 0.02, "<|>") SR_text = TPaveText(0.424, 2.75, 0.466, 2.77, "NB") CR_text = TPaveText(0.223, 2.75, 0.265, 2.77, "NB") channel_text.SetTextSize(0.04) channel_text.SetFillColor(0) channel_text.SetFillStyle(0) channel_text.SetLineColor(0) SR_text.AddText("SR") CR_text.AddText("CR") arrow_SR.SetLineColor(8) arrow_SR.SetLineWidth(2) arrow_SR.SetFillColor(8) arrow_CR.SetLineColor(kOrange + 7) arrow_CR.SetLineWidth(2) arrow_CR.SetFillColor(kOrange + 7) SR_text.SetTextSize(0.04) SR_text.SetFillColor(0) SR_text.SetFillStyle(0) SR_text.SetLineColor(0) SR_text.SetTextColor(8) CR_text.SetTextSize(0.04) CR_text.SetFillColor(0) CR_text.SetFillStyle(0) CR_text.SetLineColor(0) CR_text.SetTextColor(kOrange + 7) gStyle.SetErrorX(0.) gStyle.SetOptStat(0) canvas1 = TCanvas() h_BDT_sig.SetTitle("") h_BDT_sig.GetXaxis().SetTitle("BDT discriminant") h_BDT_sig.GetXaxis().SetTitleSize(0.055) h_BDT_sig.GetYaxis().SetTitle("Arbitrary units") h_BDT_sig.GetYaxis().SetTitleSize(0.055) h_BDT_bkg.SetTitle("") h_BDT_data.SetTitle("") h_BDT_sig.SetFillColor(38) h_BDT_sig.SetFillStyle(3002) #h_BDT_sig.SetLineColor(1) h_BDT_bkg.SetFillColor(2) h_BDT_bkg.SetLineColor(2) h_BDT_bkg.SetFillStyle(3002) h_BDT_data.SetMarkerStyle(20) h_BDT_sig.Draw("E1, hist") h_BDT_bkg.Draw("SAME, E1, hist") #h_BDT_data.Draw("SAME, lep") h_BDT_Train_sig.SetLineColor(8) h_BDT_Train_sig.SetMarkerColor(8) h_BDT_Train_sig.SetMarkerStyle(21) h_BDT_Train_bkg.SetLineColor(9) h_BDT_Train_bkg.SetMarkerColor(9) h_BDT_Train_bkg.SetMarkerStyle(21) h_BDT_Train_sig.Draw("SAME, lep") h_BDT_Train_bkg.Draw("SAME, lep") h_BDT_sig.SetMaximum(4.5) leg1.Draw("SAME") channel_text.Draw("SAME") #SR_text.Draw("SAME") #CR_text.Draw("SAME") #arrow_SR.Draw() #arrow_CR.Draw() CMS_lumi.CMS_lumi(canvas1, iPeriod, iPos) if isMuon: canvas1.Print("plots/BDT_output_mu.pdf") else: canvas1.Print("plots/BDT_output_ele.pdf") raw_input()
def Draw(self): ROOT.gErrorIgnoreLevel = ROOT.kFatal tdrstyle.setTDRStyle() ROOT.TH1.AddDirectory(False) for Region in self.RegionsToDraw: print '## Drawing ' + Region.Name ## Read binning data Rebins, XaxisRanges = self.ReadBinningInfo(Region.Name) ## Input/Output directotry Indir = self.InputDirectory Outdir = self.OutputDirectory + '/' + Region.Name + '/' if self.ScaleMC: Outdir = self.OutputDirectory + '/ScaleMC/' + Region.Name + '/' print '## Outputs => ' + Outdir os.system('mkdir -p ' + Outdir) ## Data file f_Data = ROOT.TFile(Indir + '/' + self.DataDirectory + '/' + self.Filename_prefix + self.Filename_skim + '_data_' + Region.PrimaryDataset + self.Filename_suffix + '.root') ## Loop over variables for Variable in self.VariablesToDraw: ## BinInfo nRebin = Rebins[Variable.Name] xMin = XaxisRanges[Variable.Name][0] xMax = XaxisRanges[Variable.Name][1] yMax = -999 if self.DoDebug: print '[DEBUG] Trying to draw variable = ' + Variable.Name print '[DEBUG] (xMin,xMax) = (%s,%s)' % (xMin, xMax) ## xtitle xtitle = Variable.TLatexAlias if Variable.Name == "WRCand_Mass": if "Resolved" in Region.Name: xtitle = "m_{lljj} (GeV)" else: xtitle = "m_{lJ} (GeV)" ## Save hists ## For legend later.. HistsToDraw = dict() ## Get data first if self.DoDebug: print '[DEBUG] Trying to get data histogram..' h_Data = f_Data.Get(Region.Name + '/' + Variable.Name + '_' + Region.Name) if not h_Data: print Variable.Name + '_' + Region.Name + '.pdf ==> No data, skipped' continue ## Make overflow h_Data.GetXaxis().SetRangeUser(xMin, xMax) h_Data = mylib.MakeOverflowBin(h_Data) ## Rebin h_Data = self.Rebin(h_Data, Region.Name, Variable.Name, nRebin) ## Copy data axis dataAxis = h_Data.GetXaxis() nBin = dataAxis.GetNbins() xBins = [dataAxis.GetBinLowEdge(1)] for ix in range(0, nBin): xBins.append(dataAxis.GetBinUpEdge(ix + 1)) xBins = array("d", xBins) ### Att data histogram h_Data.SetMarkerStyle(20) h_Data.SetMarkerSize(1.2) h_Data.SetMarkerColor(ROOT.kBlack) h_Data.SetLineColor(ROOT.kBlack) if self.DoDebug: print '[DEBUG] data histogram finished' ## Loop over samples ## For Legend, save HistsForLegend = [] AliasForLegend = [] ## Prevent double-counting stack_Bkgd = ROOT.THStack("stack_Bkgd", "") h_Bkgd = 0 ## Save systematic SystematicUps = dict() SystematicDowns = dict() ## If we take errors fro shapes h_TotalBackgroundFromShape = 0 ## Loop over systematics for Syst in self.Systematics: if self.DoDebug: print '[DEBUG] Trying to make histogram for Syst = ', Syst.Print() h_Bkgd_ForSyst = 0 dirName = Region.Name if Syst.Name != "Central": if Syst.Direction > 0: dirName = "Syst_" + Syst.Name + "Up_" + Region.Name else: dirName = "Syst_" + Syst.Name + "Down_" + Region.Name for SampleGroup in self.SampleGroups: Color = SampleGroup.Color LegendAdded = False for Sample in SampleGroup.Samples: if self.DoDebug: print '[DEBUG] Trying to make histogram for Sample = ' + Sample f_Sample = ROOT.TFile(Indir + '/' + str(SampleGroup.Year) + '/' + self.Filename_prefix + self.Filename_skim + '_' + Sample + self.Filename_suffix + '.root') h_Sample = 0 ## Uncorrelated sources has Syst.Year = 2016 or 2017 or 2018 ## For this cases, SampleGroup.Year should be matched if (Syst.Year > 0) and (Syst.Year != SampleGroup.Year): tmp_dirName = Region.Name h_Sample = f_Sample.Get(tmp_dirName + '/' + Variable.Name + '_' + tmp_dirName) ## Exception control ## 1) ZPtRw only for the samples with "Reweighted" ## if other samples, we just call nominal shape elif (Syst.Name == "ZPtRw") and ("Reweighted" not in Sample): tmp_dirName = Region.Name h_Sample = f_Sample.Get(tmp_dirName + '/' + Variable.Name + '_' + tmp_dirName) ## 2) Lumi, DYNorm ## Use centralm and scale them later elif (Syst.Name in ["Lumi", "DYNorm"]): tmp_dirName = Region.Name h_Sample = f_Sample.Get(tmp_dirName + '/' + Variable.Name + '_' + tmp_dirName) ## For all other cases else: h_Sample = f_Sample.Get(dirName + '/' + Variable.Name + '_' + dirName) if not h_Sample: #print 'No hist : %s %s'%(Syst.Name,Sample) continue ## Make overflow h_Sample.GetXaxis().SetRangeUser(xMin, xMax) h_Sample = mylib.MakeOverflowBin(h_Sample) h_Sample = self.Rebin(h_Sample, Region.Name, Variable.Name, nRebin) h_Sample.SetLineColor(Color) h_Sample.SetLineWidth(1) h_Sample.SetFillColor(Color) ## Scale MCSF, MCSFerr = 1., 0. if self.ScaleMC: ## now, only for DY if "DYJets" in Sample: MCSF, MCSFerr = mylib.GetDYNormSF( SampleGroup.Year, Region.Name) h_Sample.Scale(MCSF) ## Manual systematic ## 1) [Lumi] Uncorrelated if (Syst.Name == "Lumi") and (Syst.Year == SampleGroup.Year): lumierr = mylib.LumiError(SampleGroup.Year) for ix in range( 0, h_Sample.GetXaxis().GetNbins()): y = h_Sample.GetBinContent(ix + 1) y_new = y + y * float( Syst.Direction) * lumierr h_Sample.SetBinContent(ix + 1, y_new) ## 2) [DYNorm] Correlated, only for DY if (Syst.Name == "DYNorm") and ("DYJets" in Sample): for ix in range( 0, h_Sample.GetXaxis().GetNbins()): y = h_Sample.GetBinContent( ix + 1) ## already scaled by MCSF y_new = y * (MCSF + float(Syst.Direction) * MCSFerr) / MCSF h_Sample.SetBinContent(ix + 1, y_new) ## AddError option AddErrorOption = '' if self.AddErrorLinear: AddErrorOption = 'L' ## If central, add to h_Bkgd if Syst.Name == "Central" and Sample == 'total_background': if not h_TotalBackgroundFromShape: h_TotalBackgroundFromShape = h_Sample.Clone( ) else: h_TotalBackgroundFromShape = mylib.AddHistograms( h_TotalBackgroundFromShape, h_Sample, AddErrorOption) HistsToDraw[Sample] = h_Sample.Clone() elif Syst.Name == "Central": stack_Bkgd.Add(h_Sample) if not h_Bkgd: h_Bkgd = h_Sample.Clone() else: h_Bkgd = mylib.AddHistograms( h_Bkgd, h_Sample, AddErrorOption) HistsToDraw[Sample] = h_Sample.Clone() if (not LegendAdded) and ( SampleGroup.TLatexAlias not in AliasForLegend): HistsForLegend.append([ HistsToDraw[Sample], SampleGroup.TLatexAlias ]) AliasForLegend.append( SampleGroup.TLatexAlias) LegendAdded = True ## else (i.e., systematic), add to h_Bkgd_ForSyst else: if not h_Bkgd_ForSyst: h_Bkgd_ForSyst = h_Sample.Clone() else: h_Bkgd_ForSyst = mylib.AddHistograms( h_Bkgd_ForSyst, h_Sample, AddErrorOption) ## Close file f_Sample.Close() ##==>End Sample loop ##==>End SampleGroup loop if Syst.Name != "Central": if Syst.Direction > 0: SystematicUps[Syst.FullName()] = h_Bkgd_ForSyst else: SystematicDowns[Syst.FullName()] = h_Bkgd_ForSyst ##==>End Syst loop #print SystematicUps #print SystematicDowns ## Syst Up/Down . Max/Min h_Bkgd_TotErr_Max = h_Bkgd.Clone() h_Bkgd_TotErr_Min = h_Bkgd.Clone() for SystKey in SystematicUps: #print 'SystKey = '+SystKey h_Up = SystematicUps[SystKey] h_Down = SystematicDowns[SystKey] for ix in range(0, h_Bkgd.GetXaxis().GetNbins()): x_l = h_Bkgd.GetXaxis().GetBinLowEdge(ix + 1) x_r = h_Bkgd.GetXaxis().GetBinUpEdge(ix + 1) y_Central = h_Bkgd.GetBinContent(ix + 1) y_Up = h_Up.GetBinContent(ix + 1) y_Down = h_Down.GetBinContent(ix + 1) ## -. y_Max = max(max(y_Central, y_Up), y_Down) y_Min = min(min(y_Central, y_Up), y_Down) #print '[%d,%d] : %f, (Max,Min) = (%f,%f)'%(x_l,x_r,y_Central,y_Up,y_Down) ## Update Max err_Max_Current = h_Bkgd_TotErr_Max.GetBinError(ix + 1) err_Max_ToAdd = y_Max - y_Central err_Max_Updated = math.sqrt( err_Max_Current * err_Max_Current + err_Max_ToAdd * err_Max_ToAdd) h_Bkgd_TotErr_Max.SetBinError(ix + 1, err_Max_Updated) ## Update Min err_Min_Current = h_Bkgd_TotErr_Min.GetBinError(ix + 1) err_Min_ToAdd = y_Central - y_Min err_Min_Updated = math.sqrt( err_Min_Current * err_Min_Current + err_Min_ToAdd * err_Min_ToAdd) h_Bkgd_TotErr_Min.SetBinError(ix + 1, err_Min_Updated) ##==>End Systematic loop ## Blind mode if not Region.UnblindData: h_Data = h_Bkgd.Clone(h_Data.GetName()) h_Data.SetMarkerStyle(20) h_Data.SetMarkerSize(1.2) h_Data.SetMarkerColor(ROOT.kBlack) h_Data.SetLineColor(ROOT.kBlack) ## hist => gr gr_Bkgd_TotErr = mylib.GetAsymmError(h_Bkgd_TotErr_Max, h_Bkgd_TotErr_Min) gr_Data = ROOT.TGraphAsymmErrors(h_Data) ## Error from shape if self.ErrorFromShape: if self.DoDebug: print 'Total background :' for z in range( 0, h_TotalBackgroundFromShape.GetXaxis().GetNbins( )): x_l = h_TotalBackgroundFromShape.GetXaxis( ).GetBinLowEdge(z + 1) x_r = h_TotalBackgroundFromShape.GetXaxis( ).GetBinUpEdge(z + 1) y = h_TotalBackgroundFromShape.GetBinContent(z + 1) print '[%f,%f] : %f' % (x_l, x_r, y) gr_Bkgd_TotErr = ROOT.TGraphAsymmErrors( h_TotalBackgroundFromShape) err_up_tmp = [] err_down_tmp = [] alpha = 1. - 0.6827 for i in range(0, gr_Data.GetN()): N = gr_Data.GetY()[i] L = 0. if (N == 0.) else (ROOT.Math.gamma_quantile( alpha / 2., N, 1.)) U = (ROOT.Math.gamma_quantile_c( alpha, N + 1, 1)) if (N == 0.) else (ROOT.Math.gamma_quantile_c( alpha / 2., N + 1., 1.)) if N != 0: gr_Data.SetPointEYlow(i, N - L) gr_Data.SetPointEYhigh(i, U - N) err_down_tmp.append(N - L) err_up_tmp.append(U - N) if Variable.Name != "WRCand_Mass": gr_Data.SetPointEXlow(i, 0) gr_Data.SetPointEXhigh(i, 0) else: zerodata_err_low = 0.1 zerodata_err_high = 1.8 xlow = gr_Data.GetX()[i] - gr_Data.GetEXlow()[i] xhigh = gr_Data.GetX()[i] + gr_Data.GetEXhigh()[i] if self.ZeroDataCheckCut(Variable.Name, xlow, xhigh): zerodata_err_low = 0. zerodata_err_high = 0. gr_Data.SetPointEYlow(i, zerodata_err_low) gr_Data.SetPointEYhigh(i, zerodata_err_high) err_down_tmp.append(zerodata_err_low) err_up_tmp.append(zerodata_err_high) if Variable.Name != "WRCand_Mass": gr_Data.SetPointEXlow(i, 0) gr_Data.SetPointEXhigh(i, 0) ## Legend lg = 0 ## No signal if len(self.SignalsToDraw) == 0: lg = ROOT.TLegend(0.55, 0.45, 0.92, 0.90) ## With Signal else: if Region.DrawRatio: lg = ROOT.TLegend(0.55, 0.46, 0.92, 0.90) else: lg = ROOT.TLegend(0.50, 0.56, 0.92, 0.90) lg.SetBorderSize(0) lg.SetFillStyle(0) lg.AddEntry(gr_Bkgd_TotErr, "Stat.+syst. uncert.", "f") ## dummy graph for legend.. ## this is because h_Data does not have horizontal error bars, ## and gr_data does not have points gr_Data_dummy = ROOT.TGraphAsymmErrors(gr_Data) gr_Data_dummy.SetMarkerStyle(20) gr_Data_dummy.SetMarkerSize(1.2) dataLegendGOption = "ep" if Variable.Name == "WRCand_Mass": dataLegendGOption = "lpe" if Region.DrawData: if Region.UnblindData: lg.AddEntry(gr_Data_dummy, "Data", dataLegendGOption) else: lg.AddEntry(gr_Data_dummy, "Total background", dataLegendGOption) for i_lg in range(0, len(HistsForLegend)): h_lg = HistsForLegend[len(HistsForLegend) - 1 - i_lg][0] tlatexaliax = HistsForLegend[len(HistsForLegend) - 1 - i_lg][1] lg.AddEntry(h_lg, tlatexaliax, "f") ## Prepare canvas if self.DoDebug: print '[DEBUG] Preparing canvas..' c1 = ROOT.TCanvas('c1', '', 800, 800) c1_up = ROOT.TPad("c1_up", "", 0, 0.25, 1, 1) c1_down = ROOT.TPad("c1_down", "", 0, 0, 1, 0.25) if Region.DrawRatio: c1, c1_up, c1_down = canvas_margin.canvas_margin( c1, c1_up, c1_down) c1.Draw() c1_up.Draw() c1_down.Draw() c1_up.cd() if Region.Logy > 0: c1_up.SetLogy(True) else: c1_up = ROOT.TPad("c1_up", "", 0, 0, 1, 1) c1_up.SetTopMargin(0.052) c1_up.SetBottomMargin(0.13) c1_up.SetRightMargin(0.032) c1_up.SetLeftMargin(0.15) c1.Draw() c1_up.Draw() c1_up.cd() if Region.Logy > 0: c1_up.SetLogy(True) c1.cd() latex_CMSPriliminary = ROOT.TLatex() latex_Lumi = ROOT.TLatex() latex_CMSPriliminary.SetNDC() latex_Lumi.SetNDC() latex_CMSPriliminary.SetTextSize(0.035) latex_CMSPriliminary.DrawLatex( 0.15, 0.96, "#font[62]{CMS} #font[42]{#it{#scale[0.8]{Preliminary}}}") latex_Lumi.SetTextSize(0.035) latex_Lumi.SetTextFont(42) latex_Lumi.DrawLatex( 0.73, 0.96, mylib.TotalLumi(float(self.DataYear)) + " fb^{-1} (13 TeV)") #### axis histograms h_dummy_up = ROOT.TH1D('h_dumy_up', '', nBin, xBins) h_dummy_up.GetXaxis().SetRangeUser(xMin, xMax) if nRebin > 0: binsize = h_dummy_up.GetXaxis().GetBinUpEdge( 1) - h_dummy_up.GetXaxis().GetBinLowEdge(1) str_binsize = '%d' % (binsize) if binsize != int(binsize): str_binsize = '%1.2f' % (binsize) h_dummy_up.GetYaxis().SetTitle('Events / ' + str_binsize + ' ' + Variable.Unit) else: h_dummy_up.GetYaxis().SetTitle('Events / bin') if Variable.Name == 'WRCand_Mass': h_dummy_up.GetYaxis().SetTitle('Events / bin') h_dummy_down = ROOT.TH1D('h_dumy_down', '', nBin, xBins) h_dummy_down.GetYaxis().SetRangeUser(0., 2.0) if (self.ErrorFromShape): if ('DYCR' in Region.Name) and ('PostFit' in self.OutputDirectory): h_dummy_down.GetYaxis().SetRangeUser(0.89, 1.11) else: h_dummy_down.GetYaxis().SetRangeUser(0., 3.4) h_dummy_down.SetNdivisions(504, "Y") h_dummy_down.GetXaxis().SetRangeUser(xMin, xMax) h_dummy_down.GetXaxis().SetTitle(xtitle) h_dummy_down.GetYaxis().SetTitle("#frac{Data}{Sim.}") h_dummy_down.SetFillColor(0) h_dummy_down.SetMarkerSize(0) h_dummy_down.SetMarkerStyle(0) h_dummy_down.SetLineColor(ROOT.kWhite) if Region.DrawRatio: h_dummy_up, h_dummy_down = canvas_margin.hist_axis( h_dummy_up, h_dummy_down) else: h_dummy_up.SetTitle("") h_dummy_up.GetYaxis().SetLabelSize(0.04) h_dummy_up.GetYaxis().SetTitleSize(0.054) h_dummy_up.GetYaxis().SetTitleOffset(1.30) h_dummy_up.GetXaxis().SetLabelSize(0.035) h_dummy_up.GetXaxis().SetTitleSize(0.055) h_dummy_up.GetXaxis().SetTitle(xtitle) ## Get Y maximum yMax = max(yMax, mylib.GetMaximum(gr_Data)) yMax = max(yMax, mylib.GetMaximum(gr_Bkgd_TotErr)) ## Yaxis range yMin = 0. yMaxScale = 1.2 if Region.Logy > 0: yMaxScale = 10 yMin = Region.Logy h_dummy_up.GetYaxis().SetRangeUser(yMin, yMaxScale * yMax) ## Exception control if (Variable.Name == "WRCand_Mass") and ( "_SR" in Region.Name) and ("EMu" not in Region.Name): if ("Resolved" in Region.Name): h_dummy_up.GetYaxis().SetRangeUser( 1E-1, yMaxScale * yMax) else: h_dummy_up.GetYaxis().SetRangeUser(1, yMaxScale * yMax) if (Variable.Name == "ZCand_Mass" or Variable.Name == "DiJet_Mass") and ("_DYCR" in Region.Name): h_dummy_up.GetYaxis().SetRangeUser(10, 2E8) if (Variable.Name == "ZCand_Pt" or Variable.Name == "DiJet_Pt") and ("_DYCR" in Region.Name): if ("Resolved" in Region.Name): h_dummy_up.GetYaxis().SetRangeUser(10, 5E6) else: h_dummy_up.GetYaxis().SetRangeUser(10, 2E5) if self.DoDebug: print '[DEBUG] Canvas is ready' ## Draw up c1_up.cd() h_dummy_up.Draw("histsame") stack_Bkgd.Draw("histsame") gr_Bkgd_TotErr.SetMarkerColor(0) gr_Bkgd_TotErr.SetMarkerSize(0) gr_Bkgd_TotErr.SetFillStyle(3013) gr_Bkgd_TotErr.SetFillColor(ROOT.kBlack) gr_Bkgd_TotErr.SetLineColor(0) gr_Bkgd_TotErr.Draw("sameE2") gr_Data.SetLineWidth(2) gr_Data.SetMarkerSize(0.) gr_Data.SetMarkerColor(ROOT.kBlack) gr_Data.SetLineColor(ROOT.kBlack) if Region.DrawData: h_Data.Draw("phistsame") gr_Data.Draw("p0same") ## Signal LeptonChannel = "EE" if ("Electron" in Region.Name) else "MuMu" h_Sigs = [] for Sig in self.SignalsToDraw: f_Sig = ROOT.TFile(Indir + '/' + self.DataDirectory + '/Signal_' + LeptonChannel + '/' + self.Filename_prefix + '_WRtoNLtoLLJJ_WR%d_N%d' % (Sig.mWR, Sig.mN) + self.Filename_suffix + '.root') h_Sig = f_Sig.Get(Region.Name + '/' + Variable.Name + '_' + Region.Name) if not h_Sig: continue h_Sigs.append(h_Sig) ## Make overflow h_Sig.GetXaxis().SetRangeUser(xMin, xMax) h_Sig = mylib.MakeOverflowBin(h_Sig) ## Rebin h_Sig = self.Rebin(h_Sig, Region.Name, Variable.Name, nRebin) ## Scale h_Sig.Scale(Sig.xsec * Sig.kfactor) ## Att h_Sig.SetLineWidth(3) h_Sig.SetLineColor(Sig.Color) h_Sig.SetLineStyle(Sig.Style) ## legend lg.AddEntry(h_Sig, Sig.TLatexAlias, 'l') ## Draw h_Sig.Draw("histsame") h_dummy_up.Draw("axissame") ## Legend lg.Draw() ## Draw down c1_down.cd() h_dummy_down.Draw("histsame") ## values must be set later h_Data_Ratio = h_Data.Clone('h_Data_Ratio') ## BinContent set by divide here, but errors must be set later tmp_h_Data_Ratio = h_Data.Clone() tmp_h_Data_Ratio.Divide(h_Bkgd) gr_Data_Ratio = ROOT.TGraphAsymmErrors(tmp_h_Data_Ratio) gr_Data_Ratio.SetName('gr_Data_Ratio') gr_Data_Ratio.SetLineWidth(2) gr_Data_Ratio.SetMarkerSize(0.) gr_Data_Ratio.SetLineColor(ROOT.kBlack) ## values must be set later, but BinContent will be simply 1 gr_Bkgd_Ratio = gr_Bkgd_TotErr.Clone('gr_Bkgd_Ratio') for i in range(1, h_Data_Ratio.GetXaxis().GetNbins() + 1): ## FIXME for zero? how? if h_Bkgd.GetBinContent(i) != 0: ## ratio point ## BinContent = Data/Bkgd ## BinError = DataError/Bkgd h_Data_Ratio.SetBinContent( i, h_Data_Ratio.GetBinContent(i) / h_Bkgd.GetBinContent(i)) h_Data_Ratio.SetBinError( i, h_Data_Ratio.GetBinError(i) / h_Bkgd.GetBinContent(i)) if err_down_tmp[i - 1] != 0.: gr_Data_Ratio.SetPointEYlow( i - 1, err_down_tmp[i - 1] / h_Bkgd.GetBinContent(i)) gr_Data_Ratio.SetPointEYhigh( i - 1, err_up_tmp[i - 1] / h_Bkgd.GetBinContent(i)) if Variable.Name != "WRCand_Mass": gr_Data_Ratio.SetPointEXlow(i - 1, 0) gr_Data_Ratio.SetPointEXhigh(i - 1, 0) else: gr_Data_Ratio.SetPointEYlow(i - 1, 0) gr_Data_Ratio.SetPointEYhigh( i - 1, 1.8 / h_Bkgd.GetBinContent(i)) if Variable.Name != "WRCand_Mass": gr_Data_Ratio.SetPointEXlow(i - 1, 0) gr_Data_Ratio.SetPointEXhigh(i - 1, 0) ## ratio allerr ## BinContent = 1 ## BinError = Bkgd(Stat+Syst)Error/Bkgd gr_Bkgd_Ratio.SetPoint( i - 1, h_Bkgd.GetXaxis().GetBinCenter(i), 1.) gr_Bkgd_Ratio.SetPointEYhigh( i - 1, gr_Bkgd_Ratio.GetErrorYhigh(i - 1) / h_Bkgd.GetBinContent(i)) gr_Bkgd_Ratio.SetPointEYlow( i - 1, gr_Bkgd_Ratio.GetErrorYlow(i - 1) / h_Bkgd.GetBinContent(i)) elif h_Bkgd.GetBinContent( i) == 0. and h_Data_Ratio.GetBinContent(i) == 0.: h_Data_Ratio.SetBinContent(i, 0) h_Data_Ratio.SetBinError(i, 0) gr_Data_Ratio.SetPoint(i - 1, 0, 0) gr_Data_Ratio.SetPointEYlow(i - 1, 0) gr_Data_Ratio.SetPointEYhigh(i - 1, 0) gr_Bkgd_Ratio.SetPoint( i - 1, h_Bkgd.GetXaxis().GetBinCenter(i), 1.) gr_Bkgd_Ratio.SetPointEYhigh(i - 1, 0.) gr_Bkgd_Ratio.SetPointEYlow(i - 1, 0.) if Variable.Name != "WRCand_Mass": gr_Data_Ratio.SetPointEXlow(i - 1, 0) gr_Data_Ratio.SetPointEXhigh(i - 1, 0) ## If bkgd <= 0 else: this_max_ratio = 20.0 this_data = h_Data_Ratio.GetBinContent(i) this_data_err = h_Data_Ratio.GetBinError(i) h_Data_Ratio.SetBinContent(i, this_max_ratio) h_Data_Ratio.SetBinError( i, this_data_err * this_max_ratio / this_data) tmp_x = ROOT.Double(0.) tmp_y = ROOT.Double(0.) gr_Data_Ratio.GetPoint(i - 1, tmp_x, tmp_y) gr_Data_Ratio.SetPoint(i - 1, tmp_x, this_max_ratio) gr_Data_Ratio.SetPointEYlow( i - 1, err_down_tmp[i - 1] * this_max_ratio / this_data) gr_Data_Ratio.SetPointEYhigh( i - 1, err_up_tmp[i - 1] * this_max_ratio / this_data) gr_Bkgd_Ratio.SetPoint( i - 1, h_Bkgd.GetXaxis().GetBinCenter(i), 1.) gr_Bkgd_Ratio.SetPointEYhigh(i - 1, 0.) gr_Bkgd_Ratio.SetPointEYlow(i - 1, 0.) if Variable.Name != "WRCand_Mass": gr_Data_Ratio.SetPointEXlow(i - 1, 0) gr_Data_Ratio.SetPointEXhigh(i - 1, 0) ##==>End bin loop gr_Bkgd_Ratio.SetMarkerColor(0) gr_Bkgd_Ratio.SetMarkerSize(0) gr_Bkgd_Ratio.SetFillStyle(3013) gr_Bkgd_Ratio.SetFillColor(ROOT.kBlack) gr_Bkgd_Ratio.SetLineColor(0) gr_Bkgd_Ratio.Draw("sameE2") h_Data_Ratio.Draw("p9histsame") gr_Data_Ratio.Draw("p0same") ## y=1 graph g1_x = [-9000, 9000] g1_y = [1, 1] g1 = ROOT.TGraph(2, array("d", g1_x), array("d", g1_y)) g1.Draw("same") ## TLatex c1.cd() channelname = ROOT.TLatex() channelname.SetNDC() channelname.SetTextSize(0.037) channelname.DrawLatex(0.2, 0.88, Region.TLatexAlias) ## Extra lines exec(self.ExtraLines) ## Save c1.SaveAs(Outdir + Variable.Name + '_' + Region.Name + '.pdf') print Variable.Name + '_' + Region.Name + '.pdf ==> Saved' c1.Close() ##==>End Variable loop if self.DoDebug: print '[DEBUG] All variables are done for this region, closing data TFile' f_Data.Close() ##==>End Region loop if self.DoDebug: print '[DEBUG] All regions are done.'
def saveComparisons(target): import ROOT colorsDict = { "red": ROOT.kRed + 2, "khaki": ROOT.kYellow + 2, "green": ROOT.kGreen + 2, "teal": ROOT.kCyan + 2, "blue": ROOT.kBlue + 2, "violet": ROOT.kMagenta + 2, "black": ROOT.kBlack, "grey": ROOT.kWhite + 2 } import tdrstyle, CMS_lumi ROOT.gROOT.SetBatch(ROOT.kTRUE) ROOT.TH1.AddDirectory(ROOT.kFALSE) tdrstyle.setTDRStyle() commonTitleOffset = 0.7 commonLineWidth = 3 commonTitleSize = 0.06 commonLabelSize = 0.05 HEIGHT_REF = 600 WIDTH_REF = 800 WIDTH = WIDTH_REF HEIGHT = HEIGHT_REF TOP = 0.08 * HEIGHT_REF BOTTOM = 0.12 * HEIGHT_REF LEFT = 0.12 * WIDTH_REF RIGHT = 0.04 * WIDTH_REF print("Saving comparisons for target: {t}".format(t=target)) inputDetails = inputPlots["targets"][target] canvas = ROOT.TCanvas("oC_{t}".format(t=target), "oC_{t}".format(t=target), 50, 50, WIDTH, HEIGHT) canvas.SetFillColor(0) canvas.SetBorderMode(0) canvas.SetFrameFillStyle(0) canvas.SetFrameBorderMode(0) canvas.SetLeftMargin(LEFT / WIDTH) canvas.SetRightMargin(RIGHT / WIDTH) canvas.SetTopMargin(TOP / HEIGHT) canvas.SetBottomMargin(BOTTOM / HEIGHT) canvas.SetTickx(0) canvas.SetTicky(0) canvas.Draw() bottomFraction = 0.4 bottomToTopRatio = bottomFraction / (1.0 - bottomFraction) upperPad = ROOT.TPad("upperPad_{t}".format(t=target), "upperPad_{t}".format(t=target), 0., bottomFraction, 0.97, 0.97) upperPad.SetMargin(0.12, 0.03, 0.025, 0.08) # left, right, bottom, top lowerPad = ROOT.TPad("lowerPad_{t}".format(t=target), "lowerPad_{t}".format(t=target), 0., 0., 0.97, bottomFraction) lowerPad.SetMargin(0.12, 0.03, 0.38, 0.03) # left, right, bottom, top upperPad.Draw() lowerPad.Draw() upperPad.cd() if (str(inputDetails["logY"]) == "true"): upperPad.SetLogy() legend = None try: legend = ROOT.TLegend(float(str(inputDetails["legend"]["edgeLeft"])), float(str(inputDetails["legend"]["edgeBottom"])), float(str(inputDetails["legend"]["edgeRight"])), float(str(inputDetails["legend"]["edgeTop"]))) except KeyError: print( "Coordinates of edges of legend box not found in input JSON, setting default: 0.4, 0.85, 0.9, 0.9" ) legend = ROOT.TLegend(0.4, 0.85, 0.9, 0.9) try: legend.SetNColumns( int(0.5 + float(str(inputDetails["legend"]["nColumns"])))) except KeyError: print( "Number of columns in legend not found in input JSON, setting default: 1" ) legend.SetNColumns(1) legend.SetBorderSize(commonLineWidth) legend.SetFillStyle(0) try: ROOT.gStyle.SetLegendTextSize( float(str(inputDetails["legend"]["textSize"]))) except KeyError: print( "Legend text size not found in input JSON, setting default: 0.05") ROOT.gStyle.SetLegendTextSize(0.05) # Get "scaled" versions of the input histograms inputHistogramsScaled = {} normalizeToIntegral = False try: if (inputDetails["normType"] == "integral"): normalizeToIntegral = True else: sys.exit( "ERROR: unrecognized \"normType\": {nT}, currently can only take the value \"integral\"." .format(nT=inputDetails["normType"])) except KeyError: pass sources_order = [ labelWithSpaces.strip() for labelWithSpaces in (str(inputDetails["order"])).split(",") ] if (sources_order[0] != str(inputDetails["ratioDenominatorLabel"])): sys.exit( "ERROR: Code assumes that first element in sources_order is the basis of comparison. Currently, sources_order[0] = {s}, ratioDenominatorLabel = {r}" .format(s=sources_order[0], r=str(inputDetails["ratioDenominatorLabel"]))) suppress_histogram = {} for label in sources_order: print("Fetching histogram for label: {l}".format(l=label)) inputHistogram = ROOT.TH1F() if ("filePath" in inputDetails["sources"][label]): inputFile = ROOT.TFile.Open( getFormattedInputData( inputDetails["sources"][label]["filePath"]), "READ") if ((inputFile.IsZombie() == ROOT.kTRUE) or not (inputFile.IsOpen() == ROOT.kTRUE)): sys.exit("ERROR in opening file: {f}".format( f=getFormattedInputData(inputDetails["sources"][label] ["filePath"]))) inputFile.GetObject( str(inputDetails["sources"][label]["histogramName"]), inputHistogram) if (not (inputHistogram)): sys.exit( "Unable to find non-null histogram with name {n} in file {f}" .format(n=str( inputDetails["sources"][label]["histogramName"]), f=getFormattedInputData( inputDetails["sources"][label]["filePath"]))) inputFile.Close() elif ("combineSources" in str(inputDetails["sources"][label])): filePathHistNamePairs = getFormattedInputData( inputDetails["sources"][label]["combineSources"]).split(";") firstPairSplit = (filePathHistNamePairs[0]).split(":") firstPair_inputFile = ROOT.TFile.Open(firstPairSplit[0], "READ") if ((firstPair_inputFile.IsZombie() == ROOT.kTRUE) or not (firstPair_inputFile.IsOpen() == ROOT.kTRUE)): sys.exit( "ERROR in opening file: {f}".format(f=firstPairSplit[0])) firstPair_inputFile.GetObject(str(firstPairSplit[1]), inputHistogram) firstPair_inputFile.Close() if (not (inputHistogram)): sys.exit( "Unable to find non-null histogram with name {n} in file {f}" .format(n=firstPairSplit[1], f=firstPairSplit[0])) remainingPairs = filePathHistNamePairs[1:] for pair in remainingPairs: pairSplit = pair.split(":") pair_inputFile = ROOT.TFile.Open(pairSplit[0], "READ") if ((pair_inputFile.IsZombie() == ROOT.kTRUE) or not (pair_inputFile.IsOpen() == ROOT.kTRUE)): sys.exit( "ERROR in opening file: {f}".format(f=pairSplit[0])) inputHistogramTemp = ROOT.TH1F() pair_inputFile.GetObject(str(pairSplit[1]), inputHistogramTemp) if (not (inputHistogramTemp)): sys.exit( "Unable to find non-null histogram with name {n} in file {f}" .format(n=pairSplit[1], f=pairSplit[0])) inputHistogram.Add(inputHistogramTemp) pair_inputFile.Close() else: sys.exit( "ERROR: Expected one of \"filePath\" or \"combineSources\" in input JSON source details for label: {l}, found neither." .format(l=label)) inputHistogramsScaled[label] = inputHistogram.Clone() inputHistogramsScaled[label].SetName("{t}_{l}".format(t=target, l=label)) scaleFactor = 1.0 try: if normalizeToIntegral: scaleFactor = 1.0 / tmROOTUtils.getSumOfBinContents( inputTH1=inputHistogramsScaled[label]) else: scaleFactor = 1.0 / inputHistogramsScaled[label].GetBinContent( inputHistogramsScaled[label].GetXaxis().FindFixBin( float(str(inputDetails["normX"])))) except ZeroDivisionError: # It could be that the normalization bin has 0 events... in that case pick the bin with maximum events. if (label == str(inputDetails["ratioDenominatorLabel"])): sys.exit( "You're out of luck: histogram chosen as the basis of comparison has 0 events in the target normalization bin, or 0 integral." ) else: maximumBin = inputHistogramsScaled[label].GetMaximumBin() try: scaleFactor = inputHistogramsScaled[str( inputDetails["ratioDenominatorLabel"])].GetBinContent( maximumBin) / inputHistogramsScaled[ label].GetBinContent(maximumBin) # inputHistogramsScaled[str(inputDetails["ratioDenominatorLabel"])] is guaranteed to be set first, so this is OK except ZeroDivisionError: sys.exit( "You're out of luck: histogram with label {l} appears empty" .format(l=label)) suppress_histogram[label] = False if ((scaleFactor < 0.00000001) or scaleFactor > 10000000.0): suppress_histogram[label] = True print( "WARNING: Unexpected scale factor: {s} for label: {l}; not drawing histogram." .format(s=scaleFactor, l=label)) inputHistogramsScaled[label].Scale( scaleFactor ) # Scale such that the value in the normalization bin is 1 for all sources if ("slopeCorrection" in inputDetails["sources"][label]): slopeFile = ((getFormattedInputData( inputDetails["sources"][label]["slopeCorrection"])).split(":") )[0] slopeName = ((getFormattedInputData( inputDetails["sources"][label]["slopeCorrection"])).split(":") )[1] slopeScale = None try: slopeScale = float(((getFormattedInputData( inputDetails["sources"][label]["slopeCorrection"]) ).split(":"))[2]) except IndexError: slopeScale = 1.0 slopeParameters = tmGeneralUtils.getConfigurationFromFile( inputFilePath=slopeFile) slope = slopeParameters[slopeName] / slopeScale inputHistogramsScaled[ label] = tmROOTUtils.getHistogramCorrectedBySlope( inputHistogram=inputHistogramsScaled[label], slope=slope, normX=float(str(inputDetails["normX"]))) # Find ratios and, if requested, save them in a file saveRatiosToFile = False try: saveRatiosToFile = (str(inputDetails["saveRatiosToFile"]) == "true") except KeyError: pass # Make ratio plots and, if requested, save them in a file saveRatioPlotsToFile = False try: saveRatioPlotsToFile = (str( inputDetails["saveRatioPlotsToFile"]) == "true") except KeyError: pass ratioHistograms = {} ratioGraphs = {} ratioPullGraphs = {} ratioPullMultigraph = ROOT.TMultiGraph() plotPulls = False try: ratioType = str(inputDetails["ratioType"]) if (ratioType == "pull"): plotPulls = True elif (ratioType == "nominal"): plotPulls = False else: sys.exit( "ERROR: \"ratioType\" can be either \"pull\" or \"nominal\". Currently, its value is: {rT}" .format(rT=ratioType)) except KeyError: sys.exit("ERROR: \"ratioType\" not found; needs to be set explicitly.") fractionalUncertaintiesList = [] for label in sources_order: if ((label == str(inputDetails["ratioDenominatorLabel"])) or (suppress_histogram[label])): continue ratioHistograms[label] = inputHistogramsScaled[label].Clone() ratioHistograms[label].SetName( "ratio_{t}_{l}_to_{ldenominator}".format( t=target, l=label, ldenominator=str(inputDetails["ratioDenominatorLabel"]))) ratioGraphs[label] = ROOT.TGraphErrors() ratioGraphs[label].SetName( "ratioGraph_{t}_{l}_to_{ldenominator}".format( t=target, l=label, ldenominator=str(inputDetails["ratioDenominatorLabel"]))) ratioPullGraphs[label] = ROOT.TGraphErrors() ratioPullGraphs[label].SetName( "ratioPullGraph_{t}_{l}_to_{ldenominator}".format( t=target, l=label, ldenominator=str(inputDetails["ratioDenominatorLabel"]))) for xCounter in range( 1, 1 + inputHistogramsScaled[label].GetXaxis().GetNbins()): minFractionalError = 0. fractionalErrorDown = 0. fractionalErrorUp = 0. if saveRatiosToFile: minFractionalError = float( str(inputDetails["minFractionalError"])) fractionalErrorDown = -1.0 * minFractionalError fractionalErrorUp = minFractionalError try: numerator = inputHistogramsScaled[label].GetBinContent( xCounter) numeratorError = inputHistogramsScaled[label].GetBinError( xCounter) denominator = inputHistogramsScaled[str( inputDetails["ratioDenominatorLabel"])].GetBinContent( xCounter) denominatorError = inputHistogramsScaled[str( inputDetails["ratioDenominatorLabel"])].GetBinError( xCounter) ratio = numerator / denominator ratioFractionalError = math.sqrt( pow(numeratorError / numerator, 2) + pow(denominatorError / denominator, 2)) ratioError = ratio * ratioFractionalError normBinIndex = inputHistogramsScaled[label].GetXaxis( ).FindFixBin(float(str(inputDetails["normX"]))) normBinFractionalError_normNJets = inputHistogramsScaled[str( inputDetails["ratioDenominatorLabel"] )].GetBinError(normBinIndex) / inputHistogramsScaled[str( inputDetails["ratioDenominatorLabel"])].GetBinContent( normBinIndex) normBinFractionalError_thisNJets = inputHistogramsScaled[ label].GetBinError(normBinIndex) / inputHistogramsScaled[ label].GetBinContent(normBinIndex) normBinFractionalError = math.sqrt( pow(normBinFractionalError_normNJets, 2) + pow(normBinFractionalError_thisNJets, 2)) ratioHistograms[label].SetBinContent(xCounter, ratio) if normalizeToIntegral: ratioHistograms[label].SetBinError(xCounter, ratioError) else: ratioHistograms[label].SetBinError( xCounter, ratio * math.sqrt( pow(ratioFractionalError, 2) + pow(normBinFractionalError, 2))) ratioBinIndex = ratioGraphs[label].GetN() ratioGraphs[label].SetPoint( ratioBinIndex, ratioHistograms[label].GetBinCenter(xCounter), ratio) if normalizeToIntegral: ratioGraphs[label].SetPointError( ratioBinIndex, 0.5 * (ratioHistograms[label].GetXaxis().GetBinUpEdge( xCounter) - ratioHistograms[label].GetXaxis(). GetBinLowEdge(xCounter)), ratioError) else: ratioGraphs[label].SetPointError( ratioBinIndex, 0.5 * (ratioHistograms[label].GetXaxis().GetBinUpEdge( xCounter) - ratioHistograms[label].GetXaxis(). GetBinLowEdge(xCounter)), ratioError ) # norm bin error not included because the intention is to fit to a straight line... ratioPullBinIndex = ratioPullGraphs[label].GetN() ratioPullGraphs[label].SetPoint( ratioPullBinIndex, ratioHistograms[label].GetBinCenter(xCounter), (ratio - 1.0) / ratioError) if normalizeToIntegral: ratioPullGraphs[label].SetPointError( ratioPullBinIndex, 0.5 * (ratioHistograms[label].GetXaxis().GetBinUpEdge( xCounter) - ratioHistograms[label].GetXaxis(). GetBinLowEdge(xCounter)), 0.) else: ratioPullGraphs[label].SetPointError( ratioPullBinIndex, 0.5 * (ratioHistograms[label].GetXaxis().GetBinUpEdge( xCounter) - ratioHistograms[label].GetXaxis(). GetBinLowEdge(xCounter)), ratio * normBinFractionalError / ratioError) if saveRatiosToFile: if (ratio < (1.0 - minFractionalError)): fractionalErrorDown = ratio - 1.0 # lnN (1+delta) = ratio fractionalErrorUp = minFractionalError # lnN (1+delta) = 1 + minFractionalError elif (ratio < (1.0 + minFractionalError)): fractionalErrorDown = -1.0 * minFractionalError # lnN (1+delta) = 1 - minFractionalError fractionalErrorUp = minFractionalError # lnN (1+delta) = 1 + minFractionalError else: # ratio > (1 + minFractionalError) fractionalErrorDown = -1.0 * minFractionalError # lnN (1+delta) = 1 - minFractionalError fractionalErrorUp = ratio - 1.0 # lnN (1+delta) = ratio except ZeroDivisionError: ratioHistograms[label].SetBinContent(xCounter, 1.) ratioHistograms[label].SetBinError(xCounter, 0.) # default: factor-of-5 in both directions fractionalErrorDown = -0.8 fractionalErrorUp = 4.0 ratioPullBinIndex = ratioPullGraphs[label].GetN() ratioPullGraphs[label].SetPoint( ratioPullBinIndex, ratioHistograms[label].GetBinCenter(xCounter), 0.) ratioPullGraphs[label].SetPointError( ratioPullBinIndex, 0.5 * (ratioHistograms[label].GetXaxis().GetBinUpEdge(xCounter) - ratioHistograms[label].GetXaxis().GetBinLowEdge(xCounter) ), 0.) if saveRatiosToFile: fractionalUncertaintiesList.append( tuple([ "float", (str(inputDetails["saveRatiosPatternDown"])).format( i=xCounter, l=label), fractionalErrorDown ])) fractionalUncertaintiesList.append( tuple([ "float", (str(inputDetails["saveRatiosPatternUp"])).format( i=xCounter, l=label), fractionalErrorUp ])) if saveRatiosToFile: tmGeneralUtils.writeConfigurationParametersToFile( configurationParametersList=fractionalUncertaintiesList, outputFilePath=str(inputDetails["saveRatiosFile"])) # Find maximum value for scaled histogram and the label that has it runningMaxValue = None labelWithMaxValue = None for label in sources_order: if (suppress_histogram[label]): continue currentMax = inputHistogramsScaled[label].GetBinContent( inputHistogramsScaled[label].GetMaximumBin()) if ((runningMaxValue is None) or (currentMax > runningMaxValue)): runningMaxValue = currentMax labelWithMaxValue = label # First draw the histogram with the max bin inputHistogramsScaled[labelWithMaxValue].SetLineColor(colorsDict[str( inputDetails["sources"][labelWithMaxValue]["color"])]) inputHistogramsScaled[labelWithMaxValue].SetLineWidth(commonLineWidth) inputHistogramsScaled[labelWithMaxValue].GetXaxis().SetTitleSize( commonTitleSize) inputHistogramsScaled[labelWithMaxValue].GetXaxis().SetLabelSize( commonLabelSize) inputHistogramsScaled[labelWithMaxValue].GetXaxis().SetTickLength(0) inputHistogramsScaled[labelWithMaxValue].GetXaxis().SetLabelOffset(999) try: inputHistogramsScaled[labelWithMaxValue].GetYaxis().SetTitle( str(inputDetails["yLabel"])) except KeyError: print("yLabel not found in input JSON, setting default: \"A.U.\"") inputHistogramsScaled[labelWithMaxValue].GetYaxis().SetTitle("A.U.") inputHistogramsScaled[labelWithMaxValue].GetYaxis().SetTitleSize( commonTitleSize) inputHistogramsScaled[labelWithMaxValue].GetYaxis().SetLabelSize( commonLabelSize) inputHistogramsScaled[labelWithMaxValue].GetYaxis().SetTitleOffset( commonTitleOffset) drawOptions = None try: drawOptions = str(inputDetails["customDrawOptions"]) except KeyError: print( "customDrawOptions not found in input JSON, setting default \"P0\"" ) drawOptions = "P0" inputHistogramsScaled[labelWithMaxValue].Draw(drawOptions) # First "Draw" command is just to initialize the axes etc.; it will get overwritten. upperPad.Update() try: inputHistogramsScaled[labelWithMaxValue].GetXaxis().SetRangeUser( float(str(inputDetails["plotXMin"])), float(str(inputDetails["plotXMax"]))) except KeyError: print( "xmin and xmax not found in input JSON, not setting it explicly.") try: inputHistogramsScaled[labelWithMaxValue].GetYaxis().SetRangeUser( float(str(inputDetails["plotYMin"])), float(str(inputDetails["plotYMax"]))) except KeyError: print( "ymin and ymax not found in input JSON, not setting it explicly.") upperPad.Update() # Next draw all histograms with option "SAME" for label in sources_order: # if (label == labelWithMaxValue): continue if (suppress_histogram[label]): continue inputHistogramsScaled[label].SetLineColor(colorsDict[str( inputDetails["sources"][label]["color"])]) inputHistogramsScaled[label].SetLineWidth(commonLineWidth) inputHistogramsScaled[label].Draw("A {dO} SAME".format(dO=drawOptions)) upperPad.Update() legendEntry = legend.AddEntry( inputHistogramsScaled[label], str(inputDetails["sources"][label]["label"])) legendEntry.SetLineColor(colorsDict[str( inputDetails["sources"][label]["color"])]) legendEntry.SetTextColor(colorsDict[str( inputDetails["sources"][label]["color"])]) legendEntry.SetMarkerColor(colorsDict[str( inputDetails["sources"][label]["color"])]) legend.Draw() upperPad.Update() if (str(inputDetails["drawCMSLumi"]) == "true"): CMS_lumi.lumi_sqrtS = "13 TeV" # used with iPeriod = 0, e.g. for simulation-only plots (default is an empty string) try: CMS_lumi.lumi_13TeV = str(inputDetails["CMSLumi"]) except KeyError: CMS_lumi.lumi_13TeV = "137.2 fb^{-1}" CMS_lumi.relPosX = 0.15 CMS_lumi.CMS_lumi(canvas, 4, 0) upperPad.cd() upperPad.Update() upperPad.RedrawAxis() frame = upperPad.GetFrame() frame.Draw() yTitleSize_upper = inputHistogramsScaled[labelWithMaxValue].GetYaxis( ).GetTitleSize() yLabelSize_upper = inputHistogramsScaled[labelWithMaxValue].GetYaxis( ).GetLabelSize() yTickLength_upper = inputHistogramsScaled[labelWithMaxValue].GetYaxis( ).GetTickLength() upperPad.Update() lowerPad.cd() plotPropertiesSet = False for label in sources_order: if ((label == str(inputDetails["ratioDenominatorLabel"])) or (suppress_histogram[label])): continue if plotPulls: ratioPullGraphs[label].SetLineColor(colorsDict[str( inputDetails["sources"][label]["color"])]) ratioPullGraphs[label].SetMarkerColor(colorsDict[str( inputDetails["sources"][label]["color"])]) if not (normalizeToIntegral): ratioPullGraphs[label].SetFillColorAlpha( colorsDict[str(inputDetails["sources"][label]["color"])], 0.9) ratioPullGraphs[label].SetFillStyle(3001) ratioPullGraphs[label].SetLineWidth(commonLineWidth) ratioPullMultigraph.Add(ratioPullGraphs[label]) else: ratioHistograms[label].SetLineColor(colorsDict[str( inputDetails["sources"][label]["color"])]) ratioHistograms[label].SetLineWidth(commonLineWidth) if (plotPropertiesSet): ratioHistograms[label].Draw("AP0 SAME") continue ratioHistograms[label].GetXaxis().SetTitle( str(inputDetails["xLabel"])) ratioHistograms[label].GetXaxis().SetTitleSize(yTitleSize_upper / bottomToTopRatio) ratioHistograms[label].GetXaxis().SetLabelSize(yLabelSize_upper / bottomToTopRatio) ratioHistograms[label].GetXaxis().SetTickLength(yTickLength_upper) ratioHistograms[label].GetXaxis().SetTitleOffset(0.86) ratioHistograms[label].GetYaxis().SetTitle("ratio") ratioHistograms[label].GetYaxis().SetTitleOffset( 1.4 * bottomToTopRatio * commonTitleOffset) ratioHistograms[label].GetYaxis().SetTitleSize( 0.75 * yTitleSize_upper / bottomToTopRatio) ratioHistograms[label].GetYaxis().SetLabelSize(yLabelSize_upper / bottomToTopRatio) ratioHistograms[label].GetYaxis().SetTickLength(yTickLength_upper) ratioHistograms[label].GetYaxis().SetNdivisions(2, 0, 0) ratioHistograms[label].Draw("P0") ratioHistograms[label].GetXaxis().SetRangeUser( float(str(inputDetails["plotXMin"])), float(str(inputDetails["plotXMax"]))) plotPropertiesSet = True try: ratioHistograms[label].GetYaxis().SetRangeUser( float(str(inputDetails["ratioYMin"])), float(str(inputDetails["ratioYMax"]))) except KeyError: print( "min and max values for ratio y-axis not found in input JSON, setting default: (0, 5)" ) ratioHistograms[label].GetYaxis().SetRangeUser(0., 5.) if plotPulls: if normalizeToIntegral: ratioPullMultigraph.Draw("AP") else: ratioPullMultigraph.Draw("A2") ratioPullMultigraph.Draw("P") ratioPullMultigraph.GetXaxis().SetTitle(str(inputDetails["xLabel"])) ratioPullMultigraph.GetXaxis().SetTitleSize(yTitleSize_upper / bottomToTopRatio) ratioPullMultigraph.GetXaxis().SetLabelSize(yLabelSize_upper / bottomToTopRatio) ratioPullMultigraph.GetXaxis().SetTickLength(yTickLength_upper) ratioPullMultigraph.GetXaxis().SetTitleOffset(0.86) ratioPullMultigraph.GetYaxis().SetTitle( "#frac{ratio-1.0}{#Delta ratio}") ratioPullMultigraph.GetYaxis().SetTitleOffset(1.4 * bottomToTopRatio * commonTitleOffset) ratioPullMultigraph.GetYaxis().SetTitleSize(0.75 * yTitleSize_upper / bottomToTopRatio) ratioPullMultigraph.GetYaxis().SetLabelSize(yLabelSize_upper / bottomToTopRatio) ratioPullMultigraph.GetYaxis().SetTickLength(yTickLength_upper) ratioPullMultigraph.GetYaxis().SetNdivisions(2, 0, 0) ratioPullMultigraph.GetXaxis().SetRangeUser( float(str(inputDetails["plotXMin"])), float(str(inputDetails["plotXMax"]))) try: ratioPullMultigraph.GetYaxis().SetRangeUser( float(str(inputDetails["pullYMin"])), float(str(inputDetails["pullYMax"]))) except KeyError: print( "min and max values for ratio y-axis not found in input JSON, not setting explicitly." ) lowerPad.Update() nominalExpectation = 1. if plotPulls: nominalExpectation = 0. nominalExpectationLine = ROOT.TLine(float(str(inputDetails["plotXMin"])), nominalExpectation, float(str(inputDetails["plotXMax"])), nominalExpectation) nominalExpectationLine.SetLineColor(colorsDict[str(inputDetails["sources"][ inputDetails["ratioDenominatorLabel"]]["color"])]) nominalExpectationLine.SetLineWidth(commonLineWidth) nominalExpectationLine.Draw() lowerPad.cd() lowerPad.Update() lowerPad.RedrawAxis() frame = lowerPad.GetFrame() frame.Draw() canvas.Update() canvas.SaveAs("{oD}/{oP}".format(oD=outputDirectory, oP=getFormattedInputData( inputDetails["outputPath"]))) if saveRatioPlotsToFile: canvas = ROOT.TCanvas("oC_ratioGraphs_{t}".format(t=target), "oC_ratioGraphs_{t}".format(t=target), 50, 50, WIDTH, HEIGHT) ROOT.gStyle.SetOptStat(0) ROOT.gStyle.SetOptFit(0) ratioPlotsLegend = ROOT.TLegend(0.17, 0.17, 0.95, 0.45) ratioPlotsLegend.SetNColumns(1) ratioPlotsLegend.SetBorderSize(commonLineWidth) ratioPlotsLegend.SetFillStyle(0) ROOT.gStyle.SetLegendTextSize(0.02) axesDrawn = False for label in sources_order: if ((label == str(inputDetails["ratioDenominatorLabel"])) or (suppress_histogram[label])): continue ratioGraphs[label].SetLineColor(colorsDict[str( inputDetails["sources"][label]["color"])]) ratioGraphs[label].SetMarkerColor(colorsDict[str( inputDetails["sources"][label]["color"])]) if not (axesDrawn): ratioGraphs[label].Draw("AP") ratioGraphs[label].GetXaxis().SetTitle( str(inputDetails["xLabel"])) ratioGraphs[label].GetYaxis().SetTitle("ratio") ratioGraphs[label].GetXaxis().SetRangeUser( float(str(inputDetails["plotXMin"])), float(str(inputDetails["plotXMax"]))) try: ratioGraphs[label].GetYaxis().SetRangeUser( float(str(inputDetails["ratioYMin"])), float(str(inputDetails["ratioYMax"]))) except KeyError: print( "min and max values for ratio y-axis not found in input JSON, not setting explicitly." ) axesDrawn = True else: ratioGraphs[label].Draw("P") fitFunction_const = ROOT.TF1( "constFit_{l}".format(l=label), "pol0", inputHistogramsScaled[label].GetXaxis().GetBinLowEdge(2), inputHistogramsScaled[label].GetXaxis().GetBinUpEdge( inputHistogramsScaled[label].GetXaxis().GetNbins())) fitResult_const = ratioGraphs[label].Fit( "constFit_{l}".format(l=label), "QREMS+") fitFunction_const_plot = ratioGraphs[label].GetFunction( "constFit_{l}".format(l=label)) fitFunction_const_plot.SetLineColor(colorsDict[str( inputDetails["sources"][label]["color"])]) fitFunction_const_plot.SetLineStyle(ROOT.kSolid) # fitFunction_const_plot.SetLineWidth(3) legendText_const = str( inputDetails["sources"][label]["label"] ) + " best fit const: ratio = ({C:.2f} +/- {deltaC:.2f}), #chi^2 /ndf = {chi2perndf:.2f}".format( C=fitResult_const.Parameter(0), deltaC=fitResult_const.ParError(0), chi2perndf=fitResult_const.Chi2() / fitResult_const.Ndf()) canvas.Update() fitFunction_slope = ROOT.TF1( "lineFit_{l}".format(l=label), "pol1", inputHistogramsScaled[label].GetXaxis().GetBinLowEdge(2), inputHistogramsScaled[label].GetXaxis().GetBinUpEdge( inputHistogramsScaled[label].GetXaxis().GetNbins())) fitResult_slope = ratioGraphs[label].Fit( "lineFit_{l}".format(l=label), "QREMS+") fitFunction_slope_plot = ratioGraphs[label].GetFunction( "lineFit_{l}".format(l=label)) fitFunction_slope_plot.SetLineColor(colorsDict[str( inputDetails["sources"][label]["color"])]) fitFunction_slope_plot.SetLineStyle(ROOT.kDashed) # fitFunction_slope_plot.SetLineWidth(3) legendText_slope = str( inputDetails["sources"][label]["label"] ) + " best fit line: ratio = ({C:.2f} +/- {deltaC:.2f}) + ({M:.2f} +/- {deltaM:.2f}) (ST/1000), #chi^2 /ndf = {chi2perndf:.2f}".format( C=fitResult_slope.Parameter(0), deltaC=fitResult_slope.ParError(0), M=1000 * fitResult_slope.Parameter(1), deltaM=1000 * fitResult_slope.ParError(1), chi2perndf=fitResult_slope.Chi2() / fitResult_slope.Ndf()) canvas.Update() legendText = "#splitline{" + legendText_const + "}{" + legendText_slope + "}" legendEntry = ratioPlotsLegend.AddEntry(ratioGraphs[label], legendText) legendEntry.SetLineColor(colorsDict[str( inputDetails["sources"][label]["color"])]) legendEntry.SetTextColor(colorsDict[str( inputDetails["sources"][label]["color"])]) legendEntry.SetMarkerColor(colorsDict[str( inputDetails["sources"][label]["color"])]) canvas.Update() lineAt1 = ROOT.TLine(float(str(inputDetails["plotXMin"])), 1.0, float(str(inputDetails["plotXMax"])), 1.0) lineAt1.SetLineColor(colorsDict[str(inputDetails["sources"][ inputDetails["ratioDenominatorLabel"]]["color"])]) lineAt1.SetLineWidth(4) lineAt1.SetLineStyle(ROOT.kSolid) lineAt1.Draw() ratioPlotsLegend.Draw() canvas.Update() canvas.SaveAs("{oD}/{oP}".format( oD=outputDirectory, oP=str(inputDetails["saveRatioPlotsFile"]))) del ROOT, tdrstyle, CMS_lumi
def DrawPU(canvas, f, l1seed, count, key=None): df = f[(f.L1Seed == l1seed )] RetVar = None for i in range(0, len(pubins) -1): pumap[pubins[i]] = [] pumap[pubins[i]].append(df[np.logical_and(df.PileUp > pubins[i], df.PileUp <= pubins[i+1])].Fired0.sum()) pumap[pubins[i]].append(df[np.logical_and(df.PileUp > pubins[i], df.PileUp <= pubins[i+1])].Total.sum()) x = [] y = [] yerr = [] for k, v in pumap.iteritems(): if v[1] != 0: x.append(k) if unit == "Hz": y.append(float(v[0])/v[1] * freq * nBunches ) yerr.append( math.sqrt(float(v[0]))/v[1] * freq * nBunches ) if unit == "kHz": y.append(float(v[0])/v[1] * freq * nBunches / 1000) yerr.append( math.sqrt(float(v[0]))/v[1] * freq * nBunches / 1000) ## Draw the plot graph = ROOT.TGraphErrors(len(x)) for i, (xx, yy, yee) in enumerate(zip(x, y, yerr)): # if yy != 0 and yee/yy >0.3: # continue #if i == 22 or i == 23 or i == 24: # continue graph.SetPoint(i, xx, yy) #print (i,xx,yy,yee) #print "h1->SetBinContent( %d, %f);" %(xx,yy) #print "h1->SetBinError( %d, %f);" %(xx,yee) graph.SetPointError(i, 0, yee) graph.SetMarkerStyle(20+count) graph.SetMarkerSize(1.5) graph.SetMarkerColor(1+count) graph.SetLineColor(1+count) graph.SetLineWidth(2) tdrstyle.setTDRStyle() canvas.cd() canvas.Update() if count == 0: graph.Draw("AP") graph.GetXaxis().SetTitle("PileUp") graph.GetXaxis().SetLimits(plot_min, maxx) graph.GetYaxis().SetRangeUser(0, maxy) graph.GetYaxis().SetTitle("Rate (nBunches = %d) [%s]" % (nBunches, unit)) else: graph.Draw("P") canvas.Update() leg.AddEntry(graph, l1seed, "p") result_ptr = graph.Fit(fitname, "SQ", "", fit_min, fit_max) error_vec = result_ptr.GetConfidenceIntervals() print ("error vec size = %d, fitted PU = %d" % (error_vec.size(), fit_max - fit_min + 1)) f2 = graph.GetFunction("fitname").Clone() #f2 = graph.GetFunction(fitname).Clone() f2.SetLineColor(1+count) f2.SetLineWidth(2) f2.SetRange(plot_min, fit_min) f2.SetLineStyle(5) minChi = f2.GetChisquare() / f2.GetNDF() #fun = "Fit = %.2f + %.2f*x + %.3f*x^2" % (f2.GetParameter(0), f2.GetParameter(1), f2.GetParameter(2) ) #fun = "Fit = %f*x + %f*x^2" % (f2.GetParameter(0), f2.GetParameter(1) ) #print fun f2.Draw("same") f2_2 = f2.Clone("dashline2") f2_2.SetRange(fit_max, plot_max) f2_2.Draw("same") if config == 2017: if PU <= fit_max: key = "Rate(PU=%d): %.2f +- %.2f, chi2/NDF=%.2f" %(PU, f2_2.Eval(PU), error_vec.at(PU-fit_min), minChi) else: key = "Rate(PU=%d): %.2f +- %.2f, chi2/NDF=%.2f" %(PU, f2_2.Eval(PU), error_vec.back(), minChi) if config == 2018: #key = "" key = "Rate: %.2f +- %.2f @PU50, %.2f +- %.2f @PU56, %.2f +- %.2f @PU62" %(f2_2.Eval(50), error_vec.at(50-fit_min), f2_2.Eval(56), error_vec.at(56-fit_min), f2_2.Eval(62), error_vec.at(62-fit_min)) if key is not None: tex = ROOT.TLatex(0.2, 0.85, key) tex.SetNDC() tex.SetTextFont(61) tex.SetTextSize(0.055) tex.SetTextColor(ROOT.kGreen+2) tex.SetLineWidth(2) tex.Draw() canvas.Update()
import sys import ROOT from tdrstyle import setTDRStyle from CMSStyle import CMS_lumi #------------------ # define histograms #------------------ setTDRStyle() h1_3glb_A1_signal = ROOT.TH1D("h1_3glb_A1_signal", " 3 global muons (A1)", 25, 1.65, 1.90) h1_3glb_A2_signal = ROOT.TH1D("h1_3glb_A2_signal", " 3 global muons (A2)", 25, 1.65, 1.90) h1_3glb_B1_signal = ROOT.TH1D("h1_3glb_B1_signal", " 3 global muons (B1)", 25, 1.65, 1.90) h1_3glb_B2_signal = ROOT.TH1D("h1_3glb_B2_signal", " 3 global muons (B2)", 25, 1.65, 1.90) h1_3glb_C1_signal = ROOT.TH1D("h1_3glb_C1_signal", " 3 global muons (C1)", 25, 1.65, 1.90) h1_3glb_C2_signal = ROOT.TH1D("h1_3glb_C2_signal", " 3 global muons (C2)", 25, 1.65, 1.90) h1_2glbTrk_A1_signal = ROOT.TH1D("h1_2glbTrk_A1_signal", " 2 global muons and tracker muon (A1)", 25, 1.65, 1.90) h1_2glbTrk_A2_signal = ROOT.TH1D("h1_2glbTrk_A2_signal", " 2 global muons and tracker muon (A2)", 25, 1.65, 1.90) h1_2glbTrk_B1_signal = ROOT.TH1D("h1_2glbTrk_B1_signal", " 2 global muons and tracker muon (B1)", 25,
def plot(folder, fitPhase, region, samps, lumi = "35.89"): ### Setting canvas and pad style tdrstyle.setTDRStyle(); H=600 W=700 #T = 0.08*H #B = 0.12*H L = 0.12*W R = 0.08*W c1 = ROOT.TCanvas("c1","c1",50,50,W,H) #c1 = ROOT.TCanvas() c1.SetFillColor(0) c1.SetBorderMode(0) c1.SetFrameFillStyle(0) c1.SetFrameBorderMode(0) c1.SetLeftMargin(0.12 ) c1.SetRightMargin(0.9) c1.SetTopMargin( 1) c1.SetBottomMargin(-1) c1.SetTickx(1) c1.SetTicky(1) c1.cd() unit = " fb^{-1}" CMS_lumi.writeExtraText = 1 CMS_lumi.extraText = "Preliminary" lumi_sqrtS = str(lumi)+ unit +" (13 TeV)" iPeriod = 0 iPos = 11 # writing the lumi information and the CMS "logo" pad1= ROOT.TPad("pad", "pad", 0, 0.31 , 1, 1) SetOwnership(pad1, 0) pad1.SetTopMargin(0.1) pad1.SetBottomMargin(0) pad1.SetLeftMargin(0.12) pad1.SetRightMargin(0.05) pad1.SetBorderMode(0) pad1.SetTickx(1) pad1.SetTicky(1) pad1.Draw() pad1.cd() ### Creating and drawing TStack and Legend print "region " , region[0] tmp = ROOT.TH1F() h_data = Histo.fromTH1(tmp) if(region[1].startswith("muon")): h_data,leg=getData("muon",region[0]) if(region[1].startswith("electron")): h_data,leg=getData("electron",region[0]) xmin=h_data._h.GetXaxis().GetXmin() xmax=h_data._h.GetXaxis().GetXmax() stack,leg,h_sig = getStack(folder, fitPhase, region[1], samps, leg) stack.SetMaximum(stack.GetMaximum()*1.55) stack.DrawStack() h_data.Draw("eSAMEpx0") leg.Draw("same") if(h_sig.Integral()>0): h_sig._h.SetOption("hist same") h_sig._h.SetLineStyle(9) h_sig._h.SetLineColor(ROOT.kBlue) h_sig._h.SetLineWidth(3) # hsig.SetFillColor(0) h_sig._h.SetMarkerSize(0.) h_sig._h.SetMarkerColor(ROOT.kBlue) h_sig.Draw("same L") # h_sig.Draw("same") CMS_lumi.CMS_lumi(pad1, lumi_sqrtS, iPos) c1.cd() h_ratio = ROOT.TH1F() ratio = ROOT.TH1F() h_ratio = stack.GetLast() pad2= ROOT.TPad("pad2", "pad2", 0, 0.01 , 1, 0.30) pad2.SetTopMargin(0.05) pad2.SetBottomMargin(0.45) pad2.SetLeftMargin(0.12) pad2.SetRightMargin(0.05) ROOT.gStyle.SetHatchesSpacing(2) ROOT.gStyle.SetHatchesLineWidth(2) c1.cd() pad2.Draw() pad2.cd() ratio = h_data._h.Clone("ratio") ratio.SetLineColor(ROOT.kBlack) ratio.SetMaximum(1.5) ratio.SetMinimum(0.5) ratio.Sumw2() ratio.SetStats(0) ratio.Divide(h_ratio) ratio.SetMarkerStyle(20) ratio.SetMarkerSize(0.9) ratio.Draw("epx0e0") ratio.SetTitle("") f1 = ROOT.TLine(xmin, 1., xmax,1.) f1.SetLineColor(ROOT.kBlack) f1.SetLineStyle(ROOT.kDashed) f1.Draw("same") ratio.GetYaxis().SetTitle("Data / Bkg") ratio.GetYaxis().SetNdivisions(503) ratio.GetXaxis().SetLabelFont(42) ratio.GetYaxis().SetLabelFont(42) ratio.GetXaxis().SetTitleFont(42) ratio.GetYaxis().SetTitleFont(42) ratio.GetXaxis().SetTitleOffset(1.1) ratio.GetYaxis().SetTitleOffset(0.35) ratio.GetXaxis().SetLabelSize(0.15) ratio.GetYaxis().SetLabelSize(0.15) ratio.GetXaxis().SetTitleSize(0.16) ratio.GetYaxis().SetTitleSize(0.16) ratio.GetYaxis().SetRangeUser(0.5,1.5) ratio.GetXaxis().SetTitle("") ratio.GetXaxis().SetLabelOffset(0.04) ratio.GetYaxis().SetLabelOffset(0.01) c1.cd() c1.Update() ROOT.TGaxis.SetMaxDigits(3) c1.RedrawAxis() path = "./post_fit_"+folder+"/" if not os.path.isdir(path): os.makedirs(path) pdfname = fitPhase+"_" + region[1]+".pdf" pngname = fitPhase+"_" + region[1]+".png" c1.Print(path+pdfname) c1.Print(path+pngname)
#!/usr/bin/env python #execfile('loadPyRoot.py') from ROOT import TFile, TCanvas, TGraphErrors, TH1D, TF1, gStyle, TAxis, TH1F from tdrstyle import setTDRStyle setTDRStyle(False) gStyle.SetOptFit(True) file_official = TFile("/home/home2/institut_3b/kargoll/TauAnalysis/H2TauLimits/CMSSW_7_1_5/src/auxiliaries/shapes/CERN/htt_mt.inputs-sm-8TeV.root","READ") channels = ["0jet_high", "0jet_medium", "1jet_high_mediumhiggs", "1jet_high_lowhiggs", "1jet_medium", "vbf_loose", "vbf_tight"] mLow = 90 mHigh = 160 mStep = 5 for channel in channels: can = TCanvas() NPoints = (mHigh-mLow)/mStep + 1 graph = TGraphErrors(NPoints) graph.SetTitle(channel) m = mLow while m <= mHigh: i = (m-mLow)/5 x = m
def drawTH1(name, cmsLumi, mclist, data, x_name, y_name, doLog=False, doRatio=True, ratioRange=0.45, legx=0.68, legfontsize=0.030): leg = ROOT.TLegend(legx, 0.68, legx + 0.2, 0.91) leg.SetBorderSize(0) #leg.SetNColumns(2) leg.SetTextSize(legfontsize) leg.SetTextFont(42) leg.SetLineColor(0) leg.SetFillColor(0) leg.SetFillStyle(0) leg.AddEntry(data, "Data", "lp") hs = ROOT.THStack("mcstack", "mcstack") hratio = mclist[0].Clone("hratio") hratio.Reset() leghist = [] for i, mc in enumerate(mclist): hnew = mc.Clone("hnew" + mc.GetName()) hnew.Sumw2(False) hs.Add(hnew) hratio.Add(mc) inversed = mclist[len(mclist) - 1 - i] if not any(inversed.GetTitle() == s for s in leghist): leg.AddEntry(inversed, inversed.GetTitle(), "f") leghist.append(inversed.GetTitle()) #hratio = hs.GetStack().Last() hratio.Divide(data, hratio, 1., 1., "B") tdrstyle.setTDRStyle() setDefTH1Style(data, x_name, y_name) data.SetName('data') data.SetMaximum(data.GetMaximum() * 1.8) if doLog: data.SetMaximum(data.GetMaximum() * 100) #data.SetMinimum(10**-3) else: data.GetYaxis().SetTitleSize(0.04) data.GetYaxis().SetLabelSize(0.024) data.GetYaxis().SetTitleOffset(1.35) ratio_fraction = 0 if doRatio: ratio_fraction = 0.3 data.GetXaxis().SetLabelSize(0) data.GetXaxis().SetTitleSize(0) setDefTH1Style(hratio, x_name, "Data/MC") hratio.GetYaxis().CenterTitle() hratio.GetYaxis().SetNdivisions(5) canv = makeCanvas(name, doRatio) pads = [canv] pads = rootplotcore.divide_canvas(canv, ratio_fraction) pads[0].cd() setMargins(pads[0], doRatio) if doLog: pads[0].SetLogy() data.Draw() hs.Draw("same") data.Draw("esamex0") leg.Draw("same") pads[0].Update() if doRatio: pads[1].cd() pads[1].SetGridy() setMargins(pads[1], doRatio) hratio.SetLineColor(1) hratio.Draw("e") hratio.SetMaximum(1. + ratioRange) hratio.SetMinimum(1. - ratioRange) # hratio.SetMaximum(2) # hratio.SetMinimum(0) for p in pads: p.RedrawAxis() p.Modified() p.Update() canv.cd() #iPos = 0 # in frame iPos = 11 # out frame if (iPos == 0): cmsLumi.relPosX = 0.1 cmsLumi.CMS_lumi(pads[0], 0, iPos) canv.Modified() canv.Update() return copy.deepcopy(canv)
def Plot2DPAS(hdict,outputdir="plots",outfile=0,cname="canvas" ,logscale=False,scale="No",lumitext="Preliminary"): # CMS style plots tdrstyle.setTDRStyle() # First do some checks on the input if outfile == 0: print "You did not pass me a root file to store the plots. I will only produce pdf files." if not os.path.isdir(outputdir): print "Output directory doesn't exist yet" print "Will create directory %s" % (outputdir) os.makedirs(outputdir) # placeholder for draw objects rootEvil = [] # Make the canvas canvas = rt.TCanvas(cname,"",50,50,800,600) CMS_lumi.lumi_8TeV = "19.7 fb^{-1}" CMS_lumi.writeExtraText = 1 CMS_lumi.extraText = lumitext iPos = 0#11 if( iPos==0 ): CMS_lumi.relPosX = 0.12 iPeriod = 2 H_ref = 600 W_ref = 800 W = W_ref H = H_ref # references for T, B, L, R T = 0.08*H_ref B = 0.12*H_ref L = 0.12*W_ref R = 0.12*W_ref canvas.SetLeftMargin( L/W ) canvas.SetRightMargin( R/W ) canvas.SetTopMargin( T/H ) canvas.SetBottomMargin( B/H ) #canvas.SetLeftMargin(0.13) #canvas.SetRightMargin(0.17) #canvas.SetBottomMargin(0.13) if logscale: canvas.SetLogz(1) canvas.cd() # Get histogram from dictionary, and plot it print "Getting histogram" h = hdict["histogram"] # Get the histogram if scale == "Yes": sf = h.Integral(0,h.GetNbinsX()+1,0,h.GetNbinsY()+1) h.Scale(1./sf) if scale == "Width": h.Scale(1,"width") if scale == "Yes": h.GetZaxis().SetTitle("A.U.") else: h.GetZaxis().SetTitle("Events") maxi = h.GetMaximum() if logscale: h.SetMaximum(maxi*2) else: h.SetMaximum(maxi*1.2) if scale == "Yes": h.SetMaximum(1) h.GetXaxis().SetTitle(hdict["xtitle"]) h.GetXaxis().SetTitleSize(0.05) h.GetXaxis().SetTitleOffset(1.05) h.GetXaxis().SetLabelSize(0.04) h.GetYaxis().SetTitle(hdict["ytitle"]) h.GetYaxis().SetTitleSize(0.05) h.GetYaxis().SetTitleOffset(1.05) h.GetYaxis().SetLabelSize(0.04) #h.GetZaxis().SetTitleSize(0.05) #h.GetZaxis().SetTitleOffset(1.1) #h.GetZaxis().SetLabelSize(0.04) h.SetTitle(hdict["title"]) drawoption = hdict["drawoption"] palette = hdict["palette"] if "colz" in drawoption and palette == "SMS": print "change color palette" SetColorPaletteSMS() if "colz" in drawoption and palette == "2DRatio": SetColorPalette2DRatio() rootEvil.append(h.DrawClone(drawoption)) print "Drew histogram" print hdict["name"] if hdict["name"] != "": t = '#scale[1.1]{%s}' % (hdict["name"]) if len(hdict["name"]) > 20: tex = rt.TLatex(0.45,0.82,t) else: tex = rt.TLatex(0.6,0.82,t) tex.SetNDC(); #tex.SetFillColor(kWhite) tex.Draw("same"); canvas.cd() CMS_lumi.CMS_lumi(canvas, iPeriod, iPos) canvas.SaveAs(outputdir+"/"+cname+".pdf") if outfile != 0: outfile.cd() canvas.Write() canvas.Close()
def PlotDataMCPAS(hdictlist_bg, hdict_data, hdictlist_sig=0, legdict=0 , outputdir="plots", outfile=0, cname="canvas", plotinfo="Selection X" , ratiotitle="ratio", logscale=False, scale="No", scalefactor=1, intlumi=19.7, style="CMS"): # CMS style plots if style == "CMS": tdrstyle.setTDRStyle() # First do some checks on the input if outfile == 0: print "You did not pass me a root file to store the plots. I will only produce pdf files." if not os.path.isdir(outputdir): print "Output directory doesn't exist yet. \nWill create directory %s" % (outputdir) os.makedirs(outputdir) # Get clones of all the mc histograms and put them in a list hQCD_index = -1 # will need this if we want to scale QCD only histos = [] for i,hdict in enumerate(hdictlist_bg): # first check that the histogram exists if not hdict["histogram"]: print "Histogram for sample", hdict["name"], "and canvas", cname, "doesn't exist, will stop making this plot now" return h = hdict["histogram"].Clone() h.Sumw2() h.SetFillColor(hdict["color"]) h.SetLineColor(hdict["color"]) h.GetYaxis().SetTitle(hdict["ytitle"]) h.GetXaxis().SetTitle(hdict["xtitle"]) h.SetTitle(hdict["title"]) histos.append(h) if "QCD" in hdict["name"]: hQCD_index = i # Get data histogram hdata = 0 if hdict_data == 0: print "Will make plots without data" else: if not hdict_data["histogram"]: print hdict["name"], "doesn't exist, will stop making this plot now" return hdata = hdict_data["histogram"].Clone() hdata.Sumw2() hdata.SetMarkerStyle(hdict_data["markerstyle"]) hdata.SetLineColor(hdict_data["color"]) hdata.GetYaxis().SetTitle(hdict_data["ytitle"]) hdata.SetTitle(hdict_data["title"]) # Get signal histograms hsignal = [] if hdictlist_sig != 0: for hdict in hdictlist_sig: if not hdict["histogram"]: print hdict["name"], "doesn't exist, will stop making this plot now" return h = hdict["histogram"].Clone() h.Sumw2() h.SetFillColor(hdict["color"]) h.SetLineColor(hdict["color"]) hsignal.append(h) # make a stack of all the mc, will use the reverse order of the list mc = rt.THStack() for h in reversed(histos): mc.Add(h,"hist") for h in hsignal: mc.Add(h,"hist") # make the total mc histogram, used for the ratio plot htotal = histos[0].Clone() for h in histos[1:]: htotal.Add(h) # scale MC to data if required if scale == "Yes" and hdata != 0: sf = scalefactor if sf == 1: # we should rescale to match data mc_int = htotal.Integral(0,htotal.GetNbinsX()+1) if mc_int == 0: mc_int = 1. data_int = hdata.Integral() sf = data_int/mc_int for h in histos: h.Scale(sf) print "Scaled all histograms by factor", sf # Scale everything according to the bin width if scale == "Width": for h in histos: h.Scale(scalefactor,"width") if hdata != 0: hdata.Scale(scalefactor,"width") for h in hsignal: h.Scale(scalefactor,"width") print "Will plot per bin width" # scale only QCD to match data in the first non-empty bin if scale == "QCD" and hdata != 0: sf = scalefactor if sf == 1: # find first non-empty bin first_bin = 0 for b in range(hdata.GetNbinsX()): if hdata.GetBinContent(b+1)>0: first_bin = b+1 break # compute the scale factor if histos[hQCD_index].GetBinContent(first_bin) != 0: sf = (hdata.GetBinContent(first_bin) - htotal.GetBinContent(first_bin) + histos[hQCD_index].GetBinContent(first_bin)) / histos[hQCD_index].GetBinContent(first_bin) histos[hQCD_index].Scale(sf) print "Scaled QCD histogram by factor", sf if scale != "No": # we scaled some histograms, will need to remake htotal htotal = histos[0].Clone() for h in histos[1:]: htotal.Add(h) # make the legend legend = rt.TLegend(0.63,0.4,0.87,0.8,"") if legdict != 0: legend = rt.TLegend(legdict["xmin"],legdict["ymin"],legdict["xmax"],legdict["ymax"],legdict["title"]) legend.SetNColumns(legdict["ncolumns"]) legend.SetFillColor(0) legend.SetBorderSize(0) if hdata != 0: legend.AddEntry(hdata," data ("+ str(intlumi) + "/fb)","epl") for i,h in enumerate(histos): if hdictlist_bg[i]["appear in legend"]: legend.AddEntry(h,hdictlist_bg[i]["name"],"f") for i,h in enumerate(hsignal): if hdictlist_sig[i]["appear in legend"]: legend.AddEntry(h,hdictlist_sig[i]["name"],"f") # Get the maximum of the histograms, so that we can set the Y-axis range maxi = 0 if hdata != 0: hdata.GetMaximum() if htotal.GetMaximum() > maxi: maxi = htotal.GetMaximum() # Make the canvas, which will have two pads if we have data, and only one if there is no data canvas = rt.TCanvas(cname,"",50,50,800,600) canvas.cd() pad1 = 0 if hdata != 0: pad1 = rt.TPad("pad1","",0,0.25,1,1) pad1.SetBottomMargin(0) pad1.SetRightMargin(0.03) pad1.SetLeftMargin(0.1) pad1.SetTopMargin(0.1) if logscale: pad1.SetLogy(1) pad1.Draw() pad1.cd() else: pad1 = rt.TPad("pad1","",0,0,1,1) if logscale: pad1.SetLogy(1) pad1.SetTopMargin(0.08) pad1.SetBottomMargin(0.12) pad1.SetLeftMargin(0.12) pad1.Draw() pad1.cd() if hdata != 0: hdata.GetYaxis().SetTitleSize(0.06) hdata.GetYaxis().SetTitleOffset(0.8) hdata.GetYaxis().SetLabelSize(0.055) hdata.SetMaximum(2.*maxi) if logscale: hdata.SetMaximum(5.*maxi) hdata.SetMinimum(0.007) hdata.Draw("EP") else: mc.Draw() mc.SetTitle(hdictlist_bg[0]["title"]) mc.GetYaxis().SetTitleSize(0.05) mc.GetYaxis().SetTitleOffset(1) mc.GetYaxis().SetLabelSize(0.045) mc.GetXaxis().SetTitleSize(0.05) mc.GetXaxis().SetTitleOffset(1) mc.GetXaxis().SetLabelSize(0.045) mc.GetYaxis().SetTitle(hdictlist_bg[0]["ytitle"]) mc.GetXaxis().SetTitle(hdictlist_bg[0]["xtitle"]) mc.SetMaximum(1.5*maxi) if logscale: mc.SetMaximum(5.*maxi) mc.SetMinimum(0.007) mc.Draw("same") mc.Draw("axis same") if hdata != 0: hdata.Draw("EPsame") legend.Draw("same") t = '#scale[1.1]{%s}' % (plotinfo) tex = rt.TLatex() tex.SetNDC() if len(plotinfo) > 20: tex.DrawLatex(0.42,0.82,t) else: tex.DrawLatex(0.65,0.82,t) #tex.SetNDC(); #tex.DrawLatex("same"); # Make the second pad, with the ratios; only if hdata!=0 if hdata != 0: canvas.cd() pad2 = rt.TPad("pad2","",0,0,1,0.25) pad2.SetBottomMargin(0.35)#0.25 pad2.SetTopMargin(0)#0.05 pad2.SetLeftMargin(0.1) pad2.SetRightMargin(0.03) pad2.SetGridy(1) pad2.Draw() pad2.cd() ratio = rt.TH1D() ratio = hdata.Clone() ratio.Divide(htotal) ratio.SetTitle("") ratio.SetName("histoRatio") ratio.GetYaxis().SetRangeUser(0,2.2) ratio.GetYaxis().SetNdivisions(4,8,0) ratio.GetYaxis().SetLabelSize(0.15) ratio.GetYaxis().SetTitleSize(0.18) ratio.GetYaxis().SetTitle(ratiotitle) ratio.GetYaxis().SetTitleOffset(0.22) ratio.GetXaxis().SetLabelSize(0.15) ratio.GetXaxis().SetTitleSize(0.18) ratio.GetXaxis().SetTitleOffset(0.8) ratio.GetXaxis().SetTickLength(0.1) ratio.GetXaxis().SetTitle(hdict_data["xtitle"]) ratio.SetStats(0) ratio.Draw("pe") rt.SetOwnership(pad1, False) # to avoid seg fault rt.SetOwnership(pad2, False) # to avoid seg fault canvas.cd() if style == "CMS": CMS_lumi.lumi_8TeV = "19.7 fb^{-1}" CMS_lumi.writeExtraText = 1 CMS_lumi.extraText = "Preliminary" iPos = 0#11 if( iPos==0 ): CMS_lumi.relPosX = 0.12 iPeriod = 2 CMS_lumi.CMS_lumi(pad1, iPeriod, iPos) canvas.cd() canvas.SaveAs(outputdir+"/"+cname+".pdf") if outfile != 0: outfile.cd() canvas.Write() canvas.Close()
def plot_eta(x, y, name): print "------ Setting Up Format ----------" tdrstyle.setTDRStyle() #change the CMS_lumi variables (see CMS_lumi.py) CMS_lumi.writeExtraText = 1 CMS_lumi.extraText = "Preliminary" CMS_lumi.extraText2 = "2018 pp data" CMS_lumi.lumi_sqrtS = "13 TeV" # used with iPeriod = 0, e.g. for simulation-only plots (default is an empty string) CMS_lumi.writeTitle = 1 CMS_lumi.textTitle = 'title' iPos = 11 if (iPos == 0): CMS_lumi.relPosX = 0.12 H_ref = 600 W_ref = 800 W = W_ref H = H_ref iPeriod = 0 # references for T, B, L, R T = 0.08 * H_ref B = 0.12 * H_ref L = 0.12 * W_ref R = 0.04 * W_ref print "----- Creating TCanvas -----" H = 800 W = 1600 canv = TCanvas("c1", "Canvas", 50, 50, W, H) canv.SetFillColor(0) canv.SetBorderMode(0) canv.SetFrameFillStyle(0) canv.SetFrameBorderMode(0) canv.SetLeftMargin(L / W) canv.SetRightMargin(R / W) canv.SetTopMargin(T / H) canv.SetBottomMargin(B / H) canv.SetTickx(0) canv.SetTicky(0) #canv.Divide(3,2,0.001,0.001) CMS_lumi.CMS_lumi(canv, iPeriod, iPos) canv.cd() canv.Update() maxY = max(y) * 1.5 canv.cd(1) gPad.SetLogy() print "------ Creating Wheel TGraph ----------" n = len(x) gr = TGraph(n, x, y) gr.SetMarkerColor(kGreen + 3) gr.SetMarkerStyle(20) gr.SetMarkerSize(1.5) gr.SetLineColor(5) gr.SetLineWidth(7) gr.SetTitle(name) gr.GetXaxis().SetTitle('#eta') gr.GetYaxis().SetTitle('DT single hit rate (Hz/cm^{2})') print " ------------ Creating TMultiGraph -----------" mg = TMultiGraph() mg.Add(gr, "AP") mg.Draw("a") mg.SetTitle(name) mg.GetXaxis().SetTitle('#eta') mg.GetYaxis().SetTitle('DT single hit rate (Hz/cm^{2})') mg.SetMaximum(maxY) mg.GetXaxis().SetLabelFont(42) mg.GetXaxis().SetLabelOffset(0.007) mg.GetXaxis().SetLabelSize(0.043) mg.GetXaxis().SetTitleSize(0.05) mg.GetXaxis().SetTitleOffset(1.06) mg.GetXaxis().SetTitleFont(42) mg.GetYaxis().SetLabelFont(42) mg.GetYaxis().SetLabelOffset(0.008) mg.GetYaxis().SetLabelSize(0.05) mg.GetYaxis().SetTitleSize(0.06) mg.GetYaxis().SetTitleOffset(0.87) mg.GetYaxis().SetTitleFont(42) pv = TPaveText(.1, 0.97, .55, 0.97, "NDC") #(.06,.4,.55,.73) pv.AddText('CMS Preliminary') pv.SetFillStyle(0) pv.SetBorderSize(0) pv.SetTextSize(0.03) pv.Draw() pv1 = TPaveText(.7, 0.97, .9, 0.97, "NDC") pv1.AddText('1.5 #times 10^{34} Hz/cm^{2} (13 TeV)') pv1.SetFillStyle(0) pv1.SetBorderSize(0) pv1.SetTextSize(0.03) pv1.Draw() l = TLegend(0.4, 0.6, .7, .8) l.SetNColumns(1) l.AddEntry(gr, name, "p") l.SetTextSize(0.05) l.Draw("a") canv.SaveAs("etaDistro{}.png".format(name)) canv.Close()
def drawPlots_tdrstyle(data, signal, signalSF, signalName, background, backgroundSF, backgroundName, xlo, xhi, name, xaxisLabel, axisMin, axisMax, doLogy): tdrstyle.setTDRStyle() CMS_lumi.lumi_8TeV = '19.7 fb^{-1}' CMS_lumi.extraText = 'Preliminary' CMS_lumi.writeExtraText = 1 CMS_lumi.lumi_sqrtS = '8 TeV' iPos = 11 H = 600 W = 800 # iPeriod = 1*(0/1 7 TeV) + 2*(0/1 8 TeV) + 4*(0/1 13 TeV) iPeriod = 2 # references for T, B, L, R T = 0.08*H B = 0.12*H L = 0.12*W R = 0.04*W can = ROOT.TCanvas('can', 'plot', 50, 50, W, H) padFraction = 0.3 padhi = ROOT.TPad('padhi', 'padhi', 0, padFraction, 1, 1) padhi.SetLeftMargin( L/W ) padhi.SetRightMargin( R/W ) padhi.SetTopMargin(T/H/(1.0 - padFraction)) padhi.SetBottomMargin(0) padhi.SetTickx(0) padhi.SetTicky(0) padhi.SetLogy(doLogy) padlo = ROOT.TPad('padlo', 'padlo', 0, 0, 1, padFraction) padlo.SetLeftMargin( L/W ) padlo.SetRightMargin( R/W ) padlo.SetTopMargin(0) padlo.SetBottomMargin(B/H/padFraction) padlo.SetTickx(0) padlo.SetTicky(0) padhi.Draw() padlo.Draw() signal.Scale(signalSF) background.Scale(backgroundSF) background.SetFillColor(8) sumHist = signal.Clone('sumHist') sumHist.Add(background) sumHist.SetFillColor(ROOT.kGray) sumHist.GetXaxis().SetRangeUser(xlo, xhi) sumHist.GetYaxis().SetRangeUser(axisMin, axisMax) sumHist.GetYaxis().SetTitle('Events / 10 GeV') ratio = data.Clone('ratio') ratio.Reset() for ibin in range(ratio.GetNbinsX()): if(sumHist.GetBinContent(ibin+1) == 0): continue ratio.SetBinContent(ibin+1, data.GetBinContent(ibin+1) / sumHist.GetBinContent(ibin+1)) ratio.SetBinError(ibin+1, data.GetBinError(ibin+1) / sumHist.GetBinContent(ibin+1)) ratio.GetYaxis().SetRangeUser(0.45, 1.55) ratio.GetYaxis().SetTitle('Data / Background') ratio.GetYaxis().SetLabelSize(0.06) ratio.GetYaxis().SetTitleSize(0.06) ratio.GetYaxis().SetTitleOffset(0.5) #ratio.GetYaxis().SetNdivisions(512) ratio.GetXaxis().SetRangeUser(xlo, xhi) ratio.GetXaxis().SetTitle(xaxisLabel) ratio.GetXaxis().SetLabelSize(0.10) ratio.GetXaxis().SetTitleSize(0.12) ratio.GetXaxis().SetTitleOffset(1.2) oneLine = ROOT.TLine(xlo, 1.0, xhi + 10.0, 1.0) oneLine.SetLineStyle(2) reqtitle = '' if 'ele_bjj' in name or 'ele_jjj' in name: if 'z_mass' in name: reqtitle = 'ee' else: reqtitle = 'e#gamma' else: if 'z_mass' in name: reqtitle = '#mu#mu' else: reqtitle = '#mu#gamma' if 'bjj' in name: reqtitle = reqtitle + '+bjj' else: reqtitle = reqtitle + '+jjj' #leg = ROOT.TLegend(0.7, 0.6, 0.85, 0.85, '', 'brNDC') leg = ROOT.TLegend(0.72, 0.6, 0.89, 0.85, '', 'brNDC') leg.SetFillColor(0) #leg.SetTextSize(0.028) leg.SetTextSize(0.028 / 0.6) leg.SetBorderSize(0) leg.AddEntry(data, 'Data', 'LP') leg.AddEntry(sumHist, signalName, 'F') leg.AddEntry(background, backgroundName, 'F') padhi.cd() sumHist.Draw('hist') background.Draw('hist same') data.Draw('e1 same') sumHist.Draw('axis same') leg.Draw() padlo.cd() ratio.Draw('e1') oneLine.Draw() ratio.Draw('axis same') padhi.cd() CMS_lumi.CMS_lumi(padhi, iPeriod, iPos, reqtitle) can.cd() padFix = ROOT.TPad('pad4', 'pad4', .09, .295, .118, .33) if not doLogy: padFix.Draw() can.SaveAs('plots/'+name+'.pdf') can.SaveAs('canvases/'+name+'.C')
def printCovarianceMatrix(tsk): var, ty, fidornot, normornot = tsk if ty == 'unfolded' and not fidornot: tfile = r.TFile("temp/{vr}_/unfOutput_{vr}.root".format(vr=var), "read") elif fidornot and not normornot: tfile = r.TFile("temp/{vr}_/fidOutput_{vr}.root".format(vr=var), "read") elif normornot and fidornot: tfile = r.TFile("temp/{vr}_/fidOutput_{vr}norm.root".format(vr=var), "read") elif not fidornot and normornot: tfile = r.TFile("temp/{vr}_/unfOutput_{vr}.root".format(vr=var), "read") else: tfile = r.TFile("temp/{vr}_/cutOutput_{vr}.root".format(vr=var), "read") if ty == "folded": nominal = copy.deepcopy(tfile.Get("data_").Clone("nominal")) else: nominal = copy.deepcopy(tfile.Get(var).Clone("nominal")) if vl.doxsec and ty == 'folded': nominal.Scale(scaleval) varMat = {} for key in tfile.GetListOfKeys(): if key.GetName() == "data_" or "asimov" in key.GetName( ) or key.GetName().replace("data_", "").replace( var + "_", '') in vl.varList['Names']['colorSysts'] or key.GetName( ) == var or key.GetName() == "nom0" or key.GetName() == "nom1": continue # Colour envelope is applied in any case elif key.GetName() == "CovMat" and ty == "unfolded": varMat["unfCovMat"] = copy.deepcopy(key.ReadObj()) else: if "Down" in key.GetName() or "Up" not in key.GetName(): continue #elif "Up" not in key.GetName(): #print key.GetName() #varMat[key.GetName().replace("data_", "").replace(var + "_", "")] = copy.deepcopy(ep.getCovarianceFromVar(nominal, key.ReadObj(), var, ty)) else: tmphistoup = copy.deepcopy(key.ReadObj().Clone("tmphistoup")) for key2 in tfile.GetListOfKeys(): if key2.GetName() == key.GetName().replace("Up", "Down"): tmphistodw = copy.deepcopy( key2.ReadObj().Clone("tmphistodw")) varsup = [ abs( tmphistoup.GetBinContent(binin) - nominal.GetBinContent(binin)) for binin in range(1, nominal.GetNbinsX() + 1) ] varsdw = [ abs( tmphistodw.GetBinContent(binin) - nominal.GetBinContent(binin)) for binin in range(1, nominal.GetNbinsX() + 1) ] varsfin = [(varsup[binin] + varsdw[binin]) / 2 for binin in range(nominal.GetNbinsX())] for binin in range(1, nominal.GetNbinsX() + 1): tmphistoup.SetBinContent( binin, nominal.GetBinContent(binin) + varsfin[binin - 1]) del varsup, varsdw, varsfin, tmphistodw varMat[key.GetName().replace("data_", "").replace( var + "_", "")] = copy.deepcopy( ep.getCovarianceFromVar(nominal, tmphistoup, var, ty)) del tmphistoup colup = copy.deepcopy(nominal.Clone("ColorRUp")) coldn = copy.deepcopy(nominal.Clone("ColorRDown")) for bin in range(1, nominal.GetNbinsX() + 1): # Colour envelope is applied in any case tmpuncUp = nominal.GetBinContent(bin) tmpuncDown = nominal.GetBinContent(bin) tmpunc = 0. for key in tfile.GetListOfKeys(): if key.GetName().replace("data_", "").replace( var + "_", "") in vl.varList['Names']['colorSysts']: tmpunc = key.ReadObj().GetBinContent(bin) if tmpunc > tmpuncUp: tmpuncUp = tmpunc elif tmpunc < tmpuncDown: tmpuncDown = tmpunc colup.SetBinContent(bin, tmpuncUp) coldn.SetBinContent(bin, tmpuncDown) varsup = [ abs(colup.GetBinContent(binin) - nominal.GetBinContent(binin)) for binin in range(1, nominal.GetNbinsX() + 1) ] varsdw = [ abs(coldn.GetBinContent(binin) - nominal.GetBinContent(binin)) for binin in range(1, nominal.GetNbinsX() + 1) ] varsfin = [(varsup[binin] + varsdw[binin]) / 2 for binin in range(nominal.GetNbinsX())] for binin in range(1, nominal.GetNbinsX() + 1): colup.SetBinContent(binin, nominal.GetBinContent(binin) + varsfin[binin - 1]) del varsup, varsdw, varsfin varMat["ColorRUp"] = ep.getCovarianceFromVar(nominal, colup, var, ty) #varMat["ColorRDown"] = ep.getCovarianceFromVar(nominal, coldn, var, ty) binning = array( 'f', vl.varList[var]['recobinning'] if ty == "folded" else vl.varList[var]['genbinning']) if fidornot: # We must calculate the (complete) covariance matrix for the statistical uncertainties for this case, as it is not directly providen by doFiducial.py nor TUnfold. ffid = r.TFile.Open("temp/Fiducial_/unfOutput_Fiducial.root", "read") fvar = r.TFile.Open("temp/" + var + "_/unfOutput_" + var + ".root", "read") newmat = r.TH2F('newmat', '', nominal.GetNbinsX(), binning, nominal.GetNbinsX(), binning) dxs = copy.deepcopy(fvar.Get(var).Clone("dxs")) covm = copy.deepcopy(fvar.Get("CovMat").Clone("covm")) for key in ffid.GetListOfKeys(): if key.GetName() != "Fiducial": continue dfid = r.TH1D(fvar.Get(var)) for bin in range(1, dfid.GetNbinsX() + 1): dfid.SetBinContent(bin, key.ReadObj().GetBinContent(1)) dfid.SetBinError(bin, key.ReadObj().GetBinError(1)) #print "\nFiducial" for bin1 in range(1, nominal.GetNbinsX() + 1): for bin2 in range(1, nominal.GetNbinsX() + 1): goodunc = ( covm.GetBinContent(bin1, bin2) / dfid.GetBinContent(bin1)**2 + dxs.GetBinContent(bin1) * dxs.GetBinContent(bin2) * dfid.GetBinError(bin1)**2 / dfid.GetBinContent(bin1)**4 - dxs.GetBinContent(bin2) / dfid.GetBinContent(bin1)**3 * sum([ covm.GetBinContent(bin1, j) for j in range(1, dxs.GetNbinsX() + 1) ]) - dxs.GetBinContent(bin1) / dfid.GetBinContent(bin1)**3 * sum([ covm.GetBinContent(bin2, j) for j in range(1, dxs.GetNbinsX() + 1) ])) #if bin1 == bin2: print "bin", bin1, goodunc newmat.SetBinContent(bin1, bin2, goodunc) if normornot: newmat.Scale(1, "width") # THIS IS A COVARIANCE!! Constants that apply to the random variable apply SQUARED to the covariance (and variance)! NOTE: when you have a 2D histo, the scale is already done "two times". #print "\nFiducialnorm" varMat["statistical"] = copy.deepcopy(newmat.Clone("statistical")) #for bin in range(1, nominal.GetNbinsX() + 1): #print "bin", bin, newmat.GetBinContent(bin, bin) ffid.Close() fvar.Close() del ffid, fvar, dfid, dxs, newmat if ty == "folded": newmat = r.TH2F('newmat', '', nominal.GetNbinsX(), binning, nominal.GetNbinsX(), binning) for bin in range(1, nominal.GetNbinsX() + 1): newmat.SetBinContent(bin, bin, nominal.GetBinError(bin)**2) varMat["statistical"] = copy.deepcopy(newmat.Clone("statistical")) del newmat idnx = 0 finalmat = r.TH2F('finalmat', '', nominal.GetNbinsX(), binning, nominal.GetNbinsX(), binning) for key in varMat: idnx += 1 #print idnx, key #print "finalmat.GetNbinsX()", finalmat.GetNbinsX() #print "varMat[key].GetNbinsX()", varMat[key].GetNbinsX() finalmat.Add(varMat[key]) #for bin in range(1, nominal.GetNbinsX() + 1): print "matfinal bin", bin, ":", finalmat.GetBinContent(bin, bin) if normornot and not fidornot: finalmat.Scale(1, "width") if fidornot and ("unfCovMat" in varMat or "statistical" not in varMat): raise RuntimeError( "You are calculating the covariance matrix of some fiducial results but you do not have the statistical uncertainties covariance matrix!!!!" ) tdrstyle.setTDRStyle() finalmat.SetStats(False) finalmat.SetXTitle(vl.varList[var]['xaxis']) finalmat.SetYTitle(vl.varList[var]['xaxis']) finalmat.SetMarkerColor(r.kRed) finalmat.SetMarkerColor(r.kRed) if 'covtxtsizeunf' in vl.varList[var] and ty == "unfolded" and not fidornot: finalmat.SetMarkerSize(vl.varList[var]['covtxtsizeunf']) elif 'covtxtsizefol' in vl.varList[var] and ty == "folded": finalmat.SetMarkerSize(vl.varList[var]['covtxtsizefol']) elif 'covtxtsizefidnorm' in vl.varList[var] and fidornot and normornot: finalmat.SetMarkerSize(vl.varList[var]['covtxtsizefidnorm']) fcovmat = r.TFile( "temp/{vr}_/CovMat_{vr}_{t}{lodefid}{lodenorm}.root".format( vr=var, t=ty, lodefid="_fiducial" * (fidornot), lodenorm="norm" * (normornot)), "recreate") finalmat.Write() fcovmat.Close() r.gStyle.SetPaintTextFormat("4.5f" if not normornot else "4.8f") r.gStyle.SetPadRightMargin(0.17) r.gStyle.SetPadTopMargin(0.05) r.gStyle.SetPadBottomMargin(0.1) r.gStyle.SetPadLeftMargin(0.12) finalmat.GetYaxis().SetTitleOffset(1.5) finalmat.GetXaxis().SetTitleOffset(1.1) finalmat.GetXaxis().SetTitleFont(43) finalmat.GetXaxis().SetTitleSize(22) finalmat.GetXaxis().SetLabelFont(43) finalmat.GetXaxis().SetLabelSize(22) finalmat.GetYaxis().SetTitleFont(43) finalmat.GetYaxis().SetTitleSize(22) finalmat.GetYaxis().SetLabelFont(43) finalmat.GetYaxis().SetLabelSize(22) r.gStyle.SetLabelFont(43, "XYZ") r.gStyle.SetLabelSize(22, "XYZ") c = r.TCanvas('c', "", 200, 10, 600, 600) finalmat.Draw("colz text{s}".format( s=vl.varList[var]['covtxtangle'] if 'covtxtangle' in vl.varList[var] and ty == "folded" else vl.varList[var]['covtxtangleunf'] if ( 'covtxtangleunf' in vl.varList[var] and ty == "unfolded" and not fidornot) else vl.varList[var]['covtxtangleunffid'] if ('covtxtangleunffid' in vl.varList[var] and fidornot and not normornot ) else vl.varList[var]['covtxtangleunffidnorm'] if ('covtxtangleunffidnorm' in vl.varList[var] and normornot) else "")) r.gPad.Update() CMS_lumi.lumi_13TeV = "" #CMS_lumi.extraText = 'Simulation Supplementary' CMS_lumi.extraText = 'Simulation Preliminary' CMS_lumi.lumi_sqrtS = '' #CMS_lumi.cmsTextSize += 0.1 CMS_lumi.CMS_lumi(r.gPad, 0, 0, 0.05) c.SaveAs( plotsoutputpath + "/Cov_{vr}_{t}{lodefid}{lodenorm}.png".format(vr=var, t=ty, lodefid="_fiducial" * (fidornot), lodenorm="norm" * (normornot))) c.SaveAs( plotsoutputpath + "/Cov_{vr}_{t}{lodefid}{lodenorm}.pdf".format(vr=var, t=ty, lodefid="_fiducial" * (fidornot), lodenorm="norm" * (normornot))) c.SaveAs( plotsoutputpath + "/Cov_{vr}_{t}{lodefid}{lodenorm}.eps".format(vr=var, t=ty, lodefid="_fiducial" * (fidornot), lodenorm="norm" * (normornot))) c.SaveAs( plotsoutputpath + "/Cov_{vr}_{t}{lodefid}{lodenorm}.root".format(vr=var, t=ty, lodefid="_fiducial" * (fidornot), lodenorm="norm" * (normornot))) c.Close() tfile.Close() del c, nominal, colup, coldn, tfile, varMat, finalmat, binning return
def PlotOnCanvas(self, pdf_name): tdrstyle.setTDRStyle() canvas = TCanvas("c", "c", 600, 600) pad1 = TPad("pad1", "pad1", 0, 0.0, 1, 1.0) pad1.SetTopMargin(0.15) pad1.SetBottomMargin(0.32) pad1.SetRightMargin(0.05) pad1.SetLeftMargin(0.15) if self.title == '': pad1.SetTopMargin(0.05) pad1.SetGridx() pad1.Draw() pad1.cd() self.histo1.SetStats(0) self.histo1.Draw(self.option) self.histo2.Draw(self.option + " same") if self.logx: pad1.SetLogx() if self.logy: pad1.SetLogy() # Redraw axis to avoid clipping 0 self.histo1.GetXaxis().SetLabelSize(0.) self.histo1.GetXaxis().SetTitle('') axis = TGaxis(-9, -2.8, -9, 2.8, 0, 10000, 50510, "") axis.SetLabelFont(43) axis.SetLabelSize(15) axis.Draw("same") pad2 = TPad("pad2", "pad2", 0, 0.0, 1, 0.3) pad2.SetTopMargin(0) pad2.SetBottomMargin(0.4) pad2.SetRightMargin(0.05) pad2.SetLeftMargin(0.15) pad2.SetGridx() pad2.Draw() pad2.cd() if self.logx: pad2.SetLogx() self.ratio.SetLineColor(ROOT.kBlack) self.ratio.SetMinimum(0.5) self.ratio.SetMaximum(1.5) self.ratio.SetStats(0) self.ratio.SetMarkerStyle(21) self.ratio.Draw("ep") self.histo1.SetLineColor(ROOT.kBlue + 1) self.histo1.SetLineWidth(2) max_y = max(self.histo1.GetMaximum(), self.histo2.GetMaximum()) self.histo1.SetMaximum(max_y * 1.1) self.histo1.GetXaxis().SetTitleOffset(1.5) self.histo1.GetXaxis().SetLabelSize(0.) self.histo1.GetXaxis().SetTitleSize(0.) self.histo1.GetYaxis().SetTitleOffset(1.5) self.histo1.GetYaxis().SetLabelSize(0.03) self.histo1.GetYaxis().SetTitleSize(0.05) self.histo1.GetYaxis().SetNdivisions(505) self.histo2.SetLineColor(ROOT.kRed) self.histo2.SetLineWidth(2) self.ratio.SetTitle("") self.ratio.GetXaxis().SetNdivisions(510) self.ratio.GetXaxis().SetTitleOffset(1.1) self.ratio.GetXaxis().SetLabelSize(0.10) self.ratio.GetXaxis().SetTitleSize(0.15) if len(self.xlabel) > 30: self.ratio.GetXaxis().SetTitleSize(0.13) if len(self.xlabel) > 60: self.ratio.GetXaxis().SetTitleSize(0.11) self.ratio.GetYaxis().SetTitle("Ratio") self.ratio.GetYaxis().SetNdivisions(505) self.ratio.GetYaxis().SetTitleOffset(0.5) self.ratio.GetYaxis().SetLabelSize(0.10) self.ratio.GetYaxis().SetTitleSize(0.15) if len(self.ylabel) > 30: self.ratio.GetYaxis().SetTitleSize(0.13) if len(self.ylabel) > 60: self.ratio.GetYaxis().SetTitleSize(0.11) # Legend # canvas.cd() if self.title == '': self.legend = TLegend(0.60, 0.80, 0.93, 0.93) else: self.legend = TLegend(0.60, 0.70, 0.93, 0.83) self.legend.SetTextSize(0.05) self.legend.SetBorderSize(0) self.legend.SetFillColor(0) self.legend.AddEntry(self.histo1, self.legend1, "l") self.legend.AddEntry(self.histo2, self.legend2, "l") self.legend.Draw() ROOT.SetOwnership(canvas, False) ROOT.SetOwnership(pad1, False) ROOT.SetOwnership(pad2, False) return canvas, self.filename
def easyPlot(name, tag, histlist, bkglist=[], signals=[], colors=[], titles=[], logy=False, rootfile=False, xtitle='', ytitle='', dataOff=False, datastyle='pe'): # histlist is just the generic list but if bkglist is specified (non-empty) # then this function will stack the backgrounds and compare against histlist as if # it is data. The important bit is that bkglist is a list of lists. The first index # of bkglist corresponds to the index in histlist (the corresponding data). # For example you could have: # histlist = [data1, data2] # bkglist = [[bkg1_1,bkg2_1],[bkg1_2,bkg2_2]] if len(histlist) == 1: width = 800 height = 700 padx = 1 pady = 1 elif len(histlist) == 2: width = 1200 height = 700 padx = 2 pady = 1 elif len(histlist) == 3: width = 1600 height = 700 padx = 3 pady = 1 elif len(histlist) == 4: width = 1200 height = 1000 padx = 2 pady = 2 elif len(histlist) == 6 or len(histlist) == 5: width = 1600 height = 1000 padx = 3 pady = 2 else: raise ValueError('histlist of size ' + str(len(histlist)) + ' not currently supported') tdrstyle.setTDRStyle() myCan = TCanvas(name, name, width, height) myCan.Divide(padx, pady) # Just some colors that I think work well together and a bunch of empty lists for storage if needed default_colors = [kRed, kMagenta, kGreen, kCyan, kBlue] if len(colors) == 0: colors = default_colors stacks = [] tot_hists = [] legends = [] mains = [] subs = [] pulls = [] logString = '' # For each hist/data distribution for hist_index, hist in enumerate(histlist): # Grab the pad we want to draw in myCan.cd(hist_index + 1) # if len(histlist) > 1: thisPad = myCan.GetPrimitive(name + '_' + str(hist_index + 1)) thisPad.cd() # If this is a TH2, just draw the lego if hist.ClassName().find('TH2') != -1: if logy == True: gPad.SetLogy() gPad.SetLeftMargin(0.2) hist.GetXaxis().SetTitle(xtitle) hist.GetYaxis().SetTitle(ytitle) hist.GetXaxis().SetTitleOffset(1.5) hist.GetYaxis().SetTitleOffset(2.3) hist.GetZaxis().SetTitleOffset(1.8) if len(titles) > 0: hist.SetTitle(titles[hist_index]) hist.Draw('lego') if len(bkglist) > 0: print( 'ERROR: It seems you are trying to plot backgrounds with data on a 2D plot. This is not supported since there is no good way to view this type of distribution.' ) # Otherwise it's a TH1 hopefully else: alpha = 1 if dataOff: alpha = 0 hist.SetLineColorAlpha(kBlack, alpha) if 'pe' in datastyle.lower(): hist.SetMarkerColorAlpha(kBlack, alpha) hist.SetMarkerStyle(8) if 'hist' in datastyle.lower(): hist.SetFillColorAlpha(0, 0) # If there are no backgrounds, only plot the data (semilog if desired) if len(bkglist) == 0: hist.GetXaxis().SetTitle(xtitle) hist.GetYaxis().SetTitle(ytitle) if len(titles) > 0: hist.SetTitle(titles[hist_index]) hist.Draw(datastyle) # Otherwise... else: # Create some subpads, a legend, a stack, and a total bkg hist that we'll use for the error bars if not dataOff: mains.append( TPad(hist.GetName() + '_main', hist.GetName() + '_main', 0, 0.3, 1, 1)) subs.append( TPad(hist.GetName() + '_sub', hist.GetName() + '_sub', 0, 0, 1, 0.3)) else: mains.append( TPad(hist.GetName() + '_main', hist.GetName() + '_main', 0, 0.1, 1, 1)) subs.append( TPad(hist.GetName() + '_sub', hist.GetName() + '_sub', 0, 0, 0, 0)) legends.append(TLegend(0.65, 0.6, 0.95, 0.93)) stacks.append( THStack(hist.GetName() + '_stack', hist.GetName() + '_stack')) tot_hist = hist.Clone(hist.GetName() + '_tot') tot_hist.Reset() tot_hist.SetTitle(hist.GetName() + '_tot') tot_hist.SetMarkerStyle(0) tot_hists.append(tot_hist) # Set margins and make these two pads primitives of the division, thisPad mains[hist_index].SetBottomMargin(0.0) mains[hist_index].SetLeftMargin(0.16) mains[hist_index].SetRightMargin(0.05) mains[hist_index].SetTopMargin(0.1) subs[hist_index].SetLeftMargin(0.16) subs[hist_index].SetRightMargin(0.05) subs[hist_index].SetTopMargin(0) subs[hist_index].SetBottomMargin(0.3) mains[hist_index].Draw() subs[hist_index].Draw() # Build the stack for bkg_index, bkg in enumerate( bkglist[hist_index]): # Won't loop if bkglist is empty # bkg.Sumw2() tot_hists[hist_index].Add(bkg) bkg.SetLineColor(kBlack) if logy: bkg.SetMinimum(1e-3) if bkg.GetName().find('qcd') != -1: bkg.SetFillColor(kYellow) else: if colors[bkg_index] != None: bkg.SetFillColor(colors[bkg_index]) else: bkg.SetFillColor(default_colors[bkg_index]) stacks[hist_index].Add(bkg) legends[hist_index].AddEntry(bkg, bkg.GetName().split('_')[0], 'f') # Go to main pad, set logy if needed mains[hist_index].cd() # Set y max of all hists to be the same to accomodate the tallest histList = [stacks[hist_index], tot_hists[hist_index], hist] yMax = histList[0].GetMaximum() maxHist = histList[0] for h in range(1, len(histList)): if histList[h].GetMaximum() > yMax: yMax = histList[h].GetMaximum() maxHist = histList[h] for h in histList: h.SetMaximum(yMax * 1.1) if logy == True: h.SetMaximum(yMax * 10) mLS = 0.06 # Now draw the main pad data_leg_title = hist.GetTitle() if len(titles) > 0: hist.SetTitle(titles[hist_index]) hist.SetTitleOffset(1.5, "xy") hist.GetYaxis().SetTitle('Events') hist.GetYaxis().SetLabelSize(mLS) hist.GetYaxis().SetTitleSize(mLS) if logy == True: hist.SetMinimum(1e-3) hist.Draw(datastyle) stacks[hist_index].Draw('same hist') # Do the signals if len(signals) > 0: signals[hist_index].SetLineColor(kBlue) signals[hist_index].SetLineWidth(2) if logy == True: signals[hist_index].SetMinimum(1e-3) legends[hist_index].AddEntry( signals[hist_index], signals[hist_index].GetName().split('_')[0], 'L') signals[hist_index].Draw('hist same') tot_hists[hist_index].SetFillColor(kBlack) tot_hists[hist_index].SetFillStyle(3354) tot_hists[hist_index].Draw('e2 same') # legends[hist_index].Draw() if not dataOff: legends[hist_index].AddEntry(hist, 'data', datastyle) hist.Draw(datastyle + ' same') gPad.RedrawAxis() # Draw the pull subs[hist_index].cd() # Build the pull pulls.append(Make_Pull_plot(hist, tot_hists[hist_index])) pulls[hist_index].SetFillColor(kBlue) pulls[hist_index].SetTitle(";" + hist.GetXaxis().GetTitle() + ";(Data-Bkg)/#sigma") pulls[hist_index].SetStats(0) LS = .13 pulls[hist_index].GetYaxis().SetRangeUser(-2.9, 2.9) pulls[hist_index].GetYaxis().SetTitleOffset(0.4) pulls[hist_index].GetXaxis().SetTitleOffset(0.9) pulls[hist_index].GetYaxis().SetLabelSize(LS) pulls[hist_index].GetYaxis().SetTitleSize(LS) pulls[hist_index].GetYaxis().SetNdivisions(306) pulls[hist_index].GetXaxis().SetLabelSize(LS) pulls[hist_index].GetXaxis().SetTitleSize(LS) pulls[hist_index].GetXaxis().SetTitle(xtitle) pulls[hist_index].GetYaxis().SetTitle("(Data-Bkg)/#sigma") pulls[hist_index].Draw('hist') if logy == True: mains[hist_index].SetLogy() CMS_lumi.CMS_lumi(thisPad, 4, 11) if rootfile: myCan.Print(tag + 'plots/' + name + '.root', 'root') else: myCan.Print(tag + 'plots/' + name + '.png', 'png')
#------------------------------------------------------------------ #Script to combine the plots from all the Sets and fit the tau mass #------------------------------------------------------------------ import ROOT from ROOT import RooFit from ROOT import TFile, TH1F, TLine, TCanvas from ROOT import RooRealVar, RooCBShape, RooGaussian, RooAddPdf, RooDataHist, RooArgSet, RooArgList, RooAbsArg from tdrstyle import setTDRStyle setTDRStyle() # use cms tdrstyle c = TCanvas("c", "Tau Mass Fit", 1600, 1200) #--------------- # Get histograms #--------------- rootFile = TFile("LOCAL_ANALYSIS_threemu_MC_merged.root") h1 = rootFile.Get("threemu_default_TauMassMC2") h2 = rootFile.Get("threemu_default_TauMassMC3") h3 = rootFile.Get("threemu_default_TauMassMC4") h0 = TH1F("h0", "Tau Mass", 40, 1.5, 1.9) h0.Add(h1) h0.Add(h2) h0.Add(h3) #------------- # Setup model #-------------
def main(): # ROOT.gROOT.SetBatch(True) sys.path.insert(0, '~/CMSstyle/') import tdrstyle tdrstyle.setTDRStyle() # ROOT.LoadMacro("~/bbH/atlasstyle-00-03-05/AtlasStyle.C") # SetAtlasStyle() gStyle.SetStatColor(0) gStyle.SetCanvasColor(0) gStyle.SetPadColor(0) gStyle.SetPadBorderMode(0) gStyle.SetCanvasBorderMode(0) gStyle.SetFrameBorderMode(0) #gStyle.SetOptStat(1110) gStyle.SetOptStat(0) gStyle.SetStatH(0.2) gStyle.SetStatW(0.2) gStyle.SetStatX(0.99) gStyle.SetTitleColor(1) gStyle.SetTitleFillColor(0) # gStyle.SetTitleY(1.) # gStyle.SetTitleX(.15) gStyle.SetTitleBorderSize(0) gStyle.SetPadTickX(1) gStyle.SetPadTickY(1) gStyle.SetPalette(1) # gStyle.SetMarkerStyle(20); # gStyle.SetMarkerSize(2); # gStyle.SetLineWidth(2); # gStyle.SetLineStyleString(2,"[12 12]"); # postscript dashes v_samples = ["WH-1000", "WH-1400", "WH-2000"] prefix = "WHAnalysis." directories = ["VWindow_NoTau21_SubjetPreTag", "VWindow_NoTau21_SubjetNoTag", "VWindow_NoTau21_SubjetSingleTagIncl", "VWindow_NoTau21_SubjetSingleTagExcl", "VWindow_NoTau21_SubjetDoubleTag", "VWindow_Tau21LP_SubjetPreTag", "VWindow_Tau21LP_SubjetNoTag", "VWindow_Tau21LP_SubjetSingleTagIncl", "VWindow_Tau21LP_SubjetSingleTagExcl", "VWindow_Tau21LP_SubjetDoubleTag", "WWindow_Tau21LP_SubjetPreTag", "WWindow_Tau21LP_SubjetNoTag", "WWindow_Tau21LP_SubjetSingleTagIncl", "WWindow_Tau21LP_SubjetSingleTagExcl", "WWindow_Tau21LP_SubjetDoubleTag", "ZWindow_Tau21LP_SubjetPreTag", "ZWindow_Tau21LP_SubjetNoTag", "ZWindow_Tau21LP_SubjetSingleTagIncl", "ZWindow_Tau21LP_SubjetSingleTagExcl", "ZWindow_Tau21LP_SubjetDoubleTag", "VWindow_Tau21HP_SubjetPreTag", "VWindow_Tau21HP_SubjetNoTag", "VWindow_Tau21HP_SubjetSingleTagIncl", "VWindow_Tau21HP_SubjetSingleTagExcl", "VWindow_Tau21HP_SubjetDoubleTag", "WWindow_Tau21HP_SubjetPreTag", "WWindow_Tau21HP_SubjetNoTag", "WWindow_Tau21HP_SubjetSingleTagIncl", "WWindow_Tau21HP_SubjetSingleTagExcl", "WWindow_Tau21HP_SubjetDoubleTag", "ZWindow_Tau21HP_SubjetPreTag", "ZWindow_Tau21HP_SubjetNoTag", "ZWindow_Tau21HP_SubjetSingleTagIncl", "ZWindow_Tau21HP_SubjetSingleTagExcl", "ZWindow_Tau21HP_SubjetDoubleTag"] histNames = ["cutflow", "vjet_pt", "vjet_eta", "vjet_phi", "vjet_m", "vjet_mpruned", "vjet_tau1", "vjet_tau2", "vjet_tau3", "vjet_tau21", "vjet_tau31", "vjet_tau32", "vjet_nSubjets", "vjet_nTaggedSubjets", "vjet_subjet0_csv", "vjet_subjet1_csv", "hjet_pt", "hjet_eta", "hjet_phi", "hjet_m", "hjet_mpruned", "hjet_tau1", "hjet_tau2", "hjet_tau3", "hjet_tau21", "hjet_tau31", "hjet_tau32", "hjet_nSubjets", "hjet_nTaggedSubjets", "hjet_subjet0_csv", "hjet_subjet1_csv", "jets_deta", "jets_dphi", "jets_dr", "dijet_pt", "dijet_eta", "dijet_phi", "dijet_m", "dijet_template_m", ] _files = {} for sample in v_samples: inFile = "../AnalysisOutput/%s%s.root" %(prefix,sample) print "Opening "+inFile _files[sample]=TFile.Open(inFile,"READ") canvasList = [] for i in range(len(histNames)): for direct in directories: hists = {} for sample in v_samples: hist = _files[sample].Get("%s/%s" %(direct,histNames[i]) ) print "names: %s" %("%s/%s" %(direct,histNames[i])) hists["%s_%s_%s" %(sample, direct, histNames[i])] = hist.Clone("%s_%s_%s" %(sample, direct, histNames[i])) hist.Delete() # scale to unity hists["%s_%s_%s" %(sample, direct, histNames[i])].Scale(1./(hists["%s_%s_%s" %(sample, direct, histNames[i])].Integral(0, hists["%s_%s_%s" %(sample, direct, histNames[i])].GetNbinsX()+1))) MakeRatioPlot(hists["%s_%s_%s" %(v_samples[0], direct, histNames[i])], hists["%s_%s_%s" %(v_samples[1], direct, histNames[i])], "ratio_%s_%s" %(direct, histNames[i])) for sample in v_samples: hists["%s_%s_%s" %(sample, direct, histNames[i])].Delete() for i in range(len(histNamesAK8)): for direct in directories: if (direct.find("AK8") >= 0): hists = {} for sample in v_samples: hist = _files[sample].Get("%s/%s" %(direct,histNamesAK8[i]) ) print "names: %s" %("%s/%s" %(direct,histNamesAK8[i])) hists["%s_%s_%s" %(sample, direct, histNamesAK8[i])] = hist.Clone("%s_%s_%s" %(sample, direct, histNamesAK8[i])) hist.Delete() # scale to unity hists["%s_%s_%s" %(sample, direct, histNamesAK8[i])].Scale(1./(hists["%s_%s_%s" %(sample, direct, histNamesAK8[i])].Integral(0, hists["%s_%s_%s" %(sample, direct, histNamesAK8[i])].GetNbinsX()+1))) canvasList.append(MakeRatioPlot(hists["%s_%s_%s" %(v_samples[0], direct, histNamesAK8[i])], hists["%s_%s_%s" %(v_samples[1], direct, histNamesAK8[i])], "ratio_%s_%s" %(direct, histNamesAK8[i]))) for sample in v_samples: hists["%s_%s_%s" %(sample, direct, histNamesAK8[i])].Delete() # print "Filling summary canvas" # print canvasList # counter = 0 # for canvas in canvasList: # if (counter == 0): # canvas.Print("plots/all.pdf[") # elif (counter == len(canvasList)-1): # canvas.Print("plots/all.pdf]") # print "last" # else: # canvas.Print("plots/all.pdf") # counter += 1 c2 = TCanvas("empty", "empty", 500, 600) c2.Print("plots/all.pdf]")
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 DrawPU(canvas, f, l1seed, count, key=None): list_fromDrawPU = [ ] # Making Python objects used here known within the DrawL1 function df = f[(f.L1Seed == l1seed)] #print "\n Dataframe:\n", df for i in range(0, len(pubins) - 1): pumap[pubins[i]] = [] pumap[pubins[i]].append(df[np.logical_and( df.PileUp >= pubins[i], df.PileUp < pubins[i + 1])].Fired0.sum()) pumap[pubins[i]].append(df[np.logical_and( df.PileUp >= pubins[i], df.PileUp < pubins[i + 1])].Total.sum()) x = [] y = [] yerr = [] for k, v in pumap.items(): if v[1] != 0: x.append(k) if unit == "Hz": y.append(float(v[0]) / v[1] * freq * nBunches) if (isReweight): w = ExtractPileUpWeight(k) yerr.append( math.sqrt(float(v[0]) * w) / v[1] * freq * nBunches) else: yerr.append( math.sqrt(float(v[0])) / v[1] * freq * nBunches) if unit == "kHz": y.append(float(v[0]) / v[1] * freq * nBunches / 1000) if (isReweight): w = ExtractPileUpWeight(k) yerr.append( math.sqrt(float(v[0]) * w) / v[1] * freq * nBunches / 1000) else: yerr.append( math.sqrt(float(v[0])) / v[1] * freq * nBunches / 1000) ## Draw the plot graph = ROOT.TGraphErrors(len(x)) list_fromDrawPU.append(graph) for i, (xx, yy, yee) in enumerate(zip(x, y, yerr)): graph.SetPoint(i, xx, yy) graph.SetPointError(i, 0, yee) graph.SetMarkerStyle(20 + count) graph.SetMarkerSize(1.5) graph.SetMarkerColor(1 + count) graph.SetLineColor(1 + count) graph.SetLineWidth(2) tdrstyle.setTDRStyle() canvas.cd() if count == 0: graph.Draw("AP") graph.GetXaxis().SetTitle("PileUp") graph.GetXaxis().SetLimits(plot_min, maxx) graph.GetYaxis().SetRangeUser(0, maxy) graph.GetYaxis().SetTitle("Rate (nBunches = %d) [%s]" % (nBunches, unit)) else: graph.Draw("P") leg.AddEntry(graph, l1seed, "p") result_ptr = graph.Fit(fitname, "SQ", "", fit_min, fit_max) checkVariable = result_ptr.Get( ) # TFitResult * TFitResultPtr::Get ( ) const => Return contained pointer if (not (checkVariable)): print("TFitResult is empty, returned null pointer: checkVariable =", checkVariable) else: error_vec = result_ptr.GetConfidenceIntervals() print("error vec size = %d, fitted PU = %d" % (error_vec.size(), fit_max - fit_min + 1)) if (fitname == "pol4" or fitname == "expo"): f2 = graph.GetFunction(fitname).Clone() else: f2 = graph.GetFunction("fitname").Clone() list_fromDrawPU.append(f2) f2.SetLineColor(1 + count) f2.SetLineWidth(2) f2.SetRange(plot_min, fit_min) f2.SetLineStyle(5) #minChi = f2.GetChisquare() / f2.GetNDF() f2.Draw("same") f2_2 = f2.Clone("dashline2") list_fromDrawPU.append(f2_2) f2_2.SetRange(fit_max, plot_max) f2_2.Draw("same") key = "" if key is not None: tex = ROOT.TLatex(0.2, 0.85, key) tex.SetNDC() tex.SetTextFont(61) tex.SetTextSize(0.055) tex.SetTextColor(ROOT.kGreen + 2) tex.SetLineWidth(2) tex.Draw() return list_fromDrawPU
# ofile.write("Events after minDPhi cut : %.2f\n" %(h.GetBinContent(9)) ) # if(h.GetBinContent(0)!=0):ofile.write("Selection efficiency : %.2f\n" %(h.GetBinContent(9)/h.GetBinContent(0)) ) #elif(channel == "fullhadronic"): # ofile.write("Events after minDPhi cut : %.2f\n" %(h.GetBinContent(7)) ) # if(h.GetBinContent(0)!=0):ofile.write("Selection efficiency : %.2f\n" %(h.GetBinContent(7)/h.GetBinContent(0)) ) ROOT.gROOT.Reset(); ROOT.gROOT.SetStyle('Plain') ROOT.gStyle.SetPalette(1) ROOT.gStyle.SetOptStat(0) ROOT.gROOT.SetBatch() # don't pop up canvases ROOT.TH1.SetDefaultSumw2() ROOT.TH1.AddDirectory(False) tdrstyle.setTDRStyle(); settings = {} store = [] #settings.update(plots.common.settings) #store += plots.common.store settings.update(plots.Bprime.settings) store += plots.Bprime.store if opt.channel == 'semileptonic': # Add semileptonic specific settings and plots to store settings.update(plots.semileptonic.settings) store += plots.semileptonic.store
def drawTH1(name, cmsLumi, mclist, data, x_name, y_name, doLog=False, doRatio=True, ratioRange=0.45): #leg = ROOT.TLegend(0.58,0.78,0.8,0.9) leg = ROOT.TLegend(0.71,0.68,0.88,0.91) leg.SetBorderSize(0) #leg.SetNColumns(2) leg.SetTextSize(0.029) leg.SetTextFont(42) leg.SetLineColor(0) leg.SetFillColor(0) leg.AddEntry(data,"Data","lp") hs = ROOT.THStack("hs_%s_mc"%(name), "hs_%s_mc"%(name)) hratio = mclist[0].Clone("hratio") hratio.Reset() leghist = [] for i, mc in enumerate(mclist): hnew = mc.Clone("hnew"+mc.GetName()) hnew.Sumw2(False) hs.Add(hnew) hratio.Add(mc) inversed = mclist[len(mclist)-1-i] if not any(inversed.GetTitle() == s for s in leghist): leg.AddEntry(inversed, inversed.GetTitle(), "f") leghist.append(inversed.GetTitle()) hratio.Divide(data,hratio,1.,1.,"B") tdrstyle.setTDRStyle() setDefTH1Style(data, x_name, y_name) data.SetMaximum(data.GetMaximum()*1.8) if doLog: #data.SetMaximum(10**7) data.SetMaximum(data.GetMaximum()*100) ratio_fraction = 0 if doRatio: ratio_fraction = 0.3 data.GetXaxis().SetLabelSize(0) data.GetXaxis().SetTitleSize(0) data.GetYaxis().CenterTitle() setDefTH1Style(hratio, x_name, "Data/MC") hratio.GetYaxis().SetNdivisions(5) canv = makeCanvas(name, doRatio) pads=[canv] pads = rootplotcore.divide_canvas(canv, ratio_fraction) pads[0].cd() setMargins(pads[0],doRatio) if doLog: pads[0].SetLogy() data.Draw() hs.Draw("same") data.Draw("same") data.Draw("esamex0") leg.Draw("same") pads[0].Update() if doRatio: pads[1].cd() pads[1].SetGridy() setMargins(pads[1],doRatio) hratio.SetLineColor(1) hratio.SetMarkerStyle(10) hratio.Draw("ep") hratio.SetMaximum(1.+ratioRange) hratio.SetMinimum(1.-ratioRange) for p in pads: p.RedrawAxis() p.Modified() p.Update() canv.cd() iPos = 11 if( iPos==0 ): cmsLumi.relPosX = 0.12 cmsLumi.CMS_lumi(canv, 0, iPos) canv.Modified() canv.Update() canv.SaveAs(name)
def main(): f = ROOT.TFile.Open(sys.argv[1]) t = f.Get('tree') eff_csv = ROOT.TEfficiency('h_csv', 'Highest CSV Higgs;p_{T}(V) (GeV);Efficiency', 20, 0, 500) eff_dijet = ROOT.TEfficiency('h_dijet', 'Highest Dijet Higgs;p_{T}(V) (GeV);Efficiency', 20, 0, 500) # Creating references to instance methods avoids spending time on attribute lookup in the for loop. fill_csv = eff_csv.Fill fill_dijet = eff_dijet.Fill # Preload threshold value for simplified function call. isdRMatch = functools.partial(ROOT.isdRMatch, 0.5) for i, e in enumerate(t): if i % 10000 == 0: print 'Processing event {!s}'.format(i) # Generator level selection cuts. min_GenBQuarkFromH_pt = min(e.GenBQuarkFromH_pt[0], e.GenBQuarkFromH_pt[1]) max_abs_GenBQuarkFromH_eta = max(abs(e.GenBQuarkFromH_eta[0]), abs(e.GenBQuarkFromH_eta[1])) if min_GenBQuarkFromH_pt < 20 or max_abs_GenBQuarkFromH_eta > 2.5: continue # Higgs candidate dR matching. Note that GenHiggsBoson is a PyFloatBuffer, # so it must be accessed by index as opposed to the Higgs candidate. match_csv = isdRMatch(e.GenHiggsBoson_eta[0], e.GenHiggsBoson_phi[0], e.HCSV_eta, e.HCSV_phi) fill_csv(match_csv, e.V_pt) match_dijet = isdRMatch(e.GenHiggsBoson_eta[0], e.GenHiggsBoson_phi[0], e.H_eta, e.H_phi) fill_dijet(match_dijet, e.V_pt) # Format plotting style. tdrstyle.setTDRStyle() CMS_lumi.extraText = 'Simulation' CMS_lumi.lumi_sqrtS = '13 TeV' c = ROOT.TCanvas('c', 'c', 50, 50, 800, 600) c.SetFillColor(0) c.SetBorderMode(0) c.SetFrameFillStyle(0) c.SetFrameBorderMode(0) c.SetLeftMargin(0.12) c.SetRightMargin(0.04) c.SetTopMargin(0.08) c.SetBottomMargin(0.12) c.SetTickx(0) c.SetTicky(0) eff_csv.SetLineColor(ROOT.kRed) eff_csv.SetFillColor(ROOT.kRed) eff_csv.Draw() eff_dijet.SetLineColor(ROOT.kBlue) eff_dijet.SetFillColor(ROOT.kBlue) eff_dijet.Draw('same') ROOT.gPad.Update() graph_csv = eff_csv.GetPaintedGraph() graph_dijet = eff_dijet.GetPaintedGraph() graph_csv.SetMaximum(1.3) x_axis = graph_csv.GetXaxis() line_unity = ROOT.TLine(x_axis.GetXmin(), 1, x_axis.GetXmax(), 1) line_unity.SetLineStyle(2) line_unity.Draw('same') y_axis = graph_csv.GetYaxis() y_axis.SetTitleOffset(1) legend = ROOT.TLegend(0.75, 0.18, 0.95, 0.35) legend.AddEntry(graph_csv, 'Highest CSV', 'le') legend.AddEntry(graph_dijet, 'Highest Dijet', 'le') legend.Draw('same') latex = ROOT.TLatex() latex.SetNDC() latex.SetTextFont(42) latex.SetTextAngle(0) latex.SetTextColor(ROOT.kBlack) latex.SetTextSize(0.57 * ROOT.gPad.GetTopMargin()) latex.SetTextAlign(12) latex.DrawLatex(0.78, 0.88, 'WH #rightarrow l#nu b#bar{b}') CMS_lumi.CMS_lumi(pad=c, iPeriod=0, iPosX=11) c.cd() c.Update() c.RedrawAxis() frame = c.GetFrame() frame.Draw() c.SaveAs('higgs_efficiency_WlnH.png') c.SaveAs('higgs_efficiency_WlnH.pdf') f.Close()
def drawTH1NoStack(name, cmsLumi, mclist, x_name, y_name, doLog=False): #leg = ROOT.TLegend(0.58,0.78,0.8,0.9) leg = ROOT.TLegend(0.71,0.68,0.88,0.91) leg.SetBorderSize(0) #leg.SetNColumns(2) leg.SetTextSize(0.029) leg.SetTextFont(42) leg.SetLineColor(0) leg.SetFillColor(0) leghist = [] nMax = 0. for i, mc in enumerate(mclist): mc.SetLineWidth(2) mc.Sumw2(False) mc.SetFillColor(0) if (mc.Integral() != 0): mc.Scale(1./mc.Integral()) tempMax = mc.GetMaximum() if (tempMax > nMax): nMax = tempMax inversed = mclist[len(mclist)-1-i] if not any(inversed.GetTitle() == s for s in leghist): leg.AddEntry(inversed, inversed.GetTitle(), "f") leghist.append(inversed.GetTitle()) tdrstyle.setTDRStyle() setDefTH1Style(mclist[0], x_name, y_name) mclist[0].SetMaximum(nMax*1.2) if doLog: mclist[0].SetMaximum(nMax*2) canv = makeCanvas(name, False) pads=[canv] pads[0].cd() setMargins(pads[0],False) if doLog: pads[0].SetLogy() for i, mc in enumerate(mclist): if (i==0): mc.Draw() else: mc.Draw("same") leg.Draw("same") pads[0].Update() for p in pads: p.RedrawAxis() p.Modified() p.Update() canv.cd() iPos = 11 if( iPos==0 ): cmsLumi.relPosX = 0.12 cmsLumi.CMS_lumi(canv, 0, iPos) canv.Modified() canv.Update() canv.SaveAs(name)
def getArgs() : import argparse parser = argparse.ArgumentParser() parser.add_argument("-v","--verbose",default=0,type=int,help="Print level.") parser.add_argument("-f","--inFileName",default='./VBF_sync_input.root',help="File to be analyzed.") parser.add_argument("-o","--outFileName",default='',help="File to be used for output.") parser.add_argument("-y","--year",default=2017,type=int,help="Year for data.") parser.add_argument("-l","--LTcut",default=0.,type=float,help="H_LTcut") parser.add_argument("-s","--sign",default='OS',help="Opposite or same sign (OS or SS).") return parser.parse_args() args = getArgs() nBins, xMin, xMax = 10, 0., 200. cats = { 1:'eeet', 2:'eemt', 3:'eett', 4:'mmet', 5:'mmmt', 6:'mmtt', 7:'et', 8:'mt', 9:'tt' } tdrstyle.setTDRStyle() outFileName = 'Mtt_{0:d}_{1:s}_LT{2:02d}.root'.format(args.year,args.sign,int(args.LTcut)) print("Opening {0:s} as output.".format(outFileName)) fOut = TFile( outFileName, 'recreate' ) inFileName = './MC/ZHToTauTau/ZHToTauTau.root' inFile = TFile.Open(inFileName) inFile.cd() inTree = inFile.Get("Events") nentries = inTree.GetEntries() hMC = {} for cat in cats.values()[0:6] : hName = 'h{0:s}_Mtt'.format(cat) hMC[cat] = TH1D(hName,hName,nBins,xMin,xMax)
def Plot2DPAS(hdict, outputdir="plots", outfile=0, cname="canvas", logscale=False, scale="No", lumitext="Preliminary"): # CMS style plots tdrstyle.setTDRStyle() # First do some checks on the input if outfile == 0: print "You did not pass me a root file to store the plots. I will only produce pdf files." if not os.path.isdir(outputdir): print "Output directory doesn't exist yet" print "Will create directory %s" % (outputdir) os.makedirs(outputdir) # placeholder for draw objects rootEvil = [] # Make the canvas canvas = rt.TCanvas(cname, "", 50, 50, 800, 600) CMS_lumi.lumi_8TeV = "19.7 fb^{-1}" CMS_lumi.writeExtraText = 1 CMS_lumi.extraText = lumitext iPos = 0 #11 if (iPos == 0): CMS_lumi.relPosX = 0.12 iPeriod = 2 H_ref = 600 W_ref = 800 W = W_ref H = H_ref # references for T, B, L, R T = 0.08 * H_ref B = 0.12 * H_ref L = 0.12 * W_ref R = 0.12 * W_ref canvas.SetLeftMargin(L / W) canvas.SetRightMargin(R / W) canvas.SetTopMargin(T / H) canvas.SetBottomMargin(B / H) #canvas.SetLeftMargin(0.13) #canvas.SetRightMargin(0.17) #canvas.SetBottomMargin(0.13) if logscale: canvas.SetLogz(1) canvas.cd() # Get histogram from dictionary, and plot it print "Getting histogram" h = hdict["histogram"] # Get the histogram if scale == "Yes": sf = h.Integral(0, h.GetNbinsX() + 1, 0, h.GetNbinsY() + 1) h.Scale(1. / sf) if scale == "Width": h.Scale(1, "width") if scale == "Yes": h.GetZaxis().SetTitle("A.U.") else: h.GetZaxis().SetTitle("Events") maxi = h.GetMaximum() if logscale: h.SetMaximum(maxi * 2) else: h.SetMaximum(maxi * 1.2) if scale == "Yes": h.SetMaximum(1) h.GetXaxis().SetTitle(hdict["xtitle"]) h.GetXaxis().SetTitleSize(0.05) h.GetXaxis().SetTitleOffset(1.05) h.GetXaxis().SetLabelSize(0.04) h.GetYaxis().SetTitle(hdict["ytitle"]) h.GetYaxis().SetTitleSize(0.05) h.GetYaxis().SetTitleOffset(1.05) h.GetYaxis().SetLabelSize(0.04) #h.GetZaxis().SetTitleSize(0.05) #h.GetZaxis().SetTitleOffset(1.1) #h.GetZaxis().SetLabelSize(0.04) h.SetTitle(hdict["title"]) drawoption = hdict["drawoption"] palette = hdict["palette"] if "colz" in drawoption and palette == "SMS": print "change color palette" SetColorPaletteSMS() if "colz" in drawoption and palette == "2DRatio": SetColorPalette2DRatio() rootEvil.append(h.DrawClone(drawoption)) print "Drew histogram" print hdict["name"] if hdict["name"] != "": t = '#scale[1.1]{%s}' % (hdict["name"]) if len(hdict["name"]) > 20: tex = rt.TLatex(0.45, 0.82, t) else: tex = rt.TLatex(0.6, 0.82, t) tex.SetNDC() #tex.SetFillColor(kWhite) tex.Draw("same") canvas.cd() CMS_lumi.CMS_lumi(canvas, iPeriod, iPos) canvas.SaveAs(outputdir + "/" + cname + ".pdf") if outfile != 0: outfile.cd() canvas.Write() canvas.Close()
def Plot1(hs, savename, logy=0, norm=0): #set the tdr style tdrstyle.setTDRStyle() H_ref = 600 W_ref = 800 W = W_ref H = H_ref # references for T, B, L, R T = 0.08 * H_ref B = 0.12 * H_ref L = 0.12 * W_ref R = 0.04 * W_ref canvas = rt.TCanvas("c2", "c2", 50, 50, W, H) canvas.SetLogy(logy) canvas.SetFillColor(0) canvas.SetBorderMode(0) canvas.SetFrameFillStyle(0) canvas.SetFrameBorderMode(0) canvas.SetLeftMargin(L / W) canvas.SetRightMargin(R / W) canvas.SetTopMargin(T / H) canvas.SetBottomMargin(B / H) canvas.SetTickx(0) canvas.SetTicky(0) xAxis = hs.GetXaxis() xAxis.SetNdivisions(6, 5, 0) yAxis = hs.GetYaxis() yAxis.SetNdivisions(6, 5, 0) yAxis.SetTitleOffset(.9) if norm: yAxis.SetTitle('Normalized Events') if norm == 1: if hs.Integral() != 0: hs.Scale(1. / hs.Integral()) colorind = [ '#1de41a', '#0000ff', '#ff33ff', '#286ba6', '#b86637', '#af4a4d', '#a39d4e' ] color = rt.TColor.GetColorTransparent(rt.TColor.GetColor(colorind[1]), 0.5) hs.SetMarkerColor(color) hs.SetMarkerSize(3) hs.SetLineColor(1) hs.SetLineWidth(3) hs.Draw("lp") canvas.cd() canvas.Update() canvas.Modified() canvas.RedrawAxis() #update the canvas to draw the legend canvas.Update() canvas.SaveAs(savename + '.png')
def PlotDataMCPAS(hdictlist_bg, hdict_data, hdictlist_sig=0, legdict=0, outputdir="plots", outfile=0, cname="canvas", plotinfo="Selection X", ratiotitle="ratio", logscale=False, scale="No", scalefactor=1, intlumi=19.7, style="CMS"): # CMS style plots if style == "CMS": tdrstyle.setTDRStyle() # First do some checks on the input if outfile == 0: print "You did not pass me a root file to store the plots. I will only produce pdf files." if not os.path.isdir(outputdir): print "Output directory doesn't exist yet. \nWill create directory %s" % ( outputdir) os.makedirs(outputdir) # Get clones of all the mc histograms and put them in a list hQCD_index = -1 # will need this if we want to scale QCD only histos = [] for i, hdict in enumerate(hdictlist_bg): # first check that the histogram exists if not hdict["histogram"]: print "Histogram for sample", hdict[ "name"], "and canvas", cname, "doesn't exist, will stop making this plot now" return h = hdict["histogram"].Clone() h.Sumw2() h.SetFillColor(hdict["color"]) h.SetLineColor(hdict["color"]) h.GetYaxis().SetTitle(hdict["ytitle"]) h.GetXaxis().SetTitle(hdict["xtitle"]) h.SetTitle(hdict["title"]) histos.append(h) if "QCD" in hdict["name"]: hQCD_index = i # Get data histogram hdata = 0 if hdict_data == 0: print "Will make plots without data" else: if not hdict_data["histogram"]: print hdict[ "name"], "doesn't exist, will stop making this plot now" return hdata = hdict_data["histogram"].Clone() hdata.Sumw2() hdata.SetMarkerStyle(hdict_data["markerstyle"]) hdata.SetLineColor(hdict_data["color"]) hdata.GetYaxis().SetTitle(hdict_data["ytitle"]) hdata.SetTitle(hdict_data["title"]) # Get signal histograms hsignal = [] if hdictlist_sig != 0: for hdict in hdictlist_sig: if not hdict["histogram"]: print hdict[ "name"], "doesn't exist, will stop making this plot now" return h = hdict["histogram"].Clone() h.Sumw2() h.SetFillColor(hdict["color"]) h.SetLineColor(hdict["color"]) hsignal.append(h) # make a stack of all the mc, will use the reverse order of the list mc = rt.THStack() for h in reversed(histos): mc.Add(h, "hist") for h in hsignal: mc.Add(h, "hist") # make the total mc histogram, used for the ratio plot htotal = histos[0].Clone() for h in histos[1:]: htotal.Add(h) # scale MC to data if required if scale == "Yes" and hdata != 0: sf = scalefactor if sf == 1: # we should rescale to match data mc_int = htotal.Integral(0, htotal.GetNbinsX() + 1) if mc_int == 0: mc_int = 1. data_int = hdata.Integral() sf = data_int / mc_int for h in histos: h.Scale(sf) print "Scaled all histograms by factor", sf # Scale everything according to the bin width if scale == "Width": for h in histos: h.Scale(scalefactor, "width") if hdata != 0: hdata.Scale(scalefactor, "width") for h in hsignal: h.Scale(scalefactor, "width") print "Will plot per bin width" # scale only QCD to match data in the first non-empty bin if scale == "QCD" and hdata != 0: sf = scalefactor if sf == 1: # find first non-empty bin first_bin = 0 for b in range(hdata.GetNbinsX()): if hdata.GetBinContent(b + 1) > 0: first_bin = b + 1 break # compute the scale factor if histos[hQCD_index].GetBinContent(first_bin) != 0: sf = (hdata.GetBinContent(first_bin) - htotal.GetBinContent(first_bin) + histos[hQCD_index].GetBinContent(first_bin) ) / histos[hQCD_index].GetBinContent(first_bin) histos[hQCD_index].Scale(sf) print "Scaled QCD histogram by factor", sf if scale != "No": # we scaled some histograms, will need to remake htotal htotal = histos[0].Clone() for h in histos[1:]: htotal.Add(h) # make the legend legend = rt.TLegend(0.63, 0.4, 0.87, 0.8, "") if legdict != 0: legend = rt.TLegend(legdict["xmin"], legdict["ymin"], legdict["xmax"], legdict["ymax"], legdict["title"]) legend.SetNColumns(legdict["ncolumns"]) legend.SetFillColor(0) legend.SetBorderSize(0) if hdata != 0: legend.AddEntry(hdata, " data (" + str(intlumi) + "/fb)", "epl") for i, h in enumerate(histos): if hdictlist_bg[i]["appear in legend"]: legend.AddEntry(h, hdictlist_bg[i]["name"], "f") for i, h in enumerate(hsignal): if hdictlist_sig[i]["appear in legend"]: legend.AddEntry(h, hdictlist_sig[i]["name"], "f") # Get the maximum of the histograms, so that we can set the Y-axis range maxi = 0 if hdata != 0: hdata.GetMaximum() if htotal.GetMaximum() > maxi: maxi = htotal.GetMaximum() # Make the canvas, which will have two pads if we have data, and only one if there is no data canvas = rt.TCanvas(cname, "", 50, 50, 800, 600) canvas.cd() pad1 = 0 if hdata != 0: pad1 = rt.TPad("pad1", "", 0, 0.25, 1, 1) pad1.SetBottomMargin(0) pad1.SetRightMargin(0.03) pad1.SetLeftMargin(0.1) pad1.SetTopMargin(0.1) if logscale: pad1.SetLogy(1) pad1.Draw() pad1.cd() else: pad1 = rt.TPad("pad1", "", 0, 0, 1, 1) if logscale: pad1.SetLogy(1) pad1.SetTopMargin(0.08) pad1.SetBottomMargin(0.12) pad1.SetLeftMargin(0.12) pad1.Draw() pad1.cd() if hdata != 0: hdata.GetYaxis().SetTitleSize(0.06) hdata.GetYaxis().SetTitleOffset(0.8) hdata.GetYaxis().SetLabelSize(0.055) hdata.SetMaximum(2. * maxi) if logscale: hdata.SetMaximum(5. * maxi) hdata.SetMinimum(0.007) hdata.Draw("EP") else: mc.Draw() mc.SetTitle(hdictlist_bg[0]["title"]) mc.GetYaxis().SetTitleSize(0.05) mc.GetYaxis().SetTitleOffset(1) mc.GetYaxis().SetLabelSize(0.045) mc.GetXaxis().SetTitleSize(0.05) mc.GetXaxis().SetTitleOffset(1) mc.GetXaxis().SetLabelSize(0.045) mc.GetYaxis().SetTitle(hdictlist_bg[0]["ytitle"]) mc.GetXaxis().SetTitle(hdictlist_bg[0]["xtitle"]) mc.SetMaximum(1.5 * maxi) if logscale: mc.SetMaximum(5. * maxi) mc.SetMinimum(0.007) mc.Draw("same") mc.Draw("axis same") if hdata != 0: hdata.Draw("EPsame") legend.Draw("same") t = '#scale[1.1]{%s}' % (plotinfo) tex = rt.TLatex() tex.SetNDC() if len(plotinfo) > 20: tex.DrawLatex(0.42, 0.82, t) else: tex.DrawLatex(0.65, 0.82, t) #tex.SetNDC(); #tex.DrawLatex("same"); # Make the second pad, with the ratios; only if hdata!=0 if hdata != 0: canvas.cd() pad2 = rt.TPad("pad2", "", 0, 0, 1, 0.25) pad2.SetBottomMargin(0.35) #0.25 pad2.SetTopMargin(0) #0.05 pad2.SetLeftMargin(0.1) pad2.SetRightMargin(0.03) pad2.SetGridy(1) pad2.Draw() pad2.cd() ratio = rt.TH1D() ratio = hdata.Clone() ratio.Divide(htotal) ratio.SetTitle("") ratio.SetName("histoRatio") ratio.GetYaxis().SetRangeUser(0, 2.2) ratio.GetYaxis().SetNdivisions(4, 8, 0) ratio.GetYaxis().SetLabelSize(0.15) ratio.GetYaxis().SetTitleSize(0.18) ratio.GetYaxis().SetTitle(ratiotitle) ratio.GetYaxis().SetTitleOffset(0.22) ratio.GetXaxis().SetLabelSize(0.15) ratio.GetXaxis().SetTitleSize(0.18) ratio.GetXaxis().SetTitleOffset(0.8) ratio.GetXaxis().SetTickLength(0.1) ratio.GetXaxis().SetTitle(hdict_data["xtitle"]) ratio.SetStats(0) ratio.Draw("pe") rt.SetOwnership(pad1, False) # to avoid seg fault rt.SetOwnership(pad2, False) # to avoid seg fault canvas.cd() if style == "CMS": CMS_lumi.lumi_8TeV = "19.7 fb^{-1}" CMS_lumi.writeExtraText = 1 CMS_lumi.extraText = "Preliminary" iPos = 0 #11 if (iPos == 0): CMS_lumi.relPosX = 0.12 iPeriod = 2 CMS_lumi.CMS_lumi(pad1, iPeriod, iPos) canvas.cd() canvas.SaveAs(outputdir + "/" + cname + ".pdf") if outfile != 0: outfile.cd() canvas.Write() canvas.Close()
denominator.Sumw2() numeratorJet.Sumw2() denominatorJet.Sumw2() print "Events: ", NEvt, ", with Muon: ", NEvtMuon, ", with good MT: ", NEvtMuonMT, ", with tau: ", NEvtMuonMTTau print "Matched Taus: L1: ", NMatchedL1, ", L2: ", NMatchedL2, ", L2.5: ", NMatchedL2p5, ", L3Full: ", NMatchedL3Full, ", L3Reg: ", NMatchedL3Reg return denominator, numeratorL1, numeratorL2, numeratorL2p5, numeratorL3Full, numeratorL3Reg, numeratorL1L2, numeratorL1L2L2p5, numeratorL1_HLTFull, numeratorL1_HLTReg, deltaZTauTau, mTH, numeratorJet, denominatorJet, invM, invMSel, nTaus # running the macro # just to avoid opening windows ROOT.gROOT.SetBatch() setTDRStyle() frame = ROOT.TH1F("frame","",len(xbin)-1,xbins) frame.SetMinimum(0.01) frame.SetMaximum(1.01) ### input files ## Run2012A dataset = "Whole2012" folder = "dcap://grid-dcap.physik.rwth-aachen.de/pnfs/physik.rwth-aachen.de/cms/store/user/bkargoll/TriggerEfficiencies/SingleMuDataset/MuTauSkim/HLTRerunDoubleTauForMichal/Run2012A/" files = ["hltDiTauForMichal_offlineSelectedMuTau_6_1_KHx.root", "hltDiTauForMichal_offlineSelectedMuTau_4_1_Q0W.root", "hltDiTauForMichal_offlineSelectedMuTau_1_1_grf.root", "hltDiTauForMichal_offlineSelectedMuTau_5_1_B2E.root", "hltDiTauForMichal_offlineSelectedMuTau_8_1_dOY.root", "hltDiTauForMichal_offlineSelectedMuTau_9_1_auc.root", "hltDiTauForMichal_offlineSelectedMuTau_2_1_6NG.root",
def plot(limitInfo, era, outDir, label, lumiText, suffix): l_xs = limitInfo.l_xs l_stop1_m = limitInfo.l_stop1_m l_neutralino1_m = limitInfo.l_neutralino1_m l_observedLimit = copy.deepcopy(limitInfo.l_observedLimit) l_observedLimit_1sigLwr = copy.deepcopy(limitInfo.l_observedLimit_1sigLwr) l_observedLimit_1sigUpr = copy.deepcopy(limitInfo.l_observedLimit_1sigUpr) l_expectedLimit = copy.deepcopy(limitInfo.l_expectedLimit) l_expectedLimit_1sigLwr = copy.deepcopy(limitInfo.l_expectedLimit_1sigLwr) l_expectedLimit_1sigUpr = copy.deepcopy(limitInfo.l_expectedLimit_1sigUpr) l_expectedLimit_2sigLwr = copy.deepcopy(limitInfo.l_expectedLimit_2sigLwr) l_expectedLimit_2sigUpr = copy.deepcopy(limitInfo.l_expectedLimit_2sigUpr) # Exclude the problematic low mass points #for iPoint in range(0, len(l_observedLimit)) : # # if (abs(l_observedLimit[iPoint] - l_expectedLimit[iPoint]) > 100) : # # l_observedLimit[iPoint] = 0 # graph_observedLimit = ROOT.TGraph2D(label + "_obs", label, len(l_stop1_m), array.array("d", l_stop1_m), array.array("d", l_neutralino1_m), array.array("d", l_observedLimit)) graph_observedLimit_1sigLwr = ROOT.TGraph2D( label + "_obs1lwr", label, len(l_stop1_m), array.array("d", l_stop1_m), array.array("d", l_neutralino1_m), array.array("d", l_observedLimit_1sigLwr)) graph_observedLimit_1sigUpr = ROOT.TGraph2D( label + "_obs1upr", label, len(l_stop1_m), array.array("d", l_stop1_m), array.array("d", l_neutralino1_m), array.array("d", l_observedLimit_1sigUpr)) graph_expectedLimit = ROOT.TGraph2D(label + "_exp", label, len(l_stop1_m), array.array("d", l_stop1_m), array.array("d", l_neutralino1_m), array.array("d", l_expectedLimit)) graph_expectedLimit_1sigLwr = ROOT.TGraph2D( label + "_exp1lwr", label, len(l_stop1_m), array.array("d", l_stop1_m), array.array("d", l_neutralino1_m), array.array("d", l_expectedLimit_1sigLwr)) graph_expectedLimit_1sigUpr = ROOT.TGraph2D( label + "_exp1upr", label, len(l_stop1_m), array.array("d", l_stop1_m), array.array("d", l_neutralino1_m), array.array("d", l_expectedLimit_1sigUpr)) graph_expectedLimit_2sigLwr = ROOT.TGraph2D( label + "_exp2lwr", label, len(l_stop1_m), array.array("d", l_stop1_m), array.array("d", l_neutralino1_m), array.array("d", l_expectedLimit_2sigLwr)) graph_expectedLimit_2sigUpr = ROOT.TGraph2D( label + "_exp2upr", label, len(l_stop1_m), array.array("d", l_stop1_m), array.array("d", l_neutralino1_m), array.array("d", l_expectedLimit_2sigUpr)) # Revert back to the original values #l_observedLimit = copy.deepcopy(limitInfo.l_observedLimit) for iMass in range(0, len(l_stop1_m)): if ([l_stop1_m[iMass], l_neutralino1_m[iMass]] not in [[1000, 1]]): continue print l_stop1_m[iMass], l_neutralino1_m[iMass], l_observedLimit[iMass] graph_observedLimit.SetNpx(nInterpolate) graph_observedLimit.SetNpy(nInterpolate) graph_observedLimit_1sigLwr.SetNpx(nInterpolate) graph_observedLimit_1sigLwr.SetNpy(nInterpolate) graph_observedLimit_1sigUpr.SetNpx(nInterpolate) graph_observedLimit_1sigUpr.SetNpy(nInterpolate) graph_expectedLimit.SetNpx(nInterpolate) graph_expectedLimit.SetNpy(nInterpolate) graph_expectedLimit_1sigLwr.SetNpx(nInterpolate) graph_expectedLimit_1sigLwr.SetNpy(nInterpolate) graph_expectedLimit_1sigUpr.SetNpx(nInterpolate) graph_expectedLimit_1sigUpr.SetNpy(nInterpolate) graph_expectedLimit_2sigLwr.SetNpx(nInterpolate) graph_expectedLimit_2sigLwr.SetNpy(nInterpolate) graph_expectedLimit_2sigUpr.SetNpx(nInterpolate) graph_expectedLimit_2sigUpr.SetNpy(nInterpolate) #graph_observedLimit_1sigUpr = graph_observedLimit.Clone() #graph_observedLimit_1sigUpr.SetName(label+"_obs1upr") #graph_observedLimit_1sigUpr.SetTitle(label) # #iPoint = 0 # #print "*"*50, graph_observedLimit_1sigUpr.GetN() # #while(iPoint < graph_observedLimit_1sigUpr.GetN()) : # # x = graph_observedLimit_1sigUpr.GetX()[iPoint] # y = graph_observedLimit_1sigUpr.GetY()[iPoint] # z = graph_observedLimit_1sigUpr.GetZ()[iPoint] # # #print x, y, z # # #print limitInfo.fInter_xs(x), limitInfo.fInter_xs_lwr(x) # # graph_observedLimit_1sigUpr.SetPoint( # iPoint, # x, y, # z * limitInfo.fInter_xs(x) / limitInfo.fInter_xs_lwr(x) # ) # # iPoint += 1 # Observed graph_observedLimit.Print() #print l_observedLimit #print graph_observedLimit.GetMinimum(), graph_observedLimit.GetMaximum() #print ROOT.TMath.MinElement(graph_observedLimit.GetN(), graph_observedLimit.GetZ()), ROOT.TMath.MaxElement(graph_observedLimit.GetN(), graph_observedLimit.GetZ()) #print graph_expectedLimit.GetMinimum(), graph_expectedLimit.GetMaximum() #print graph_observedLimit.GetXmax(), graph_observedLimit.GetYmax() #print graph_observedLimit.GetContourList(2.0) #print graph_observedLimit.GetZ() #print graph_observedLimit.GetN(), len(l_observedLimit) #for i in range(0, graph_observedLimit.GetN()) : # # print "%0.2f, " %(graph_observedLimit.GetZ()[i]-limitInfo.l_observedLimit[i]), # #print "" contourList_observedLimit = getContourListFromGraph( graph_observedLimit, 1.0, nSmooth=nSmooth_central_obs) #contourList_observedLimit = graph_observedLimit.GetContourList(1.0) #contourList_observedLimit = graph_expectedLimit.GetContourList(1.0) #print graph_observedLimit.GetContourList(1.0) #print graph_observedLimit #print graph_observedLimit.GetN() print "contourList_observedLimit: No. of contours: %d \n" % ( contourList_observedLimit.GetSize()) contour_observedLimit = contourList_observedLimit[0] #contour_observedLimit = contourList_observedLimit.First() clearDiagonal(contour_observedLimit) contour_observedLimit.SetMarkerColor(1) contour_observedLimit.SetMarkerSize(0) contour_observedLimit.SetLineColor(1) contour_observedLimit.SetLineWidth(3) contour_observedLimit.SetLineStyle(1) contour_observedLimit.SetFillColor(0) # Observed -1 sigma #clearDiagonal(graph_observedLimit_1sigLwr, replace = True, replaceVal = 100) contourList_observedLimit_1sigLwr = getContourListFromGraph( graph_observedLimit_1sigLwr, 1.0, nSmooth=nSmooth_1sig_obs) #contourList_observedLimit_1sigLwr = graph_observedLimit_1sigLwr.GetContourList(1.0) print "contourList_observedLimit_1sigLwr: No. of contours: %d \n" % ( contourList_observedLimit_1sigLwr.GetSize()) contour_observedLimit_1sigLwr = contourList_observedLimit_1sigLwr[0] #contour_observedLimit_1sigLwr = contourList_observedLimit_1sigLwr.First() clearDiagonal(contour_observedLimit_1sigLwr) contour_observedLimit_1sigLwr.SetMarkerColor(1) contour_observedLimit_1sigLwr.SetMarkerSize(0) contour_observedLimit_1sigLwr.SetLineColor(1) contour_observedLimit_1sigLwr.SetLineWidth(3) contour_observedLimit_1sigLwr.SetLineStyle(2) contour_observedLimit_1sigLwr.SetFillColor(0) # Observed +1 sigma #clearDiagonal(graph_observedLimit_1sigUpr, replace = True, replaceVal = 100) contourList_observedLimit_1sigUpr = getContourListFromGraph( graph_observedLimit_1sigUpr, 1.0, nSmooth=nSmooth_1sig_obs) #contourList_observedLimit_1sigUpr = graph_observedLimit_1sigUpr.GetContourList(1.0) print "contourList_observedLimit_1sigUpr: No. of contours: %d \n" % ( contourList_observedLimit_1sigUpr.GetSize()) contour_observedLimit_1sigUpr = contourList_observedLimit_1sigUpr[0] #contour_observedLimit_1sigUpr = contourList_observedLimit_1sigUpr.First() clearDiagonal(contour_observedLimit_1sigUpr) contour_observedLimit_1sigUpr.SetMarkerColor(1) contour_observedLimit_1sigUpr.SetMarkerSize(0) contour_observedLimit_1sigUpr.SetLineColor(1) contour_observedLimit_1sigUpr.SetLineWidth(3) contour_observedLimit_1sigUpr.SetLineStyle(2) contour_observedLimit_1sigUpr.SetFillColor(0) #removeIntersection(contour_observedLimit_1sigLwr, contour_observedLimit_1sigUpr) # Expected contourList_expectedLimit = getContourListFromGraph( graph_expectedLimit, 1.0, nSmooth=nSmooth_central_exp) #contourList_expectedLimit = graph_expectedLimit.GetContourList(1.0) print "No. of contours: %d \n" % (contourList_expectedLimit.GetSize()) contour_expectedLimit = contourList_expectedLimit[0] #contour_expectedLimit = contourList_expectedLimit.First() clearDiagonal(contour_expectedLimit) contour_expectedLimit.SetMarkerColor(ROOT.kRed + 1) contour_expectedLimit.SetMarkerSize(0) contour_expectedLimit.SetLineColor(ROOT.kRed + 1) contour_expectedLimit.SetLineWidth(3) contour_expectedLimit.SetLineStyle(1) contour_expectedLimit.SetFillColor(0) # Expected -1 sigma contourList_expectedLimit_1sigLwr = getContourListFromGraph( graph_expectedLimit_1sigLwr, 1.0, nSmooth=nSmooth_1sig_exp) #contourList_expectedLimit_1sigLwr = graph_expectedLimit_1sigLwr.GetContourList(1.0) print "No. of contours: %d \n" % ( contourList_expectedLimit_1sigLwr.GetSize()) contour_expectedLimit_1sigLwr = contourList_expectedLimit_1sigLwr[0] #contour_expectedLimit_1sigLwr = contourList_expectedLimit_1sigLwr.First() clearDiagonal(contour_expectedLimit_1sigLwr) contour_expectedLimit_1sigLwr.SetMarkerColor(ROOT.kRed + 1) contour_expectedLimit_1sigLwr.SetMarkerSize(0) contour_expectedLimit_1sigLwr.SetLineColor(ROOT.kRed + 1) contour_expectedLimit_1sigLwr.SetLineWidth(3) contour_expectedLimit_1sigLwr.SetLineStyle(2) contour_expectedLimit_1sigLwr.SetFillColor(0) # Expected +1 sigma contourList_expectedLimit_1sigUpr = getContourListFromGraph( graph_expectedLimit_1sigUpr, 1.0, nSmooth=nSmooth_1sig_exp) #contourList_expectedLimit_1sigUpr = graph_expectedLimit_1sigUpr.GetContourList(1.0) print "No. of contours: %d \n" % ( contourList_expectedLimit_1sigUpr.GetSize()) contour_expectedLimit_1sigUpr = contourList_expectedLimit_1sigUpr[0] #contour_expectedLimit_1sigUpr = contourList_expectedLimit_1sigUpr.First() clearDiagonal(contour_expectedLimit_1sigUpr) contour_expectedLimit_1sigUpr.SetMarkerColor(ROOT.kRed + 1) contour_expectedLimit_1sigUpr.SetMarkerSize(0) contour_expectedLimit_1sigUpr.SetLineColor(ROOT.kRed + 1) contour_expectedLimit_1sigUpr.SetLineWidth(3) contour_expectedLimit_1sigUpr.SetLineStyle(2) contour_expectedLimit_1sigUpr.SetFillColor(0) ############################################## #################### Plot #################### ############################################## ROOT.gStyle.SetOptStat(0) tdrstyle.setTDRStyle() if (isSmooth): ROOT.TColor.CreateGradientColorTable(NRGBs, numpy.array(l_stops), numpy.array(l_red), numpy.array(l_green), numpy.array(l_blue), NCont) ROOT.gStyle.SetNumberContours(NCont) #canvas = ROOT.TCanvas("canvas", "canvas", 400, 400) canvas = ROOT.TCanvas("canvas", "canvas", 1000, 800) canvas.SetLeftMargin(0.125) canvas.SetRightMargin(0.17) #canvas.SetTopMargin(0.05) canvas.SetBottomMargin(0.12) #legend = ROOT.TLegend(0.125, 0.53, 0.83, 0.95) legend = ROOT.TLegend(0.125, 0.65, 0.83, 0.95) #legend.SetFillStyle(0) legend.SetBorderSize(1) #legend.SetTextSize(0.045) legend.SetTextSize(0.035) legend.SetNColumns(2) #legend.SetTextAlign(12) # VERY important # Otherwise, seg-faults when accessing GetListOfPrimitives(), etc. ROOT.SetOwnership(legend, 0) #legend.SetMargin(0.5) #legend.SetHeader( # "#lower[0.35]{#splitline{" + # "#splitline{" + # " "*27 + # "#scale[1.3]{#font[22]{%s}}" %(label) + # "}{" + # "#scale[1.0]{#font[22]{" + # "pp#rightarrow#tilde{t}_{1}#tilde{t}_{1}, " + # "#tilde{t}_{1}#rightarrowb#tilde{#chi}^{#pm}_{1}, " + # "#tilde{#chi}^{#pm}_{1}#rightarrow#tilde{#tau}^{#pm}_{1}#nu (50%) or #tilde{#nu}_{#tau}#tau^{#pm} (50%), " + # "#tilde{#tau}^{#pm}_{1}#rightarrow#tau^{#pm}#tilde{#chi}^{0}_{1}, " + # "#tilde{#nu}_{#tau}#rightarrow#nu#tilde{#chi}^{0}_{1} " + # "}}" + # "}" + # "}{" + # "#scale[1.0]{#font[22]{" + # " "*7 + # "m_{#tilde{#chi}^{#pm}_{1}}#minus m_{#tilde{#chi}^{0}_{1}} = 0.5 (m_{#tilde{t}_{1}}#minus m_{#tilde{#chi}^{0}_{1}}), " + # "m_{#tilde{#tau}^{#pm}_{1}}#minus m_{#tilde{#chi}^{0}_{1}} = x (m_{#tilde{#chi}^{#pm}_{1}}#minus m_{#tilde{#chi}^{0}_{1}}), " + # "m_{#tilde{#nu}_{#tau}} = m_{#tilde{#tau}^{#pm}_{1}}" + # "}}" + # "}}" #) #legend.SetHeader( # "#lower[0.435]{#splitline{" + # "#splitline{" + # " "*22 + # "#scale[1.35]{#font[22]{%s}}" %(label) + # "}{" + # "#scale[1.2]{#font[22]{#splitline{#lower[-0.05]{" + # "pp#rightarrow#tilde{t}_{1}#tilde{t}_{1}, " + # "#tilde{t}_{1}#rightarrowb#tilde{#chi}^{+}_{1}, " + # "#tilde{#chi}^{+}_{1}#rightarrow#tilde{#tau}^{+}_{1}#nu (50%) or #tilde{#nu}_{#tau}#tau^{+} (50%)" + # "}}{#lower[-0.05]{" + # " "*11 + # "#tilde{#tau}^{+}_{1}#rightarrow#tau^{+}#tilde{#chi}^{0}_{1}, " + # "#tilde{#nu}_{#tau}#rightarrow#nu#tilde{#chi}^{0}_{1} " + # "}}}}" + # "}" + # "}{" + # "#scale[1.2]{#font[22]{" + # "#splitline{#lower[-0.06]{" + # " "*20 + # "m_{#tilde{#chi}^{+}_{1}}#minus m_{#tilde{#chi}^{0}_{1}} = 0.5 (m_{#tilde{t}_{1}}#minus m_{#tilde{#chi}^{0}_{1}}) " + # "}}{#lower[-0.05]{" + # " "*12 + # "m_{#tilde{#tau}^{+}_{1}}#minus m_{#tilde{#chi}^{0}_{1}} = x (m_{#tilde{#chi}^{+}_{1}}#minus m_{#tilde{#chi}^{0}_{1}}), " + # "m_{#tilde{#nu}_{#tau}} = m_{#tilde{#tau}^{+}_{1}}" + # "}}" + # "}}" + # "}}" #) legend.SetHeader( "#lower[0.65]{#splitline{" + "#splitline{" + " " * 29 + "#scale[1.45]{#font[22]{%s}}" % (label) + "}{" + " " * 5 + "#scale[1.2]{#font[22]{#splitline{#lower[-0.05]{" + "pp#rightarrow#tilde{t}_{1}#tilde{t}_{1}, " + "#tilde{t}_{1}#rightarrowb#tilde{#chi}^{+}_{1}, " + "#tilde{#chi}^{+}_{1}#rightarrow#tilde{#tau}^{+}_{1}#nu (50%) or #tilde{#nu}_{#tau}#tau^{+} (50%)" + "}}{#lower[-0.05]{" + " " * 13 + "#tilde{#tau}^{+}_{1}#rightarrow#tau^{+}#tilde{#chi}^{0}_{1}, " + "#tilde{#nu}_{#tau}#rightarrow#nu#tilde{#chi}^{0}_{1} " + "}}}}" + "}" + "}{" + "#scale[1.2]{#font[22]{" + "#lower[-0.05]{" + #" "*20 + "m_{#tilde{#chi}^{+}_{1}}#minus m_{#tilde{#chi}^{0}_{1}} = 0.5 (m_{#tilde{t}_{1}}#minus m_{#tilde{#chi}^{0}_{1}}), " + "}#lower[-0.05]{" + #" "*12 + "m_{#tilde{#tau}^{+}_{1}}#minus m_{#tilde{#chi}^{0}_{1}} = x (m_{#tilde{#chi}^{+}_{1}}#minus m_{#tilde{#chi}^{0}_{1}}), " + "m_{#tilde{#nu}_{#tau}} = m_{#tilde{#tau}^{+}_{1}}" + "}" + "}}" + "}}") legendHeader = legend.GetListOfPrimitives().First() legendHeader.SetTextAlign(22) #legendHeader.SetTextSize(0.035) legendHeader.SetTextSize(0.0275) # Blank entries required fot shifting the true entries lower # Otherwise the header overlaps with the entries legend.AddEntry(0, "", "") legend.AddEntry(0, "", "") legend.AddEntry(0, "", "") legend.AddEntry(0, "", "") legend.AddEntry(0, "", "") legend.AddEntry(0, "", "") #################### x-sec #################### if (isSmooth): if (drawObserved): l_xsLimit = [ l_xs[iMass] * l_observedLimit[iMass] for iMass in range(0, len(l_stop1_m)) ] else: l_xsLimit = [ l_xs[iMass] * l_expectedLimit[iMass] for iMass in range(0, len(l_stop1_m)) ] else: l_xsLimit = [ l_observedLimit[iMass] for iMass in range(0, len(l_stop1_m)) ] #l_xsLimit = [l_xs[iMass] * l_expectedLimit[iMass] for iMass in range(0, len(l_stop1_m))] graph_xs = ROOT.TGraph2D("xs", "xs", len(l_stop1_m), array.array("d", l_stop1_m), array.array("d", l_neutralino1_m), array.array("d", l_xsLimit)) if (isSmooth): graph_xs.SetNpx(nInterpolate) graph_xs.SetNpy(nInterpolate) h2_xs = graph_xs.GetHistogram().Clone() ##### #h2_axisRange = ROOT.TH2F("h2_axisRange", "h2_axisRange", 1, 200, 1500, 1, 1, 850) #h2_axisRange = ROOT.TH2F("h2_axisRange", "h2_axisRange", 1, 200, 1500, 1, 1, 1000) h2_axisRange = ROOT.TH2F("h2_axisRange", "h2_axisRange", 1, 200, 1500, 1, 1, 800) h2_axisRange.SetTitle("Exclusion (%s) (%s)" % (label, era)) h2_axisRange.GetXaxis().SetTitle("m_{#tilde{t}_{1}} [GeV]") h2_axisRange.GetYaxis().SetTitle("m_{#tilde{#chi}^{0}_{1}} [GeV]") h2_axisRange.GetXaxis().SetTitleSize(0.06) h2_axisRange.GetXaxis().SetTitleOffset(0.85) h2_axisRange.GetXaxis().CenterTitle(True) h2_axisRange.GetXaxis().SetLabelSize(0.0425) h2_axisRange.GetYaxis().SetTitleSize(0.06) h2_axisRange.GetYaxis().SetTitleOffset(0.9) h2_axisRange.GetYaxis().CenterTitle(True) h2_axisRange.GetYaxis().SetLabelSize(0.0425) h2_axisRange.Draw() ##### #h2_xs.Smooth(10) if (isSmooth): h2_xs.GetZaxis().SetTitle("95% CL upper limit on cross-section [pb]") else: h2_xs.GetZaxis().SetTitle("95% CL upper limit on signal strength") h2_xs.GetZaxis().SetTitleSize(0.045) h2_xs.GetZaxis().SetTitleOffset(1.35) h2_xs.GetZaxis().CenterTitle(True) h2_xs.GetZaxis().SetLabelSize(0.0425) if (isSmooth): h2_xs.SetMinimum(1e-3) h2_xs.SetMaximum(1e2) else: h2_xs.SetMinimum(1) h2_xs.SetMaximum(10) h2_xs.Draw("colz same") #graph_xs.Draw("colz same") #graph_xs.Draw("colz") #graph_xs.GetYaxis().SetLimits(1, 900) #graph_xs.GetZaxis()->SetRangeUser(1e-5, 1e2) #graph_xs.SetMinimum(1e-4) #graph_xs.SetMaximum(1e2) #graph_xs.Draw("colz") #canvas.Update() ######################################## if (isSmooth): contour_expectedLimit.Draw("C same") contour_expectedLimit_1sigLwr.Draw("C same") contour_expectedLimit_1sigUpr.Draw("C same") if (drawObserved): contour_observedLimit.Draw("C same") if (isSmooth): contour_observedLimit_1sigLwr.Draw("C same") contour_observedLimit_1sigUpr.Draw("C same") legend.AddEntry(contour_observedLimit, "Observed") legend.AddEntry(contour_observedLimit_1sigLwr, "Observed #pm 1#sigma_{theory}") if (isSmooth): #legend.AddEntry(contour_observedLimit_1sigLwr, "#lower[0.2]{Observed #pm 1#sigma_{theory}}") legend.AddEntry(contour_expectedLimit, "Expected") #legend.AddEntry(contour_expectedLimit_1sigLwr, "#lower[0.1]{Expected #pm 1#sigma_{experiment}}") legend.AddEntry(contour_expectedLimit_1sigLwr, "Expected #pm 1#sigma_{experiment}") canvas.RedrawAxis() if (isSmooth): canvas.SetLogz(True) #canvas.SetRightMargin(2*canvas.GetRightMargin()) legend.Draw() #print canvas.GetRightMargin() # CMS label CMS_lumi.CMS_lumi( pad=canvas, iPeriod=0, iPosX=0, CMSextraText=Common.getCMSextraText(isPrelim=(not noPrelim)), #lumiText = Common.getLumitext(era) lumiText="#lower[-0.1]{%s}" % (lumiText)) if (isSmooth): outFileName = "%s/exclusion2D_%s.pdf" % (outDir, suffix) else: outFileName = "%s/exclusion2D_%s_coarse.pdf" % (outDir, suffix) outRootFile = ROOT.TFile.Open("%s/exclusion2D_%s.root" % (outDir, suffix), "RECREATE") graph_expectedLimit.Write("expectedXsecLimit") contour_expectedLimit.Write("expectedExclusion") contour_expectedLimit_1sigLwr.Write("expectedExclusion_1sigLwr") contour_expectedLimit_1sigUpr.Write("expectedExclusion_1sigUpr") if (drawObserved): graph_observedLimit.Write("observedXsecLimit") contour_observedLimit.Write("observedExclusion") contour_observedLimit_1sigLwr.Write("observedExclusion_1sigLwr") contour_observedLimit_1sigUpr.Write("observedExclusion_1sigUpr") canvas.Write() outRootFile.Close() canvas.SaveAs(outFileName) canvas.Clear() canvas.Close() contourList_observedLimit.Delete()
myhistos[i][j].Write() for i in range(nHistos - 8, nHistos): myhistos[i].Write() newfile.Close() print nHistos, " histograms have been saved to ", outputFileName # running the macro # just to avoid opening windows print "Let's go!" ROOT.gROOT.SetBatch() setTDRStyle(1) # MSSM Higgs # executeCode("config_DoubleTauProng1_2012A.py") #executeCode("config_DoubleTauProng1_2012B.py") #executeCode("config_DoubleTauProng1_2012Cv3.py") #executeCode("config_DoubleTauProng1_2012Cv4.py") #executeCode("config_DoubleTauProng1_2012Dpart1.py") #executeCode("config_DoubleTauProng1_2012Dpart2.py") # ## SM Higgs executeCode("config_DoubleTauJet_2012A.py") executeCode("config_DoubleTauJet_2012B.py") executeCode("config_DoubleTauJet_2012Cv3.py") executeCode("config_DoubleTauJet_2012Cv4.py") executeCode("config_DoubleTauJet_2012Dpart1.py") executeCode("config_DoubleTauJet_2012Dpart2.py")
def makeDiTauStack(outDir, inFile, rootDir, s, labelX, units="GeV", left=False, channel="", json="Golden", log=False, dndm=False, doRatio=False): cat = 'mmtt' tdrstyle.setTDRStyle() writeExtraText = True # if extra text extraText = "Preliminary" # default extra text is "Preliminary" lumi_sqrtS = "13 TeV" if json == "Golden": lumi_13TeV = channel + " 41.8 fb^{-1}, 2017" iPeriod = 4 # 1=7TeV, 2=8TeV, 3=7+8TeV, 7=7+8+13TeV xR = 0.65 #legend parameters xR = 0.2 #legend parameters H = 600 W = 600 H_ref = 600 W_ref = 600 # references for T, B, L, R T = 0.08 * H_ref B = 0.12 * H_ref L = 0.16 * W_ref R = 0.04 * W_ref #margins for inbetween the pads in a ratio plot B_ratio = 0.1 * H_ref T_ratio = 0.03 * H_ref #margin required for lebal on bottom of raito plot B_ratio_label = 0.3 * H_ref c = TCanvas('c1', 'c1', 50, 50, W, H) c.SetFillColor(0) c.SetBorderMode(0) c.SetFrameFillStyle(0) c.SetFrameBorderMode(0) if not doRatio: c.SetLeftMargin(L / W) c.SetRightMargin(R / W) c.SetTopMargin(T / H) c.SetBottomMargin(B / H) c.cd() ratioPad = TPad("pad2", "", 0.0, 0.0, 1.0, 0.29) plotPad = TPad("pad1", "", 0.0016, 0.291, 1.0, 1.0) if doRatio: plotPad.SetTicks(0, 0) plotPad.SetLeftMargin(L / W) plotPad.SetRightMargin(R / W) plotPad.SetTopMargin(T / H) plotPad.SetBottomMargin(B_ratio / H) plotPad.SetFillColor(0) plotPad.SetBottomMargin(0) ratioPad.SetLeftMargin(L / W) ratioPad.SetRightMargin(R / W) ratioPad.SetTopMargin(T_ratio / H) ratioPad.SetTopMargin(0.007) ratioPad.SetBottomMargin(B_ratio_label / H) ratioPad.SetGridy(1) ratioPad.SetFillColor(4000) else: plotPad = TPad("pad1", "", 0.0, 0.03, 1.0, 1.0) plotPad.SetLeftMargin(L / W) plotPad.SetRightMargin(R / W) plotPad.SetTopMargin(T / H) plotPad.SetBottomMargin(B / H) plotPad.Draw() plotPad.cd() print("In makeStack inFile={0:s}".format(inFile)) f = TFile(inFile) groups = ['data', 'Reducible', 'Rare', 'ZZ4L', 'Signal'] histo = {} colors = { 'data': 0, 'Reducible': kMagenta - 10, 'Rare': kBlue - 8, 'ZZ4L': kAzure - 9, 'Signal': kOrange - 4 } hs = THStack("hs", "") for group in groups: histo[group] = f.Get("h{0:s}_{1:s}_Mtt".format(group, cat)) #print("In makeStack(): histo={0:s} type(histo)={1:s}".format(str(histo[group]),type(histo[group]))) if dndm: convertToDNDM(histo[group]) if group == 'data': applyDATAStyle(histo[group]) elif group == 'Signal': applySignalStyle(histo[group]) else: applyStyle(histo[group], colors[group], 1, 1001) if group != 'data': hs.Add(histo[group]) hMax = 1.2 * max(histo['data'].GetMaximum(), hs.GetMaximum()) print("hMax={0:f}".format(hMax)) hs.SetMaximum(hMax) hs.Draw("HIST") histo['data'].Draw("e,SAME") if doRatio: hs.GetXaxis().SetLabelSize(0) else: if units != "": hs.GetXaxis().SetTitle(labelX + " [" + units + "]") else: hs.GetXaxis().SetTitle(labelX) hs.GetYaxis().SetTitle("Events") hs.GetYaxis().SetTitleOffset(1) if dndm: hs.GetYaxis().SetTitle("dN/d" + labelX) c.cd() if doRatio: data2 = histo['data'].Clone("data") mc = histo['Rare'] mc.Add(histo['Reducible']) mc.Add(histo['ZZ4L']) xmin = mc.GetXaxis().GetXmin() xmax = mc.GetXaxis().GetXmax() line = TLine(xmin, 1.0, xmax, 1.0) line.SetLineWidth(1) line.SetLineColor(kBlack) ratioPad.Draw() ratioPad.cd() data2.Divide(data2, mc) data2.SetMarkerStyle(20) data2.SetTitleSize(0.12, "Y") data2.SetTitleOffset(0.40, "Y") data2.SetTitleSize(0.12, "X") data2.SetLabelSize(0.10, "X") data2.SetLabelSize(0.08, "Y") data2.GetYaxis().SetRangeUser(0.62, 1.38) data2.GetYaxis().SetNdivisions(305) data2.GetYaxis().SetTitle("Obs/Exp ") if units != "": data2.GetXaxis().SetTitle(labelX + " [" + units + "]") else: data2.GetXaxis().SetTitle(labelX) data2.Draw("P") line.Draw() c.cd() plotPad.cd() l = TLegend(xR, 0.55, xR + 0.28, 0.9) for group in groups: l.AddEntry(histo[group], group, "F") l.SetBorderSize(0) l.SetFillColor(0) l.SetFillStyle(0) l.Draw() factor = 1.05 if left: factor = 1. / 2.2 xL = hs.GetXaxis().GetXmin() + (hs.GetXaxis().GetXmax() - hs.GetXaxis().GetXmin()) * xR * factor yL = hs.GetMaximum() * 0.35 offsetF = yL - 0.1 * hs.GetMaximum() offsetFF = yL - 0.2 * hs.GetMaximum() plotPad.Draw() #CMS_lumi(plotPad,4,11) c.SaveAs("stack.png") c.SaveAs("stack.root") raw_input()
from ROOT import * import math, time import tdrstyle tdrStyle = tdrstyle.setTDRStyle() tdrStyle.SetOptStat(0) tdrStyle.SetPadTopMargin(0.059) TGaxis.SetMaxDigits(3) gROOT.SetBatch(0) isMC = True dir_ = 'finalMassPlots/' # Data #ksfin_7000 = TFile('massHistos/data_dNdX_kshort_7000.root', 'READ') #ksfin_900 = TFile('massHistos/data_dNdX_kshort_900.root', 'READ') #lamfin_7000 = TFile('massHistos/data_dNdX_lambda.root', 'READ') #lamfin_900 = TFile('massHistos/data_dNdX_lambda_900.root', 'READ') # MC ksfin_7000 = TFile('mcmass/sim_dNdX_kshort_pythia8.root', 'READ') ksfin_900 = TFile('mcmass/sim_dNdX_kshort_tuneD6T.root', 'READ') lamfin_7000 = TFile('mcmass/sim_dNdX_lambda_pythia8.root', 'READ') lamfin_900 = TFile('mcmass/sim_dNdX_lambda_tuneD6T.root', 'READ') ksmass7000 = ksfin_7000.Get('vee_withcuts') lammass7000 = lamfin_7000.Get('vee_withcuts') ksmass900 = ksfin_900.Get('vee_withcuts') lammass900 = lamfin_900.Get('vee_withcuts')
def TDRify(canvas, inset, name, writeOutput=False, outputdir="~/physics/_tests"): for i in range(0, 1): canvas.Draw() #canvas=originalcanvas.Clone() #print "\n --->TDRifying!" tdrstyle.setTDRStyle() gStyle.SetOptStat(0) CMS_lumi.lumi_13TeV = "35.9 fb^{-1}" CMS_lumi.writeExtraText = 1 CMS_lumi.extraText = "Preliminary" CMS_lumi.lumi_sqrtS = "13 TeV" # used with iPeriod = 0, e.g. for simulation-only plots (default is an empty string) iPos = 11 if (iPos == 0): CMS_lumi.relPosX = 0.12 H_ref = 600 W_ref = 800 W = W_ref H = H_ref iPeriod = 4 T = 0.08 * H_ref B = 0.12 * H_ref L = 0.12 * W_ref R = 0.04 * W_ref #tgraph = tfile.Get("") #tgraph.Draw() #canvas.Draw() #canvas.SetFillColor(0) #canvas.SetBorderMode(0) #canvas.SetFrameFillStyle(0) #canvas.SetFrameBorderMode(0) canvas.SetLeftMargin(L / W) canvas.SetRightMargin(R / W) canvas.SetTopMargin(T / H) canvas.SetBottomMargin(B / H) canvas.SetTickx(0) canvas.SetTicky(0) if not inset: CMS_lumi.CMS_lumi(canvas, iPeriod, iPos) gStyle.SetOptStat(0) for primitive in canvas.GetListOfPrimitives(): #print primitive if primitive.GetName() in ["data"]: primitive.SetStats(kFALSE) canvas.cd() #print "cd'd to canvas" canvas.Update() #print "updated canvas" canvas.RedrawAxis() #print "redrew axis" if writeOutput: canvas.Print("%s/%s_plot.pdf" % (outputdir, name)) outputFilename = "%s/%s_plot.root" % (outputdir, name) outfile = TFile(outputFilename, "RECREATE") outfile.cd() canvas.SetName("ddPlot_%s" % name) canvas.Write() outfile.Close() #print " --->done TDRifying! \n\n" return canvas
##------------------------------------------------------------------------------------- if __name__ == '__main__': parser = OptionParser() parser.add_option('-b', action='store_true', dest='noX', default=False, help='no X11 windows') parser.add_option("--lumi", dest="lumi", type=float, default = 30,help="luminosity", metavar="lumi") parser.add_option('-i','--ifile', dest='ifile', default = 'hist_1DZbb.root',help='file with histogram inputs', metavar='ifile') parser.add_option('--ifile-loose', dest='ifile_loose', default=None, help='second file with histogram inputs (looser b-tag cut to take W/Z/H templates)', metavar='ifile_loose') parser.add_option('-o','--odir', dest='odir', default = 'cards/',help='directory to write cards', metavar='odir') parser.add_option('--pseudo', action='store_true', dest='pseudo', default =False,help='signal comparison', metavar='isData') parser.add_option('--blind', action='store_true', dest='blind', default =False,help='blind signal region', metavar='blind') parser.add_option('--remove-unmatched', action='store_true', dest='removeUnmatched', default =False,help='remove unmatched', metavar='removeUnmatched') parser.add_option('--no-mcstat-shape', action='store_true', dest='noMcStatShape', default =False,help='change mcstat uncertainties to lnN', metavar='noMcStatShape') (options, args) = parser.parse_args() import tdrstyle tdrstyle.setTDRStyle() r.gStyle.SetPadTopMargin(0.10) r.gStyle.SetPadLeftMargin(0.16) r.gStyle.SetPadRightMargin(0.10) r.gStyle.SetPalette(1) r.gStyle.SetPaintTextFormat("1.1f") r.gStyle.SetOptFit(0000) r.gROOT.SetBatch() main(options,args) ##-------------------------------------------------------------------------------------
def eta_plot(X0W,Y0W,X1W,Y1W,X2W,Y2W,X3W, Y3W, X4W, Y4W, X5W, Y5W, X6W, Y6W, X7W,Y7W,X8W,Y8W,X9W,Y9W,X10W,Y10W,X11W,Y11W,X12W,Y12W,X13W,Y13W, X0E,Y0E,X1E,Y1E,X2E,Y2E,X3E, Y3E, X4E, Y4E, X5E, Y5E, X6E, Y6E, X7E,Y7E,X8E,Y8E,X9E,Y9E,X10E,Y10E,X11E,Y11E,X12E,Y12E,X13E,Y13E): print "------ Setting Up Format ----------" tdrstyle.setTDRStyle() #change the CMS_lumi variables (see CMS_lumi.py) CMS_lumi.writeExtraText = 1 CMS_lumi.extraText = "Preliminary" CMS_lumi.extraText2 = "2018 pp data" CMS_lumi.lumi_sqrtS = "13 TeV" # used with iPeriod = 0, e.g. for simulation-only plots (default is an empty string) CMS_lumi.writeTitle = 1 CMS_lumi.textTitle = 'title' iPos = 11 if( iPos==0 ): CMS_lumi.relPosX = 0.12 H_ref = 600; W_ref = 800; W = W_ref H = H_ref iPeriod = 0 # references for T, B, L, R T = 0.08*H_ref B = 0.12*H_ref L = 0.12*W_ref R = 0.04*W_ref print "------ Creating Wheel TGraph ----------" n0W = len(X0W) gr0W = TGraph(n0W,X0W,Y0W) gr0W.SetMarkerColor( kRed ) gr0W.SetMarkerStyle( 20 ) gr0W.SetMarkerSize( 1.5 ) gr0W.SetTitle( 'RB1 in' ) gr0W.GetXaxis().SetTitle( '#eta' ) gr0W.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' ) n1W = len(X1W) gr1W = TGraph(n1W,X1W,Y1W) gr1W.SetLineColor( 2 ) gr1W.SetLineWidth( 4 ) gr1W.SetMarkerColor( kBlue ) gr1W.SetMarkerStyle( 29 ) gr1W.SetMarkerSize( 1.7 ) gr1W.SetTitle( 'Layer 1 Wheel' ) gr1W.GetXaxis().SetTitle( '#eta' ) gr1W.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' ) n2W = len(X2W) gr2W = TGraph(n2W,X2W,Y2W) gr2W.SetLineColor( 3 ) gr2W.SetLineWidth( 5 ) gr2W.SetMarkerColor( kRed+2 ) gr2W.SetMarkerStyle( 21 ) gr2W.SetMarkerSize( 1.5 ) gr2W.SetTitle( 'Layer 2 Wheel') gr2W.GetXaxis().SetTitle( '#eta' ) gr2W.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' ) n3W = len(X3W) gr3W = TGraph(n3W,X3W,Y3W) gr3W.SetLineColor( 4 ) gr3W.SetLineWidth( 6 ) gr3W.SetMarkerColor( kRed ) gr3W.SetMarkerStyle( 21 ) gr3W.SetMarkerSize( 1.5 ) gr3W.SetTitle( 'Layer 3 Wheel' ) gr3W.GetXaxis().SetTitle( '#eta' ) gr3W.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' ) n4W = len(X4W) gr4W = TGraph(n4W,X4W,Y4W) gr4W.SetLineColor( 5 ) gr4W.SetLineWidth( 7 ) gr4W.SetMarkerColor( kBlue ) gr4W.SetMarkerStyle( 23 ) gr4W.SetMarkerSize( 1.5 ) gr4W.SetTitle( 'Layer 4 Wheel' ) gr4W.GetXaxis().SetTitle( '#eta' ) gr4W.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' ) print "------ Creating Endcap TGraph ----------" n0E = len(X0E) gr0E = TGraph(n0E,X0E,Y0E) gr0E.SetLineColor( 2 ) gr0E.SetLineWidth( 4 ) gr0E.SetMarkerColor( kRed ) gr0E.SetMarkerStyle( 24 ) gr0E.SetMarkerSize( 1.5 ) gr0E.SetTitle( 'Layer 1 Endcap' ) gr0E.GetXaxis().SetTitle( '#eta' ) gr0E.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' ) n1E = len(X1E) gr1E = TGraph(n1E,X1E,Y1E) gr1E.SetLineColor( 2 ) gr1E.SetLineWidth( 4 ) gr1E.SetMarkerColor( kBlue ) gr1E.SetMarkerStyle( 30 ) gr1E.SetMarkerSize( 1.5 ) gr1E.SetTitle( 'Layer 1 Endcap' ) gr1E.GetXaxis().SetTitle( '#eta' ) gr1E.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' ) n2E = len(X2E) gr2E = TGraph(n2E,X2E,Y2E) gr2E.SetLineColor( 3 ) gr2E.SetLineWidth( 5 ) gr2E.SetMarkerColor( kRed+2 ) gr2E.SetMarkerStyle( 25 ) gr2E.SetMarkerSize( 1.5 ) gr2E.SetTitle( 'Layer 2 Endcap') gr2E.GetXaxis().SetTitle( '#eta' ) gr2E.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' ) n3E = len(X3E) gr3E = TGraph(n3E,X3E,Y3E) gr3E.SetLineColor( 4 ) gr3E.SetLineWidth( 6 ) gr3E.SetMarkerColor( kRed ) gr3E.SetMarkerStyle( 25 ) gr3E.SetMarkerSize( 1.5 ) gr3E.SetTitle( 'Layer 3 Endcap' ) gr3E.GetXaxis().SetTitle( '#eta' ) gr3E.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' ) n4E = len(X4E) gr4E = TGraph(n4E,X4E,Y4E) gr4E.SetLineColor( 5 ) gr4E.SetLineWidth( 7 ) gr4E.SetMarkerColor( kBlue ) gr4E.SetMarkerStyle( 32 ) gr4E.SetMarkerSize( 1.5 ) gr4E.SetTitle( 'Layer 4 Endcap' ) gr4E.GetXaxis().SetTitle( '#eta' ) gr4E.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' ) print "------ Creating Wheel TGraph ----------" n5W = len(X5W) gr5W = TGraph(n5W,X5W,Y5W) gr5W.SetLineColor( 2 ) gr5W.SetLineWidth( 4 ) gr5W.SetMarkerColor( 6 ) gr5W.SetMarkerStyle( 22 ) gr5W.SetMarkerSize( 1.5 ) gr5W.SetTitle( 'Layer 1 Wheel' ) gr5W.GetXaxis().SetTitle( '#eta' ) gr5W.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' ) n6W = len(X6W) gr6W = TGraph(n6W,X6W,Y6W) gr6W.SetLineColor( 3 ) gr6W.SetLineWidth( 5 ) gr6W.SetMarkerColor( 28 ) gr6W.SetMarkerStyle( 23 ) gr6W.SetMarkerSize( 1.7 ) gr6W.SetTitle( 'Layer 2 Wheel') gr6W.GetXaxis().SetTitle( '#eta' ) gr6W.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' ) n7W = len(X7W) gr7W = TGraph(n7W,X7W,Y7W) gr7W.SetLineColor( 4 ) gr7W.SetLineWidth( 6 ) gr7W.SetMarkerColor( kRed ) gr7W.SetMarkerStyle( 20 ) gr7W.SetMarkerSize( 1.5 ) gr7W.SetTitle( 'Layer 3 Wheel' ) gr7W.GetXaxis().SetTitle( '#eta' ) gr7W.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' ) n8W = len(X8W) gr8W = TGraph(n8W,X8W,Y8W) gr8W.SetLineColor( 5 ) gr8W.SetLineWidth( 7 ) gr8W.SetMarkerColor( kBlue ) gr8W.SetMarkerStyle( 29 ) gr8W.SetMarkerSize( 1.5 ) gr8W.SetTitle( 'Layer 4 Wheel' ) gr8W.GetXaxis().SetTitle( '#eta' ) gr8W.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' ) n9W = len(X9W) gr9W = TGraph(n9W,X9W,Y9W) gr9W.SetLineColor( 5 ) gr9W.SetLineWidth( 7 ) gr9W.SetMarkerColor( kRed+2 ) gr9W.SetMarkerStyle( 21 ) gr9W.SetMarkerSize( 1.5 ) gr9W.SetTitle( 'Layer 4 Wheel' ) gr9W.GetXaxis().SetTitle( '#eta' ) gr9W.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' ) n10W = len(X10W) gr10W = TGraph(n10W,X10W,Y10W) gr10W.SetLineColor( 5 ) gr10W.SetLineWidth( 7 ) gr10W.SetMarkerColor( kRed ) gr10W.SetMarkerStyle( 21 ) gr10W.SetMarkerSize( 1.5 ) gr10W.SetTitle( 'Layer 4 Wheel' ) gr10W.GetXaxis().SetTitle( '#eta' ) gr10W.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' ) n11W = len(X11W) gr11W = TGraph(n11W,X11W,Y11W) gr11W.SetLineColor( 5 ) gr11W.SetLineWidth( 7 ) gr11W.SetMarkerColor( kBlue ) gr11W.SetMarkerStyle( 23 ) gr11W.SetMarkerSize( 1.5 ) gr11W.SetTitle( 'Layer 4 Wheel' ) gr11W.GetXaxis().SetTitle( '#eta' ) gr11W.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' ) n12W = len(X12W) gr12W = TGraph(n12W,X12W,Y12W) gr12W.SetLineColor( 5 ) gr12W.SetLineWidth( 7 ) gr12W.SetMarkerColor( 6 ) gr12W.SetMarkerStyle( 22 ) gr12W.SetMarkerSize( 1.5 ) gr12W.SetTitle( 'Layer 4 Wheel' ) gr12W.GetXaxis().SetTitle( '#eta' ) gr12W.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' ) n13W = len(X13W) gr13W = TGraph(n13W,X13W,Y13W) gr13W.SetLineColor( 5 ) gr13W.SetLineWidth( 7 ) gr13W.SetMarkerColor( 28 ) gr13W.SetMarkerStyle( 23 ) gr13W.SetMarkerSize( 1.5 ) gr13W.SetTitle( 'Layer 4 Wheel' ) gr13W.GetXaxis().SetTitle( '#eta' ) gr13W.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' ) print "------ Creating Endcap TGraph ----------" n5E = len(X5E) gr5E = TGraph(n5E,X5E,Y5E) gr5E.SetLineColor( 2 ) gr5E.SetLineWidth( 4 ) gr5E.SetMarkerColor( 6 ) gr5E.SetMarkerStyle( 26 ) gr5E.SetMarkerSize( 1.5 ) gr5E.SetTitle( 'Layer 1 Endcap' ) gr5E.GetXaxis().SetTitle( '#eta' ) gr5E.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' ) n6E = len(X6E) gr6E = TGraph(n6E,X6E,Y6E) gr6E.SetLineColor( 3 ) gr6E.SetLineWidth( 5 ) gr6E.SetMarkerColor( 28 ) gr6E.SetMarkerStyle( 32 ) gr6E.SetMarkerSize( 1.5 ) gr6E.SetTitle( 'Layer 2 Endcap') gr6E.GetXaxis().SetTitle( '#eta' ) gr6E.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' ) n7E = len(X7E) gr7E = TGraph(n7E,X7E,Y7E) gr7E.SetLineColor( 4 ) gr7E.SetLineWidth( 6 ) gr7E.SetMarkerColor( kRed ) gr7E.SetMarkerStyle( 24 ) gr7E.SetMarkerSize( 1.5 ) gr7E.SetTitle( 'Layer 3 Endcap' ) gr7E.GetXaxis().SetTitle( '#eta' ) gr7E.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' ) n8E = len(X8E) gr8E = TGraph(n8E,X8E,Y8E) gr8E.SetLineColor( 5 ) gr8E.SetLineWidth( 7 ) gr8E.SetMarkerColor( kBlue ) gr8E.SetMarkerStyle( 30 ) gr8E.SetMarkerSize( 1.5 ) gr8E.SetTitle( 'Layer 4 Endcap' ) gr8E.GetXaxis().SetTitle( '#eta' ) gr8E.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' ) n9E = len(X9E) gr9E = TGraph(n9E,X9E,Y9E) gr9E.SetLineColor( 5 ) gr9E.SetLineWidth( 7 ) gr9E.SetMarkerColor( kRed+2 ) gr9E.SetMarkerStyle( 25 ) gr9E.SetMarkerSize( 1.5 ) gr9E.SetTitle( 'Layer 4 Endcap' ) gr9E.GetXaxis().SetTitle( '#eta' ) gr9E.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' ) n10E = len(X10E) gr10E = TGraph(n10E,X10E,Y10E) gr10E.SetLineColor( 5 ) gr10E.SetLineWidth( 7 ) gr10E.SetMarkerColor( kRed ) gr10E.SetMarkerStyle( 25 ) gr10E.SetMarkerSize( 1.5 ) gr10E.SetTitle( 'Layer 4 Endcap' ) gr10E.GetXaxis().SetTitle( '#eta' ) gr10E.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' ) n11E = len(X11E) gr11E = TGraph(n11E,X11E,Y11E) gr11E.SetLineColor( 5 ) gr11E.SetLineWidth( 7 ) gr11E.SetMarkerColor( kBlue ) gr11E.SetMarkerStyle( 32 ) gr11E.SetMarkerSize( 1.5 ) gr11E.SetTitle( 'Layer 4 Endcap' ) gr11E.GetXaxis().SetTitle( '#eta' ) gr11E.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' ) n12E = len(X12E) gr12E = TGraph(n12E,X12E,Y12E) gr12E.SetLineColor( 5 ) gr12E.SetLineWidth( 7 ) gr12E.SetMarkerColor( 6 ) gr12E.SetMarkerStyle( 26 ) gr12E.SetMarkerSize( 1.5 ) gr12E.SetTitle( 'Layer 4 Endcap' ) gr12E.GetXaxis().SetTitle( '#eta' ) gr12E.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' ) n13E = len(X13E) gr13E = TGraph(n13E,X13E,Y13E) gr13E.SetLineColor( 5 ) gr13E.SetLineWidth( 7 ) gr13E.SetMarkerColor( 28 ) gr13E.SetMarkerStyle( 32 ) gr13E.SetMarkerSize( 1.5 ) gr13E.SetTitle( 'Layer 4 Endcap' ) gr13E.GetXaxis().SetTitle( '#eta' ) gr13E.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' ) print "----- Creating TCanvas -----" H = 800 W = 1600 canv = TCanvas("c1", "Canvas",50,50,W,H) canv.SetFillColor(0) canv.SetBorderMode(0) canv.SetFrameFillStyle(0) canv.SetFrameBorderMode(0) canv.SetLeftMargin( L/W ) canv.SetRightMargin( R/W ) canv.SetTopMargin( T/H ) canv.SetBottomMargin( B/H ) canv.SetTickx(0) canv.SetTicky(0) canv.Divide(3,2,0.001,0.001) CMS_lumi.CMS_lumi(canv, iPeriod, iPos) canv.cd() canv.Update() maxY = 1000 canv.cd(1) gPad.SetLogy() print " ------------ Creating TMultiGraph -----------" mg1 = TMultiGraph() #graphAxis(mg1) mg1.Add(gr0E,"AP") mg1.Add(gr0W,"AP") mg1.Add(gr7E,"AP") mg1.Add(gr7W,"AP") mg1.Draw("a") mg1.SetTitle( 'RB1in') mg1.GetXaxis().SetTitle( '#eta' ) mg1.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' ) mg1.SetMaximum(maxY) mg1.GetXaxis().SetLabelFont(42) mg1.GetXaxis().SetLabelOffset(0.007) mg1.GetXaxis().SetLabelSize(0.043) mg1.GetXaxis().SetTitleSize(0.05) mg1.GetXaxis().SetTitleOffset(1.06) mg1.GetXaxis().SetTitleFont(42) mg1.GetYaxis().SetLabelFont(42) mg1.GetYaxis().SetLabelOffset(0.008) mg1.GetYaxis().SetLabelSize(0.05) mg1.GetYaxis().SetTitleSize(0.06) mg1.GetYaxis().SetTitleOffset(0.87) mg1.GetYaxis().SetTitleFont(42) pvtxt = TPaveText(.1,0.97,.55,0.97,"NDC") #(.06,.4,.55,.73) pvtxt.AddText('CMS Preliminary') pvtxt.SetFillStyle(0) pvtxt.SetBorderSize(0) pvtxt.SetTextSize(0.03) pvtxt.Draw() pvtxt100 = TPaveText(.7,0.97,.9,0.97,"NDC") pvtxt100.AddText('5.0 #times 10^{34} Hz/cm^{2} (13 TeV)') pvtxt100.SetFillStyle(0) pvtxt100.SetBorderSize(0) pvtxt100.SetTextSize(0.03) pvtxt100.Draw() canv.cd(2) gPad.SetLogy() gr00 = TGraph() gr00.SetMarkerColor( kBlack ) gr00.SetMarkerStyle( 20 ) gr00.SetMarkerSize( 1.5 ) gr01 = TGraph() gr01.SetMarkerColor( kBlack ) gr01.SetMarkerStyle( 24 ) gr01.SetMarkerSize( 1.5 ) legend0 = TLegend(0.2, 0.7, .8, .9) legend0.SetNColumns(1) legend0.AddEntry(gr00, "Barrel", "p") legend0.AddEntry(gr01, "Endcaps", "p") legend0.Draw("a same") legendi = TLegend(0.2, 0.2, .8, .6) legendi.SetNColumns(1) legendi.AddEntry(gr7W, "RB1in + RE1" , "p") legendi.AddEntry(gr8W, "RB1out + RE1" , "p") legendi.AddEntry(gr9W, "RB2 + RE2" , "p") # legendi.AddEntry(gr10W, "RB2in + RE2" , "p") # legendi.AddEntry(gr11W, "RB2out + RE2" , "p") legendi.AddEntry(gr12W, "RB3 + RE3" , "p") legendi.AddEntry(gr13W, "RB4 + RE4" , "p") legendi.SetTextSize(0.05) legendi.Draw("a"); canv.cd(3) gPad.SetLogy() mg2 = TMultiGraph() mg2.Add(gr1E,"AP") mg2.Add(gr1W,"AP") mg2.Add(gr8E,"AP") mg2.Add(gr8W,"AP") mg2.Draw("a") mg2.SetTitle( 'RB1out') mg2.GetXaxis().SetTitle( '#eta' ) mg2.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' ) mg2.SetMaximum(maxY) mg2.GetXaxis().SetLabelFont(42) mg2.GetXaxis().SetLabelOffset(0.007) mg2.GetXaxis().SetLabelSize(0.043) mg2.GetXaxis().SetTitleSize(0.05) mg2.GetXaxis().SetTitleOffset(1.06) mg2.GetXaxis().SetTitleFont(42) mg2.GetYaxis().SetLabelFont(42) mg2.GetYaxis().SetLabelOffset(0.008) mg2.GetYaxis().SetLabelSize(0.05) mg2.GetYaxis().SetTitleSize(0.06) mg2.GetYaxis().SetTitleOffset(0.87) mg2.GetYaxis().SetTitleFont(42) pvtxt3 = TPaveText(.1,0.97,.55,0.97,"NDC") #(.06,.4,.55,.73) pvtxt3.AddText('CMS Preliminary') pvtxt3.SetFillStyle(0) pvtxt3.SetBorderSize(0) pvtxt3.SetTextSize(0.03) pvtxt3.Draw() pvtxt4 = TPaveText(.7,0.97,.9,0.97,"NDC") pvtxt4.AddText('5.0 #times 10^{34} Hz/cm^{2} (13 TeV)') pvtxt4.SetFillStyle(0) pvtxt4.SetBorderSize(0) pvtxt4.SetTextSize(0.03) pvtxt4.Draw() canv.cd(4) gPad.SetLogy() mg3 = TMultiGraph() #graphAxis(mg3) mg3.Add(gr2E,"AP") mg3.Add(gr2W,"AP") mg3.Add(gr9E,"AP") mg3.Add(gr9W,"AP") mg3.Draw("a") mg3.SetTitle( 'RB2') mg3.GetXaxis().SetTitle( '#eta' ) mg3.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' ) mg3.SetMaximum(maxY) mg3.GetXaxis().SetLabelFont(42) mg3.GetXaxis().SetLabelOffset(0.007) mg3.GetXaxis().SetLabelSize(0.043) mg3.GetXaxis().SetTitleSize(0.05) mg3.GetXaxis().SetTitleOffset(1.06) mg3.GetXaxis().SetTitleFont(42) mg3.GetYaxis().SetLabelFont(42) mg3.GetYaxis().SetLabelOffset(0.008) mg3.GetYaxis().SetLabelSize(0.05) mg3.GetYaxis().SetTitleSize(0.06) mg3.GetYaxis().SetTitleOffset(0.87) mg3.GetYaxis().SetTitleFont(42) pvtxt5 = TPaveText(.1,0.97,.55,0.97,"NDC") #(.06,.4,.55,.73) pvtxt5.AddText('CMS Preliminary') pvtxt5.SetFillStyle(0) pvtxt5.SetBorderSize(0) pvtxt5.SetTextSize(0.03) pvtxt5.Draw() pvtxt6 = TPaveText(.7,0.97,.9,0.97,"NDC") pvtxt6.AddText('5.0 #times 10^{34} Hz/cm^{2} (13 TeV)') pvtxt6.SetFillStyle(0) pvtxt6.SetBorderSize(0) pvtxt6.SetTextSize(0.03) pvtxt6.Draw() canv.cd(5) gPad.SetLogy() mg4 = TMultiGraph() #graphAxis(mg4) mg4.Add(gr5E,"AP") mg4.Add(gr5W,"AP") mg4.Add(gr12E,"AP") mg4.Add(gr12W,"AP") mg4.Draw("a") mg4.SetTitle( 'RB3') mg4.GetXaxis().SetTitle( '#eta' ) mg4.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' ) mg4.SetMaximum(maxY) mg4.GetXaxis().SetLabelFont(42) mg4.GetXaxis().SetLabelOffset(0.007) mg4.GetXaxis().SetLabelSize(0.043) mg4.GetXaxis().SetTitleSize(0.05) mg4.GetXaxis().SetTitleOffset(1.06) mg4.GetXaxis().SetTitleFont(42) mg4.GetYaxis().SetLabelFont(42) mg4.GetYaxis().SetLabelOffset(0.008) mg4.GetYaxis().SetLabelSize(0.05) mg4.GetYaxis().SetTitleSize(0.06) mg4.GetYaxis().SetTitleOffset(0.87) mg4.GetYaxis().SetTitleFont(42) pvtxt7 = TPaveText(.1,0.97,.55,0.97,"NDC") #(.06,.4,.55,.73) pvtxt7.AddText('CMS Preliminary') pvtxt7.SetFillStyle(0) pvtxt7.SetBorderSize(0) pvtxt7.SetTextSize(0.03) pvtxt7.Draw() pvtxt8 = TPaveText(.7,0.97,.9,0.97,"NDC") pvtxt8.AddText('5.0 #times 10^{34} Hz/cm^{2} (13 TeV)') pvtxt8.SetFillStyle(0) pvtxt8.SetBorderSize(0) pvtxt8.SetTextSize(0.03) pvtxt8.Draw() canv.cd(6) gPad.SetLogy() mg5 = TMultiGraph() #graphAxis(mg5) mg5.Add(gr6E,"AP") mg5.Add(gr6W,"AP") mg5.Add(gr13E,"AP") mg5.Add(gr13W,"AP") mg5.Draw("a") mg5.SetTitle( 'RB4') mg5.GetXaxis().SetTitle( '#eta' ) mg5.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' ) mg5.SetMaximum(maxY) mg5.GetXaxis().SetLabelFont(42) mg5.GetXaxis().SetLabelOffset(0.007) mg5.GetXaxis().SetLabelSize(0.043) mg5.GetXaxis().SetTitleSize(0.05) mg5.GetXaxis().SetTitleOffset(1.06) mg5.GetXaxis().SetTitleFont(42) mg5.GetYaxis().SetLabelFont(42) mg5.GetYaxis().SetLabelOffset(0.008) mg5.GetYaxis().SetLabelSize(0.05) mg5.GetYaxis().SetTitleSize(0.06) mg5.GetYaxis().SetTitleOffset(0.87) mg5.GetYaxis().SetTitleFont(42) pvtxt10 = TPaveText(.1,0.97,.55,0.97,"NDC") #(.06,.4,.55,.73) pvtxt10.AddText('CMS Preliminary') pvtxt10.SetFillStyle(0) pvtxt10.SetBorderSize(0) pvtxt10.SetTextSize(0.03) pvtxt10.Draw() pvtxt9 = TPaveText(.7,0.97,.9,0.97,"NDC") pvtxt9.AddText('5.0 #times 10^{34} Hz/cm^{2} (13 TeV)') pvtxt9.SetFillStyle(0) pvtxt9.SetBorderSize(0) pvtxt9.SetTextSize(0.03) pvtxt9.Draw() canv.SaveAs("etaDistro.gif") canv.Close() print "----- Creating Second TCanvas -----" H = 800 W = 800 c = TCanvas("c1", "Canvas",50,50,W,H) c.SetFillColor(0) c.SetBorderMode(0) c.SetFrameFillStyle(0) c.SetFrameBorderMode(0) c.SetLeftMargin( L/W ) c.SetRightMargin( R/W ) c.SetTopMargin( T/H ) c.SetBottomMargin( B/H ) c.SetTickx(0) c.SetTicky(0) gPad.SetLogy() print " ------------ Creating TMultiGraph -----------" mg = TMultiGraph() mg.Add(gr0E,"AP") mg.Add(gr0W,"AP") mg.Add(gr7E,"AP") mg.Add(gr7W,"AP") mg.Add(gr1W,"AP") mg.Add(gr8W,"AP") mg.Draw("a") mg.SetTitle( 'RB1in') mg.GetXaxis().SetTitle( '#eta' ) mg.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' ) mg.SetMaximum(maxY) mg.GetXaxis().SetLabelFont(42) mg.GetXaxis().SetLabelOffset(0.007) mg.GetXaxis().SetLabelSize(0.043) mg.GetXaxis().SetTitleSize(0.05) mg.GetXaxis().SetTitleOffset(1.06) mg.GetXaxis().SetTitleFont(42) mg.GetYaxis().SetLabelFont(42) mg.GetYaxis().SetLabelOffset(0.008) mg.GetYaxis().SetLabelSize(0.05) mg.GetYaxis().SetTitleSize(0.06) mg.GetYaxis().SetTitleOffset(0.87) mg.GetYaxis().SetTitleFont(42) pvt = TPaveText(.1,0.97,.55,0.97,"NDC") #(.06,.4,.55,.73) pvt.AddText('CMS Preliminary') pvt.SetFillStyle(0) pvt.SetBorderSize(0) pvt.SetTextSize(0.03) pvt.Draw() pvt1 = TPaveText(.7,0.97,.9,0.97,"NDC") pvt1.AddText('5.0 #times 10^{34} Hz/cm^{2} (13 TeV)') pvt1.SetFillStyle(0) pvt1.SetBorderSize(0) pvt1.SetTextSize(0.03) pvt1.Draw() legenda = TLegend(0.4, 0.7, .7, .9) legenda.SetNColumns(1) legenda.AddEntry(gr0E, "RE1", "p") legenda.AddEntry(gr0W, "RB1in", "p") legenda.AddEntry(gr1W, "RB1out", "p") legenda.SetTextSize(0.05) legenda.Draw("a"); c.SaveAs("etaDistroDetailRB1.png") c.Close() print "----- Creating Second TCanvas -----" c1 = TCanvas("c1", "Canvas",50,50,W,H) c1.SetFillColor(0) c1.SetBorderMode(0) c1.SetFrameFillStyle(0) c1.SetFrameBorderMode(0) c1.SetLeftMargin( L/W ) c1.SetRightMargin( R/W ) c1.SetTopMargin( T/H ) c1.SetBottomMargin( B/H ) c1.SetTickx(0) c1.SetTicky(0) gPad.SetLogy() print " ------------ Creating TMultiGraph -----------" mgd2 = TMultiGraph() mgd2.Add(gr3E,"AP") mgd2.Add(gr3W,"AP") mgd2.Add(gr10E,"AP") mgd2.Add(gr10W,"AP") mgd2.Add(gr4W,"AP") mgd2.Add(gr11W,"AP") mgd2.Draw("a") mgd2.SetTitle( 'RB1in') mgd2.GetXaxis().SetTitle( '#eta' ) mgd2.GetYaxis().SetTitle( 'RPC single hit rate (Hz/cm^{2})' ) mgd2.SetMaximum(maxY) mgd2.GetXaxis().SetLabelFont(42) mgd2.GetXaxis().SetLabelOffset(0.007) mgd2.GetXaxis().SetLabelSize(0.043) mgd2.GetXaxis().SetTitleSize(0.05) mgd2.GetXaxis().SetTitleOffset(1.06) mgd2.GetXaxis().SetTitleFont(42) mgd2.GetYaxis().SetLabelFont(42) mgd2.GetYaxis().SetLabelOffset(0.008) mgd2.GetYaxis().SetLabelSize(0.05) mgd2.GetYaxis().SetTitleSize(0.06) mgd2.GetYaxis().SetTitleOffset(0.87) mgd2.GetYaxis().SetTitleFont(42) pv = TPaveText(.1,0.97,.55,0.97,"NDC") #(.06,.4,.55,.73) pv.AddText('CMS Preliminary') pv.SetFillStyle(0) pv.SetBorderSize(0) pv.SetTextSize(0.03) pv.Draw() pv1 = TPaveText(.7,0.97,.9,0.97,"NDC") pv1.AddText('5.0 #times 10^{34} Hz/cm^{2} (13 TeV)') pv1.SetFillStyle(0) pv1.SetBorderSize(0) pv1.SetTextSize(0.03) pv1.Draw() legendd2 = TLegend(0.4, 0.6, .7, .8) legendd2.SetNColumns(1) legendd2.AddEntry(gr3E, "RE2", "p") legendd2.AddEntry(gr3W, "RB2in", "p") legendd2.AddEntry(gr4W, "RB2out", "p") legendd2.SetTextSize(0.05) legendd2.Draw("a"); c1.SaveAs("etaDistroDetailRB2.png") c1.Close() print "is there an error here?"