def plot(var, cut, year, norm=False, nm1=False): ### Preliminary Operations ### treeRead = not cut in [ "nnqq", "en", "enqq", "mn", "mnqq", "ee", "eeqq", "mm", "mmqq", "em", "emqq", "qqqq" ] # Read from tree channel = cut unit = '' if "GeV" in variable[var]['title']: unit = ' GeV' isBlind = BLIND and 'SR' in channel isAH = False #'qqqq' in channel or 'hp' in channel or 'lp' in channel showSignal = False if 'SB' in cut or 'TR' in cut else True #'SR' in channel or channel=='qqqq'#or len(channel)==5 stype = "HVT model B" if len(sign) > 0 and 'AZh' in sign[0]: stype = "2HDM" elif len(sign) > 0 and 'monoH' in sign[0]: stype = "Z'-2HDM m_{A}=300 GeV" if treeRead: for k in sorted(alias.keys(), key=len, reverse=True): if BTAGGING == 'semimedium': if k in cut: if ADDSELECTION: cut = cut.replace( k, aliasSM[k] + SELECTIONS[options.selection]) else: cut = cut.replace(k, aliasSM[k]) else: if k in cut: if ADDSELECTION: cut = cut.replace( k, alias[k].format(WP=working_points[BTAGGING]) + SELECTIONS[options.selection]) else: cut = cut.replace( k, alias[k].format(WP=working_points[BTAGGING])) # Determine Primary Dataset pd = sample['data_obs']['files'] print "Plotting from", ("tree" if treeRead else "file"), var, "in", channel, "channel with:" print " dataset:", pd print " cut :", cut if var == 'jj_deltaEta_widejet': if "jj_deltaEta_widejet<1.1 && " in cut: print print "omitting jj_deltaEta_widejet<1.1 cut to draw the deltaEta distribution" print cut = cut.replace("jj_deltaEta_widejet<1.1 && ", "") else: print print "no 'jj_deltaEta_widejet<1.1 && ' in the cut string detected, so it cannot be ommited explicitly" print ### Create and fill MC histograms ### # Create dict file = {} tree = {} hist = {} ### Create and fill MC histograms ### for i, s in enumerate(data + back + sign): if treeRead: # Project from tree tree[s] = TChain("tree") for j, ss in enumerate(sample[s]['files']): if not 'data' in s or ('data' in s and ss in pd): if year == "run2" or year in ss: tree[s].Add(NTUPLEDIR + ss + ".root") if variable[var]['nbins'] > 0: hist[s] = TH1F( s, ";" + variable[var]['title'] + ";Events / ( " + str( (variable[var]['max'] - variable[var]['min']) / variable[var]['nbins']) + unit + " );" + ('log' if variable[var]['log'] else ''), variable[var]['nbins'], variable[var]['min'], variable[var]['max']) else: hist[s] = TH1F( s, ";" + variable[var]['title'] + ";Events" + ('log' if variable[var]['log'] else ''), len(variable[var]['bins']) - 1, array('f', variable[var]['bins'])) hist[s].Sumw2() cutstring = "(eventWeightLumi)" + ("*(" + cut + ")" if len(cut) > 0 else "") tree[s].Project(s, var, cutstring) if not tree[s].GetTree() == None: hist[s].SetOption("%s" % tree[s].GetTree().GetEntriesFast()) else: # Histogram written to file for j, ss in enumerate(sample[s]['files']): if not 'data' in s or ('data' in s and ss in pd): file[ss] = TFile(NTUPLEDIR + ss + ".root", "R") if file[ss].IsZombie(): print "WARNING: file", NTUPLEDIR + ss + ".root", "does not exist" continue tmphist = file[ss].Get(cut + "/" + var) if tmphist == None: continue if not s in hist.keys(): hist[s] = tmphist else: hist[s].Add(tmphist) hist[s].Scale(sample[s]['weight'] if hist[s].Integral() >= 0 else 0) hist[s].SetFillColor(sample[s]['fillcolor']) hist[s].SetFillStyle(sample[s]['fillstyle']) hist[s].SetLineColor(sample[s]['linecolor']) hist[s].SetLineStyle(sample[s]['linestyle']) if channel.endswith('TR') and channel.replace('TR', '') in topSF: hist['TTbarSL'].Scale(topSF[channel.replace('TR', '')][0]) hist['ST'].Scale(topSF[channel.replace('TR', '')][0]) hist['BkgSum'] = hist['data_obs'].Clone( "BkgSum") if 'data_obs' in hist else hist[back[0]].Clone("BkgSum") hist['BkgSum'].Reset("MICES") hist['BkgSum'].SetFillStyle(3003) hist['BkgSum'].SetFillColor(1) for i, s in enumerate(back): hist['BkgSum'].Add(hist[s]) if options.norm: for i, s in enumerate(back + ['BkgSum']): hist[s].Scale(hist[data[0]].Integral() / hist['BkgSum'].Integral()) # Create data and Bkg sum histograms if options.blind or 'SR' in channel: hist['data_obs'] = hist['BkgSum'].Clone("data_obs") hist['data_obs'].Reset("MICES") # Set histogram style hist['data_obs'].SetMarkerStyle(20) hist['data_obs'].SetMarkerSize(1.25) for i, s in enumerate(data + back + sign + ['BkgSum']): addOverflow(hist[s], False) # Add overflow for i, s in enumerate(sign): hist[s].SetLineWidth(3) for i, s in enumerate(sign): sample[s][ 'plot'] = True #sample[s]['plot'] and s.startswith(channel[:2]) if isAH: for i, s in enumerate(back): hist[s].SetFillStyle(3005) hist[s].SetLineWidth(2) #for i, s in enumerate(sign): # hist[s].SetFillStyle(0) if not var == "Events": sfnorm = hist[data[0]].Integral() / hist['BkgSum'].Integral() print "Applying SF:", sfnorm for i, s in enumerate(back + ['BkgSum']): hist[s].Scale(sfnorm) if BLIND and var.endswith("Mass"): for i, s in enumerate(data + back + ['BkgSum']): first, last = hist[s].FindBin(65), hist[s].FindBin(135) for j in range(first, last): hist[s].SetBinContent(j, -1.e-4) if BLIND and var.endswith("Tau21"): for i, s in enumerate(data): first, last = hist[s].FindBin(0), hist[s].FindBin(0.6) for j in range(first, last): hist[s].SetBinContent(j, -1.e-4) if SYNC and var == "jj_mass_widejet" and year in ["2016", "2017", "2018"]: #iFile = TFile("sync/JetHT_run" + year + "_red_cert_scan.root", "READ") #hist['sync'] = iFile.Get("Mjj") if year == '2016': iFile = TFile("sync/2016/2016_07Aug2017_1246_1p1.root", "READ") hist['sync'] = iFile.Get("h_mjj_data") elif year == '2017': iFile = TFile( "sync/2017/histos_Run2017BCDEF_17Nov2017_JEC2017_mjj1530_cemf_lt_0p8_deltaETA_lt_1p1.root", "READ") hist['sync'] = iFile.Get("h_mjj_data") elif year == '2018': iFile = TFile( "sync/2018/Double_sideband_inputs_18v10_preliminary_v2.root", "READ") hist['sync'] = iFile.Get("h_mjj") # hist['sync'] = tmp.Rebin(len(dijet_bins)-1, "sync", array('d', dijet_bins)) # hist['sync'] = tmp.Rebin(100, "sync") hist['sync'].SetMarkerStyle(31) hist['sync'].SetMarkerSize(1.25) hist['sync'].SetMarkerColor(2) print "Imported and drawing sync file" # Create stack if variable[var]['nbins'] > 0: bkg = THStack( "Bkg", ";" + hist['BkgSum'].GetXaxis().GetTitle() + ";Events / ( " + str( (variable[var]['max'] - variable[var]['min']) / variable[var]['nbins']) + unit + " )") else: bkg = THStack("Bkg", ";" + hist['BkgSum'].GetXaxis().GetTitle() + ";Events; ") for i, s in enumerate(back): bkg.Add(hist[s]) # Legend leg = TLegend(0.65, 0.6, 0.95, 0.9) leg.SetBorderSize(0) leg.SetFillStyle(0) #1001 leg.SetFillColor(0) if len(data) > 0: leg.AddEntry(hist[data[0]], sample[data[0]]['label'], "pe") for i, s in reversed(list(enumerate(['BkgSum'] + back))): leg.AddEntry(hist[s], sample[s]['label'], "f") if showSignal: for i, s in enumerate(sign): if sample[s]['plot']: leg.AddEntry(hist[s], sample[s]['label'], "fl") leg.SetY1(0.9 - leg.GetNRows() * 0.05) # --- Display --- c1 = TCanvas("c1", hist.values()[0].GetXaxis().GetTitle(), 800, 800 if RATIO else 600) if RATIO: c1.Divide(1, 2) setTopPad(c1.GetPad(1), RATIO) setBotPad(c1.GetPad(2), RATIO) c1.cd(1) c1.GetPad(bool(RATIO)).SetTopMargin(0.06) c1.GetPad(bool(RATIO)).SetRightMargin(0.05) c1.GetPad(bool(RATIO)).SetTicks(1, 1) log = variable[var]['log'] #"log" in hist['BkgSum'].GetZaxis().GetTitle() if log: c1.GetPad(bool(RATIO)).SetLogy() # Draw bkg.Draw("HIST") # stack hist['BkgSum'].Draw("SAME, E2") # sum of bkg if not isBlind and len(data) > 0: hist['data_obs'].Draw("SAME, PE") # data if 'sync' in hist: hist['sync'].Draw("SAME, PE") #data_graph.Draw("SAME, PE") if showSignal: smagn = 1. #if treeRead else 1.e2 #if log else 1.e2 for i, s in enumerate(sign): # if sample[s]['plot']: hist[s].Scale(smagn) hist[s].Draw( "SAME, HIST" ) # signals Normalized, hist[s].Integral()*sample[s]['weight'] textS = drawText(0.80, 0.9 - leg.GetNRows() * 0.05 - 0.02, stype + " (x%d)" % smagn, True) #bkg.GetYaxis().SetTitleOffset(bkg.GetYaxis().GetTitleOffset()*1.075) bkg.GetYaxis().SetTitleOffset(0.9) #bkg.GetYaxis().SetTitleOffset(2.) bkg.SetMaximum((5. if log else 1.25) * max( bkg.GetMaximum(), hist['data_obs'].GetBinContent(hist['data_obs'].GetMaximumBin()) + hist['data_obs'].GetBinError(hist['data_obs'].GetMaximumBin()))) #if bkg.GetMaximum() < max(hist[sign[0]].GetMaximum(), hist[sign[-1]].GetMaximum()): bkg.SetMaximum(max(hist[sign[0]].GetMaximum(), hist[sign[-1]].GetMaximum())*1.25) bkg.SetMinimum( max( min(hist['BkgSum'].GetBinContent(hist['BkgSum'].GetMinimumBin( )), hist['data_obs'].GetMinimum()), 5.e-1) if log else 0.) if log: bkg.GetYaxis().SetNoExponent(bkg.GetMaximum() < 1.e4) #bkg.GetYaxis().SetMoreLogLabels(True) bkg.GetXaxis().SetRangeUser(variable[var]['min'], variable[var]['max']) #if log: bkg.SetMinimum(1) leg.Draw() #drawCMS(LUMI[year], "Preliminary") #drawCMS(LUMI[year], "Work in Progress", suppressCMS=True) drawCMS(LUMI[year], "", suppressCMS=True) drawRegion('XVH' + channel, True) drawAnalysis(channel) setHistStyle(bkg, 1.2 if RATIO else 1.1) setHistStyle(hist['BkgSum'], 1.2 if RATIO else 1.1) if RATIO: c1.cd(2) err = hist['BkgSum'].Clone("BkgErr;") err.SetTitle("") if SYNC: err.GetYaxis().SetTitle("Nano/Mini") else: err.GetYaxis().SetTitle("Data / MC") err.GetYaxis().SetTitleOffset(0.9) err.GetXaxis().SetRangeUser(variable[var]['min'], variable[var]['max']) for i in range(1, err.GetNbinsX() + 1): err.SetBinContent(i, 1) if hist['BkgSum'].GetBinContent(i) > 0: err.SetBinError( i, hist['BkgSum'].GetBinError(i) / hist['BkgSum'].GetBinContent(i)) setBotStyle(err) errLine = err.Clone("errLine") errLine.SetLineWidth(1) errLine.SetFillStyle(0) res = hist['data_obs'].Clone("Residues") for i in range(0, res.GetNbinsX() + 1): if hist['BkgSum'].GetBinContent(i) > 0: res.SetBinContent( i, res.GetBinContent(i) / hist['BkgSum'].GetBinContent(i)) res.SetBinError( i, res.GetBinError(i) / hist['BkgSum'].GetBinContent(i)) if 'sync' in hist: res.SetMarkerColor(1) res.SetMarkerStyle(20) res.Reset() for i in range(0, res.GetNbinsX() + 1): x = hist['data_obs'].GetXaxis().GetBinCenter(i) if hist['sync'].GetBinContent(hist['sync'].FindBin(x)) > 0: res.SetBinContent( i, hist['data_obs'].GetBinContent( hist['data_obs'].FindBin(x)) / hist['sync'].GetBinContent(hist['sync'].FindBin(x))) res.SetBinError( i, hist['data_obs'].GetBinError( hist['data_obs'].FindBin(x)) / hist['sync'].GetBinContent(hist['sync'].FindBin(x))) setBotStyle(res) #err.GetXaxis().SetLabelOffset(err.GetXaxis().GetLabelOffset()*5) #err.GetXaxis().SetTitleOffset(err.GetXaxis().GetTitleOffset()*2) err.Draw("E2") errLine.Draw("SAME, HIST") if not isBlind and len(data) > 0: res.Draw("SAME, PE0") #res_graph.Draw("SAME, PE0") if len(err.GetXaxis().GetBinLabel( 1)) == 0: # Bin labels: not a ordinary plot drawRatio(hist['data_obs'], hist['BkgSum']) drawStat(hist['data_obs'], hist['BkgSum']) if SYNC: err.GetYaxis().SetRangeUser(0.9, 1.1) c1.Update() if gROOT.IsBatch(): if channel == "": channel = "nocut" varname = var.replace('.', '_').replace('()', '') if not os.path.exists("plots/" + channel): os.makedirs("plots/" + channel) suffix = '' if "b" in channel or 'mu' in channel: suffix += "_" + BTAGGING if ADDSELECTION: suffix += "_" + options.selection c1.Print("plots/" + channel + "/" + varname + "_" + year + suffix + ".png") c1.Print("plots/" + channel + "/" + varname + "_" + year + suffix + ".pdf") # Print table printTable(hist, sign) # if True: # sFile = TFile("sync/data_2016.root", "RECREATE") # sFile.cd() # hist['data_obs']. if not gROOT.IsBatch(): raw_input("Press Enter to continue...")
pad = c1.cd(1) pad.SetPad(0, 0.3, 1, 1) pad.SetTopMargin(0.1) pad.SetBottomMargin(0.005) t = pad.GetTopMargin() # prepare the 2nd pad pad = c1.cd(2) pad.SetPad(0, 0.0, 1, 0.3) pad.SetTopMargin(0.06) pad.SetBottomMargin(0.4) pad.SetTickx(1) pad.SetTicky(1) c1.cd(1) hs.SetMaximum(hs.GetMaximum() * 5) hs.SetMinimum(0.1) gPad.SetLogy() hs.Draw("Hist") h_bkg.Draw("e2 same") h_data.Draw("same") for ihist in reversed(templates[5:8]): print 'overlaying, ', ihist.GetName() ihist.Draw("ehist same") xTitle = h_top.GetXaxis().GetTitle() yTitle = h_top.GetYaxis().GetTitle() setTitle(hs, xTitle)
def SaveHisto1D(HIST, suffix, output, snorm=1, ratio=0, poisson=True, logy=False, isVal=False): # only data and mc # SUFFIX = 2016_ss_lep1_pt bkgsum = 'BkgSum_%s' % (suffix) HIST[bkgsum] = HIST['DATA_%s' % (suffix)].Clone("BkgSum") if 'DATA_%s' % ( suffix) in HIST else HIST['MC_%s' % (suffix)].Clone("BkgSum") HIST[bkgsum].Reset("MICES") HIST[bkgsum].SetFillStyle(3003) HIST[bkgsum].SetFillColor(1) HIST[bkgsum].SetMarkerStyle(0) HIST[bkgsum].Add(HIST['MC_%s' % (suffix)]) HIST['DATA_%s' % (suffix)].SetMarkerStyle(20) HIST['DATA_%s' % (suffix)].SetMarkerSize(1.25) HIST['DATA_%s' % (suffix)].SetFillColor(418) HIST['DATA_%s' % (suffix)].SetFillStyle(1001) HIST['DATA_%s' % (suffix)].SetLineColor(1) HIST['DATA_%s' % (suffix)].SetLineStyle(1) HIST['DATA_%s' % (suffix)].SetLineWidth(2) HIST['MC_%s' % (suffix)].SetFillColor(418) HIST['MC_%s' % (suffix)].SetFillStyle(1001) HIST['MC_%s' % (suffix)].SetLineColor(418) HIST['MC_%s' % (suffix)].SetLineStyle(1) HIST['MC_%s' % (suffix)].SetLineWidth(2) for i, s in enumerate(HIST): addOverflow(HIST[s], False) # Add overflow #Stack bkg = THStack( 'bkg', ";" + HIST[bkgsum].GetXaxis().GetTitle() + ";" + HIST[bkgsum].GetYaxis().GetTitle()) bkg.Add(HIST['MC_%s' % (suffix)]) # ADD ALL BKG #Legend n = len(HIST) leg = TLegend(0.7, 0.9 - 0.05 * n, 0.95, 0.9) leg.SetBorderSize(0) leg.SetFillStyle(0) #1001 leg.SetFillColor(0) leg.SetTextSize(0.03) leg.AddEntry(HIST['DATA_%s' % (suffix)], 'Data [%.1f]' % (HIST['DATA_%s' % (suffix)].Integral()), "pl") leg.AddEntry(HIST['MC_%s' % (suffix)], 'DY [%.1f]' % (HIST['MC_%s' % (suffix)].Integral()), "f") #if isFake: leg.AddEntry(HIST['FAKE_%s' %(suffix)], 'Fake [%.1f]' %(HIST['FAKE_%s' %(suffix)].Integral()), "f") leg.AddEntry(HIST[bkgsum], 'BkgSum [%.1f]' % (HIST[bkgsum].Integral()), "f") c1 = TCanvas("c1", HIST.values()[-1].GetXaxis().GetTitle(), 800, 800 if ratio else 600) #Ratio pad if ratio: c1.Divide(1, 2) setTopPad(c1.GetPad(1), ratio) setBotPad(c1.GetPad(2), ratio) c1.cd(1) c1.GetPad(bool(ratio)).SetTopMargin(0.06) c1.GetPad(bool(ratio)).SetRightMargin(0.05) c1.GetPad(bool(ratio)).SetTicks(1, 1) if logy: c1.GetPad(bool(ratio)).SetLogy() #Draw bkg.Draw("HIST") # stack HIST[bkgsum].Draw("SAME, E2") # sum of bkg HIST['DATA_%s' % (suffix)].Draw("SAME, PE") # data bkg.GetYaxis().SetTitleOffset(bkg.GetYaxis().GetTitleOffset() * 1) #1.075 bkg.SetMaximum((6.0 if logy else 1.5) * max( bkg.GetMaximum(), HIST['DATA_%s' % (suffix)].GetBinContent(HIST['DATA_%s' % (suffix)].GetMaximumBin()) + HIST['DATA_%s' % (suffix)].GetBinError(HIST['DATA_%s' % (suffix)].GetMaximumBin()))) bkg.SetMinimum( max( min(HIST[bkgsum].GetBinContent(HIST[bkgsum].GetMinimumBin( )), HIST['DATA_%s' % (suffix)].GetMinimum()), 5.e-1) if logy else 0.) #bkg.SetMinimum(1.0) leg.Draw() setHistStyle(bkg, 1.2 if ratio else 1.1) setHistStyle(HIST[bkgsum], 1.2 if ratio else 1.1) ########################## if ratio: c1.cd(2) err = HIST[bkgsum].Clone("BkgErr;") err.SetTitle("") err.GetYaxis().SetTitle("Data / Bkg") for i in range(1, err.GetNbinsX() + 1): err.SetBinContent(i, 1) if HIST[bkgsum].GetBinContent(i) > 0: err.SetBinError( i, HIST[bkgsum].GetBinError(i) / HIST[bkgsum].GetBinContent(i)) setBotStyle(err) errLine = err.Clone("errLine") errLine.SetLineWidth(1) errLine.SetFillStyle(0) errLine.SetLineColor(1) err.Draw("E2") errLine.Draw("SAME, HIST") if 'DATA_%s' % (suffix) in HIST: res = HIST['DATA_%s' % (suffix)].Clone("Residues") for i in range(0, res.GetNbinsX() + 1): if HIST[bkgsum].GetBinContent(i) > 0: res.SetBinContent( i, res.GetBinContent(i) / HIST[bkgsum].GetBinContent(i)) res.SetBinError( i, res.GetBinError(i) / HIST[bkgsum].GetBinContent(i)) setBotStyle(res) res.Draw("SAME, PE0") if len(err.GetXaxis().GetBinLabel( 1)) == 0: # Bin labels: not a ordinary plot drawRatio(HIST['DATA_%s' % (suffix)], HIST[bkgsum]) drawKolmogorov(HIST['DATA_%s' % (suffix)], HIST[bkgsum]) #drawRelativeYield(HIST['DATA_%s' %(suffix)], HIST[bkgsum]) else: res = None c1.cd(1) if '2016' in output: drawCMS("35.87", "Object Study") elif '2017' in output: drawCMS("41.53", "Object Study") elif '2018' in output: drawCMS("59.74", "Object Study") if 'os' in suffix: drawRegion('Opposite Sign') elif 'ss' in suffix: drawRegion('Same Sign') c1.Update() c1.Print('%s/hstack_%s.png' % (output, suffix))
def DeepCSV_pt_distribution( year): ## everything below is jsut copy&past from above from root_numpy import root2array, fill_hist, array2root import numpy.lib.recfunctions as rfn from aliases import alias_deepCSV, WP_deepCSV ### Preliminary Operations ### treeRead = True var = 'jpt_1' channel = 'preselection' cut = alias_deepCSV['preselection'] unit = '' if "GeV" in variable[var]['title']: unit = ' GeV' isBlind = BLIND and 'SR' in channel isAH = False showSignal = True stype = "HVT model B" if len(sign) > 0 and 'AZh' in sign[0]: stype = "2HDM" elif len(sign) > 0 and 'monoH' in sign[0]: stype = "Z'-2HDM m_{A}=300 GeV" if treeRead: for k in sorted(alias_deepCSV.keys(), key=len, reverse=True): if k in cut: cut = cut.replace( k, alias_deepCSV[k].format(WP=WP_deepCSV[BTAGGING][year])) print "Plotting from", ("tree" if treeRead else "file"), var, "in", channel, "channel with:" print " cut :", cut ### Create and fill MC histograms ### # Create dict file = {} tree = {} hist = {} N_signal_tot = 0. N_signal_tag = 0. ### Create and fill MC histograms ### for i, s in enumerate(back + sign): if variable[var]['nbins'] > 0: hist[s] = TH1F( s, ";jet p_{T};Events / ( " + str( (variable[var]['max'] - variable[var]['min']) / variable[var]['nbins']) + unit + " );" + ('log' if variable[var]['log'] else ''), variable[var]['nbins'], variable[var]['min'], variable[var]['max']) else: hist[s] = TH1F( s, ";jet p_{T};Events" + ('log' if variable[var]['log'] else ''), len(variable[var]['bins']) - 1, array('f', variable[var]['bins'])) hist[s].Sumw2() for j, ss in enumerate(sample[s]['files']): if not 'data' in s: if year == "run2" or year in ss: arr = root2array(NTUPLEDIR + ss + ".root", branches=["jpt_1", "eventWeightLumi"], selection=cut + " && jdeepCSV_1>" + str(WP_deepCSV[BTAGGING][year])) if 'signal' in ss.lower(): N_signal_tag += len(arr['jpt_1'][arr['jpt_1'] > 3500]) print "imported " + NTUPLEDIR + ss + ".root" fill_hist(hist[s], arr["jpt_1"], weights=arr["eventWeightLumi"]) arr = None arr = root2array(NTUPLEDIR + ss + ".root", branches=["jpt_2", "eventWeightLumi"], selection=cut + " && jdeepCSV_2>" + str(WP_deepCSV[BTAGGING][year])) print "imported " + NTUPLEDIR + ss + ".root" if 'signal' in ss.lower(): N_signal_tag += len(arr['jpt_2'][arr['jpt_2'] > 3500]) fill_hist(hist[s], arr["jpt_2"], weights=arr["eventWeightLumi"]) arr = None if 'signal' in ss.lower(): arr = root2array(NTUPLEDIR + ss + ".root", branches=["jpt_1", "eventWeightLumi"], selection=cut) N_signal_tot += len(arr['jpt_1'][arr['jpt_1'] > 3500]) arr = None arr = root2array(NTUPLEDIR + ss + ".root", branches=["jpt_2", "eventWeightLumi"], selection=cut) N_signal_tot += len(arr['jpt_2'][arr['jpt_2'] > 3500]) arr = None hist[s].Scale(sample[s]['weight'] if hist[s].Integral() >= 0 else 0) hist[s].SetFillColor(sample[s]['fillcolor']) hist[s].SetFillStyle(sample[s]['fillstyle']) hist[s].SetLineColor(sample[s]['linecolor']) hist[s].SetLineStyle(sample[s]['linestyle']) if channel.endswith('TR') and channel.replace('TR', '') in topSF: hist['TTbarSL'].Scale(topSF[channel.replace('TR', '')][0]) hist['ST'].Scale(topSF[channel.replace('TR', '')][0]) hist['BkgSum'] = hist['data_obs'].Clone( "BkgSum") if 'data_obs' in hist else hist[back[0]].Clone("BkgSum") hist['BkgSum'].Reset("MICES") hist['BkgSum'].SetFillStyle(3003) hist['BkgSum'].SetFillColor(1) for i, s in enumerate(back): hist['BkgSum'].Add(hist[s]) # Create data and Bkg sum histograms if options.blind or 'SR' in channel: hist['data_obs'] = hist['BkgSum'].Clone("data_obs") hist['data_obs'].Reset("MICES") # Set histogram style hist['data_obs'].SetMarkerStyle(20) hist['data_obs'].SetMarkerSize(1.25) for i, s in enumerate(back + sign + ['BkgSum']): addOverflow(hist[s], False) # Add overflow for i, s in enumerate(sign): hist[s].SetLineWidth(3) for i, s in enumerate(sign): sample[s][ 'plot'] = True #sample[s]['plot'] and s.startswith(channel[:2]) if isAH: for i, s in enumerate(back): hist[s].SetFillStyle(3005) hist[s].SetLineWidth(2) #for i, s in enumerate(sign): # hist[s].SetFillStyle(0) if not var == "Events": sfnorm = hist[data[0]].Integral() / hist['BkgSum'].Integral() print "Applying SF:", sfnorm for i, s in enumerate(back + ['BkgSum']): hist[s].Scale(sfnorm) if BLIND and var.endswith("Mass"): for i, s in enumerate(data + back + ['BkgSum']): first, last = hist[s].FindBin(65), hist[s].FindBin(135) for j in range(first, last): hist[s].SetBinContent(j, -1.e-4) if BLIND and var.endswith("Tau21"): for i, s in enumerate(data): first, last = hist[s].FindBin(0), hist[s].FindBin(0.6) for j in range(first, last): hist[s].SetBinContent(j, -1.e-4) # Create stack if variable[var]['nbins'] > 0: bkg = THStack( "Bkg", ";" + hist['BkgSum'].GetXaxis().GetTitle() + ";Events / ( " + str( (variable[var]['max'] - variable[var]['min']) / variable[var]['nbins']) + unit + " )") else: bkg = THStack("Bkg", ";" + hist['BkgSum'].GetXaxis().GetTitle() + ";Events; ") for i, s in enumerate(back): bkg.Add(hist[s]) # Legend leg = TLegend(0.65, 0.6, 0.95, 0.9) leg.SetBorderSize(0) leg.SetFillStyle(0) #1001 leg.SetFillColor(0) if len(data) > 0: leg.AddEntry(hist[data[0]], sample[data[0]]['label'], "pe") for i, s in reversed(list(enumerate(['BkgSum'] + back))): leg.AddEntry(hist[s], sample[s]['label'], "f") if showSignal: for i, s in enumerate(sign): if sample[s]['plot']: leg.AddEntry(hist[s], sample[s]['label'], "fl") leg.SetY1(0.9 - leg.GetNRows() * 0.05) # --- Display --- c1 = TCanvas("c1", hist.values()[0].GetXaxis().GetTitle(), 800, 800 if RATIO else 600) if RATIO: c1.Divide(1, 2) setTopPad(c1.GetPad(1), RATIO) setBotPad(c1.GetPad(2), RATIO) c1.cd(1) c1.GetPad(bool(RATIO)).SetTopMargin(0.06) c1.GetPad(bool(RATIO)).SetRightMargin(0.05) c1.GetPad(bool(RATIO)).SetTicks(1, 1) log = variable[var]['log'] #"log" in hist['BkgSum'].GetZaxis().GetTitle() if log: c1.GetPad(bool(RATIO)).SetLogy() # Draw bkg.Draw("HIST") # stack hist['BkgSum'].Draw("SAME, E2") # sum of bkg if not isBlind and len(data) > 0: hist['data_obs'].Draw("SAME, PE") # data if 'sync' in hist: hist['sync'].Draw("SAME, PE") #data_graph.Draw("SAME, PE") if showSignal: smagn = 1. #if treeRead else 1.e2 #if log else 1.e2 for i, s in enumerate(sign): # if sample[s]['plot']: hist[s].Scale(smagn) hist[s].Draw( "SAME, HIST" ) # signals Normalized, hist[s].Integral()*sample[s]['weight'] textS = drawText(0.80, 0.9 - leg.GetNRows() * 0.05 - 0.02, stype + " (x%d)" % smagn, True) #bkg.GetYaxis().SetTitleOffset(bkg.GetYaxis().GetTitleOffset()*1.075) bkg.GetYaxis().SetTitleOffset(0.9) #bkg.GetYaxis().SetTitleOffset(2.) bkg.SetMaximum((5. if log else 1.25) * max( bkg.GetMaximum(), hist['data_obs'].GetBinContent(hist['data_obs'].GetMaximumBin()) + hist['data_obs'].GetBinError(hist['data_obs'].GetMaximumBin()))) #if bkg.GetMaximum() < max(hist[sign[0]].GetMaximum(), hist[sign[-1]].GetMaximum()): bkg.SetMaximum(max(hist[sign[0]].GetMaximum(), hist[sign[-1]].GetMaximum())*1.25) bkg.SetMinimum( max( min(hist['BkgSum'].GetBinContent(hist['BkgSum'].GetMinimumBin( )), hist['data_obs'].GetMinimum()), 5.e-1) if log else 0.) if log: bkg.GetYaxis().SetNoExponent(bkg.GetMaximum() < 1.e4) #bkg.GetYaxis().SetMoreLogLabels(True) bkg.GetXaxis().SetRangeUser(variable[var]['min'], variable[var]['max']) #if log: bkg.SetMinimum(1) leg.Draw() #drawCMS(LUMI[year], "Preliminary") drawCMS(LUMI[year], "", suppressCMS=True) drawRegion('XVH' + channel, True) drawAnalysis(channel) setHistStyle(bkg, 1.2 if RATIO else 1.1) setHistStyle(hist['BkgSum'], 1.2 if RATIO else 1.1) if RATIO: c1.cd(2) err = hist['BkgSum'].Clone("BkgErr;") err.SetTitle("") err.GetYaxis().SetTitle("Data / MC") err.GetYaxis().SetTitleOffset(0.9) err.GetXaxis().SetRangeUser(variable[var]['min'], variable[var]['max']) for i in range(1, err.GetNbinsX() + 1): err.SetBinContent(i, 1) if hist['BkgSum'].GetBinContent(i) > 0: err.SetBinError( i, hist['BkgSum'].GetBinError(i) / hist['BkgSum'].GetBinContent(i)) setBotStyle(err) errLine = err.Clone("errLine") errLine.SetLineWidth(1) errLine.SetFillStyle(0) res = hist['data_obs'].Clone("Residues") for i in range(0, res.GetNbinsX() + 1): if hist['BkgSum'].GetBinContent(i) > 0: res.SetBinContent( i, res.GetBinContent(i) / hist['BkgSum'].GetBinContent(i)) res.SetBinError( i, res.GetBinError(i) / hist['BkgSum'].GetBinContent(i)) if 'sync' in hist: res.SetMarkerColor(2) res.SetMarkerStyle(31) res.Reset() for i in range(0, res.GetNbinsX() + 1): x = hist['data_obs'].GetXaxis().GetBinCenter(i) if hist['sync'].GetBinContent(hist['sync'].FindBin(x)) > 0: res.SetBinContent( i, hist['data_obs'].GetBinContent( hist['data_obs'].FindBin(x)) / hist['sync'].GetBinContent(hist['sync'].FindBin(x))) res.SetBinError( i, hist['data_obs'].GetBinError( hist['data_obs'].FindBin(x)) / hist['sync'].GetBinContent(hist['sync'].FindBin(x))) setBotStyle(res) #err.GetXaxis().SetLabelOffset(err.GetXaxis().GetLabelOffset()*5) #err.GetXaxis().SetTitleOffset(err.GetXaxis().GetTitleOffset()*2) err.Draw("E2") errLine.Draw("SAME, HIST") if not isBlind and len(data) > 0: res.Draw("SAME, PE0") #res_graph.Draw("SAME, PE0") if len(err.GetXaxis().GetBinLabel( 1)) == 0: # Bin labels: not a ordinary plot drawRatio(hist['data_obs'], hist['BkgSum']) drawStat(hist['data_obs'], hist['BkgSum']) c1.Update() if gROOT.IsBatch(): if channel == "": channel = "nocut" varname = var.replace('.', '_').replace('()', '') if not os.path.exists("plots/" + channel): os.makedirs("plots/" + channel) suffix = '' if "b" in channel or 'mu' in channel: suffix += "_" + BTAGGING c1.Print("plots/MANtag_study/deepCSV_plots/pt_" + year + suffix + ".png") c1.Print("plots/MANtag_study/deepCSV_plots/pt_" + year + suffix + ".pdf") # Print table printTable(hist, sign) print 'deepCSV efficiency:', N_signal_tag / N_signal_tot
latex.SetTextFont(42) latex.SetTextAlign(31) latex.SetTextSize(lumiTextSize * t) posX_ = 0 posY_ = 1 - t - relPosY * (1 - t - b) latex.SetTextFont(cmsTextFont) latex.SetTextSize(0.8 * cmsTextSize * t) latex.SetTextAlign(align_) extraTextSize = extraOverCmsTextSize * cmsTextSize latex.SetTextFont(extraTextFont) latex.SetTextAlign(align_) latex.SetTextSize(0.8 * extraTextSize * t) hs.SetMaximum(1.6 * hs.GetMaximum()) fPads1.cd() hs.Draw("HIST") hs.GetYaxis().SetTitle("Events/bin") hs.GetYaxis().SetTitleSize(0.04) hs.GetYaxis().SetTickLength(0.02) hs.GetYaxis().SetTitleOffset(1.2) hs.GetXaxis().SetTitleOffset(1.3) hs.GetXaxis().SetLabelSize(0.0) hs.GetXaxis().SetTitle("M_{jj} [GeV]") bin_width_signal = ['500', '600', '700', '1000', 'inf'] bin_width_control = ['200', '300', '400', '500'] hs.Print("all") x1 = array('d', (4, 4))
SipMCTTbar[i].SetFillColor(kAzure - 3) SipMCTTbar[i].SetLineColor(kBlack) hs.Add(SipMCTTbar[i]) #MC DY hist SipMCDY[i].Scale(norm) # MC normalization SipMCDY[i].SetFillColor(kAzure + 6) SipMCDY[i].SetLineColor(kBlack) hs.Add(SipMCDY[i]) #upper plot pad pad1 = TPad("pad1", "pad1", 0, 0.3, 1, 1.0) pad1.Draw() pad1.cd() hs.SetMaximum(1.3 * max(hs.GetMaximum(), SipDATA[i].GetMaximum())) SipDATA[i].SetMaximum(1.3 * max(hs.GetMaximum(), SipDATA[i].GetMaximum())) hs.Draw("histo") SipDATA[i].Draw("sameEP") hs.SetTitle("") hs.GetXaxis().SetTitle("SIP") hs.GetXaxis().SetLabelFont(43) hs.GetXaxis().SetLabelSize(15) hs.GetYaxis().SetTitleSize(20) hs.GetYaxis().SetTitleFont(43) hs.GetYaxis().SetTitleOffset(1.8) hs.GetYaxis().SetLabelFont(43) hs.GetYaxis().SetLabelSize(15) hs.GetYaxis().SetTitle("Events")
def draw(hist, data, back, sign, snorm=1, ratio=0, poisson=False, log=False): # If not present, create BkgSum if not 'BkgSum' in hist.keys(): hist['BkgSum'] = hist['data_obs'].Clone( "BkgSum") if 'data_obs' in hist else hist[back[0]].Clone("BkgSum") hist['BkgSum'].Reset("MICES") for i, s in enumerate(back): hist['BkgSum'].Add(hist[s]) hist['BkgSum'].SetMarkerStyle(0) # Some style for i, s in enumerate(data): hist[s].SetMarkerStyle(21) hist[s].SetMarkerSize(1.25) for i, s in enumerate(sign): hist[s].SetLineWidth(3) for i, s in enumerate(data + back + sign + ['BkgSum']): addOverflow(hist[s], False) # Add overflow # Set Poisson error bars #if len(data) > 0: hist['data_obs'].SetBinErrorOption(1) # doesn't work # Poisson error bars for data if poisson: alpha = 1 - 0.6827 hist['data_obs'].SetBinErrorOption(TH1.kPoisson) data_graph = TGraphAsymmErrors(hist['data_obs'].GetNbinsX()) data_graph.SetMarkerStyle(hist['data_obs'].GetMarkerStyle()) data_graph.SetMarkerSize(hist['data_obs'].GetMarkerSize()) res_graph = data_graph.Clone() for i in range(hist['data_obs'].GetNbinsX()): N = hist['data_obs'].GetBinContent(i + 1) B = hist['BkgSum'].GetBinContent(i + 1) L = 0 if N == 0 else ROOT.Math.gamma_quantile(alpha / 2, N, 1.) U = ROOT.Math.gamma_quantile_c(alpha / 2, N + 1, 1) data_graph.SetPoint( i, hist['data_obs'].GetXaxis().GetBinCenter(i + 1), N if not N == 0 else -1.e99) data_graph.SetPointError( i, hist['data_obs'].GetXaxis().GetBinWidth(i + 1) / 2., hist['data_obs'].GetXaxis().GetBinWidth(i + 1) / 2., N - L, U - N) res_graph.SetPoint(i, hist['data_obs'].GetXaxis().GetBinCenter(i + 1), N / B if not B == 0 and not N == 0 else -1.e99) res_graph.SetPointError( i, hist['data_obs'].GetXaxis().GetBinWidth(i + 1) / 2., hist['data_obs'].GetXaxis().GetBinWidth(i + 1) / 2., (N - L) / B if not B == 0 else -1.e99, (U - N) / B if not B == 0 else -1.e99) # Create stack bkg = THStack("Bkg", ";" + hist['BkgSum'].GetXaxis().GetTitle() + ";Events") for i, s in enumerate(back): bkg.Add(hist[s]) # Legend n = len([x for x in data + back + ['BkgSum'] + sign if samples[x]['plot']]) for i, s in enumerate(sign): if 'sublabel' in samples[s]: n += 1 if 'subsublabel' in samples[s]: n += 1 #leg = TLegend(0.68, 0.9-0.05*n, 0.93, 0.9) leg = TLegend(0.68 - 0.05, 0.9 - 0.05 * n, 0.93, 0.9) #DCMS leg.SetTextSize(0.03) #DCMS leg.SetBorderSize(0) leg.SetFillStyle(0) #1001 leg.SetFillColor(0) leg.SetHeader("Signal x-sec=%.0f pb" % (1 * snorm)) if len(data) > 0: leg.AddEntry(hist[data[0]], samples[data[0]]['label'], "ple1") for i, s in reversed(list(enumerate(['BkgSum'] + back))): leg.AddEntry(hist[s], samples[s]['label'], "f") for i, s in enumerate(sign): leg.AddEntry(hist[s], samples[s]['label'], "f") # --- Display --- c1 = TCanvas("c1", hist.values()[-1].GetXaxis().GetTitle(), 1000, 800 if ratio else 700) if ratio: c1.Divide(1, 2) setTopPad(c1.GetPad(1), ratio) setBotPad(c1.GetPad(2), ratio) c1.cd(1) c1.GetPad(bool(ratio)).SetTopMargin(0.06) c1.GetPad(bool(ratio)).SetRightMargin(0.05) c1.GetPad(bool(ratio)).SetTicks(1, 1) if log: c1.GetPad(bool(ratio)).SetLogy() #c1.GetPad(bool(ratio)).SetLogx() # Draw bkg.Draw("HIST") # stack hist['BkgSum'].Draw("SAME, E2") # sum of bkg if poisson: data_graph.Draw("SAME, PE") elif len(data) > 0: hist['data_obs'].Draw("SAME, PE") for i, s in enumerate(sign): if samples[s]['plot']: hist[s].DrawNormalized("SAME, HIST", hist[s].Integral() * snorm) # signals bkg.GetYaxis().SetTitleOffset(bkg.GetYaxis().GetTitleOffset() * 1.075) # Determine range if 'data_obs' in hist: bkg.SetMaximum((2.5 if log else 1.2) * max( bkg.GetMaximum(), hist['data_obs'].GetBinContent(hist['data_obs'].GetMaximumBin()) + hist['data_obs'].GetBinError(hist['data_obs'].GetMaximumBin()))) bkg.SetMinimum( max( min( hist['BkgSum'].GetBinContent(hist['BkgSum'].GetMinimumBin( )), hist['data_obs'].GetMinimum()), 5.e-1) if log else 0.) else: bkg.SetMaximum(bkg.GetMaximum() * (2.5 if log else 1.2)) bkg.SetMinimum(5.e-1 if log else 0.) if log: bkg.GetYaxis().SetNoExponent(bkg.GetMaximum() < 1.e4) bkg.GetYaxis().SetMoreLogLabels(True) leg.Draw() #drawCMS(LUMI, "Preliminary") #drawRegion(channel) #drawAnalysis("LL") setHistStyle(bkg, 1.2 if ratio else 1.1) setHistStyle(hist['BkgSum'], 1.2 if ratio else 1.1) if ratio: c1.cd(2) err = hist['BkgSum'].Clone("BkgErr;") err.SetTitle("") err.GetYaxis().SetTitle("Data / Bkg") for i in range(1, err.GetNbinsX() + 1): err.SetBinContent(i, 1) if hist['BkgSum'].GetBinContent(i) > 0: err.SetBinError( i, hist['BkgSum'].GetBinError(i) / hist['BkgSum'].GetBinContent(i)) setBotStyle(err) errLine = err.Clone("errLine") errLine.SetLineWidth(2) errLine.SetFillStyle(0) errLine.SetLineColor(2) #L# errLine.SetLineStyle(2) #L# #err.GetXaxis().SetLabelOffset(err.GetXaxis().GetLabelOffset()*5) #err.GetXaxis().SetTitleOffset(err.GetXaxis().GetTitleOffset()*2) err.Draw("E2") errLine.Draw("SAME, HIST") if 'data_obs' in hist: res = hist['data_obs'].Clone("Residues") for i in range(0, res.GetNbinsX() + 1): if hist['BkgSum'].GetBinContent(i) > 0: res.SetBinContent( i, res.GetBinContent(i) / hist['BkgSum'].GetBinContent(i)) res.SetBinError( i, res.GetBinError(i) / hist['BkgSum'].GetBinContent(i)) setBotStyle(res) if poisson: res_graph.Draw("SAME, PE0") else: res.Draw("SAME, PE0") if len(err.GetXaxis().GetBinLabel( 1)) == 0: # Bin labels: not a ordinary plot drawRatio(hist['data_obs'], hist['BkgSum']) drawKolmogorov(hist['data_obs'], hist['BkgSum']) else: res = None c1.Update() # return list of objects created by the draw() function return [ c1, bkg, leg, err if ratio else None, errLine if ratio else None, res if ratio else None, data_graph if poisson else None, res_graph if poisson else None ]
def DrawSplotHistograms(DataFileName, DataTreeName, SFileName, STreeName, noStack=True): fData = TFile(DataFileName) tData = fData.Get(DataTreeName) tData.AddFriend(STreeName, SFileName) histoListe = setupHistograms() HistDic = {} for i, h in enumerate(histoListe): legende = TLegend(0.75, 0.83, 0.97, 0.97) CanvasName = "c" + str(i) CanvasName = TCanvas(CanvasName, 'Defining histogram size') g = THStack("", "") #tMC.Draw(histoListe[i][3],CutMC) #hist_MC = tMC.GetHistogram().Clone("hist_MC") #hist_MC.SetLineColor(6) #hist_MC.SetLineWidth(1) ##hist_MC.SetMarkerStyle(21) #legende.AddEntry(hist_MC, "MC", "lp") #hist_MC.GetXaxis().SetTitle(h[1]) #hist_MC.GetYaxis().SetTitle(h[2]) #hist_MC.Scale(1/hist_MC.Integral()) #MaxMC = hist_MC.GetMaximum() #g.Add(hist_MC) tData.Draw(histoListe[i][3], "B_M>5300") hist_data = tData.GetHistogram().Clone("hist_data") hist_data.SetLineColor(5) hist_data.SetLineWidth(1) #hist_data.SetMarkerStyle(21) legende.AddEntry(hist_data, "Data", "lp") hist_data.GetXaxis().SetTitle(h[1]) hist_data.GetYaxis().SetTitle(h[2]) MaxData = hist_data.GetMaximum() g.Add(hist_data) tData.Draw(histoListe[i][3], "nsig_sw") hist_sw = tData.GetHistogram().Clone("hist_sw") hist_sw.SetLineColor(4) hist_sw.SetLineWidth(1) ##hist_RS.SetMarkerStyle(21) legende.AddEntry(hist_sw, "sweighted Data", "lp") MaxSW = hist_sw.GetMaximum() g.Add(hist_sw) if noStack: if (MaxSW > MaxData): g.SetMaximum(MaxSW * 1.2) else: g.SetMaximum(MaxData * 1.2) g.Draw("nostackhist") else: g.SetMaximum(g.GetMaximum() * 1.2) g.Draw("hist") legende.Draw() g.GetXaxis().SetTitle(h[1]) g.GetYaxis().SetTitle(h[2]) g.GetYaxis().SetTitleOffset(1.4) g.GetXaxis().SetTitleOffset(1.1) my_Latex = TLatex() my_Latex.SetTextSize(0.04) my_Latex.DrawLatexNDC(0.13, 0.85, "LHCb Data 2012") CanvasName.Update() outDir = '/sps/lhcb/volle/FitBMass/v1_Min5120' if not os.path.isdir(outDir): os.makedirs(outDir) CanvasName.SaveAs("{}/{}_both.pdf".format(outDir, histoListe[i][0])) #_both CanvasName.SaveAs("{}/{}_both.png".format(outDir, histoListe[i][0])) #_both
def main(argv): P0DBANFFStyle = INTERFACE.GetThisStyle() INTERFACE.SetStyle(P0DBANFFStyle.GetName()) OUTPUTFILENAME = "BANFFReactionCodeStacksOfficial_Joint2018_Numode_Prefit_P0DOnly_Momentum.pdf" inputFile = TFile(sys.argv[0]) dataFile = TFile(sys.argv[1]) dummyPage = TCanvas() dummyPage.Print(OUTPUTFILENAME + "[") sampleNames = [ "P0D_Air_NuMu_CC_CC1Track", "P0D_Air_NuMu_CC_CCNTracks", "P0D_Water_NuMu_CC1Track", "P0D_Water_NuMu_CCNTracks" ] fileNameRoots = [ "P0D_Air_NuMu_CC1Track", "P0D_Air_NuMu_CCNTracks", "P0D_Water_NuMu_CC1Track", "P0D_Water_NuMu_CCNTracks" ] stackHistos = [ "#nu CCQE", "#nu CC 2p-2h", "#nu CC Res 1#pi", "#nu CC Coh 1#pi", "#nu CC Other", "#nu NC modes", "#bar{#nu} modes" ] P0DBANFFStyle.SetTitleBorderSize(0) P0DBANFFStyle.SetTitleX(0.02) P0DBANFFStyle.SetTitleY(0.95) P0DBANFFStyle.SetTitleW(0.3) P0DBANFFStyle.SetTitleH(0.07) # Align left, centered in y) P0DBANFFStyle.SetTitleAlign(11) stackColours = [1300, 1302, 1303, 1304, 1305, 1308, 1310] stackFillStyle = [1001, 1001, 1001, 1001, 1001, 1001, 1001] """ The graphs will be of the form <sampleName>_rxnPredMC_<rxnCode+100> So for each sample, we'll loop from 0-200, and if the THnD is not NULL when we try and get it, add it to a list for stacking. for sampleName in sampleNames: """ for ii in xrange(0, len(sampleNames)): sampleName = sampleNames[ii] # Total the number of events for this sample going into the histogram. # (Remember: Sand is excluded here.) mcSampleTotal = 0.0 # Now make the set of histograms to show, which combine several interaction # types. # Load in the data histogram and use it to assemble the TH2Ds for the MC, as # well as making it one of the histograms on the stack. dataHist = dataFile.Get(sampleName + "_data").Projection(1, 0) dataMomProj = dataFile.Get(sampleName + "_data").Projection( 1, 0).ProjectionX("dataratio" + sampleName + "_px", 1, dataHist.GetNbinsX()) dataMomProj.SetDirectory(0) dataMomProj.SetTitle("") prefitMomProj = inputFile.Get(sampleName + "_prefit").Projection( 1, 0).ProjectionX("prefitratio" + sampleName + "_px", 1, dataHist.GetNbinsX()) prefitMomProj.SetDirectory(0) postfitMomProj = inputFile.Get(sampleName + "_postfit_0_0").Projection( 1, 0).ProjectionX("postfitratio" + sampleName + "_px", 1, dataHist.GetNbinsX()) postfitMomProj.SetDirectory(0) for ibx in xrange(1, dataMomProj.GetNbinsX() + 1): dataMomProj.SetBinContent( ibx, dataMomProj.GetBinContent(ibx) / prefitMomProj.GetBinContent(ibx)) dataMomProj.SetBinError( ibx, ROOT.Math.sqrt(dataMomProj.GetBinContent(ibx)) / prefitMomProj.GetBinContent(ibx)) print "Data = " + str( dataMomProj.GetBinContent(ibx)) + " MC = " + str( prefitMomProj.GetBinContent(ibx)) + " Ratio = " + str( dataMomProj.GetBinContent(ibx) / prefitMomProj.GetBinContent(ibx)) dataMomProj.GetYaxis().SetRangeUser(0.75, 1.25) dataMomProj.GetXaxis().SetRangeUser(MINMOMENTUM, MAXMOMENTUM) dataMomProj.GetXaxis().SetTitle("Reconstructed muon momentum (MeV/c)") dataMomProj.GetYaxis().SetTitle("Data / Sim.") # There is only one data plot for each stack, so: # Momentum projection # Assemble them here. dataOneDimPlots = [] dataOneDimPlots.append( dataHist.ProjectionX("data" + sampleName + "_px", 1, dataHist.GetNbinsY())) dataNXBins = dataHist.GetXaxis().GetNbins() dataxarray = dataHist.GetXaxis().GetXbins().GetArray() # Now, loop through all the theta bins and add the slices in. for iby in xrange(1, dataHist.GetNbinsY() + 1): thetaLow = dataHist.GetYaxis().GetBinLowEdge(iby) thetaHigh = dataHist.GetYaxis().GetBinUpEdge(iby) thetaString = " < cos# theta < " thetaString = str(thetaLow) + thetaString + str(thetaHigh) dataOneDimPlots.append( TH1D("dataslice_" + sampleName + str(iby), thetaString, dataNXBins, dataxarray)) # Now, go through the x bins in this slice and fill the plot we # just created. for ibx in xrange(1, dataHist.GetNbinsX() + 1): # Get the bin dimensions for dividing purposes to area # normalize. dataOneDimPlots[len(dataOneDimPlots) - 1].SetBinContent( ibx, dataHist.GetBinContent(ibx, iby)) # Now that the dataOneDimPlots array is filled, loop through a area # normalize the bins. for dataOneDimHist in dataOneDimPlots: for ibx in xrange(1, dataOneDimHist.GetNbinsX() + 1): mpdim = (dataOneDimHist.GetXaxis().GetBinUpEdge(ibx) - dataOneDimHist.GetXaxis().GetBinLowEdge(ibx)) / 100.0 dataOneDimHist.SetBinError( ibx, math.sqrt(dataOneDimHist.GetBinContent(ibx)) / mpdim) dataOneDimHist.SetBinContent( ibx, dataOneDimHist.GetBinContent(ibx) / mpdim) histosToStack = [] for histo in stackHistos: histosToStack.append( TH2D(sampleName + "_" + histo, sampleName + "_" + histo, dataHist.GetXaxis().GetNbins(), dataHist.GetXaxis().GetXbins().GetArray(), dataHist.GetYaxis().GetNbins(), dataHist.GetYaxis().GetXbins().GetArray())) # Now pull the histograms from the file, and add their content to the # relevant combined histogram. for i in xrange(0, 200): if inputFile.Get(sampleName + "_rxnPredMC_" + str(i)): histosToStack[CorrespondingIndex(i)].Add( inputFile.Get(sampleName + "_rxnPredMC_" + str(i)).Projection( 1, 0)) """ # OK, so now we have an array of 2D histograms for this sample that we'd # like to stack. Need to divide it up into individual ones. Do Momentum # Projection, then momentum in theta slices. Normalize by bin area. # For storing all the one dimensional plots for this sample. """ oneDimPlots = [] # Add nothing for the momentum projection, will append the thetaStrings as # needed. stackTitles = [] for i in xrange(0, len(stackHistos)): # For storing all the one dimensional plots for this reaction code. oneDimPlotsThisReac = [] nameBase = histosToStack[i].GetTitle() oneDimPlotsThisReac.append(histosToStack[i].ProjectionX( nameBase + "_px", 1, histosToStack[i].GetNbinsY())) stackTitles.append("Momentum projection") # Area normalize this now. NXBins = histosToStack[i].GetXaxis().GetNbins() for ibx in xrange(1, NXBins + 1): mpdim = (histosToStack[i].GetXaxis().GetBinUpEdge(ibx) - histosToStack[i].GetXaxis().GetBinLowEdge(ibx)) / 100.0 oneDimPlotsThisReac[0].SetBinContent( ibx, oneDimPlotsThisReac[0].GetBinContent(ibx) / mpdim) mcSampleTotal += oneDimPlotsThisReac[0].GetSumOfWeights() # Now that the x bins are filled, loop on to the next histogram. # With all the y-slices done, oneDimPlotsThisReac is now full. Append # it to oneDimPlots. oneDimPlots.append(oneDimPlotsThisReac) """" At this point in time, oneDimPlots has a momentum projection and theta slices for each reaction code grouping in this sample. So now we just need to make TStacks for them and print them out to PDF. The stack contains the plot from the same index of each entry of oneDimPlots. They should all have the same length, so use the first one to loop through (number of slices plus 1 full momenutm projection.) """ for odi in xrange(0, len(oneDimPlots[0])): # For each one create a TStack sampleStack = THStack( "mpStack_" + sampleName + str(odi), ";Reconstructed muon momentum (MeV/c);Events/(100 MeV/c)") leg = TLegend(0.7, 0.15, 0.94, 0.93) leg.SetFillColor(0) # Make data the first entry. leg.AddEntry(dataOneDimPlots[odi], "Data", "LEP") dataOneDimPlots[odi].SetMarkerStyle(20) dataOneDimPlots[odi].SetMarkerColor(kBlack) dataOneDimPlots[odi].SetLineColor(kBlack) for odj in xrange(0, len(oneDimPlots)): # Apply the appropriate plot options from the beginning. oneDimPlots[odj][odi].SetFillColor(stackColours[odj]) oneDimPlots[odj][odi].SetFillStyle(stackFillStyle[odj]) oneDimPlots[odj][odi].SetMarkerStyle(1) # Don't want P0DBANFFStyle to interfere. sampleStack.Add(oneDimPlots[odj][odi]) print oneDimPlots[odj][odi].GetTitle() + " " + str( oneDimPlots[odj][odi].GetSumOfWeights()) leg.AddEntry(oneDimPlots[odj][odi], stackHistos[odj], "F") c1 = TCanvas() upperPad = TPad("upperPad", "upperPad", .05, .35, .96, .95) lowerPad = TPad("lowerPad", "lowerPad", .05, .1, .96, .35) upperPad.Draw() lowerPad.Draw() upperPad.cd() gPad.SetBottomMargin(1e-5) c1.SetTicks(1, 1) sampleStack.Draw("") dataOneDimPlots[odi].Draw("PEsame") sampleStack.SetMaximum( max(sampleStack.GetMaximum(), FindPlotMax(dataOneDimPlots[odi], dataOneDimPlots[odi]))) leg.Draw() sampleStack.GetXaxis().SetRangeUser(MINMOMENTUM, MAXMOMENTUM) sampleStack.GetXaxis().SetTitle("") sampleStack.GetXaxis().SetTickLength(0) sampleStack.GetXaxis().SetLabelSize(0) sampleStack.SetTitle("# nu-mode") lowerPad.cd() ROOT.gPad.SetTopMargin(1e-5) ROOT.gPad.SetBottomMargin(0.35) ROOT.gPad.SetTickx() dataMomProj.SetLineColor(2) dataMomProj.SetMarkerColor(2) dataMomProj.GetYaxis().SetNdivisions(8, 1) dataMomProj.GetYaxis().SetLabelSize( dataMomProj.GetYaxis().GetLabelSize() + 0.07) dataMomProj.GetYaxis().SetTitleSize( dataMomProj.GetYaxis().GetLabelSize() + 0.05) dataMomProj.GetYaxis().SetTitleOffset(0.335) dataMomProj.GetXaxis().SetLabelSize( dataMomProj.GetXaxis().GetLabelSize() + 0.08) dataMomProj.GetXaxis().SetTitleSize( dataMomProj.GetXaxis().GetLabelSize() + 0.04) dataMomProj.GetXaxis().SetTitleOffset(0.9) dataMomProj.GetXaxis().SetTickLength(0.04) dataMomProj.Draw("PE") line = TLine(0.0, 1.0, 5000.0, 1.0) line.SetLineWidth(2) line.SetLineColor(1) line.Draw("SAME") c1.Modified() c1.Update() c1.Print(OUTPUTFILENAME) outFileName = fileNameRoots[sampleNames.index( sampleName)] + "_mumom_rxn_postfit" c1.Print(outFileName + ".pdf") c1.Print(outFileName + ".png") c1.Print(outFileName + ".eps") dummyPage.Print(OUTPUTFILENAME + ']')
def plot(var, cut, norm=False, nm1=False): ### Preliminary Operations ### fileRead = os.path.exists(options.file) treeRead = not any(x==cut for x in ['0l', '1e', '1m', '2e', '2m', '1e1m', 'Gen', 'Trigger'])#(var in variable.keys()) # Read from tree binLow = "" binHigh = "" binName = "" if "binned" in cut: binLow = cut[cut.find("LowVal")+6:cut.find("HighVal")-1] binHigh = cut[cut.find("HighVal")+7:] binName = "bin_"+binLow+"_"+binHigh cut = cut[:cut.find("binned")] useformula = True if 'formula' in variable[var]: print variable[var]['formula'] useformula = True channel = cut plotdir = cut plotname = var weight = "eventWeightLumi" #*(2.2/35.9) isBlind = BLIND and 'SR' in channel showSignal = True#('SR' in channel) cutSplit = cut.split() for s in cutSplit: if s in selection.keys(): plotdir = s cut = cut.replace(s, selection[s]) if not binLow == "": cut = cut + " && " + var + " > " + binLow + " && " + var + " < " + binHigh #if treeRead and cut in selection: cut = cut.replace(cut, selection[cut]) # Determine Primary Dataset pd = [] print cut if any(w in cut for w in ['1l', '1m', '2m', 'isWtoMN', 'isZtoMM', 'isTtoEM']): pd += [x for x in sample['data_obs']['files'] if 'SingleMuon' in x] if any(w in cut for w in ['1l', '1e', '2e', 'isWtoEN', 'isZtoEE']): pd += [x for x in sample['data_obs']['files'] if 'SingleElectron' in x] if any(w in cut for w in ['0l', 'isZtoNN']): pd += [x for x in sample['data_obs']['files'] if 'MET' in x] if len(pd)==0: raw_input("Warning: Primary Dataset not recognized, continue?") print "Plotting from", ("tree" if treeRead else "file"), var, "in", channel, "channel with:" print " dataset:", pd print " cut :", cut print " cut :", weight ### Create and fill MC histograms ### # Create dict file = {} tree = {} hist = {} ### Create and fill MC histograms ### for i, s in enumerate(data+back+sign): if fileRead: fileName = options.file if not s=='data_obs' else "rootfiles_"+options.name+"/"+channel+binName+".root" histName = "shapes_fit_b/"+channel+"/"+s if not s=='data_obs' else s file[s] = TFile(fileName, "READ") tmphist = file[s].Get(histName) if tmphist==None: tmphist = hist[back[0]].Clone(s) tmphist.Reset("MICES") print "Histogram", histName, "not found in file", fileName if s=='data_obs': hist[s] = tmphist else: hist[s] = hist['data_obs'].Clone(s) #hist[s].Reset("MICES") hist[s].SetMarkerSize(0) for i in range(tmphist.GetNbinsX()+1): hist[s].SetBinContent(i+1, tmphist.GetBinContent(i+1)) elif treeRead: # Project from tree tree[s] = TChain("tree") for j, ss in enumerate(sample[s]['files']): if not 'data' in s or ('data' in s and ss in pd): tree[s].Add(NTUPLEDIR + ss + ".root") if not binLow == "": hist[s] = TH1F(s, ";"+variable[var]['title']+";Events;"+('log' if variable[var]['log'] else ''), 1, float(binLow), float(binHigh)) elif binLow == "" and variable[var]['nbins']>0: hist[s] = TH1F(s, ";"+variable[var]['title']+";Events;"+('log' if variable[var]['log'] else ''), variable[var]['nbins'], variable[var]['min'], variable[var]['max']) else: hist[s] = TH1F(s, ";"+variable[var]['title']+";Events;"+('log' if variable[var]['log'] else ''), len(variable[var]['bins'])-1, array('f', variable[var]['bins'])) hist[s].Sumw2() redFactorString = "" redFactorValue = "" if isBlind and 'data' in s: redFactorString = " && Entry$ % 15 == 0" if isBlind and 'data' not in s: redFactorValue = " / 15" cutstring = "("+weight+redFactorValue+")" + ("*("+cut+redFactorString+")" if len(cut)>0 else "") if '-' in s: cutstring = cutstring.replace(cut, cut + "&& nBQuarks==" + s.split('-')[1][0]) if useformula == True: tree[s].Project(s, variable[var]['formula'], cutstring) else: tree[s].Project(s, var, cutstring) if not tree[s].GetTree()==None: hist[s].SetOption("%s" % tree[s].GetTree().GetEntriesFast()) else: # Histogram written to file for j, ss in enumerate(sample[s]['files']): if not 'data' in s or ('data' in s and ss in pd): file[ss] = TFile(NTUPLEDIR + ss + ".root", "R") if file[ss].IsZombie(): print "WARNING: file", NTUPLEDIR + ss + ".root", "does not exist" continue tmphist = file[ss].Get(cut+"/"+var) if tmphist==None: continue if not s in hist.keys(): hist[s] = tmphist else: hist[s].Add(tmphist) if hist[s].Integral() < 0: hist[s].Scale(0) hist[s].SetFillColor(sample[s]['fillcolor']) hist[s].SetFillStyle(sample[s]['fillstyle']) hist[s].SetLineColor(sample[s]['linecolor']) hist[s].SetLineStyle(sample[s]['linestyle']) #if 'WJetsToLNu' in s and 'SL' in channel and 'WR' in channel: hist[s].Scale(1.30) #if 'TTbar' in s and 'SL' in channel and 'TR' in channel: hist[s].Scale(0.91) hist['BkgSum'] = hist[back[0]].Clone("BkgSum") hist['BkgSum'].Reset("MICES") for i, s in enumerate(back): hist['BkgSum'].Add(hist[s], 1) if fileRead: #hist['BkgSum'] = file[back[0]].Get("shapes_fit_b/"+channel+"/"+"total_background") tmphist = file[back[0]].Get("shapes_prefit/"+channel+"/"+"total_background") hist['PreFit'] = hist['BkgSum'].Clone("PreFit") for i in range(tmphist.GetNbinsX()+1): hist['PreFit'].SetBinContent(i+1, tmphist.GetBinContent(i+1)) hist['PreFit'].SetLineStyle(2) hist['PreFit'].SetLineColor(923) hist['PreFit'].SetLineWidth(3) hist['PreFit'].SetFillStyle(0) hist['BkgSum'].SetFillStyle(3003) hist['BkgSum'].SetFillColor(1) # Create data and Bkg sum histograms # if options.blind or 'SR' in channel: # hist['data_obs'] = hist['BkgSum'].Clone("data_obs") # hist['data_obs'].Reset("MICES") # Set histogram style hist[data[0]].SetMarkerStyle(20) hist[data[0]].SetMarkerSize(1.25) for i, s in enumerate(data+back+sign+['BkgSum']): addOverflow(hist[s], False) # Add overflow for i, s in enumerate(sign): hist[s].SetLineWidth(3) #for i, s in enumerate(sign): sample[s]['plot'] = True#sample[s]['plot'] and s.startswith(channel[:2]) if norm: for i, s in enumerate(sign): hist[s].Scale(hist['BkgSum'].Integral()/hist[s].Integral()) # for i, s in enumerate(back): # hist[s].SetFillStyle(3005) # hist[s].SetLineWidth(2) # #for i, s in enumerate(sign): # # hist[s].SetFillStyle(0) # if not var=="Events": # sfnorm = hist[data[0]].Integral()/hist['BkgSum'].Integral() # print "Applying SF:", sfnorm # for i, s in enumerate(back+['BkgSum']): hist[s].Scale(sfnorm) # Create stack bkg = THStack("Bkg", ";"+hist['BkgSum'].GetXaxis().GetTitle()+";Events") for i, s in enumerate(back): bkg.Add(hist[s]) # Legend leg = TLegend(0.65, 0.6, 0.95, 0.9) leg.SetBorderSize(0) leg.SetFillStyle(0) #1001 leg.SetFillColor(0) if len(data) > 0: leg.AddEntry(hist[data[0]], sample[data[0]]['label'], "pe") for i, s in reversed(list(enumerate(['BkgSum']+back))): leg.AddEntry(hist[s], sample[s]['label'], "f") if 'PreFit' in hist: leg.AddEntry(hist['PreFit'], sample['PreFit']['label'], "l") if showSignal: for i, s in enumerate(sign): if sample[s]['plot']: leg.AddEntry(hist[s], sample[s]['label'], "fl") leg.SetY1(0.9-leg.GetNRows()*0.05) # --- Display --- c1 = TCanvas("c1", hist.values()[0].GetXaxis().GetTitle(), 800, 800 if RATIO else 600) if RATIO: c1.Divide(1, 2) setTopPad(c1.GetPad(1), RATIO) setBotPad(c1.GetPad(2), RATIO) c1.cd(1) c1.GetPad(bool(RATIO)).SetTopMargin(0.06) c1.GetPad(bool(RATIO)).SetRightMargin(0.05) c1.GetPad(bool(RATIO)).SetTicks(1, 1) log = ("log" in hist['BkgSum'].GetZaxis().GetTitle()) if log: c1.GetPad(bool(RATIO)).SetLogy() # Draw bkg.Draw("HIST") # stack hist['BkgSum'].Draw("SAME, E2") # sum of bkg if not isBlind and len(data) > 0: hist[data[0]].Draw("SAME, PE") # data #data_graph.Draw("SAME, PE") if 'PreFit' in hist: hist['PreFit'].Draw("SAME, HIST") if showSignal: for i, s in enumerate(sign): if sample[s]['plot']: hist[s].Draw("SAME, HIST") # signals Normalized, hist[s].Integral()*sample[s]['weight'] bkg.GetYaxis().SetTitleOffset(bkg.GetYaxis().GetTitleOffset()*1.075) bkg.SetMaximum((5. if log else 1.25)*max(bkg.GetMaximum(), hist[data[0]].GetBinContent(hist[data[0]].GetMaximumBin())+hist[data[0]].GetBinError(hist[data[0]].GetMaximumBin()))) if len(sign) > 0 and bkg.GetMaximum() < max(hist[sign[0]].GetMaximum(), hist[sign[-1]].GetMaximum()): bkg.SetMaximum(max(hist[sign[0]].GetMaximum(), hist[sign[-1]].GetMaximum())*1.25) bkg.SetMinimum(max(min(hist['BkgSum'].GetBinContent(hist['BkgSum'].GetMinimumBin()), hist[data[0]].GetMinimum()), 5.e-1) if log else 0.) if log: bkg.GetYaxis().SetNoExponent(bkg.GetMaximum() < 1.e4) bkg.GetYaxis().SetMoreLogLabels(True) leg.Draw() drawCMS(LUMI, "Preliminary") drawRegion(channel, True) drawAnalysis("DM"+channel[:2]) drawOverflow() setHistStyle(bkg, 1.2 if RATIO else 1.1) setHistStyle(hist['BkgSum'], 1.2 if RATIO else 1.1) if RATIO: c1.cd(2) err = hist['BkgSum'].Clone("BkgErr;") err.SetTitle("") err.GetYaxis().SetTitle("Data / Bkg") for i in range(1, err.GetNbinsX()+1): err.SetBinContent(i, 1) if hist['BkgSum'].GetBinContent(i) > 0: err.SetBinError(i, hist['BkgSum'].GetBinError(i)/hist['BkgSum'].GetBinContent(i)) setBotStyle(err) errLine = err.Clone("errLine") errLine.SetLineWidth(1) errLine.SetFillStyle(0) res = hist[data[0]].Clone("Residues") for i in range(0, res.GetNbinsX()+1): if hist['BkgSum'].GetBinContent(i) > 0: res.SetBinContent(i, res.GetBinContent(i)/hist['BkgSum'].GetBinContent(i)) res.SetBinError(i, res.GetBinError(i)/hist['BkgSum'].GetBinContent(i)) setBotStyle(res) #err.GetXaxis().SetLabelOffset(err.GetXaxis().GetLabelOffset()*5) #err.GetXaxis().SetTitleOffset(err.GetXaxis().GetTitleOffset()*2) err.Draw("E2") if 'PreFit' in hist: respre = hist['PreFit'].Clone("ResiduesPreFit") respre.Divide(hist['BkgSum']) respre.Draw("SAME, HIST") errLine.Draw("SAME, HIST") if not isBlind and len(data) > 0: res.Draw("SAME, PE0") #res_graph.Draw("SAME, PE0") if len(err.GetXaxis().GetBinLabel(1))==0: # Bin labels: not a ordinary plot drawRatio(hist['data_obs'], hist['BkgSum']) drawStat(hist['data_obs'], hist['BkgSum']) c1.Update() if gROOT.IsBatch() and options.saveplots: # and (treeRead and channel in selection.keys()): if not os.path.exists("plots_"+options.name+"/"+plotdir): os.makedirs("plots_"+options.name+"/"+plotdir) c1.Print("plots_"+options.name+"/"+plotdir+"/"+plotname+binName+".png") c1.Print("plots_"+options.name+"/"+plotdir+"/"+plotname+binName+".pdf") # Print table printTable(hist, sign) if not gROOT.IsBatch(): raw_input("Press Enter to continue...") if gROOT.IsBatch() and not fileRead and (var == 'MET_pt' or (channel.startswith('SL') and var == 'MET_sign') or (channel.endswith('ZR') and var == 'FakeMET_pt')): saveHist(hist, channel+binName)
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]) exit() 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") exit() if doRatio : hs.GetXaxis().SetLabelSize(0) else : if units!="" : hs.GetXaxis().SetTitle(labelX+" ["+units+"]") else : hs.GetXaxis().SetTitle(labelX) hs.GetYaxis().SetTitle("Events")
print integral histos_HH4lbb[i].Scale(100.) # ALL DATA histos_AllData[i].SetMarkerColor(kBlack) histos_AllData[i].SetLineColor(kBlack) histos_AllData[i].SetMarkerStyle(20) # histos_AllData[i].Rebin(6) # --- upper plot pad pad1 = TPad("pad1", "pad1", 0, 0.3, 1, 1.0) pad1.Draw() pad1.cd() # Draw all hs.SetMaximum(1.5 * max(hs.GetMaximum(), histos_AllData[i].GetMaximum())) hs.Draw('histo') histos_HH4lbb[i].Draw('histosame') histos_AllData[i].Draw('samep') # print "-----------------" # print "fondi: " , integral_fondi # print "dati: ", histos_AllData[i].Integral() hs.GetXaxis().SetLabelFont(43) hs.GetXaxis().SetLabelSize(15) hs.GetXaxis().SetTitle(histos_HH4lbb[i].GetXaxis().GetTitle()) hs.GetYaxis().SetTitleSize(20) hs.GetYaxis().SetTitleFont(43) hs.GetYaxis().SetTitleOffset(1.4) hs.GetYaxis().SetLabelFont(43)
def makePlot(hName, CR, isQCDMC, isData, isLog, isRatio): ''' We first draw stacked histograms then data then unc band. The ratio of data and background is drawn next in a separate pad. ''' #Divide canvas for the ratio plot canvas = TCanvas() if isRatio and isData: canvas.Divide(1,2) canvas.cd(1) gPad.SetRightMargin(0.03); gPad.SetPad(xPadRange[0],yPadRange[2],xPadRange[1],yPadRange[3]); gPad.SetTopMargin(0.09); gPad.SetBottomMargin(padGap); #gPad.SetTickx(0); gPad.RedrawAxis(); if isLog: gPad.SetLogy(True); #Get nominal histograms #dataHist, bkgHists, qcdMCHist, qcdDDHist = getBaseHists(fileDict, hName, CR) dataHist, bkgHists, qcdMCHist = getBaseHists(fileDict, hName, CR) hSumOtherBkg = bkgHists[0].Clone("hSumOtherBkg") hSumOtherBkg.Reset() hAllBkgs = bkgHists for bkgHist in bkgHists: hColor = Samples[bkgHist.GetName().split("_")[0]][1] hSumOtherBkg.Add(bkgHist) hSumAllBkg = hSumOtherBkg.Clone("hSumAllBkg") if isQCDMC: hSumAllBkg.Add(qcdMCHist[0]) hAllBkgs.append(qcdMCHist[0]) #else: # hSumAllBkg.Add(qcdDDHist[0]) # hAllBkgs.append(qcdDDHist[0]) #Stack nominal hists xTitle = histograms[hName][0] yTitle = histograms[hName][1] hStack = THStack(hName,hName) hForStack = sortHists(hAllBkgs, False) for h in hForStack: sampleName = h.GetName().split("_")[0] decoHist(h, xTitle, yTitle, Samples[sampleName][1]) hStack.Add(h) hStack.SetMinimum(1.0) if isLog: hStack.SetMaximum(100*hStack.GetMaximum()) else: hStack.SetMaximum(1.3*hStack.GetMaximum()) hStack.Draw("HIST") decoHistStack(hStack, xTitle, yTitle) #Get histograms for the difference between nominal and syst up/down hSumOtherBkgUps, hQCDUps = getSystHists(fileDict, hName, CR, "Up") hSumOtherBkgDowns, hQCDDowns = getSystHists(fileDict, hName, CR, "Down") hDiffUp = hSumOtherBkg.Clone("hDiffUp") hDiffUp.Reset() hDiffDown = hSumOtherBkg.Clone("hDiffDown") hDiffDown.Reset() for hUp in hSumOtherBkgUps: hDiff = hUp.Clone("hDiff") hDiff.Add(hSumOtherBkg, -1) hDiffUp.Add(hDiff) print "hDiffUp = ", hDiffUp.Integral() for hDown in hSumOtherBkgDowns: hDiff = hSumOtherBkg.Clone("hDiff") hDiff.Add(hDown, -1) hDiffDown.Add(hDiff) if isQCDMC: for hUp in hQCDUps: hDiff = hUp.Clone("hDiff") hDiff.Add(qcdMCHist[0], -1) hDiffUp.Add(hDiff) for hDown in hQCDDowns: hDiff = qcdMCHist[0].Clone("hDiff") hDiff.Add(hDown, -1) hDiffDown.Add(hDiff) #Get unc band for the top plot uncGraphTop = getUncBand(hSumAllBkg, hDiffUp, hDiffDown,False) uncGraphTop.SetFillColor(2); uncGraphTop.SetFillStyle(3001); uncGraphTop.Draw(" E2 same "); #Draw data decoHist(dataHist[0], xTitle, yTitle, Samples["Data"][1]) dataHist[0].SetMarkerStyle(20) if isData: dataHist[0].Draw("EPsame") #Draw legend hForLegend = sortHists(hAllBkgs, True) plotLegend = getLegend(dataHist, hForLegend, uncGraphTop) plotLegend.Draw() #Draw CMS, Lumi, channel if channel in ["mu", "Mu", "m"]: chName = "#mu + jets" else: chName = "e + jets" crName = formatCRString(CR) if CR=="": chName = "%s, SR"%chName else: chName = "%s, CR"%chName chCRName = "#splitline{#font[42]{%s}}{#font[42]{%s}}"%(chName, crName) extraText = "#splitline{Preliminary}{%s}"%chCRName #CMS_lumi(canvas, iPeriod, iPosX, extraText) lumi_13TeV = "35.9 fb^{-1}" if "16" in year: lumi_13TeV = "35.9 fb^{-1} (2016)" if "17" in year: lumi_13TeV = "41.5 fb^{-1} (2017)" if "18" in year: lumi_13TeV = "59.7 fb^{-1} (2018)" CMS_lumi(lumi_13TeV, canvas, iPeriod, iPosX, extraText) #Draw the ratio of data and all background if isData and isRatio: canvas.cd(2) gPad.SetTopMargin(padGap); gPad.SetBottomMargin(0.30); gPad.SetRightMargin(0.03); #gPad.SetTickx(0); gPad.SetPad(xPadRange[0],yPadRange[0],xPadRange[1],yPadRange[2]); gPad.RedrawAxis(); hRatio = dataHist[0].Clone("hRatio") hRatio.Divide(hSumAllBkg) decoHistRatio(hRatio, xTitle, "Obs./Exp.", 1) hRatio.Draw() uncGraphRatio = getUncBand(hSumAllBkg, hDiffUp, hDiffDown,True) uncGraphRatio.SetFillColor(2); uncGraphRatio.SetFillStyle(3001); uncGraphRatio.Draw("E2same"); baseLine = TF1("baseLine","1", -100, 2000); #baseLine.SetLineColor(kRed+1); baseLine.SetLineColor(3); baseLine.Draw("SAME"); hRatio.Draw("same") #canvas.SaveAs("%s/%s.pdf"%(outPlotFullDir, hName)) canvas.SaveAs("%s/%s_%s_%s.png"%(outPlotFullDir, hName, year, channel))
sigmagraph.SetPoint(pointno, pointno + 1, fitarray[pointno][2]) sigmagraph.SetPointError(pointno, 0, fitarray[pointno][5]) sigmahist.Fill(fitarray[pointno][2]) chisquaregraph.SetPoint(pointno, pointno + 1, fitarray[pointno][6]) chisquaregraph.SetPointError(pointno, 0, 0) # iterator.ls() for i in range(0, 3): fill2d(fitarray[:, i], mapsa_mat, objarr2d[i]) fill2d(fitarray[:, 6], mapsa_mat, objarr2d[3]) g.cd(str(outfile)) g.mkdir(str(outfile) + "/Channels") g.cd(str(outfile) + "/Channels") iterator.Write() # iterator.First().Print("all") Maximum = TMath.Power(10, (round(TMath.Log10(stack.GetMaximum())) - 1)) ROOT.gStyle.SetLabelSize(0.06, "xyz") ROOT.gStyle.SetTitleSize(0.06, "xyz") ROOT.gStyle.SetTitleOffset(1.2, "y") ROOT.gStyle.SetTitleOffset(.825, "x") ROOT.gStyle.SetPadGridX(1) ROOT.gStyle.SetPadGridY(1) ROOT.gStyle.SetOptStat(0) # ROOT.gStyle.SetPadLeftMargin(.2); # ROOT.gStyle.SetPadRightMargin(.1); c1.cd(1) stack.Draw("nostack hist e1 x0") stack.GetXaxis().SetRangeUser(0, 256)
def makeDiTauStack(outDir, inFile, rootDir, s, labelX, units="GeV", left=False, channel="", json="Golden", log=False, dndm=False, doRatio=False, year=2017, sign='OS', LTcut=0., cat='mmtt', wait='wait'): 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': kRed } hs = THStack("hs", "") for group in groups: if len(cat) == 4: histo[group] = f.Get("h{0:s}_{1:s}_Mtt".format(group, cat)) else: histo[group] = f.Get("h{0:s}_ee{1:s}_Mtt".format(group, cat)) histo2 = f.Get("h{0:s}_mm{1:s}_Mtt".format(group, cat)) histo[group].Add(histo2) if dndm: convertToDNDM(histo[group]) if group == 'data': applyDATAStyle(histo[group]) else: applyStyle(histo[group], colors[group], 1, 1001) if group != 'data': hs.Add(histo[group]) try: hMax = 1.2 * max(histo['data'].GetMaximum(), hs.GetMaximum()) except KeyError: hMax = 1.2 * hs.GetMaximum() hs.SetMaximum(hMax) hs.Draw("HIST") try: histo['data'].Draw("e,SAME") except KeyError: pass 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: try: l.AddEntry(histo[group], group, "F") except KeyError: continue l.SetBorderSize(0) l.SetFillColor(0) l.SetFillStyle(0) l.SetTextSize(0.04) l.Draw() lTex1 = TLatex(120., 0.97 * hMax, 'Preliminary {0:d}'.format(year)) lTex1.SetTextSize(0.04) lTex1.Draw() signText = 'Same Sign' if sign == 'OS': signText = 'Opposite Sign' lTex2 = TLatex(120., 0.90 * hMax, '{0:s}'.format(signText)) lTex2.SetTextSize(0.04) lTex2.Draw() if len(cat) == 4: lt = { 'eeet': '#it{l}#it{l}#it{e}#tau', 'eemt': '#it{l}#it{l}#mu#tau', 'eett': '#it{l}#it{l}#tau#tau', 'mmet': '#mu#mu#it{e}#tau', 'mmmt': '#mu#mu#mu#tau', 'mmtt': '#mu#mu#tau#tau' } else: lt = { 'et': '#it{l}#it{l}#it{e}#tau', 'mt': '#it{l}#it{l}#mu#tau', 'tt': '#it{l}#it{l}#tau#tau' } lTex3 = TLatex(120., 0.83 * hMax, '{0:s} H_LT > {1:d} '.format(lt[cat], int(LTcut))) lTex3.SetTextSize(0.04) lTex3.Draw() plotPad.Draw() #CMS_lumi(plotPad,4,11) outFileBase = "Stack_{0:d}_{1:s}_{2:s}_LT{3:02d}".format( year, cat, sign, int(LTcut)) c.SaveAs("{0:s}.png".format(outFileBase)) c.SaveAs("{0:s}.root".format(outFileBase)) if wait == 'wait': raw_input() else: import time time.sleep(5.)
def plot(var, cut, nm1=False): ### Preliminary Operations ### treeRead = True if not FILE else False # Read from tree channel = cut isBlind = BLIND showSignal = False if 'SB' in cut or 'TR' in cut else True # Determine explicit cut if treeRead: for k in sorted(alias.keys(), key=len, reverse=True): if k in cut: cut = cut.replace(k, alias[k]) # Determine Primary Dataset pd = [] if "isSingleMuonPhotonTrigger" in cut: pd = [x for x in sample['data_obs']['files'] if "MuonEG" in x] elif "isJPsiTrigger" in cut: pd = [x for x in sample['data_obs']['files'] if "Charmonium" in x] else: print "Cannot determine Primary Dataset." exit() print "Plotting from", ("tree" if treeRead else "file"), var, "in", channel, "channel with:" print " dataset:", pd print " cut :", cut if isBlind and "SR" in channel and var in ["H_mass"]: cut += " && ( isMC ? 1 : !(H_mass > 86 && H_mass < 96) && !(H_mass > 120 && H_mass < 130) )" ### Create and fill MC histograms ### # Create dict file = {} tree = {} hist = {} cutstring = "(eventWeightLumi)" + ("*(" + cut + ")" if len(cut) > 0 else "") ### Create and fill MC histograms ### for i, s in enumerate(data + back + sign): hist[s] = TH1F( s, ";" + variable[var]['title'] + ";Events;" + ('logx' if variable[var]['logx'] else '') + ('logy' if variable[var]['logy'] else ''), variable[var]['nbins'], variable[var]['min'], variable[var]['max']) hist[s].Sumw2() tree[s] = TChain("Events") for j, ss in enumerate(sample[s]['files']): if s in data and not ss in pd: continue if YEAR == 2016 and not ('Run2016' in ss or 'Summer16' in ss): continue if YEAR == 2017 and not ('Run2017' in ss or 'Fall17' in ss): continue if YEAR == 2018 and not ('Run2018' in ss or 'Autumn18' in ss): continue for f in os.listdir(NTUPLEDIR + '/' + ss): tree[s].Add(NTUPLEDIR + '/' + ss + '/' + f) tree[s].Project(s, var, cutstring) if not tree[s].GetTree() == None: hist[s].SetOption("%s" % tree[s].GetTree().GetEntriesFast()) # jobs = [] # queue = multiprocessing.Queue() # for i, s in enumerate(data+back+sign): # for j, ss in enumerate(sample[s]['files']): # if s in data and not ss in pd: continue # if YEAR == 2016 and not ('Run2016' in ss or 'Summer16' in ss): continue # if YEAR == 2017 and not ('Run2017' in ss or 'Fall17' in ss): continue # if YEAR == 2018 and not ('Run2018' in ss or 'Autumn18' in ss): continue # if treeRead: # Project from tree ## hist[s] = loopProject(s, ss, variable[var], cutstring, True) # p = multiprocessing.Process(target=parallelProject, args=(queue, s, ss, variable[var], cutstring, )) # jobs.append(p) # p.start() # else: # Histogram written to file # hist[s] = readhist(FILE, s, var, cut) # # # Wait for all jobs to finish # for job in jobs: # h = queue.get() # if not h.GetOption() in hist: hist[h.GetOption()] = h # else: hist[h.GetOption()].Add(h) # for job in jobs: # job.join() # Histogram style for i, s in enumerate(data + back + sign): hist[s].Scale(sample[s]['weight'] if hist[s].Integral() >= 0 else 0) hist[s].SetFillColor(sample[s]['fillcolor']) hist[s].SetFillStyle(sample[s]['fillstyle'] if not options.norm else 0) hist[s].SetLineColor(sample[s]['linecolor']) hist[s].SetLineStyle(sample[s]['linestyle']) hist[s].SetLineWidth(sample[s]['linewidth']) ### Create Bkg Sum histogram ### hist['BkgSum'] = hist['data_obs'].Clone( "BkgSum") if 'data_obs' in hist else hist[back[0]].Clone("BkgSum") hist['BkgSum'].Reset("MICES") hist['BkgSum'].SetFillStyle(3003) hist['BkgSum'].SetFillColor(1) for i, s in enumerate(back): hist['BkgSum'].Add(hist[s]) if options.norm: for i, s in enumerate(back + ['BkgSum']): hist[s].Scale(hist[data[0]].Integral() / hist['BkgSum'].Integral()) for i, s in enumerate(sign): hist[s].Scale(hist[data[0]].Integral() / hist[s].Integral()) # Create data and Bkg sum histograms # if BLIND: # or 'SR' in channel: # hist['data_obs'] = hist['BkgSum'].Clone("data_obs") # hist['data_obs'].Reset("MICES") # Set histogram style hist['data_obs'].SetMarkerStyle(20) hist['data_obs'].SetMarkerSize(1.25) # for i, s in enumerate(data+back+sign+['BkgSum']): addOverflow(hist[s], False) # Add overflow for i, s in enumerate(sign): hist[s].SetLineWidth(3) for i, s in enumerate(sign): sample[s]['plot'] = True # Create stack bkg = THStack("Bkg", ";" + hist['BkgSum'].GetXaxis().GetTitle() + ";Events") for i, s in enumerate(back): bkg.Add(hist[s]) # Legend leg = TLegend(0.65, 0.6, 0.95, 0.9) leg.SetBorderSize(0) leg.SetFillStyle(0) #1001 leg.SetFillColor(0) if len(data) > 0: leg.AddEntry(hist[data[0]], sample[data[0]]['label'], "pe") for i, s in reversed(list(enumerate(['BkgSum'] + back))): leg.AddEntry(hist[s], sample[s]['label'], "f") if showSignal: for i, s in enumerate(sign): if sample[s]['plot']: leg.AddEntry(hist[s], sample[s]['label'], "fl") leg.SetY1(0.9 - leg.GetNRows() * 0.04) # --- Display --- c1 = TCanvas("c1", hist.values()[0].GetXaxis().GetTitle(), 800, 800 if RATIO else 600) if RATIO: c1.Divide(1, 2) setTopPad(c1.GetPad(1), RATIO) setBotPad(c1.GetPad(2), RATIO) c1.cd(1) c1.GetPad(bool(RATIO)).SetTopMargin(0.06) c1.GetPad(bool(RATIO)).SetRightMargin(0.05) c1.GetPad(bool(RATIO)).SetTicks(1, 1) logX, logY = "logx" in hist['BkgSum'].GetZaxis().GetTitle( ), "logy" in hist['BkgSum'].GetZaxis().GetTitle() if logY: c1.GetPad(bool(RATIO)).SetLogy() if logX: c1.GetPad(bool(RATIO)).SetLogx() # Draw bkg.Draw("HIST") # stack hist['BkgSum'].Draw("SAME, E2") # sum of bkg if len(data) > 0: hist['data_obs'].Draw("SAME, PE") # data #data_graph.Draw("SAME, PE") # if showSignal: # smagn = 1. #if treeRead else 1.e2 #if logY else 1.e2 for i, s in enumerate(sign): if sample[s]['plot']: hist[s].Draw("SAME, HIST") # hist[s].Scale(smagn) # hist[s].Draw("SAME, HIST") # signals Normalized, hist[s].Integral()*sample[s]['weight'] # #textS = drawText(0.80, 0.9-leg.GetNRows()*0.05 - 0.02, stype+" (x%d)" % smagn, True) bkg.GetYaxis().SetTitleOffset(bkg.GetYaxis().GetTitleOffset() * 1.075) bkg.SetMaximum((5. if logY else 1.25) * max( bkg.GetMaximum(), hist['data_obs'].GetBinContent(hist['data_obs'].GetMaximumBin()) + hist['data_obs'].GetBinError(hist['data_obs'].GetMaximumBin()))) #if bkg.GetMaximum() < max(hist[sign[0]].GetMaximum(), hist[sign[-1]].GetMaximum()): bkg.SetMaximum(max(hist[sign[0]].GetMaximum(), hist[sign[-1]].GetMaximum())*1.25) bkg.SetMinimum( max( min(hist['BkgSum'].GetBinContent(hist['BkgSum'].GetMinimumBin( )), hist['data_obs'].GetMinimum()), 5.e-1) if logY else 0.) if logY: bkg.GetYaxis().SetNoExponent(bkg.GetMaximum() < 1.e4) bkg.GetYaxis().SetMoreLogLabels(True) #if logY: bkg.SetMinimum(1) leg.Draw() drawCMS(LUMI[YEAR], "Preliminary") if channel in aliasNames: drawRegion(aliasNames[channel], True) #drawAnalysis(channel) #if nm1 and not cutValue is None: drawCut(cutValue, bkg.GetMinimum(), bkg.GetMaximum()) #FIXME #if len(sign) > 0: # if channel.startswith('X') and len(sign)>0: drawNorm(0.9-0.05*(leg.GetNRows()+1), "#sigma(X) = %.1f pb" % 1.) setHistStyle(bkg, 1.2 if RATIO else 1.1) setHistStyle(hist['BkgSum'], 1.2 if RATIO else 1.1) if RATIO: c1.cd(2) if logX: c1.GetPad(2).SetLogx() err = hist['BkgSum'].Clone("BkgErr;") err.SetTitle("") err.GetYaxis().SetTitle("Data / Bkg") for i in range(1, err.GetNbinsX() + 1): err.SetBinContent(i, 1) if hist['BkgSum'].GetBinContent(i) > 0: err.SetBinError( i, hist['BkgSum'].GetBinError(i) / hist['BkgSum'].GetBinContent(i)) setBotStyle(err) errLine = err.Clone("errLine") errLine.SetLineWidth(1) errLine.SetFillStyle(0) res = hist['data_obs'].Clone("Residues") for i in range(0, res.GetNbinsX() + 1): if hist['BkgSum'].GetBinContent(i) > 0: res.SetBinContent( i, res.GetBinContent(i) / hist['BkgSum'].GetBinContent(i)) res.SetBinError( i, res.GetBinError(i) / hist['BkgSum'].GetBinContent(i)) setBotStyle(res) #err.GetXaxis().SetLabelOffset(err.GetXaxis().GetLabelOffset()*5) #err.GetXaxis().SetTitleOffset(err.GetXaxis().GetTitleOffset()*2) err.Draw("E2") errLine.Draw("SAME, HIST") if len(data) > 0: res.Draw("SAME, PE0") #res_graph.Draw("SAME, PE0") if len(err.GetXaxis().GetBinLabel( 1)) == 0: # Bin labels: not a ordinary plot drawRatio(hist['data_obs'], hist['BkgSum']) drawStat(hist['data_obs'], hist['BkgSum']) if var in ["H_mass"]: c1.cd(bool(RATIO)) boxZ = drawBox(XZMIN, hist['data_obs'].GetMinimum(), XZMAX, hist['data_obs'].GetMaximum() / 1.30, "Z") boxH = drawBox(XHMIN, hist['data_obs'].GetMinimum(), XHMAX, hist['data_obs'].GetMaximum() / 1.30, "H") c1.Update() if True: #gROOT.IsBatch(): varname = var.replace('.', '_').replace('()', '') if not os.path.exists("plots/" + channel): os.makedirs("plots/" + channel) c1.Print("plots/" + channel + "/" + varname + ".png") c1.Print("plots/" + channel + "/" + varname + ".pdf") # Print table printTable(hist, sign) if not gROOT.IsBatch(): raw_input("Press Enter to continue...")
def read_file(arr, meas_type, mapsa_fitter_inst, path): if not os.path.isfile(str(path + arr[0])): print "Root file not found at", str(path + arr[0]) #sys.exit(1) return f = TFile(str(path + arr[0]), 'READ') if (f.IsZombie()): print "Error opening file" return else: print "Reading File ", arr[0] #f.ls() tree = f.Get('tree') f_GlobalData_Map = ROOT.TMap() f_GlobalData_Map.Add(ROOT.TObjString("tree"), tree) #tree.Print() outfile = TString(arr[0]) outfile.ReplaceAll(".root", "") outfile.ReplaceAll(" ", "") # print outfile if (meas_type == 0): outfile = "pedestal" if (not g.FindKey(str(outfile))): g.mkdir(str(outfile)) g.cd(str(outfile)) else: return channels = 288 if (arr[2] == 'inv'): channels = 96 mapsa_mat = [[1, 0, 0], [1, 0, 0]] elif (arr[2] == 'norm'): channels = 288 mapsa_mat = [[1, 1, 1], [1, 0, 1]] #print "channels", channels #print "mapsa_mat", mapsa_mat c1 = TCanvas('c1', 'Pixel Monitor ', 700, 900) c2 = TCanvas('c2', 'Pixel Monitor ', 500, 500) c3 = TCanvas('c3', 'Pixel Monitor ', 1280, 720) c4 = TCanvas('c4', 'Pixel Monitor ', 500, 500) c5 = TCanvas('c5', 'Pixel Monitor ', 500, 500) f_GlobalData_Map.Add(ROOT.TObjString("c1"), c1) f_GlobalData_Map.Add(ROOT.TObjString("c2"), c2) f_GlobalData_Map.Add(ROOT.TObjString("c3"), c3) f_GlobalData_Map.Add(ROOT.TObjString("c4"), c4) f_GlobalData_Map.Add(ROOT.TObjString("c5"), c5) # c2.Divide(2,1) #c2.cd(0) c1.Divide(3, 2) for i in range(1, 7): c1.cd(i) ROOT.gPad.SetGridx() ROOT.gPad.SetGridy() # channelcounts = TH2I('HitMap','Counts; Channel; DAC Value (1.456 mV)', 288, .5,288.5,256, .5, 256.5) channelcounts = TH2I('HitMap', 'Counts; Channel; DAC Value (a.u.)', 288, .5, 288.5, 256, .5, 256.5) channelcounts_norm = TH2F('HitMap_norm', 'Occupancy ; Channel; DAC Value (a.u.)', 288, .5, 288.5, 256, .5, 256.5) f_GlobalData_Map.Add(ROOT.TObjString("HitMap"), channelcounts) f_GlobalData_Map.Add(ROOT.TObjString("HitMap"), channelcounts_norm) norm_2d = TH2F('Norm2D', 'Normalization; Column; Row', 48, .5, 48.5, 6, .5, 6.5) mean_2d = TH2F('Mean2D', 'Mean; Column; Row', 48, .5, 48.5, 6, .5, 6.5) sigma_2d = TH2F('Sigma2D', 'Sigma; Column; Row', 48, .5, 48.5, 6, .5, 6.5) chisquare = TH2F('Chisquare2D', 'Chisquare; Column; Row', 48, .5, 48.5, 6, .5, 6.5) f_GlobalData_Map.Add(ROOT.TObjString("Norm2D"), norm_2d) f_GlobalData_Map.Add(ROOT.TObjString("Mean2D"), mean_2d) f_GlobalData_Map.Add(ROOT.TObjString("Sigma2D"), sigma_2d) f_GlobalData_Map.Add(ROOT.TObjString("Chisquare2D"), chisquare) objarr2d = [] objarr2d.append(norm_2d) objarr2d.append(mean_2d) objarr2d.append(sigma_2d) objarr2d.append(chisquare) normgraph = TGraphErrors() meangraph = TGraphErrors() sigmagraph = TGraphErrors() chisquaregraph = TGraphErrors() mean_corrgraph = TGraphErrors() f_GlobalData_Map.Add(ROOT.TObjString("normgraph "), normgraph) f_GlobalData_Map.Add(ROOT.TObjString("meangraph "), meangraph) f_GlobalData_Map.Add(ROOT.TObjString("sigmagraph "), sigmagraph) f_GlobalData_Map.Add(ROOT.TObjString("chisquaregraph"), chisquaregraph) f_GlobalData_Map.Add(ROOT.TObjString("mean_corrgraph"), mean_corrgraph) meanhist = TH1F('meanhist', 'Mean DAC; DAC Value (a.u.); counts', 2560, 0, 255) sigmahist = TH1F('sigmahist', 'Sigma DAC; DAC Value (a.u.); counts', 100, 0, 10) meanhist_std = TH1F('meanhist_std', 'Mean DAC Standard; DAC Value (a.u.); counts', 2560, 0, 255) sigmahist_std = TH1F('sigmahist_std', 'Sigma DAC Standard; DAC Value (a.u.); counts', 100, 0, 10) meanhist_double = TH1F('meanhist_double', 'Mean DAC Double; DAC Value (a.u.); counts', 2560, 0, 255) sigmahist_double = TH1F('sigmahist_double', 'Sigma DAC Double; DAC Value (a.u.); counts', 100, 0, 10) meanhist_double_neighbour = TH1F( 'meanhist_double_neighbour', 'Mean DAC Double Neighbour; DAC Value (a.u.); counts', 2560, 0, 255) sigmahist_double_neighbour = TH1F( 'sigmahist_double_neighbour', 'Sigma DAC Double Neighbour; DAC Value (a.u.); counts', 100, 0, 10) objarr = [] objarr.append(normgraph) objarr.append(meangraph) objarr.append(sigmagraph) objarr.append(chisquaregraph) objarr.append(mean_corrgraph) f_GlobalData_Map.Add(ROOT.TObjString('meanhist'), meanhist) f_GlobalData_Map.Add(ROOT.TObjString('sigmahist'), sigmahist) f_GlobalData_Map.Add(ROOT.TObjString('meanhist_std'), meanhist_std) f_GlobalData_Map.Add(ROOT.TObjString('sigmahist_std'), sigmahist_std) f_GlobalData_Map.Add(ROOT.TObjString('meanhist_double'), meanhist_double) f_GlobalData_Map.Add(ROOT.TObjString('sigmahist_double'), sigmahist_double) f_GlobalData_Map.Add(ROOT.TObjString('meanhist_double_neighbour'), meanhist_double_neighbour) f_GlobalData_Map.Add(ROOT.TObjString('sigmahist_double_neighbour'), sigmahist_double_neighbour) objarr.append(meanhist) objarr.append(sigmahist) objarr.append(meanhist_std) objarr.append(sigmahist_std) objarr.append(meanhist_double) objarr.append(sigmahist_double) objarr.append(meanhist_double_neighbour) objarr.append(sigmahist_double_neighbour) for objs in objarr: objs.SetMarkerColor(2) objs.SetMarkerStyle(20) objs.SetMarkerSize(1) normgraph.SetName('normgraph') meangraph.SetName('meangraph') sigmagraph.SetName('sigmagraph') chisquaregraph.SetName('chisquare') mean_corrgraph.SetName('mean_corr') normgraph.SetTitle('Normalization; Channel; Normalization') meangraph.SetTitle('Mean; Channel; DAC Value (a.u.)') sigmagraph.SetTitle('Sigma; Channel; DAC Value (a.u.)') chisquaregraph.SetTitle('Chisquared/NDF_gr; Channel; Chisquared/NDF ') ROOT.gStyle.SetOptFit(1111) stack = THStack('a', ';DAC Value (a.u.); Occupancy') f_GlobalData_Map.Add(ROOT.TObjString("stack"), stack) fitfuncs = [] fitparams = [] gr1 = [] for pixel in range(0, channels): gr1.append( TH1D( str(pixel).zfill(3), str(pixel + 1).zfill(3) + ';DAC Value (a.u.); Occupancy ', 256, 0.5, 256.5)) f_GlobalData_Map.Add(ROOT.TObjString(str(pixel).zfill(3)), gr1[pixel]) #gr2.append(TH1F('th1f_'+str(pixel).zfill(3),str(pixel+1).zfill(3)+';DAC Value (a.u.); Occupancy',256,0.5,256.5)) color = pixel % 8 + 1 formating_th1(gr1[pixel], color) if (meas_type == 0): fitfuncs.append( TF1('gauss' + str(pixel + 1).zfill(3), 'gaus(0)', 0, 256)) fitfuncs[pixel].SetNpx(256) fitfuncs[pixel].SetLineColor(color) f_GlobalData_Map.Add( ROOT.TObjString('gauss' + str(pixel).zfill(3)), fitfuncs[pixel]) #Here we read the data and fill the histogram for event in tree: eventstr = [] for counter, vals in enumerate(tree.AR_MPA): #eventstr.append(vals) channelcounts.Fill(counter, tree.THRESHOLD, vals) if (counter < channels): gr1[counter].Fill(tree.THRESHOLD, vals) #if tree.THRESHOLD%20==0 and tree.REPETITION==0: #print eventstr #print ("Threshold %d Repetion %d" % (tree.THRESHOLD,tree.REPETITION)) #print tree.AR_MPA #now we make a small analysis of the curves fitting different functions to it: print "Finished Reading the Tree\n Normalization of Histograms\n" for pixel in range(0, channels): #gr1[pixel].ResetStats() for j in range(0, gr1[pixel].GetXaxis().GetNbins() + 1): gr1[pixel].SetBinError( gr1[pixel].GetBin(j), TMath.Sqrt(gr1[pixel].GetBinContent(gr1[pixel].GetBin(j)))) #if(pixel==0): #gr1[pixel].Print("all") #gr1[pixel].Sumw2(ROOT.kTRUE) gr1[pixel].Scale(1 / arr[1]) #if(pixel==0): #gr1[pixel].Print("all") stack.Add(gr1[pixel]) #first create a THStack with histograms: iterator = stack.GetHists() if (meas_type == 0): for idx, it in enumerate(iterator): fitparams.append([]) if (it.Integral() > 0): if (idx < channels): #fitfuncs.append(TF1('combined'+str(idx),combined, 0,256,5)) #fitfuncs.append(TF1('combined_same_mean'+str(idx),combined_mean, 0,256,4)) #fitfuncs.append(TF1('double_gauss'+str(idx),'gaus(0)+gaus(3)',0,256)) #fitfuncs.append(TF1('gauss'+str(idx),'gaus(0)',0,256)) #fitfuncs.append(TF1('double_gauss_same_mean'+str(idx),double_gauss, 0,256,5)) #print it.GetName(), idx #fitfuncs[idx].SetParameters(it.GetMaximum(),it.GetMean()+1,it.GetRMS(),it.GetMean()-1,it.GetRMS()); #fitfuncs[idx].SetParameters(it.GetMaximum(),it.GetMean(),it.GetRMS()*0.1,it.GetRMS()*0.1); #print ("Channels %f\t%f\t%f\n" % (it.GetMaximum(),it.GetMean(),it.GetRMS())) fitfuncs[idx].SetParameters(it.GetMaximum(), it.GetMean(), it.GetRMS()) #fitfuncs[idx].SetParameters(0.999*it.GetMaximum(),it.GetMean(),.7*it.GetRMS(),0.001*it.GetMaximum(),it.GetMean(),10*it.GetRMS()); #fitfuncs[idx].SetParameters(0.999*it.GetMaximum(),it.GetMean(),.7*it.GetRMS(),0.001*it.GetMaximum(),10*it.GetRMS()); #it.Fit(fitfuncs[idx],'lr0 rob=0.95','same',0,256) #it.Fit(fitfuncs[idx],'lr0q ','',0,256) it.Fit(fitfuncs[idx], 'r0q ', '', 0, 256) fitparams[idx].append(fitfuncs[idx].GetParameter(0)) fitparams[idx].append(fitfuncs[idx].GetParameter(1)) fitparams[idx].append(fitfuncs[idx].GetParameter(2)) fitparams[idx].append(fitfuncs[idx].GetParError(0)) fitparams[idx].append(fitfuncs[idx].GetParError(1)) fitparams[idx].append(fitfuncs[idx].GetParError(2)) if (fitfuncs[idx].GetNDF() > 0): fitparams[idx].append(fitfuncs[idx].GetChisquare() / fitfuncs[idx].GetNDF()) else: for kk in range(0, 7): fitparams[idx].append(0) #print "fitparamarray" fitarray = np.array(fitparams) ## print fitarray for pointno, it in enumerate(fitarray): if (fitarray[pointno][0] > 0): normgraph.SetPoint(pointno, pointno + 1, fitarray[pointno][0]) normgraph.SetPointError(pointno, 0, fitarray[pointno][3]) meangraph.SetPoint(pointno, pointno + 1, fitarray[pointno][1]) meangraph.SetPointError(pointno, 0, fitarray[pointno][4]) meanhist.Fill(fitarray[pointno][1]) sigmagraph.SetPoint(pointno, pointno + 1, fitarray[pointno][2]) sigmagraph.SetPointError(pointno, 0, fitarray[pointno][5]) sigmahist.Fill(fitarray[pointno][2]) chisquaregraph.SetPoint(pointno, pointno + 1, fitarray[pointno][6]) chisquaregraph.SetPointError(pointno, 0, 0) ## iterator.ls() # Map the data to the pixel layout: tmp_objarr = [] tmp_objarr.extend( [meanhist_std, meanhist_double, meanhist_double_neighbour]) tmp_objarr.extend( [sigmahist_std, sigmahist_double, sigmahist_double_neighbour]) for i in tmp_objarr: print str(i.GetName()) fill2d(fitarray[:, 0], mapsa_mat, objarr2d[0]) fill2d(fitarray[:, 1], mapsa_mat, objarr2d[1]) fill2d(fitarray[:, 2], mapsa_mat, objarr2d[2]) fill2d(fitarray[:, 6], mapsa_mat, objarr2d[3]) fill1d_edges(objarr2d[1], tmp_objarr[0:3]) fill1d_edges(objarr2d[2], tmp_objarr[3:]) g.cd(str(outfile)) mapsa_fitter_inst.Make_dirs() mapsa_fitter_inst.Set_run_no(outfile) if (meas_type == 1): for idx, it in enumerate(iterator): if (it.Integral() > 0): if (idx < channels): mapsa_fitter_inst.Find_signal(it, idx, 0.0025, 3) g.cd() #g.mkdir(str(outfile)+"/Channels") #g.cd(str(outfile)+"/Channels") #iterator.Write() g.cd(str(outfile)) g.mkdir(str(outfile) + "/Overview") ## iterator.First().Print("all") Maximum = TMath.Power(10, (round(TMath.Log10(stack.GetMaximum())) - 1)) #Minimum = TMath.Power(10,(round(TMath.Log10(stack.GetMinimum()))+1)) Minimum = .1 ROOT.gStyle.SetLabelSize(0.06, "xyz") ROOT.gStyle.SetTitleSize(0.06, "xyz") ROOT.gStyle.SetTitleOffset(1.2, "y") ROOT.gStyle.SetTitleOffset(.825, "x") ROOT.gStyle.SetPadGridX(1) ROOT.gStyle.SetPadGridY(1) ROOT.gStyle.SetOptStat(0) # ROOT.gStyle.SetPadLeftMargin(.2); # ROOT.gStyle.SetPadRightMargin(.1); c1.cd(1) stack.Draw("nostack hist e1 x0") stack.GetXaxis().SetRangeUser(0, 256) stack.SetMinimum(Minimum) stack.SetMaximum(Maximum) ROOT.gPad.SetLogy() c2.cd(0) stack.Draw("nostack hist e1 x0") #if(outfile.Contains("SR_90_on_top")): #stack.GetXaxis().SetRangeUser(0,256) #else: #stack.GetXaxis().SetRangeUser(0,100) stack.SetMinimum(Minimum) stack.SetMaximum(Maximum) ROOT.gPad.SetLeftMargin(.15) ROOT.gPad.SetRightMargin(.05) ROOT.gPad.SetLogy() ROOT.gPad.Update() #for idx, it in enumerate(fitfuncs): ## if idx>0 and idx<7: #c1.cd(1) #fitfuncs[idx].Draw("same") #c2.cd(0) #fitfuncs[idx].DrawCopy("psame") ## it.SetLineColor(idx%9+1) ## it.Draw("same") #g.cd(str(outfile)+"/Channels") #it.Write("HitMap_py_"+str(idx+1)+"_fit") g.cd(str(outfile) + "/Overview") c1.cd(2) chisquaregraph.Draw("ap") c1.cd(3) normgraph.Draw("ap") c1.cd(4) sigmagraph.Draw("ap") sigmagraph.GetYaxis().SetRangeUser(0, 5) sigmagraph.GetXaxis().SetRangeUser(0, channels + 1) c2.cd(2) sigmagraph.Draw("ap") ROOT.gPad.SetLeftMargin(.15) ROOT.gPad.SetRightMargin(.05) c1.cd(5) meangraph.Draw("ap") c1.cd(6) channelcounts.Draw("colz") channelcounts.GetXaxis().SetRangeUser(0, channels + 1) # c2.cd(3) c3.cd(0) ROOT.gStyle.SetOptStat(0) ROOT.gPad.SetRightMargin(.15) ROOT.gPad.SetLeftMargin(.15) ROOT.gPad.SetGrid(0) copy = channelcounts.DrawCopy("colz") #f_GlobalData_Map.Add(ROOT.TObjString("copy"),copy) #if(outfile.Contains("SR_90_on_top")): #copy.SetMaximum(100) #copy.SetMinimum(1) copy.GetYaxis().SetTitle("DAC Value (a.u.)") c4.cd(0) ROOT.gStyle.SetOptStat(0) ROOT.gPad.SetRightMargin(.15) ROOT.gPad.SetLeftMargin(.15) ROOT.gPad.SetGrid(0) copy1 = sigma_2d.DrawCopy("colz") #f_GlobalData_Map.Add(ROOT.TObjString("copy1"),copy1) copy1.GetZaxis().SetTitle("Sigma (a.u.)") copy1.GetZaxis().SetTitleOffset(1.2) ROOT.gPad.SetRightMargin(.2) if (arr[2] == 'inv'): copy1.GetXaxis().SetRangeUser(.5, 16.5) copy1.SetMaximum(5) copy1.SetMinimum(0) c5.cd(0) ROOT.gStyle.SetOptStat(0) ROOT.gPad.SetRightMargin(.15) ROOT.gPad.SetLeftMargin(.15) ROOT.gPad.SetGrid(0) #copy1 = chisquare.DrawCopy("colz") #f_GlobalData_Map.Add(ROOT.TObjString("copy2"),copy1) copy1 = sigma_2d.DrawCopy("colz") #f_GlobalData_Map.Add(ROOT.TObjString("copy2"),copy1) copy1.GetZaxis().SetTitle("sigma (a.u.)") if (arr[2] == 'inv'): copy1.GetXaxis().SetRangeUser(.5, 16.5) copy1.SetMaximum(5) copy1.SetMinimum(0) c1.Update() c1.Modified() c2.Update() c2.Modified() c3.Update() c3.Modified() c4.Update() c4.Modified() c5.Update() c5.Modified() ## c1.SaveAs("double_gauss_same_mean.pdf") ## time.sleep(2) g.cd(str(outfile) + "/Overview") #for objs in objarr: #objs.Write(objs.GetName()) #norm_2d.GetZaxis().SetRangeUser(1E5,2E6) #mean_2d.GetZaxis().SetRangeUser(54,64) ## norm_2d.GetZaxis().SetRangeUser(TMath.Power(10,(round(TMath.Log10(norm_2d.GetStdDev(3))-2)), TMath.Power(10,(round(TMath.Log10(norm_2d.GetStdDev(3)))-1))) ## mean_2d.GetZaxis().SetRangeUser(TMath.Power(10,(round(TMath.Log10(mean_2d.mean_2d.GetStdDev(3)))-1))-5,TMath.Power(10,(round(TMath.Log10(mean_2d.GetStdDev(3)))-1))+5) #sigma_2d.GetZaxis().SetRangeUser(0,5) #chisquare.GetZaxis().SetRangeUser(0,10000 ) #for objs in objarr2d: #objs.Write(objs.GetName()) #c1.Write("c1") #outfile1=outfile+TString(".pdf") #c2.SaveAs(str(outfile1)) #c2.Write("c2") #c3.SaveAs("c3"+str(outfile1)) #c3.Write("c3") #c4.SaveAs("c4"+str(outfile1)) #c4.Write("c4") ## while (TObject(iterator.Next())): ## print iterator.Next().Title() #stack.Write("stack") #g.cd(str(outfile)) #channelcounts.Write(str(outfile)) #f.Close() c1.Close() c2.Close() c3.Close() c4.Close() c5.Close() f_GlobalData_Map.DeleteAll() f.Close()
def plot(var, cut, norm=False, nm1=False): ### Preliminary Operations ### doBinned = False if options.mode == "binned": doBinned = True fileRead = os.path.exists("combinedCards_" + options.name + "/fitDiagnostics_" + options.file + ".root") treeRead = not any( x == cut for x in ['0l', '1e', '1m', '2e', '2m', '1e1m', 'Gen', 'Trigger' ]) #(var in variable.keys()) # Read from tree #signal definition if fileRead: sign = ['ttDM_MChi1_MPhi200_scalar', 'tDM_MChi1_MPhi200_scalar'] #for postfit plot if not fileRead and not options.limit: sign = ['ttDM_MChi1_MPhi100_scalar', 'tDM_MChi1_MPhi100_scalar'] #for normal plotting #bkg definition if fileRead or options.limit: back = [ "QCD", "DYJetsToNuNu_HT", "DYJetsToLL_HT", "VV", "ST", "WJetsToLNu_HT", "TTbarSL" ] #for postfit or limit if (cut).find('>250') or (cut).startswith('AH'): #for hadronic selections back = [ "QCD", "DYJetsToLL_HT", "VV", "ST", "WJetsToLNu_HT", "TTbarV", "TTbar2L", "TTbar1L", "DYJetsToNuNu_HT" ] if fileRead or options.limit: back = [ "QCD", "DYJetsToLL_HT", "VV", "ST", "WJetsToLNu_HT", "TTbarSL", "DYJetsToNuNu_HT" ] #for postfit or limit binLow = "" binHigh = "" binName = "" if "binned" in cut: binLow = cut[cut.find("LowVal") + 6:cut.find("HighVal") - 1] binHigh = cut[cut.find("HighVal") + 7:] binName = "bin_" + binLow + "_" + binHigh cut = cut[:cut.find("binned")] useformula = False if 'formula' in variable[var]: useformula = True channel = cut plotdir = cut plotname = var weight = "eventWeightLumi" #*(2.2/35.9) isBlind = BLIND and ('SR' in channel or 'ps' in channel) if fileRead: isBlind = False options.saveplots = True RESIDUAL = True elif isBlind: RATIO = 0 SIGNAL = 20 else: RATIO = 4 SIGNAL = 1 RESIDUAL = False showSignal = True #('SR' in channel) cutSplit = cut.split() for s in cutSplit: if s in selection.keys(): plotdir = s cut = cut.replace(s, selection[s]) if not binLow == "": cut = cut + " && " + var + " > " + binLow + " && " + var + " < " + binHigh #if treeRead and cut in selection: cut = cut.replace(cut, selection[cut]) # Determine Primary Dataset pd = [] if any(w in cut for w in ['1l', '1m', '2m', 'isWtoMN', 'isZtoMM', 'isTtoEM']): pd += [x for x in sample['data_obs']['files'] if 'SingleMuon' in x] if any(w in cut for w in ['1l', '1e', '2e', 'isWtoEN', 'isZtoEE']): pd += [x for x in sample['data_obs']['files'] if 'SingleElectron' in x] if any(w in cut for w in ['0l', 'isZtoNN']): pd += [x for x in sample['data_obs']['files'] if 'MET' in x] if len(pd) == 0: raw_input("Warning: Primary Dataset not recognized, continue?") print "Plotting from", ("tree" if treeRead else "file"), var, "in", channel, "channel with:" print " dataset:", pd print " cut :", cut print " cut :", weight ### Create and fill MC histograms ### # Create dict file = {} tree = {} hist = {} ### Create and fill MC histograms ### for i, s in enumerate(data + back + sign): if fileRead: var = 'MET_pt' if channel.startswith('SL'): var = 'MET_sign' if channel.endswith('ZR'): var = 'FakeMET_pt' plotname = var hist[s] = TH1F( s, ";" + variable[var]['title'] + ";Events;" + ('log' if variable[var]['log'] else ''), variable[var]['nbins'], variable[var]['min'], variable[var]['max']) if doBinned: bins = np.array([]) if 'bins' in variable[var].keys(): bins = np.array(variable[var]['bins']) else: binsize = (variable[var]['max'] - variable[var]['min']) / variable[var]['nbins'] bins = np.arange(variable[var]['min'], variable[var]['max'] + binsize, binsize) bins = np.append(bins, 10000) for i in range(0, len(bins) - 1): rbin = str(bins[i]) + "_" + str(bins[i + 1]) fileName = "combinedCards_" + options.name + "/fitDiagnostics_" + options.file + ".root" if not any( t in s for t in ['data', 'tDM'] ) else "rootfiles_" + options.name + "/" + channel + "bin_" + rbin + ".root" histName = "shapes_fit_b/" + channel + "bin_" + rbin + "/" + s if not any( t in s for t in ['data', 'tDM']) else s file[s] = TFile(fileName, "READ") tmphist = file[s].Get(histName) if 'data' not in s: hist[s].SetMarkerSize(0) if tmphist: hist[s].SetBinContent(i + 1, tmphist.GetBinContent(1)) hist[s].SetBinError(i + 1, tmphist.GetBinError(1)) else: hist[s].SetBinContent(i + 1, 0.) hist[s].SetBinError(i + 1, 0.) else: fileName = "combinedCards_" + options.name + "/fitDiagnostics_" + options.file + ".root" if not s == 'data_obs' else "rootfiles_" + options.name + "/" + channel + binName + ".root" histName = "shapes_fit_b/" + channel + "/" + s if not s == 'data_obs' else s file[s] = TFile(fileName, "READ") tmphist = file[s].Get(histName) if tmphist == None: tmphist = hist[back[0]].Clone(s) tmphist.Reset("MICES") print "Histogram", histName, "not found in file", fileName if s == 'data_obs': hist[s] = tmphist else: hist[s] = hist['data_obs'].Clone(s) hist[s].SetMarkerSize(0) for i in range(tmphist.GetNbinsX() + 1): hist[s].SetBinContent(i + 1, tmphist.GetBinContent(i + 1)) elif treeRead: # Project from tree tree[s] = TChain("tree") for j, ss in enumerate(sample[s]['files']): if not 'data' in s or ('data' in s and ss in pd): tree[s].Add(NTUPLEDIR + ss + ".root") if not binLow == "": hist[s] = TH1F( s, ";" + variable[var]['title'] + ";Events;" + ('log' if variable[var]['log'] else ''), 1, float(binLow), float(binHigh)) elif binLow == "" and variable[var]['nbins'] > 0: hist[s] = TH1F( s, ";" + variable[var]['title'] + ";Events;" + ('log' if variable[var]['log'] else ''), variable[var]['nbins'], variable[var]['min'], variable[var]['max']) else: hist[s] = TH1F( s, ";" + variable[var]['title'] + ";Events;" + ('log' if variable[var]['log'] else ''), len(variable[var]['bins']) - 1, array('f', variable[var]['bins'])) hist[s].Sumw2() redFactorString = "" redFactorValue = "" #if isBlind and 'data' in s: if isBlind and 'data' in s and options.limit: redFactorString = " && Entry$ % 15 == 1" #if isBlind and 'data' not in s: if isBlind and 'data' not in s and options.limit: redFactorValue = " / 15" cutstring = "(" + weight + redFactorValue + ")" + ( "*(" + cut + redFactorString + ")" if len(cut) > 0 else "") if '-' in s: cutstring = cutstring.replace( cut, cut + "&& nBQuarks==" + s.split('-')[1][0]) if useformula == True: tree[s].Project(s, variable[var]['formula'], cutstring) else: tree[s].Project(s, var, cutstring) if not tree[s].GetTree() == None: hist[s].SetOption("%s" % tree[s].GetTree().GetEntriesFast()) else: # Histogram written to file for j, ss in enumerate(sample[s]['files']): if not 'data' in s or ('data' in s and ss in pd): file[ss] = TFile(NTUPLEDIR + ss + ".root", "R") if file[ss].IsZombie(): print "WARNING: file", NTUPLEDIR + ss + ".root", "does not exist" continue tmphist = file[ss].Get(cut + "/" + var) if tmphist == None: continue if not s in hist.keys(): hist[s] = tmphist else: hist[s].Add(tmphist) if hist[s].Integral() < 0: hist[s].Scale(0) hist[s].SetFillColor(sample[s]['fillcolor']) hist[s].SetFillStyle(sample[s]['fillstyle']) hist[s].SetLineColor(sample[s]['linecolor']) hist[s].SetLineStyle(sample[s]['linestyle']) #if 'WJetsToLNu' in s and 'SL' in channel and 'WR' in channel: hist[s].Scale(1.30) #if 'TTbar' in s and 'SL' in channel and 'TR' in channel: hist[s].Scale(0.91) hist['BkgSum'] = hist[back[0]].Clone("BkgSum") hist['BkgSum'].Reset("MICES") for i, s in enumerate(back): hist['BkgSum'].Add(hist[s], 1) if fileRead: hist['PreFit'] = hist['BkgSum'].Clone("PreFit") if doBinned: for i in range(0, len(bins) - 1): rbin = str(bins[i]) + "_" + str(bins[i + 1]) tmphist = file[back[0]].Get("shapes_prefit/" + channel + "bin_" + rbin + "/" + "total_background") if tmphist: hist['PreFit'].SetBinContent(i + 1, tmphist.GetBinContent(1)) else: hist['PreFit'].SetBinContent(i + 1, 0.) else: tmphist = file[back[0]].Get("shapes_prefit/" + channel + "/" + "total_background") for i in range(tmphist.GetNbinsX() + 1): hist['PreFit'].SetBinContent(i + 1, tmphist.GetBinContent(i + 1)) addOverflow(hist['PreFit'], False) hist['PreFit'].SetLineStyle(2) hist['PreFit'].SetLineColor(617) #923 hist['PreFit'].SetLineWidth(3) hist['PreFit'].SetFillStyle(0) hist['BkgSum'].SetFillStyle(3002) hist['BkgSum'].SetFillColor(1) # Create data and Bkg sum histograms # if options.blind or 'SR' in channel: # hist['data_obs'] = hist['BkgSum'].Clone("data_obs") # hist['data_obs'].Reset("MICES") # Set histogram style hist[data[0]].SetMarkerStyle(20) hist[data[0]].SetMarkerSize(1.25) for i, s in enumerate(data + back + sign + ['BkgSum']): addOverflow(hist[s], False) # Add overflow for i, s in enumerate(sign): hist[s].SetLineWidth(3) #for i, s in enumerate(sign): sample[s]['plot'] = True#sample[s]['plot'] and s.startswith(channel[:2]) if norm: for i, s in enumerate(sign): hist[s].Scale(hist['BkgSum'].Integral() / hist[s].Integral()) # for i, s in enumerate(back): # hist[s].SetFillStyle(3005) # hist[s].SetLineWidth(2) # #for i, s in enumerate(sign): # # hist[s].SetFillStyle(0) # if not var=="Events": # sfnorm = hist[data[0]].Integral()/hist['BkgSum'].Integral() # print "Applying SF:", sfnorm # for i, s in enumerate(back+['BkgSum']): hist[s].Scale(sfnorm) if SIGNAL > 1: if not var == "Events": for i, s in enumerate(sign): hist[s].Scale(SIGNAL) # Create stack bkg = THStack("Bkg", ";" + hist['BkgSum'].GetXaxis().GetTitle() + ";Events") for i, s in enumerate(back): bkg.Add(hist[s]) # Legend #leg = TLegend(0.65, 0.6, 0.95, 0.9) leg = TLegend(0.45, 0.63, 0.93, 0.92) leg.SetBorderSize(0) leg.SetFillStyle(0) #1001 leg.SetFillColor(0) leg.SetNColumns(3) leg.SetTextFont(42) if len(data) > 0: leg.AddEntry(hist[data[0]], sample[data[0]]['label'], "pe") for i, s in reversed(list(enumerate(back))): leg.AddEntry(hist[s], sample[s]['label'], "f") if 'PreFit' not in hist: leg.AddEntry(hist['BkgSum'], sample['BkgSum']['label'], "f") else: leg.AddEntry(hist['BkgSum'], 'MC unc.', "l") leg.AddEntry(hist['PreFit'], sample['PreFit']['label'], "l") if showSignal: for i, s in enumerate(sign): if SIGNAL > 1: if sample[s]['plot']: leg.AddEntry(hist[s], '%s (x%d)' % (sample[s]['label'], SIGNAL), "l") else: if sample[s]['plot']: leg.AddEntry(hist[s], sample[s]['label'], "l") leg.SetY1(0.9 - leg.GetNRows() * 0.05) # --- Display --- c1 = TCanvas("c1", hist.values()[0].GetXaxis().GetTitle(), 800, 800 if RATIO else 600) if RATIO: if RESIDUAL: c1.Divide(1, 3) setFitTopPad(c1.GetPad(1), RATIO) setFitBotPad(c1.GetPad(2), RATIO) setFitResPad(c1.GetPad(3), RATIO) else: c1.Divide(1, 2) setTopPad(c1.GetPad(1), RATIO) setBotPad(c1.GetPad(2), RATIO) c1.cd(1) c1.GetPad(bool(RATIO)).SetTopMargin(0.06) c1.GetPad(bool(RATIO)).SetRightMargin(0.05) c1.GetPad(bool(RATIO)).SetTicks(1, 1) log = ("log" in hist['BkgSum'].GetZaxis().GetTitle()) if log: c1.GetPad(bool(RATIO)).SetLogy() # Draw bkg.Draw("HIST") # stack hist['BkgSum'].Draw("SAME, E2") # sum of bkg if not isBlind and len(data) > 0: graph = fixData(hist[data[0]], USEGARWOOD) graph.Draw("SAME, PE") #data_graph.Draw("SAME, PE") if 'PreFit' in hist: hist['PreFit'].Draw("SAME, HIST") if showSignal: for i, s in enumerate(sign): if sample[s]['plot']: hist[s].Draw( "SAME, HIST" ) # signals Normalized, hist[s].Integral()*sample[s]['weight'] bkg.GetYaxis().SetTitleOffset(bkg.GetYaxis().GetTitleOffset() * 1.075) bkg.SetMaximum((5. if log else 1.25) * max( bkg.GetMaximum(), hist[data[0]].GetBinContent(hist[data[0]].GetMaximumBin()) + hist[data[0]].GetBinError(hist[data[0]].GetMaximumBin()))) if len(sign) > 0 and bkg.GetMaximum() < max(hist[sign[0]].GetMaximum(), hist[sign[-1]].GetMaximum()): bkg.SetMaximum( max(hist[sign[0]].GetMaximum(), hist[sign[-1]].GetMaximum()) * 1.25) bkg.SetMinimum( max( min(hist['BkgSum'].GetBinContent(hist['BkgSum'].GetMinimumBin( )), hist[data[0]].GetMinimum()), 5.e-1) if log else 0.) if log: #bkg.GetYaxis().SetNoExponent(bkg.GetMaximum() < 1.e4) bkg.GetYaxis().SetNoExponent(bkg.GetMaximum() < 1.e3) bkg.GetYaxis().SetMoreLogLabels(True) else: bkg.GetYaxis().SetNoExponent(bkg.GetMaximum() < 1.e3) leg.Draw() if fileRead and 'SR' in channel: drawCMS(LUMI / 15., "Preliminary") else: drawCMS(LUMI, "Preliminary") drawRegion(channel, True) drawAnalysis("DM" + channel[:2]) drawOverflow() setHistStyle(bkg, 1.2 if RATIO else 1.1) setHistStyle(hist['BkgSum'], 1.2 if RATIO else 1.1) if RATIO: c1.cd(2) err = hist['BkgSum'].Clone("BkgErr;") err.SetTitle("") err.GetYaxis().SetTitle("Data / Bkg") for i in range(1, err.GetNbinsX() + 1): err.SetBinContent(i, 1) if hist['BkgSum'].GetBinContent(i) > 0: err.SetBinError( i, hist['BkgSum'].GetBinError(i) / hist['BkgSum'].GetBinContent(i)) if RESIDUAL: setFitBotStyle(err) else: setBotStyle(err) errLine = err.Clone("errLine") errLine.SetLineWidth(1) errLine.SetFillStyle(0) res = hist[data[0]].Clone("Residues") for i in range(0, res.GetNbinsX() + 1): if hist['BkgSum'].GetBinContent(i) > 0: res.SetBinContent( i, res.GetBinContent(i) / hist['BkgSum'].GetBinContent(i)) res.SetBinError( i, res.GetBinError(i) / hist['BkgSum'].GetBinContent(i)) if RESIDUAL: setFitBotStyle(res) else: setBotStyle(res) #err.GetXaxis().SetLabelOffset(err.GetXaxis().GetLabelOffset()*5) #err.GetXaxis().SetTitleOffset(err.GetXaxis().GetTitleOffset()*2) err.Draw("E2") if 'PreFit' in hist: respre = hist[data[0]].Clone("ResiduesPreFit") respre.Divide(hist['PreFit']) respre.SetLineStyle(2) respre.SetLineColor(617) #923 respre.SetLineWidth(3) respre.SetFillStyle(0) respre.Draw("SAME, HIST") errLine.Draw("SAME, HIST") if not isBlind and len(data) > 0: res.Draw("SAME, PE0") #res_graph.Draw("SAME, PE0") if len(err.GetXaxis().GetBinLabel( 1)) == 0: # Bin labels: not a ordinary plot drawRatio(hist['data_obs'], hist['BkgSum']) drawStat(hist['data_obs'], hist['BkgSum']) c1.Update() if RATIO and RESIDUAL: c1.cd(3) c1.SetGrid(1, 0) resFit = hist[data[0]].Clone("Residues") resFit.Reset("MICES") resFit.SetTitle("") #resFit.GetYaxis().SetTitle("Residuals") resFit.GetYaxis().SetTitle( "#frac{Data - Bkg}{#sqrt{#sigma_{Data}^{2}+#sigma_{Bkg}^{2}}}") for i in range(0, res.GetNbinsX() + 1): if hist['BkgSum'].GetBinContent(i) > 0: resFit.SetBinContent( i, (hist[data[0]].GetBinContent(i) - hist['BkgSum'].GetBinContent(i)) / (math.sqrt( math.pow(hist['BkgSum'].GetBinError(i), 2) + math.pow(hist[data[0]].GetBinError(i), 2)))) setFitResStyle(resFit) resFit.SetLineColor(15) resFit.SetFillColor(15) resFit.SetFillStyle(1001) resFit.Draw("HIST") resFitLine = resFit.Clone("resFitLine") resFitLine.SetLineWidth(1) resFitLine.SetFillStyle(0) resFitLine.Draw("SAME, HIST") c1.Update() if gROOT.IsBatch( ) and options.saveplots: # and (treeRead and channel in selection.keys()): AddString = "" if not os.path.exists("plots_" + options.name + "/" + plotdir): os.makedirs("plots_" + options.name + "/" + plotdir) if fileRead: if RESIDUAL: AddString = "_PostFit_Residual" else: AddString = "_PostFit" #c1.Print("plots_"+options.name+"/"+plotdir+"/"+plotname+binName+AddString+".png") c1.Print("plots_" + options.name + "/" + plotdir + "/" + plotname + binName + AddString + ".pdf") # Print table printTable(hist, sign) if not gROOT.IsBatch(): raw_input("Press Enter to continue...") if gROOT.IsBatch() and not fileRead and ( var == 'MET_pt' or (channel.startswith('SL') and var == 'MET_sign') or (channel.endswith('ZR') and var == 'FakeMET_pt')): saveHist(hist, channel + binName)
sigma1, sigma2, sigma3 = ("nan", "nan", "nan") string_sigma = "muta, tata, nunu sigma = " + str(sigma1) + " " + str( sigma2) + " " + str(sigma3) + '\n' fNevt.write(string_sigma) #Draw if nsig1 * nsig2 * nsig3 > 0: h_sig1.Scale(ntotalbkg / (nsig1 * 10000)) h_sig2.Scale(ntotalbkg / (nsig2 * 10000)) h_sig3.Scale(ntotalbkg / (nsig3 * 10000)) c = TCanvas("c_" + "{}".format(i), "c", 1) if log and h_bkg.Integral() > 0: c.SetLogy() max_hs = max([ hs.GetMaximum(), h_sig1.GetMaximum(), h_sig2.GetMaximum(), h_sig3.GetMaximum() ]) maxfrac = 0.5 if log: if max_hs > 100000: maxfrac = 1000 else: maxfrac = 100 #hs.SetMaximum(max_hs+max_hs*maxfrac) h_sig1.SetMaximum(max_hs + max_hs * maxfrac) #if log: hs.SetMinimum(10) if log: h_sig1.SetMinimum(10) h_sig1.Draw("hist same")
DATA_list[i].SetMarkerSize(0.6) #DATA_list[i].Rebin(4) #MC DY hist MCDY_list[i].Scale(norm) # MC normalization MCDY_list[i].SetFillColor(kAzure - 3) MCDY_list[i].SetLineColor(kBlack) #MCDY_list[i].Rebin(4) hs.Add(MCDY_list[i]) #upper plot pad pad1 = TPad("pad1", "pad1", 0, 0.3, 1, 1.0) pad1.Draw() pad1.cd() hs.SetMaximum(1.6 * max(hs.GetMaximum(), DATA_list[i].GetMaximum())) DATA_list[i].SetMaximum(1.6 * max(hs.GetMaximum(), DATA_list[i].GetMaximum())) hs.SetMinimum(10) #EF for ele BDT hs.Draw("histo") DATA_list[i].Draw("sameEP") hs.SetTitle("") hs.GetXaxis().SetTitle(x_axis_list[i]) hs.GetXaxis().SetLabelFont(43) hs.GetXaxis().SetLabelSize(15) hs.GetYaxis().SetTitleSize(20) hs.GetYaxis().SetTitleFont(43) hs.GetYaxis().SetTitleOffset(1.2) hs.GetYaxis().SetLabelFont(43)
def Direct_Estimator(var, cut, year): from root_numpy import root2array, fill_hist, array2root import numpy.lib.recfunctions as rfn ### Preliminary Operations ### treeRead = not cut in [ "nnqq", "en", "enqq", "mn", "mnqq", "ee", "eeqq", "mm", "mmqq", "em", "emqq", "qqqq" ] # Read from tree channel = cut unit = '' if "GeV" in variable[var]['title']: unit = ' GeV' isBlind = BLIND and 'SR' in channel isAH = False #'qqqq' in channel or 'hp' in channel or 'lp' in channel showSignal = False if 'SB' in cut or 'TR' in cut else True #'SR' in channel or channel=='qqqq'#or len(channel)==5 stype = "HVT model B" if len(sign) > 0 and 'AZh' in sign[0]: stype = "2HDM" elif len(sign) > 0 and 'monoH' in sign[0]: stype = "Z'-2HDM m_{A}=300 GeV" if treeRead: for k in sorted(alias.keys(), key=len, reverse=True): if BTAGGING == 'semimedium': if k in cut: cut = cut.replace(k, aliasSM[k]) else: if k in cut: cut = cut.replace( k, alias[k].format(WP=working_points[BTAGGING])) print "Plotting from", ("tree" if treeRead else "file"), var, "in", channel, "channel with:" print " cut :", cut if var == 'jj_deltaEta_widejet': if "jj_deltaEta_widejet<1.1 && " in cut: print print "omitting jj_deltaEta_widejet<1.1 cut to draw the deltaEta distribution" print cut = cut.replace("jj_deltaEta_widejet<1.1 && ", "") else: print print "no 'jj_deltaEta_widejet<1.1 && ' in the cut string detected, so it cannot be ommited explicitly" print ### Create and fill MC histograms ### # Create dict file = {} tree = {} hist = {} ### Create and fill MC histograms ### for i, s in enumerate(back + sign): if True: #FIXME if variable[var]['nbins'] > 0: hist[s] = TH1F( s, ";" + variable[var]['title'] + ";Events / ( " + str( (variable[var]['max'] - variable[var]['min']) / variable[var]['nbins']) + unit + " );" + ('log' if variable[var]['log'] else ''), variable[var]['nbins'], variable[var]['min'], variable[var]['max']) else: hist[s] = TH1F( s, ";" + variable[var]['title'] + ";Events" + ('log' if variable[var]['log'] else ''), len(variable[var]['bins']) - 1, array('f', variable[var]['bins'])) hist[s].Sumw2() for j, ss in enumerate(sample[s]['files']): if not 'data' in s: if year == "run2" or year in ss: arr = root2array( NTUPLEDIR + ss + ".root", branches=[ var, "jpt_1", "jpt_2", "eventWeightLumi", "TMath::Abs(jflavour_1)==5 && TMath::Abs(jflavour_2)==5", "TMath::Abs(jflavour_1)==5 && TMath::Abs(jflavour_2)!=5", "TMath::Abs(jflavour_1)!=5 && TMath::Abs(jflavour_2)==5", "TMath::Abs(jflavour_1)!=5 && TMath::Abs(jflavour_2)!=5" ], selection=cut if len(cut) > 0 else "") print "imported " + NTUPLEDIR + ss + ".root" arr.dtype.names = [ var, "jpt_1", "jpt_2", "eventWeightLumi", "bb", "bq", "qb", "qq" ] MANtag_eff1 = np.array(map(MANtag_eff, arr["jpt_1"])) MANtag_eff2 = np.array(map(MANtag_eff, arr["jpt_2"])) MANtag_mis1 = np.array(map(MANtag_mis, arr["jpt_1"])) MANtag_mis2 = np.array(map(MANtag_mis, arr["jpt_2"])) MANtag_weight = np.multiply( arr["eventWeightLumi"], np.multiply(arr['bb'], np.multiply(MANtag_eff1, MANtag_eff2)) + np.multiply( arr['bq'], np.multiply(MANtag_eff1, MANtag_mis2)) + np.multiply(arr['qb'], np.multiply(MANtag_mis1, MANtag_eff2)) + np.multiply(arr['qq'], np.multiply(MANtag_mis1, MANtag_mis2))) fill_hist(hist[s], arr[var], weights=MANtag_weight) deepCSV_eff1 = np.array(map(deepCSV_eff, arr["jpt_1"])) deepCSV_eff2 = np.array(map(deepCSV_eff, arr["jpt_2"])) deepCSV_mis1 = np.array(map(deepCSV_mis, arr["jpt_1"])) deepCSV_mis2 = np.array(map(deepCSV_mis, arr["jpt_2"])) deepCSV_weight = np.multiply( arr["eventWeightLumi"], np.multiply( arr['bb'], np.multiply(deepCSV_eff1, deepCSV_eff2)) + np.multiply( arr['bq'], np.multiply(deepCSV_eff1, deepCSV_mis2)) + np.multiply( arr['qb'], np.multiply(deepCSV_mis1, deepCSV_eff2)) + np.multiply( arr['qq'], np.multiply(deepCSV_mis1, deepCSV_mis2))) if var == "jj_mass_widejet" and options.save and not "data" in ss: arr = rfn.append_fields(arr, "MANtag_weight", MANtag_weight, usemask=False) arr = rfn.append_fields(arr, "deepCSV_weight", deepCSV_weight, usemask=False) array2root(arr, NTUPLEDIR + "MANtag/" + ss + "_" + BTAGGING + ".root", treename="tree", mode='recreate') print "saved as", NTUPLEDIR + "MANtag/" + ss + "_" + BTAGGING + ".root" arr = None hist[s].Scale(sample[s]['weight'] if hist[s].Integral() >= 0 else 0) hist[s].SetFillColor(sample[s]['fillcolor']) hist[s].SetFillStyle(sample[s]['fillstyle']) hist[s].SetLineColor(sample[s]['linecolor']) hist[s].SetLineStyle(sample[s]['linestyle']) if channel.endswith('TR') and channel.replace('TR', '') in topSF: hist['TTbarSL'].Scale(topSF[channel.replace('TR', '')][0]) hist['ST'].Scale(topSF[channel.replace('TR', '')][0]) hist['BkgSum'] = hist['data_obs'].Clone( "BkgSum") if 'data_obs' in hist else hist[back[0]].Clone("BkgSum") hist['BkgSum'].Reset("MICES") hist['BkgSum'].SetFillStyle(3003) hist['BkgSum'].SetFillColor(1) for i, s in enumerate(back): hist['BkgSum'].Add(hist[s]) # Create data and Bkg sum histograms if options.blind or 'SR' in channel: hist['data_obs'] = hist['BkgSum'].Clone("data_obs") hist['data_obs'].Reset("MICES") # Set histogram style hist['data_obs'].SetMarkerStyle(20) hist['data_obs'].SetMarkerSize(1.25) for i, s in enumerate(back + sign + ['BkgSum']): addOverflow(hist[s], False) # Add overflow for i, s in enumerate(sign): hist[s].SetLineWidth(3) for i, s in enumerate(sign): sample[s][ 'plot'] = True #sample[s]['plot'] and s.startswith(channel[:2]) if isAH: for i, s in enumerate(back): hist[s].SetFillStyle(3005) hist[s].SetLineWidth(2) #for i, s in enumerate(sign): # hist[s].SetFillStyle(0) if not var == "Events": sfnorm = hist[data[0]].Integral() / hist['BkgSum'].Integral() print "Applying SF:", sfnorm for i, s in enumerate(back + ['BkgSum']): hist[s].Scale(sfnorm) if BLIND and var.endswith("Mass"): for i, s in enumerate(data + back + ['BkgSum']): first, last = hist[s].FindBin(65), hist[s].FindBin(135) for j in range(first, last): hist[s].SetBinContent(j, -1.e-4) if BLIND and var.endswith("Tau21"): for i, s in enumerate(data): first, last = hist[s].FindBin(0), hist[s].FindBin(0.6) for j in range(first, last): hist[s].SetBinContent(j, -1.e-4) # Create stack if variable[var]['nbins'] > 0: bkg = THStack( "Bkg", ";" + hist['BkgSum'].GetXaxis().GetTitle() + ";Events / ( " + str( (variable[var]['max'] - variable[var]['min']) / variable[var]['nbins']) + unit + " )") else: bkg = THStack("Bkg", ";" + hist['BkgSum'].GetXaxis().GetTitle() + ";Events; ") for i, s in enumerate(back): bkg.Add(hist[s]) # Legend leg = TLegend(0.65, 0.6, 0.95, 0.9) leg.SetBorderSize(0) leg.SetFillStyle(0) #1001 leg.SetFillColor(0) if len(data) > 0: leg.AddEntry(hist[data[0]], sample[data[0]]['label'], "pe") for i, s in reversed(list(enumerate(['BkgSum'] + back))): leg.AddEntry(hist[s], sample[s]['label'], "f") if showSignal: for i, s in enumerate(sign): if sample[s]['plot']: leg.AddEntry(hist[s], sample[s]['label'], "fl") leg.SetY1(0.9 - leg.GetNRows() * 0.05) # --- Display --- c1 = TCanvas("c1", hist.values()[0].GetXaxis().GetTitle(), 800, 800 if RATIO else 600) if RATIO: c1.Divide(1, 2) setTopPad(c1.GetPad(1), RATIO) setBotPad(c1.GetPad(2), RATIO) c1.cd(1) c1.GetPad(bool(RATIO)).SetTopMargin(0.06) c1.GetPad(bool(RATIO)).SetRightMargin(0.05) c1.GetPad(bool(RATIO)).SetTicks(1, 1) log = variable[var]['log'] #"log" in hist['BkgSum'].GetZaxis().GetTitle() if log: c1.GetPad(bool(RATIO)).SetLogy() # Draw bkg.Draw("HIST") # stack hist['BkgSum'].Draw("SAME, E2") # sum of bkg if not isBlind and len(data) > 0: hist['data_obs'].Draw("SAME, PE") # data if 'sync' in hist: hist['sync'].Draw("SAME, PE") #data_graph.Draw("SAME, PE") if showSignal: smagn = 1. #if treeRead else 1.e2 #if log else 1.e2 for i, s in enumerate(sign): # if sample[s]['plot']: hist[s].Scale(smagn) hist[s].Draw( "SAME, HIST" ) # signals Normalized, hist[s].Integral()*sample[s]['weight'] textS = drawText(0.80, 0.9 - leg.GetNRows() * 0.05 - 0.02, stype + " (x%d)" % smagn, True) #bkg.GetYaxis().SetTitleOffset(bkg.GetYaxis().GetTitleOffset()*1.075) bkg.GetYaxis().SetTitleOffset(0.9) #bkg.GetYaxis().SetTitleOffset(2.) bkg.SetMaximum((5. if log else 1.25) * max( bkg.GetMaximum(), hist['data_obs'].GetBinContent(hist['data_obs'].GetMaximumBin()) + hist['data_obs'].GetBinError(hist['data_obs'].GetMaximumBin()))) #if bkg.GetMaximum() < max(hist[sign[0]].GetMaximum(), hist[sign[-1]].GetMaximum()): bkg.SetMaximum(max(hist[sign[0]].GetMaximum(), hist[sign[-1]].GetMaximum())*1.25) bkg.SetMinimum( max( min(hist['BkgSum'].GetBinContent(hist['BkgSum'].GetMinimumBin( )), hist['data_obs'].GetMinimum()), 5.e-1) if log else 0.) if log: bkg.GetYaxis().SetNoExponent(bkg.GetMaximum() < 1.e4) #bkg.GetYaxis().SetMoreLogLabels(True) bkg.GetXaxis().SetRangeUser(variable[var]['min'], variable[var]['max']) #if log: bkg.SetMinimum(1) leg.Draw() #drawCMS(LUMI[year], "Preliminary") drawCMS(LUMI[year], "Work in Progress", suppressCMS=True) drawRegion('XVH' + channel, True) drawAnalysis(channel) setHistStyle(bkg, 1.2 if RATIO else 1.1) setHistStyle(hist['BkgSum'], 1.2 if RATIO else 1.1) if RATIO: c1.cd(2) err = hist['BkgSum'].Clone("BkgErr;") err.SetTitle("") err.GetYaxis().SetTitle("Data / MC") err.GetYaxis().SetTitleOffset(0.9) err.GetXaxis().SetRangeUser(variable[var]['min'], variable[var]['max']) for i in range(1, err.GetNbinsX() + 1): err.SetBinContent(i, 1) if hist['BkgSum'].GetBinContent(i) > 0: err.SetBinError( i, hist['BkgSum'].GetBinError(i) / hist['BkgSum'].GetBinContent(i)) setBotStyle(err) errLine = err.Clone("errLine") errLine.SetLineWidth(1) errLine.SetFillStyle(0) res = hist['data_obs'].Clone("Residues") for i in range(0, res.GetNbinsX() + 1): if hist['BkgSum'].GetBinContent(i) > 0: res.SetBinContent( i, res.GetBinContent(i) / hist['BkgSum'].GetBinContent(i)) res.SetBinError( i, res.GetBinError(i) / hist['BkgSum'].GetBinContent(i)) if 'sync' in hist: res.SetMarkerColor(2) res.SetMarkerStyle(31) res.Reset() for i in range(0, res.GetNbinsX() + 1): x = hist['data_obs'].GetXaxis().GetBinCenter(i) if hist['sync'].GetBinContent(hist['sync'].FindBin(x)) > 0: res.SetBinContent( i, hist['data_obs'].GetBinContent( hist['data_obs'].FindBin(x)) / hist['sync'].GetBinContent(hist['sync'].FindBin(x))) res.SetBinError( i, hist['data_obs'].GetBinError( hist['data_obs'].FindBin(x)) / hist['sync'].GetBinContent(hist['sync'].FindBin(x))) setBotStyle(res) #err.GetXaxis().SetLabelOffset(err.GetXaxis().GetLabelOffset()*5) #err.GetXaxis().SetTitleOffset(err.GetXaxis().GetTitleOffset()*2) err.Draw("E2") errLine.Draw("SAME, HIST") if not isBlind and len(data) > 0: res.Draw("SAME, PE0") #res_graph.Draw("SAME, PE0") if len(err.GetXaxis().GetBinLabel( 1)) == 0: # Bin labels: not a ordinary plot drawRatio(hist['data_obs'], hist['BkgSum']) drawStat(hist['data_obs'], hist['BkgSum']) c1.Update() if gROOT.IsBatch(): if channel == "": channel = "nocut" varname = var.replace('.', '_').replace('()', '') if not os.path.exists("plots/" + channel): os.makedirs("plots/" + channel) suffix = '' if "b" in channel or 'mu' in channel: suffix += "_" + BTAGGING c1.Print("plots/MANtag_study/" + channel + "/" + varname + "_" + year + suffix + ".png") c1.Print("plots/MANtag_study/" + channel + "/" + varname + "_" + year + suffix + ".pdf") # Print table printTable(hist, sign)
c.cd() # returns to main canvas before defining pad2 pad2 = TPad("pad2", "pad2", 0.0, 0.0, 1, 0.28) pad2.SetBottomMargin(0.3) pad2.SetTopMargin(0.02) pad2.SetGridx() pad2.SetGridy() pad2.Draw() #Draw each plot pad1.cd() if log: pad1.SetLogy() h_data.SetMarkerStyle(20) h_data.SetMarkerSize(0.5) max_data = h_data.GetMaximum() max_hs = hs.GetMaximum() sigmaximums = [ hs_Hct.GetMaximum(), hs_Hut.GetMaximum(), hs_stHct.GetMaximum(), hs_stHut.GetMaximum() ] max_sig = max(sigmaximums) maxfrac = 0.5 if (max_hs > max_sig): if log: if max_data > 100000: maxfrac = 1000 else: maxfrac = 100 if max_hs > max_data:
pad2.SetFrameFillStyle(0) pad2.SetFrameBorderMode(0) pad2.SetTickx(0) pad2.SetTicky(0) pad1.Draw() pad2.Draw() noData = False oneLine = TF1("oneline", "1", -9e9, 9e9) oneLine.SetLineColor(kBlack) oneLine.SetLineWidth(1) oneLine.SetLineStyle(2) maxVal = stack.GetMaximum() if not noData: maxVal = max(rebinnedData.GetMaximum(), maxVal) minVal = 0 # minVal = max(stack.GetStack()[0].GetMinimum(),1) stack.SetMaximum(1.25 * maxVal) stack.SetMinimum(minVal) errorband = stack.GetStack().Last().Clone("error") errorband.Sumw2() errorband.SetLineColor(kBlack) errorband.SetFillColor(kBlack) errorband.SetFillStyle(3245) errorband.SetMarkerSize(0)
def draw(hist, fit, channel, data, back, sign, snorm=1, lumi=-1, ratio=0, log=False): # If not present, create BkgSum if not 'BkgSum' in hist.keys(): hist['BkgSum'] = hist['data_obs'].Clone( "BkgSum") if 'data_obs' in hist else hist[back[0]].Clone("BkgSum") hist['BkgSum'].Reset("MICES") for i, s in enumerate(back): hist['BkgSum'].Add(hist[s]) hist['BkgSum'].SetMarkerStyle(0) setHistStyle(hist['BkgSum'], 1.1 if ratio else 1.0) # Create stack bkg = THStack( "Bkg", ";" + hist['BkgSum'].GetXaxis().GetTitle() + ";" + hist['BkgSum'].GetYaxis().GetTitle()) for i, s in enumerate(back): bkg.Add(hist[s]) # Legend n = len([x for x in data + back + ['BkgSum'] + sign if sample[x]['plot']]) leg = TLegend(0.69, 0.86 - 0.04 * n, 0.95, 0.86) leg.SetBorderSize(0) leg.SetFillStyle(0) leg.SetFillColor(0) if len(data) > 0: leg.AddEntry(hist[data[0]], sample[data[0]]['label'], "pl") for i, s in reversed(list(enumerate(['BkgSum'] + back))): leg.AddEntry(hist[s], sample[s]['label'], "f") for i, s in enumerate(sign): if sample[s]['plot']: leg.AddEntry(hist[s], sample[s]['label'].replace("m_{#Chi}=1 GeV", ""), "fl") ### data/bkg ratio and systematics err = hist['BkgSum'].Clone("BkgErr;") err.SetTitle("") err.GetYaxis().SetTitle("data / bkg") if fit == "prefit": err.SetFillColor(ROOT.kOrange - 2) elif fit == "postfit": err.SetFillColor(ROOT.kBlue) err.SetFillStyle(3001) for i in range(1, err.GetNbinsX() + 1): err.SetBinContent(i, 1) if hist['BkgSum'].GetBinContent(i) > 0: err.SetBinError( i, hist['BkgSum'].GetBinError(i) / hist['BkgSum'].GetBinContent(i)) errLine = err.Clone("errLine") errLine.SetLineWidth(1) errLine.SetFillStyle(0) res = hist['data_obs'].Clone("residues") for i in range(0, res.GetNbinsX() + 1): if hist['BkgSum'].GetBinContent(i) > 0: res.SetBinContent( i, res.GetBinContent(i) / hist['BkgSum'].GetBinContent(i)) res.SetBinError( i, res.GetBinError(i) / hist['BkgSum'].GetBinContent(i)) # Legend leg1 = TLegend(0.12, 0.45, 0.25, 0.5) leg1.SetBorderSize(0) leg1.SetFillStyle(0) leg1.SetFillColor(0) leg1.SetTextSize(0.05) leg1.AddEntry(err, "systematic uncertainty (" + fit + ")", "f") # --- Display --- c1 = TCanvas("c1", hist.values()[0].GetXaxis().GetTitle(), 800, 800 if ratio else 600) gStyle.SetOptStat(0) if ratio: c1.Divide(1, 2) setTopPad(c1.GetPad(1), ratio) setBotPad(c1.GetPad(2), ratio) c1.cd(1) c1.GetPad(bool(ratio)).SetTopMargin(0.08) c1.GetPad(bool(ratio)).SetRightMargin(0.05) c1.GetPad(bool(ratio)).SetTicks(1, 1) if log: c1.GetPad(bool(ratio)).SetLogy() # Draw bkg.Draw("HIST") # stack # hist['BkgSum'].Draw("SAME, E2") # sum of bkg if len(data) > 0: hist['data_obs'].Draw("SAME, PE") # data for i, s in enumerate(sign): if sample[s]['plot']: hist[s].DrawNormalized("SAME, HIST", hist[s].Integral() * snorm) # signals pass bkg.SetMaximum((2. if log else 1.1) * max( bkg.GetMaximum(), hist['data_obs'].GetMaximum() + hist['data_obs'].GetBinError(hist['data_obs'].GetMaximumBin()))) bkg.SetMinimum( max( min(hist['BkgSum'].GetBinContent(hist['BkgSum'].GetMinimumBin( )), hist['data_obs'].GetMinimum()), 1.e-1) if log else 0.) if log: bkg.GetYaxis().SetNoExponent(bkg.GetMaximum() < 1.e4) bkg.GetYaxis().SetMoreLogLabels(True) setHistStyle(bkg, 1.1 if ratio else 1.0) leg.Draw() # drawCMS(lumi, "Preliminary",True) drawCMS(lumi, "Private", True) drawRegion(channel) drawAnalysis(channel) drawFit(fit) if ratio: c1.cd(2) setBotStyle(err, 3, True) setBotStyle(res) err.Draw("E2") errLine.Draw("SAME, HIST") if len(data) > 0: res.Draw("SAME, PE0") drawRatio(hist['data_obs'], hist['BkgSum']) drawKolmogorov(hist['data_obs'], hist['BkgSum']) leg1.Draw() c1.Update() # return list of objects created by the draw() function return [c1, bkg, leg, leg1, err, errLine, res]
inMCTTbar_list[i].SetFillColor(kAzure - 2) inMCTTbar_list[i].SetLineColor(kBlack) hs.Add(inMCTTbar_list[i]) #MC DY hist inMCDY_list[i].Scale(norm) #normalize MC inMCDY_list[i].SetFillColor(kOrange - 3) inMCDY_list[i].SetLineColor(kBlack) hs.Add(inMCDY_list[i]) #upper plot pad pad1 = TPad("pad1", "pad1", 0, 0.3, 1, 1.0) pad1.Draw() pad1.cd() hs.SetMaximum(1.3 * max(hs.GetMaximum(), inDATA_list[i].GetMaximum())) inDATA_list[i].SetMaximum( 1.3 * max(hs.GetMaximum(), inDATA_list[i].GetMaximum())) hs.Draw("histo") inDATA_list[i].Draw("sameEP") hs.SetTitle("") hs.GetXaxis().SetTitle(inDATA_list[i].GetTitle()) hs.GetXaxis().SetLabelFont(43) hs.GetXaxis().SetLabelSize(15) hs.GetYaxis().SetTitleSize(20) hs.GetYaxis().SetTitleFont(43) hs.GetYaxis().SetTitleOffset(1.8) hs.GetYaxis().SetLabelFont(43) hs.GetYaxis().SetLabelSize(15)
def draw(hist, channel, data, back, sign, snorm=1, lumi=-1, ratio=0, log=False): # If not present, create BkgSum if not 'BkgSum' in hist.keys(): hist['BkgSum'] = hist['data_obs'].Clone( "BkgSum") if 'data_obs' in hist else hist[back[0]].Clone("BkgSum") hist['BkgSum'].Reset("MICES") for i, s in enumerate(back): hist['BkgSum'].Add(hist[s]) hist['BkgSum'].SetMarkerStyle(0) # Set Poisson error bars #if len(data) > 0: hist['data_obs'].SetBinErrorOption(1) # doesn't work alpha = 1 - 0.6827 hist['data_obs'].SetBinErrorOption(TH1.kPoisson) data_graph = TGraphAsymmErrors(hist['data_obs'].GetNbinsX()) data_graph.SetMarkerStyle(hist['data_obs'].GetMarkerStyle()) data_graph.SetMarkerSize(hist['data_obs'].GetMarkerSize()) res_graph = data_graph.Clone() for i in range(hist['data_obs'].GetNbinsX()): N = hist['data_obs'].GetBinContent(i + 1) B = hist['BkgSum'].GetBinContent(i + 1) L = 0 if N == 0 else ROOT.Math.gamma_quantile(alpha / 2, N, 1.) U = ROOT.Math.gamma_quantile_c(alpha / 2, N + 1, 1) data_graph.SetPoint(i, hist['data_obs'].GetXaxis().GetBinCenter(i + 1), N if not N == 0 else -1.e99) data_graph.SetPointError( i, hist['data_obs'].GetXaxis().GetBinWidth(i + 1) / 2., hist['data_obs'].GetXaxis().GetBinWidth(i + 1) / 2., N - L, U - N) res_graph.SetPoint(i, hist['data_obs'].GetXaxis().GetBinCenter(i + 1), N / B if not B == 0 and not N == 0 else -1.e99) res_graph.SetPointError( i, hist['data_obs'].GetXaxis().GetBinWidth(i + 1) / 2., hist['data_obs'].GetXaxis().GetBinWidth(i + 1) / 2., (N - L) / B if not B == 0 else -1.e99, (U - N) / B if not B == 0 else -1.e99) # Create stack bkg = THStack("Bkg", ";" + hist['BkgSum'].GetXaxis().GetTitle() + ";Events") for i, s in enumerate(back): bkg.Add(hist[s]) # Legend n = len([x for x in data + back + ['BkgSum'] + sign if sample[x]['plot']]) leg = TLegend(0.7, 0.9 - 0.05 * n, 0.95, 0.9) leg.SetBorderSize(0) leg.SetFillStyle(0) #1001 leg.SetFillColor(0) if len(data) > 0: leg.AddEntry(hist[data[0]], sample[data[0]]['label'], "pl") for i, s in reversed(list(enumerate(['BkgSum'] + back))): leg.AddEntry(hist[s], sample[s]['label'], "f") for i, s in enumerate(sign): if sample[s]['plot']: leg.AddEntry(hist[s], sample[s]['label'].replace("m_{#Chi}=1 GeV", ""), "fl") # --- Display --- c1 = TCanvas("c1", hist.values()[0].GetXaxis().GetTitle(), 800, 800 if ratio else 600) if ratio: c1.Divide(1, 2) setTopPad(c1.GetPad(1), ratio) setBotPad(c1.GetPad(2), ratio) c1.cd(1) c1.GetPad(bool(ratio)).SetTopMargin(0.06) c1.GetPad(bool(ratio)).SetRightMargin(0.05) c1.GetPad(bool(ratio)).SetTicks(1, 1) if log: c1.GetPad(bool(ratio)).SetLogy() # Draw bkg.Draw("HIST") # stack hist['BkgSum'].Draw("SAME, E2") # sum of bkg #if len(data) > 0: hist['data_obs'].Draw("SAME, PE") # data data_graph.Draw("SAME, PE") for i, s in enumerate(sign): if sample[s]['plot']: hist[s].DrawNormalized("SAME, HIST", hist[s].Integral() * snorm) # signals bkg.GetYaxis().SetTitleOffset(bkg.GetYaxis().GetTitleOffset() * 1.075) bkg.SetMaximum((2. if log else 1.2) * max( bkg.GetMaximum(), hist['data_obs'].GetBinContent(hist['data_obs'].GetMaximumBin()) + hist['data_obs'].GetBinError(hist['data_obs'].GetMaximumBin()))) bkg.SetMinimum( max( min(hist['BkgSum'].GetBinContent(hist['BkgSum'].GetMinimumBin( )), hist['data_obs'].GetMinimum()), 5.e-1) if log else 0.) if log: bkg.GetYaxis().SetNoExponent(bkg.GetMaximum() < 1.e4) bkg.GetYaxis().SetMoreLogLabels(True) #if log: bkg.SetMinimum(1) leg.Draw() drawCMS(lumi, "Preliminary") drawRegion(channel) drawAnalysis(channel) #if nm1 and not cutValue is None: drawCut(cutValue, bkg.GetMinimum(), bkg.GetMaximum()) #FIXME if len(sign) > 0: if channel.startswith('X') and len(sign) > 0: drawNorm(0.9 - 0.04 * (n + 1), "#sigma(X) #times B(X #rightarrow Vh) = %.1f pb" % snorm) #elif "SR" in channel: drawNorm(0.9-0.04*(n+1), "DM+bb/tt, scaled by %.0f" % snorm, "m_{#chi}=1 GeV, scalar mediator") elif "SR" in channel: drawNorm(0.9 - 0.04 * (n + 1), "DM+bb/tt, m_{#chi}=1 GeV", "scalar mediator") setHistStyle(bkg, 1.2 if ratio else 1.1) setHistStyle(hist['BkgSum'], 1.2 if ratio else 1.1) if ratio: c1.cd(2) err = hist['BkgSum'].Clone("BkgErr;") err.SetTitle("") err.GetYaxis().SetTitle("Data / Bkg") for i in range(1, err.GetNbinsX() + 1): err.SetBinContent(i, 1) if hist['BkgSum'].GetBinContent(i) > 0: err.SetBinError( i, hist['BkgSum'].GetBinError(i) / hist['BkgSum'].GetBinContent(i)) setBotStyle(err) errLine = err.Clone("errLine") errLine.SetLineWidth(1) errLine.SetFillStyle(0) res = hist['data_obs'].Clone("Residues") for i in range(0, res.GetNbinsX() + 1): if hist['BkgSum'].GetBinContent(i) > 0: res.SetBinContent( i, res.GetBinContent(i) / hist['BkgSum'].GetBinContent(i)) res.SetBinError( i, res.GetBinError(i) / hist['BkgSum'].GetBinContent(i)) setBotStyle(res) #err.GetXaxis().SetLabelOffset(err.GetXaxis().GetLabelOffset()*5) #err.GetXaxis().SetTitleOffset(err.GetXaxis().GetTitleOffset()*2) err.Draw("E2") errLine.Draw("SAME, HIST") if len(data) > 0: #res.Draw("SAME, PE0") res_graph.Draw("SAME, PE0") # if len(err.GetXaxis().GetBinLabel(1))==0: # Bin labels: not a ordinary plot # drawRatio(hist['data_obs'], hist['BkgSum']) # drawKolmogorov(hist['data_obs'], hist['BkgSum']) c1.Update() # return list of objects created by the draw() function return [c1, bkg, leg, err, errLine, res, data_graph, res_graph]
def plotter(plotdir, plot, xTitle, logY, channels=['VV'], includeData=False, scaleSignal=0, UserRange=[None, None, None, None], initPath=''): # channelTex={'WPWP':'W^{+}W^{+}', 'WPWM':'W^{+}W^{-}','WMWM':'W^{-}W^{-}','WPZ':'W^{+}Z','WMZ':'W^{-}Z','ZZ':'ZZ'} channelTex = {'ZZ': 'ZZ'} # plotstyle=[(1,1),(1,2),(2,1),(2,2),(4,1),(4,2)] plotstyle = [(1, 1)] # 0 1 2 3 4 5 6 # Backgrounds=['QCD', 'WJetsToQQ_HT600ToInf', 'ZJetsToQQ_HT600ToInf', 'TT', 'WW', 'WZ', 'ZZ'] # BGColors= [rt.kAzure+7, rt.kRed-4, rt.kOrange-2, rt.kGreen+2, rt.kOrange+7, rt.kBlue+1, rt.kMagenta+2] # BGTeX= ['QCD', 'W+JetsToQQ', 'Z+JetsToQQ', 'TTbar'], 'WW', 'WZ', 'ZZ'] #stackOrder= [4,5,6,2,1,3,0] Backgrounds = [ 'QCD' ] # 'WJetsToQQ_HT600ToInf', 'ZJetsToQQ_HT600ToInf', 'ZZ'] 'TT', 'WW', 'WZ', 'ZZ'] BGColors = [ rt.kAzure + 7 ] #, rt.kOrange-2, rt.kGreen+2], rt.kOrange+7, rt.kBlue+1, rt.kMagenta+2] BGTeX = ['QCD'] # stackOrder = [0] PreSelection = [ 'nocuts', 'common', 'corrections', 'cleaner', 'softdropmassCorr', 'AK4pfidfilter', 'AK8pfidfilter', 'invMAk8sel', 'detaAk8sel', 'AK8N2sel' ] Selection = [ 'preselection', 'softdropAK8sel', 'tau21sel', 'deltaR48', 'VVRegion', 'AK4N2sel', 'OpSignsel', 'detaAk4sel', 'invMAk4sel_1p0', 'Kin_AK8' ] cutnames = [ 'cleaner', 'AK8N2sel', 'invMAk8sel', 'detaAk8sel', 'softdropAK8sel', 'tau21sel', 'AK4cleaner', 'AK4N2sel', 'OpSignsel', 'detaAk4sel', 'invMAk4sel_1p0' ] cuts = { 'cleaner': '#splitline{p_{T-AK8} > 200 GeV, |#eta_{AK8}| < 2.5}{p_{T-AK4} > 30 GeV, |#eta_{AK4}| < 5.0}', 'AK8N2sel': 'N_{AK8} #geq 2', 'invMAk8sel': 'M_{jj-AK8} > 1050 GeV', 'detaAk8sel': '|#Delta#eta_{jj-AK8}|<1.3', 'softdropAK8sel': '65 GeV <M_{SD}< 105 GeV', 'tau21sel': '0 #leq #tau_{2}/#tau_{1}<0.45', # 'AK4cleaner':'p_{T-AK4} > 30 GeV, |#eta_{AK4}| < 5.0', 'AK4cleaner': '', 'AK4N2sel': 'N_{AK4} #geq 2', 'OpSignsel': '#eta_{1-AK4} #eta_{2-AK4} < 0', 'detaAk4sel': '|#Delta#eta_{jj-AK4}| > 3.0', 'invMAk4sel_1p0': 'M_{jj-AK4} > 1.0 TeV' } VV = ('VV' in channels) seperate = (not VV) if VV: #channels=["WPWP","WPWM","WMWM","WPZ","WMZ","ZZ"] channels = ["ZZ"] plottitle = plotdir + '_' + plot lumi = 36.814 xLabelSize = 18. yLabelSize = 18. xTitleSize = 20. yTitleSize = 22. xTitleOffset = 4. yTitleOffset = 1.3 printout = False Portrait = True cutname = False ratio = includeData if ('highbin' in plot): binning = 'dijetbinning' else: binning = 'default' if (Portrait): canvX = 600 canvY = 600 else: canvX = 900 canvY = 675 if (plotdir in PreSelection): region = 'PreSelection' initPath = '' referenceHistPath = 'detaAk8sel/N_pv' if (PreSelection.index(plotdir) < 4 and ('softdrop' in plot)): return 'SofdropMass not filled yet!' else: region = 'SignalRegion' referenceHistPath = 'tau21sel/N_pv' referenceHistPath = plotdir + '/' + plot if (initPath == ''): path = '/nfs/dust/cms/user/loemkerj/bachelor/CMSSW_10_2_16/src/UHH2/aQGCVVjjhadronic/%s' % region else: path = initPath outputPath = path.replace( '/nfs/dust/cms/user/loemkerj/bachelor/CMSSW_10_2_16/src/UHH2/aQGCVVjjhadronic/SignalRegion', 'plots/') if (plotdir in PreSelection): CutNumber = PreSelection.index(plotdir) else: CutNumber = Selection.index(plotdir) outputPath = outputPath + '/%02i_%s' % (CutNumber, plotdir) + '/' if (printout): print('InputPath:', path) print('OutputPath:', outputPath) #check if OutputPath exists - and if not create it! if not os.path.exists(outputPath): os.makedirs(outputPath) # path='/home/albrec/Master/signal/' scaleVV = (scaleSignal != 0) VVScale = scaleSignal if (UserRange[2] == None or UserRange[3] == None): YRangeUser = False Ymin = UserRange[2] Ymax = UserRange[3] else: YRangeUser = True Ymin = UserRange[2] Ymax = UserRange[3] if (UserRange[0] == None or UserRange[1] == None): XRangeUser = False Xmin = UserRange[0] Xmax = UserRange[1] else: XRangeUser = True Xmin = UserRange[0] Xmax = UserRange[1] # YRangeUser=False # Ymin=0.11 # Ymax=9*10**3 # XRangeUser=False # Xmin=0 # Xmax=6000. gROOT.ProcessLine("gErrorIgnoreLevel = 2001;") SFiles = [] for i in range(len(channels)): SFiles.append( TFile( path + "/uhh2.AnalysisModuleRunner.MC.MC_aQGC_%sjj_hadronic_2016v3.root" % channels[i])) #uhh2.AnalysisModuleRunner.MC.MC_aQGC_ZZjj_hadronic_2016v3.root ##Open Files to get BackgroundHist: BFiles = [] for i in range(len(Backgrounds)): BFiles.append( TFile(path + "/uhh2.AnalysisModuleRunner.MC.MC_%s.root" % Backgrounds[i])) #Open File to get DataHist: # DataFile = TFile(path+"/uhh2.AnalysisModuleRunner.Data.DATA.root") #gROOT.ProcessLine( "gErrorIgnoreLevel = 0;") if (includeData == True): #calculate QCDscale with Integrals from the following Histogram: # referenceHistPath = 'tau21sel/N_AK4' # referenceHistPath = 'detaAk8sel/N_pv' # referenceHistPath = 'tau21sel/met_pt_over_sumptAK8_2' QCDscale = float(DataFile.Get(referenceHistPath).Integral()) QCDNorm = 1 for i in range(len(BFiles)): if ('QCD' in BFiles[i].GetName()): QCDNorm = float(BFiles[i].Get(referenceHistPath).Integral()) else: QCDscale -= float(BFiles[i].Get(referenceHistPath).Integral()) QCDscale /= QCDNorm else: QCDscale = 1.0 if (printout): print('using QCDscale:', QCDscale) SHists = [] for i in range(len(channels)): SHists.append(SFiles[i].Get(plotdir + '/' + plot)) BHists = [] for i in range(len(BFiles)): BHists.append(BFiles[i].Get(plotdir + '/' + plot)) if ('QCD' in BFiles[i].GetName()): BHists[-1].Scale(QCDscale) #if(includeData): # DataHist=DataFile.Get(plotdir+'/'+plot) if (binning == 'dijetbinning'): fitbinning = array('d') binwidth = 200 NBins = (14000 / binwidth) - ((1040 / binwidth) + 1) NBins = int(NBins) for i in range(NBins + 1): fitbinning.append(1050 + i * binwidth) for i in range(len(channels)): SHists[i] = SHists[i].Rebin(NBins, "new binning", fitbinning) for i in range(len(Backgrounds)): BHists[i] = BHists[i].Rebin(NBins, "new binning", fitbinning) if (includeData): DataHist = DataHist.Rebin(NBins, "new binning", fitbinning) canv = TCanvas(plottitle, plottitle, canvX, canvY) yplot = 0.7 yratio = 0.3 ymax = 1.0 xmax = 1.0 xmin = 0.0 if (ratio): plotpad = TPad("plotpad", "Plot", xmin, ymax - yplot, xmax, ymax) ratiopad = TPad("ratiopad", "Ratio", xmin, ymax - yplot - yratio, xmax, ymax - yplot) else: plotpad = TPad("plotpad", "Plot", xmin, ymax - yplot - yratio, xmax, ymax) plotpad.SetTopMargin(0.08) plotpad.SetLeftMargin(0.1) plotpad.SetRightMargin(0.05) plotpad.SetTicks() plotpad.Draw() if (ratio): plotpad.SetBottomMargin(0.016) ratiopad.SetTopMargin(0.016) ratiopad.SetBottomMargin(0.35) ratiopad.SetLeftMargin(0.1) ratiopad.SetRightMargin(0.05) ratiopad.SetTicks() ratiopad.Draw() else: plotpad.SetBottomMargin(0.1) if (logY): plotpad.SetLogy() canv.SetLogy() if ('-logX' in xTitle): plotpad.SetLogx() if (ratio): ratiopad.SetLogx() canv.SetLogx() drawOptions = "HE" stack = THStack(plottitle, plottitle) BHist = THStack(plottitle, plottitle) # for i in range(len(Backgrounds)): for i in stackOrder: # BHists[i].SetFillColor(BGColors[i]) BHists[i].SetLineColor(BGColors[i]) BHist.Add(BHists[i], 'Hist') BHist.SetTitle(plottitle) BHistErr = BHists[0].Clone() for i in range(1, len(Backgrounds)): BHistErr.Add(BHists[i]) BHistErr.SetFillStyle(3204) BHistErr.SetFillColor(rt.kGray + 2) BHistErr.SetLineColor(1) BGMax = BHist.GetMaximum() SIGMax = 0 #if(VV): #new # SIGMax=VVsum.GetMaximum() #else: for i in range(len(channels)): tmpmax = SHists[i].GetMaximum() if (tmpmax > SIGMax): SIGMax = tmpmax if (scaleVV): SIGMax = SIGMax * VVScale if (logY): MAX = 0.9 * float(10**(magnitude(max(BGMax, SIGMax)) + 1)) MIN = float(10**(magnitude(max(BGMax, SIGMax)) - 5)) MIN += float(10**(magnitude(MIN))) legendMIN = math.log(max(BGMax, SIGMax)) / math.log(MAX) else: MAX = (1.0 / 0.8) * max(BGMax, SIGMax) legendMIN = 0.7 MIN = 0. legendMIN = (legendMIN * 0.7) + 0.3 - 0.016 legend = TLegend(0.5, 0.75, 0.85, 0.89) legend.SetFillStyle(0) legend.SetTextSize(0.02) legend.SetMargin(0.4) legend.SetNColumns(2) legend.SetColumnSeparation(0.3) if (includeData): DataHist.SetMarkerStyle(8) DataHist.SetLineColor(1) DataHist.SetTitle(plottitle) if VV: for i in range(len(channels)): if (i == 0): VVsum = SHists[i].Clone() else: VVsum.Add(SHists[i]) legentry = 'VVjj' if (scaleVV): VVsum.Scale(VVScale) legentry += ' *%0.f' % VVScale VVsum.SetLineColor(1) VVsum.SetLineStyle(plotstyle[0][1]) VVsum.SetLineWidth(2) legend.AddEntry(VVsum, legentry) else: for i in range(len(channels)): SHists[i].SetLineColor(plotstyle[i][0]) SHists[i].SetLineStyle(plotstyle[i][1]) SHists[i].SetLineWidth(2) legentry = "%sjj" % channelTex[channels[i]] if (scaleVV): SHists[i].Scale(VVScale) legentry += ' *%.2E' % VVScale legend.AddEntry(SHists[i], legentry) for i in stackOrder: legend.AddEntry(BHists[i], BGTeX[i], "f") legend.AddEntry(BHistErr, "stat. Uncertainty", "f") if (includeData): legend.AddEntry(DataHist, "Data", "lep") canv.SetTitle(plottitle) BHistErr.GetYaxis().SetTitle('Events') BHistErr.GetYaxis().SetRangeUser(MIN, MAX) BHistErr.GetYaxis().SetTitleFont(43) BHistErr.GetYaxis().SetTitleSize(yTitleSize) BHistErr.GetYaxis().SetTitleOffset(yTitleOffset) BHistErr.GetYaxis().SetLabelFont(43) BHistErr.GetYaxis().SetLabelSize(yLabelSize) if (ratio): BHistErr.GetXaxis().SetTitleSize(0.0) BHistErr.GetXaxis().SetLabelSize(0.0) else: BHistErr.GetXaxis().SetTitle(xTitle) BHistErr.GetXaxis().SetTitleFont(43) BHistErr.GetXaxis().SetTitleSize(xTitleSize) # BHistErr.GetXaxis().SetTitleOffset(xTitleOffset) BHistErr.GetXaxis().SetTitleOffset(1.2) BHistErr.GetXaxis().SetLabelFont(43) BHistErr.GetXaxis().SetLabelSize(xLabelSize) # BHistErr.GetXaxis().SetTickLength(0.08) # BHistErr.GetXaxis().SetNdivisions(506) if (YRangeUser): BHistErr.GetYaxis().SetRangeUser(Ymin, Ymax) if (XRangeUser): BHistErr.GetXaxis().SetRangeUser(Xmin, Xmax) plotpad.cd() BHistErr.Draw("E2") BHist.Draw("HistSAME") BHistErr.Draw("E2SAME") if (VV): VVsum.Draw("SAME" + drawOptions) elif ('-noSig' not in xTitle): for i in range(len(channels)): SHists[i].Draw("SAME" + drawOptions) if (includeData): DataHist.Draw("APE1SAME") plotpad.RedrawAxis() if (ratio): ratiopad.cd() if (includeData): ratioHist = DataHist.Clone() else: ratioHist = BHistErr.Clone() ratioHist.SetLineColor(rt.kBlack) # ratioHist.Sumw2() ratioHist.SetStats(0) ratioHist.Divide(BHistErr) ratioHist.SetMarkerStyle(21) ratioHist.SetMarkerSize(0.7) #Yaxis ratioHist.GetYaxis().SetRangeUser(0.3, 1.7) ratioHist.GetYaxis().SetTitle("Data/BG") ratioHist.GetYaxis().CenterTitle() ratioHist.GetYaxis().SetTitleFont(43) ratioHist.GetYaxis().SetTitleSize(yTitleSize) ratioHist.GetYaxis().SetTitleOffset(yTitleOffset) ratioHist.GetYaxis().SetLabelFont(43) ratioHist.GetYaxis().SetLabelSize(yLabelSize) ratioHist.GetYaxis().SetNdivisions(506) #Xaxis ratioHist.GetXaxis().SetTitle(xTitle) ratioHist.GetXaxis().SetTitleFont(43) ratioHist.GetXaxis().SetTitleSize(xTitleSize) ratioHist.GetXaxis().SetTitleOffset(xTitleOffset) ratioHist.GetXaxis().SetLabelFont(43) ratioHist.GetXaxis().SetLabelSize(xLabelSize) ratioHist.GetXaxis().SetTickLength(0.08) ratioHist.GetXaxis().SetNdivisions(506) # if(YRangeUser): # ratioHist.GetYaxis().SetRangeUser(Ymin,Ymax) if (XRangeUser): ratioHist.GetXaxis().SetRangeUser(Xmin, Xmax) ratioXMin = Xmin ratioXMax = Xmax else: ratioXMin = ratioHist.GetXaxis().GetXmin() ratioXMax = ratioHist.GetXaxis().GetXmax() ratioHist.Draw("ep") zeropercent = TLine(ratioXMin, 1, ratioXMax, 1) zeropercent.Draw() plus10percent = TLine(ratioXMin, 1.1, ratioXMax, 1.1) plus10percent.SetLineStyle(rt.kDashed) plus10percent.Draw() minus10percent = TLine(ratioXMin, 0.9, ratioXMax, 0.9) minus10percent.SetLineStyle(rt.kDashed) minus10percent.Draw() canv.cd() gPad.RedrawAxis() legend.Draw() latex = TLatex() latex.SetNDC(kTRUE) latex.SetTextSize(20) latex.DrawLatex(0.69, 0.953, "%.2f fb^{-1} (13 TeV)" % lumi) latex.DrawLatex(0.1, 0.953, "private work") lastcut = 'nocuts' for cut in cutnames: if cut in plotdir: lastcut = cut if (not (lastcut == 'nocuts') and cutname): # latex.SetTextSize(0.03) latex.SetTextSize(15) for l in range(cutnames.index(lastcut) + 1): latex.DrawLatex(0.12, 0.8 - l * 0.04, cuts[cutnames[l]]) canv.Update() canv.Print(outputPath + '/%s_%s.pdf' % (plotdir, plot)) #prevents memory leak in Canvas Creation/Deletion #see: https://root.cern.ch/root/roottalk/roottalk04/2484.html gSystem.ProcessEvents() if (ratio): del ratiopad del plotpad, canv # gc.collect() return 'done!'
class Plot_Multi_TH1: def __init__(self,filepath,filename,tree,list_variable,weight,list_cut,list_legend,list_color,name,bins,xmin,xmax,title,xlabel,ylabel,option='hist',logx=False,logy=False,legend_pos=[0.5,0.5,0.9,0.85],stack=False,norm=False): self.filepath = filepath self.filename = filename self.tree = tree self.weight = weight self.name = name self.bins = bins self.xmin = xmin self.xmax = xmax self.title = title self.xlabel = xlabel self.ylabel = ylabel self.legend_pos = legend_pos self.logx = logx self.logy = logy self.option = option self.stack = stack self.norm = norm if not isinstance(list_cut,list): list_cut = [list_cut] if not isinstance(list_variable,list): list_variable = [list_variable] if not isinstance(list_legend,list): list_legend = [list_legend] if len(list_variable) == 1 and len(list_cut) > 1: logging.debug('\tOnly one variable but several cuts') self.list_variable = list_variable*len(list_cut) self.list_cut = list_cut elif len(list_variable) > 1 and len(list_cut) == 1: logging.debug('\tOnly one cut but several variables') self.list_cut = list_cut*len(list_variable) self.list_variable = list_variable elif len(list_variable) == 1 and len(list_cut) == 1: logging.warning('\tWhy do you even need to stack ?') elif len(list_variable) != len(list_cut): raise RuntimeError('Inconsistent number of variables and cuts') print (len(list_variable)) print (len(list_cut)) else: self.list_variable = list_variable self.list_cut = list_cut if len(list_legend) != max(len(list_variable),len(list_cut)): raise RuntimeError('Inconsistent number of legends compared to variables and cuts') else: self.list_legend = list_legend if len(list_color) != len(list_legend): raise RuntimeError('Inconsistent number of colors compared to legends') else: self.list_color = list_color for i in range(len(self.list_color)): if isinstance(self.list_color[i],str): self.list_color[i] = ROOT.TColor.GetColor(self.list_color[i]) def MakeHisto(self): self.list_obj = [] for i in range(0,len(self.list_variable)): instance = Plot_TH1(filepath = self.filepath, filename = self.filename, tree = self.tree, variable = self.list_variable[i], weight = self.weight, cut = self.list_cut[i], name = self.name, bins = self.bins, xmin = self.xmin, xmax = self.xmax, title = self.title, xlabel = self.xlabel, ylabel = self.ylabel, logx = self.logx, logy = self.logy) instance.MakeHisto() self.list_obj.append(copy.deepcopy(instance.histo)) 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
LepBDTMCTTbar_list[i].SetFillColor(kMagenta + 3) LepBDTMCTTbar_list[i].SetLineColor(kBlack) hs.Add(LepBDTMCTTbar_list[i]) #MC DY hist LepBDTMCDY_list[i].Scale(norm) # MC normalization LepBDTMCDY_list[i].SetFillColor(kMagenta - 6) LepBDTMCDY_list[i].SetLineColor(kBlack) hs.Add(LepBDTMCDY_list[i]) #upper plot pad pad1 = TPad("pad1", "pad1", 0, 0.3, 1, 1.0) pad1.Draw() pad1.cd() hs.SetMaximum(1.6 * max(hs.GetMaximum(), LepBDTDATA_list[i].GetMaximum())) LepBDTDATA_list[i].SetMaximum( 1.6 * max(hs.GetMaximum(), LepBDTDATA_list[i].GetMaximum())) hs.SetMinimum(10) #EF for ele BDT hs.Draw("histo") LepBDTDATA_list[i].Draw("sameEP") hs.SetTitle("") hs.GetXaxis().SetTitle("BDT score") hs.GetXaxis().SetRangeUser(0.75, 1) #EF for ele BDT hs.GetXaxis().SetLabelFont(43) hs.GetXaxis().SetLabelSize(15) hs.GetYaxis().SetTitleSize(20) hs.GetYaxis().SetTitleFont(43) hs.GetYaxis().SetTitleOffset(1.8)
def make_ratioplot(name, ttbar_file=0, qcd_file=0, signal_files=[], histo=0, rebin=1, minx=0, maxx=0, miny=0, maxy=0, logy=False, xtitle='', ytitle='', textsizefactor=1, signal_legend=[], outfile=0, signal_colors=[], signal_zoom=1, qcd_zoom=1, ttbar_zoom=1, ttbar_legend='t#bar{t}', qcd_legend='QCD from MC', dosys=False, docms=True, legendtitle=''): ###canvas setting up canvas = 0 canvas = TCanvas(name, '', 0, 0, 600, 600) canvas.SetLeftMargin(0.15) canvas.SetRightMargin(0.05) canvas.SetTopMargin(0.10) canvas.SetBottomMargin(0.10) charsize = 0.04 offset = 1.9 ###latex label latex = 0 latex = TLatex(0.6, 0.7, '13 TeV, 2.69 fb^{-1}') latex.SetTextSize(charsize) latex.SetNDC(1) latex.SetTextFont(42) ###legend setting up #legend=TLegend(0.0,0.75,0.99,1.04) legend = TLegend(0.4, 0.6, 0.94, 0.95) legend.SetNColumns(2) legend.SetHeader('') legend.SetFillStyle(0) legend.SetBorderSize(0) ###mc stack stack = THStack(name + '_stack', '') qcd_histo = qcd_file.Get(histo).Clone(name + '_make_plot') qcd_histo.Rebin(rebin) ttbar_histo = ttbar_file.Get(histo).Clone() ttbar_histo.Rebin(rebin) ttbar_histo.SetFillColor(kRed - 9) ttbar_histo.SetLineColor(kRed - 9) ttbar_histo.SetMarkerColor(kRed - 9) if ttbar_zoom != 1: ttbar_histo.Scale(ttbar_zoom) legend.AddEntry(ttbar_histo, ttbar_legend, 'f') qcd_histo.SetFillColor(kOrange - 5) qcd_histo.SetLineColor(kOrange - 5) qcd_histo.SetMarkerColor(kOrange - 5) if qcd_zoom != 1: qcd_histo.Scale(qcd_zoom) legend.AddEntry(qcd_histo, qcd_legend, 'f') sum_mc = qcd_histo.Clone(histo + 'tmp') sum_mc.Add(ttbar_histo) stack.Add(ttbar_histo) stack.Add(qcd_histo) sum_mc.SetLineColor(kBlack) sum_mc.SetFillStyle(0) err = TGraphAsymmErrors(sum_mc) legend.AddEntry(err, 'Total uncertainty', 'f') if legendtitle == '': legend.AddEntry(0, "", '') legend.AddEntry(0, "g_{RS} #rightarrow t#bar{t} (2pb)", '') else: legend.AddEntry(0, "", '') legend.AddEntry(0, legendtitle, '') ###signal setting up signal_histos = [] colors = [ kBlack, kRed, kOrange, kBlue, kGreen + 3, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60 ] styles = [ 1, 3, 5, 7, 7, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ] if signal_colors != []: colors = signal_colors for i in range(len(signal_files)): signal_histos.append(signal_files[i].Get(histo).Clone()) signal_histos[i].SetLineWidth(3) signal_histos[i].SetLineStyle(styles[i]) signal_histos[i].SetLineColor(colors[i]) signal_histos[i].SetMarkerColor(colors[i]) signal_histos[i].Rebin(rebin) if signal_zoom != 1: signal_histos[i].Scale(signal_zoom) legend.AddEntry(signal_histos[i], signal_legend[i], 'l') ###mc shape line ttbar_line = 0 ttbar_line = ttbar_histo.Clone() ttbar_line.SetLineColor(kBlack) ttbar_line.SetFillStyle(0) ###mc errors if dosys: sys_diff_qcd = [] sys_diff_ttbar = [] for imtt in range(1, ttbar_histo.GetNbinsX() + 1): sys_diff_qcd.append([]) sys_diff_ttbar.append([]) #adding stat uncertainties <--removed # for imtt in range(1,ttbar_histo.GetNbinsX()+1): # sys_diff_ttbar[imtt-1].append(ttbar_histo.GetBinError(imtt)) # sys_diff_ttbar[imtt-1].append(-ttbar_histo.GetBinError(imtt)) # sys_diff_qcd[imtt-1].append(qcd_histo.GetBinError(imtt)) # sys_diff_qcd[imtt-1].append(-qcd_histo.GetBinError(imtt)) #adding flat uncertainties for imtt in range(1, ttbar_histo.GetNbinsX() + 1): #ttbar for i in [ 2.4, #pdf 10.0, #mu 3.0, #xsec 6.0, #toppt 1.0, #lumi 3.5, #jec 3.0, #jer 10.0, #btag #3.0,#trig 10.0, #toptag 3.0 ]: #pileup sys_diff_ttbar[imtt - 1].append( i / 100.0 * ttbar_histo.GetBinContent(imtt)) sys_diff_ttbar[imtt - 1].append( -i / 100.0 * ttbar_histo.GetBinContent(imtt)) closureunc = 5.0 # if '1b' in histo: # closureunc=5.0 # elif '2b' in histo: # closureunc=10.0 for i in [ 2.0, #modmass closureunc ]: #closure sys_diff_qcd[imtt - 1].append(i / 100.0 * qcd_histo.GetBinContent(imtt)) sys_diff_qcd[imtt - 1].append(-i / 100.0 * qcd_histo.GetBinContent(imtt)) # #3% trigger # sys_diff_ttbar[imtt-1].append(0.03*ttbar_histo.GetBinContent(imtt)) # sys_diff_ttbar[imtt-1].append(-0.03*ttbar_histo.GetBinContent(imtt)) # #2.7% lumi # sys_diff_ttbar[imtt-1].append(0.023*ttbar_histo.GetBinContent(imtt)) # sys_diff_ttbar[imtt-1].append(-0.023*ttbar_histo.GetBinContent(imtt)) # #15% ttbar # #sys_diff_ttbar[imtt-1].append(0.15*ttbar_histo.GetBinContent(imtt)) # #sys_diff_ttbar[imtt-1].append(-0.15*ttbar_histo.GetBinContent(imtt)) # #2.8% QCD # sys_diff_qcd[imtt-1].append(0.028*qcd_histo.GetBinContent(imtt)) # sys_diff_qcd[imtt-1].append(-0.028*qcd_histo.GetBinContent(imtt)) #combining uncertainties sys_tot_ttbar = [] sys_tot_qcd = [] sys_tot = [] sys_global_ttbar = [0.0, 0.0] sys_global_qcd = [0.0, 0.0] nevt_global = [0.0, 0.0, 0.0] for imtt in range(1, ttbar_histo.GetNbinsX() + 1): uperr_qcd = 0 downerr_qcd = 0 uperr_ttbar = 0 downerr_ttbar = 0 for error in sys_diff_ttbar[imtt - 1]: if error < 0: downerr_ttbar = downerr_ttbar + error * error else: uperr_ttbar = uperr_ttbar + error * error for error in sys_diff_qcd[imtt - 1]: if error < 0: downerr_qcd = downerr_qcd + error * error else: uperr_qcd = uperr_qcd + error * error sys_tot_ttbar.append( [math.sqrt(downerr_ttbar), math.sqrt(uperr_ttbar)]) sys_tot_qcd.append([math.sqrt(downerr_qcd), math.sqrt(uperr_qcd)]) sys_tot.append([ math.sqrt(downerr_qcd + downerr_ttbar), math.sqrt(uperr_qcd + uperr_ttbar) ]) sys_global_qcd[0] = sys_global_qcd[0] + downerr_qcd sys_global_qcd[1] = sys_global_qcd[1] + uperr_qcd sys_global_ttbar[0] = sys_global_ttbar[0] + downerr_ttbar sys_global_ttbar[1] = sys_global_ttbar[1] + uperr_ttbar # nevt_global[0]=nevt_global[0]+data_histo.GetBinContent(imtt) nevt_global[1] = nevt_global[1] + qcd_histo.GetBinContent(imtt) nevt_global[2] = nevt_global[2] + ttbar_histo.GetBinContent(imtt) #print 'ttbar+qcd',math.sqrt(uperr_qcd+uperr_ttbar),math.sqrt(downerr_qcd+downerr_ttbar) #print 'qcd',math.sqrt(uperr_qcd),math.sqrt(downerr_qcd) #print 'ttbar',math.sqrt(uperr_ttbar),math.sqrt(downerr_ttbar) err.SetPointEYhigh(imtt - 1, math.sqrt(uperr_qcd + uperr_ttbar)) err.SetPointEYlow(imtt - 1, math.sqrt(downerr_qcd + downerr_ttbar)) sys_global = [0.0, 0.0] sys_global[0] = math.sqrt(sys_global_qcd[0] + sys_global_ttbar[0]) sys_global[1] = math.sqrt(sys_global_qcd[1] + sys_global_ttbar[1]) sys_global_qcd[0] = math.sqrt(sys_global_qcd[0]) sys_global_qcd[1] = math.sqrt(sys_global_qcd[1]) sys_global_ttbar[0] = math.sqrt(sys_global_ttbar[0]) sys_global_ttbar[1] = math.sqrt(sys_global_ttbar[1]) # print name # print "\hline" # print "Multijet QCD & $%.0f^{+%.0f}_{-%.0f}$ \\\\" % (nevt_global[1],sys_global_qcd[1],sys_global_qcd[0]) # print "SM ttbar & $%.0f^{+%.0f}_{-%.0f}$ \\\\" % (nevt_global[2],sys_global_ttbar[1],sys_global_ttbar[0]) # print "\hline" # print "Total background & $%.0f^{+%.0f}_{-%.0f}$ \\\\" % (nevt_global[1]+nevt_global[2],sys_global[1],sys_global[0]) # print 'DATA & %.0f' %nevt_global[0] err.SetFillStyle(3145) err.SetFillColor(kGray + 1) ###drawing top canvas.cd() stack.Draw('hist') stack.GetXaxis().SetTitle(ttbar_histo.GetXaxis().GetTitle()) stack.GetYaxis().SetTitle(ttbar_histo.GetYaxis().GetTitle()) stack.GetXaxis().SetLabelSize(charsize) stack.GetXaxis().SetTitleSize(charsize) stack.GetYaxis().SetLabelSize(charsize) stack.GetYaxis().SetTitleSize(charsize) stack.GetYaxis().SetTitleOffset(offset) if minx != 0 or maxx != 0: stack.GetXaxis().SetRangeUser(minx, maxx) #else: # stack.GetXaxis().SetRangeUser(0,4000) if miny != 0 or maxy != 0: stack.SetMaximum(maxy) stack.SetMinimum(miny) else: if logy: stack.SetMaximum(stack.GetMaximum() * 10) stack.SetMinimum(0.2) else: stack.SetMaximum(stack.GetMaximum() * 2.0) stack.SetMinimum(0.001) err.Draw('2') sum_mc.Draw('samehist') if ttbar_file != 0: ttbar_line.Draw('samehist') for i in signal_histos: i.Draw('samehist') if logy: canvas.SetLogy() legend.Draw() latex2text = '' if 'ldy_0b' in name: latex2text = '#Deltay < 1; 0 b tag' elif 'ldy_1b' in name: latex2text = '#Deltay < 1; 1 b tag' elif 'ldy_2b' in name: latex2text = '#Deltay < 1; 2 b tag' elif 'hdy_0b' in name: latex2text = '#Deltay > 1; 0 b tag' elif 'hdy_1b' in name: latex2text = '#Deltay > 1; 1 b tag' elif 'hdy_2b' in name: latex2text = '#Deltay > 1; 2 b tag' latex2 = TLatex(0.19, 0.7, latex2text) latex2.SetTextSize(0.03) latex2.SetNDC(1) latex2.SetTextFont(42) latex2.Draw() if docms: if '3000' in name: CMS_lumi.CMS_lumi(canvas, 3, 11) elif '1000' in name: CMS_lumi.CMS_lumi(canvas, 2, 11) elif '300' in name: CMS_lumi.CMS_lumi(canvas, 1, 11) elif '36' in name: CMS_lumi.CMS_lumi(canvas, 0, 11) ###saving canvas.SaveAs('pdf/' + name + '.pdf') if outfile != 0: canvas.Write()