def plot_hist_diff(histlist1, histlist2, labellist, log, overflow, filename, options): canv = TCanvas("c1", "c1", 800, 600) canv.SetTopMargin(10) canv.SetRightMargin(100) if log: gPad.SetLogy() histstack = THStack("stack", histlist1[0].GetTitle()) legend = TLegend(0.76, 0.88 - 0.08 * len(histlist1), 0.91, 0.88, '', 'NDC') colorlist = [4, 8, 2, 6, 1] if options: options += " NOSTACK" else: options = "NOSTACK" maximum = 0 for i in range(len(histlist1)): entries = histlist1[i].GetEntries() bad_entries = histlist2[i].GetEntries() histlist1[i].SetLineColorAlpha(colorlist[i], 0.65) histlist1[i].SetLineWidth(3) if entries: histlist1[i].Scale(1. / entries) if bad_entries: histlist2[i].Scale(1. / bad_entries) histlist1[i].Add(histlist2[i], -1.) nbins = histlist1[i].GetNbinsX() legend.AddEntry( histlist1[i], "#splitline{" + labellist[i] + "}{#splitline{%d total jets}{%d bad jets}}" % (entries, bad_entries), "l") if overflow: histlist1[i].SetBinContent( nbins, histlist1[i].GetBinContent(nbins) + histlist1[i].GetBinContent(nbins + 1)) #overflow histlist1[i].SetBinContent( 1, histlist1[i].GetBinContent(0) + histlist1[i].GetBinContent(1)) #underflow if histlist1[i].GetMaximum() > maximum: maximum = histlist1[i].GetMaximum() histstack.Add(histlist1[i]) #if i == 0: histlist[i].Draw(options) #else: histlist[i].Draw(same+options) histstack.SetMaximum(maximum * 1.4) histstack.Draw(options) histstack.GetXaxis().SetTitle(histlist1[0].GetXaxis().GetTitle()) histstack.GetYaxis().SetTitle(histlist1[0].GetYaxis().GetTitle()) legend.SetTextSize(0.02) legend.SetFillStyle(0) legend.SetBorderSize(0) legend.Draw("SAME") canv.SaveAs(filename) if log: gPad.Clear() canv.Clear() del canv
def DrawStackHistograms(histograms, outname, blind=True, verbose=False): #hists_sorted = sorted(histograms, key=lambda h: h.Integral()) hs = THStack("h_stack", "") h_obs = None l = TLegend(0.77, 0.60, 0.90, 0.87) for hist in histograms: hname = hist.GetName() if "data_obs" in hname: if not blind: h_obs = hist SetHistogramStyle(h_obs, "Observed") l.AddEntry(h_obs, "Observed", "p") else: SetHistogramStyle(hist) label = GetLabelName(hist) hs.Add(hist) l.AddEntry(hist, label, "f") h_est = hs.GetStack().Last().Clone() if verbose: est_err = Double(0.) nbins_est = h_est.GetNbinsX() est_yields = h_est.IntegralAndError(1, nbins_est, est_err) print "predicted yields :", est_yields, "+/-", est_err if not blind: print "observed yields :", h_obs.Integral() # draw # SetCMSStyle() TODO canvas = TCanvas() gPad.SetLogy() #ymax_hs = hs.GetMaximum() #ymax = ymax_hs if h_obs is None else max(ymax_hs, h_obs.GetMaximum()) ymax = 10000 ymin = 0.1 hs.SetMaximum(ymax) hs.SetMinimum(ymin) hs.Draw("HIST") l.Draw("same") if not blind: h_obs.Draw("same") canvas.SaveAs(outname)
def plot_bar(histlist, axislabels, labels, norm, log, filename, options): canv = TCanvas("c1", "c1", 800, 600) canv.SetTopMargin(10) canv.SetRightMargin(100) if log: gPad.SetLogy() histstack = THStack("stack", histlist[0].GetTitle()) if labels: legend = TLegend(0.76, 0.88 - 0.08 * len(histlist), 0.91, 0.88, '', 'NDC') colorlist = [4, 8, 2, 6, 1] if options: options += " NOSTACK" else: options = "NOSTACK" maximum = 0 for i in range(len(histlist)): histlist[i].SetLineColorAlpha(colorlist[i], 0.65) histlist[i].SetLineWidth(3) entries = histlist[i].GetEntries() if entries and norm: histlist[i].Scale(1. / entries) if histlist[i].GetMaximum() > maximum: maximum = histlist[i].GetMaximum() if labels: legend.AddEntry(histlist[i], labels[i], "l") histstack.Add(histlist[i]) histstack.SetMaximum(maximum * 1.4) histstack.Draw(options) histstack.GetXaxis().SetTitle(histlist[0].GetXaxis().GetTitle()) histstack.GetYaxis().SetTitle(histlist[0].GetYaxis().GetTitle()) histstack.GetXaxis().SetNdivisions(len(axislabels)) histstack.GetXaxis().CenterLabels(True) for i, label in enumerate(axislabels): histstack.GetXaxis().ChangeLabel(i + 1, -1, -1, -1, -1, -1, str(label)) if labels: legend.SetTextSize(0.02) legend.SetFillStyle(0) legend.SetBorderSize(0) legend.Draw("SAME") canv.SaveAs(filename) if log: gPad.Clear() canv.Clear() del canv
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
def createPlots_(plot, geometry): """Cumulative material budget from simulation. Internal function that will produce a cumulative profile of the material budget inferred from the simulation starting from the single detectors that compose the tracker. It will iterate over all existing detectors contained in the DETECTORS dictionary. The function will automatically skip non-existent detectors. """ IBs = ["InnerServices", "Phase2PixelBarrel", "TIB", "TIDF", "TIDB"] theDirname = "Figures" if plot not in plots.keys(): print("Error: chosen plot name not known %s" % plot) return hist_X0_detectors = OrderedDict() hist_X0_IB = None hist_X0_elements = OrderedDict() for subDetector,color in six.iteritems(DETECTORS): h = get1DHisto_(subDetector,plots[plot].plotNumber,geometry) if not h: print('Warning: Skipping %s'%subDetector) continue hist_X0_detectors[subDetector] = h # Merge together the "inner barrel detectors". if subDetector in IBs: hist_X0_IB = assignOrAddIfExists_( hist_X0_IB, hist_X0_detectors[subDetector] ) # category profiles for label, [num, color, leg] in six.iteritems(hist_label_to_num): if label is 'SUM': continue hist_label = get1DHisto_(subDetector, num + plots[plot].plotNumber, geometry) hist_X0_elements[label] = assignOrAddIfExists_( hist_X0_elements.setdefault(label,None), hist_label, ) hist_X0_elements[label].SetFillColor(color) cumulative_matbdg = TH1D("CumulativeSimulMatBdg", "CumulativeSimulMatBdg", hist_X0_IB.GetNbinsX(), hist_X0_IB.GetXaxis().GetXmin(), hist_X0_IB.GetXaxis().GetXmax()) cumulative_matbdg.SetDirectory(0) # colors for det, color in six.iteritems(DETECTORS): setColorIfExists_(hist_X0_detectors, det, color) # First Plot: BeamPipe + Pixel + TIB/TID + TOB + TEC + Outside # stack stackTitle_SubDetectors = "Tracker Material Budget;%s;%s" % ( plots[plot].abscissa,plots[plot].ordinate) stack_X0_SubDetectors = THStack("stack_X0",stackTitle_SubDetectors) for det, histo in six.iteritems(hist_X0_detectors): stack_X0_SubDetectors.Add(histo) cumulative_matbdg.Add(histo, 1) # canvas can_SubDetectors = TCanvas("can_SubDetectors","can_SubDetectors",800,800) can_SubDetectors.Range(0,0,25,25) can_SubDetectors.SetFillColor(kWhite) # Draw stack_X0_SubDetectors.SetMinimum(plots[plot].ymin) stack_X0_SubDetectors.SetMaximum(plots[plot].ymax) stack_X0_SubDetectors.Draw("HIST") stack_X0_SubDetectors.GetXaxis().SetLimits(plots[plot].xmin, plots[plot].xmax) # Legenda theLegend_SubDetectors = TLegend(0.180,0.8,0.98,0.92) theLegend_SubDetectors.SetNColumns(3) theLegend_SubDetectors.SetFillColor(0) theLegend_SubDetectors.SetFillStyle(0) theLegend_SubDetectors.SetBorderSize(0) for det, histo in six.iteritems(hist_X0_detectors): theLegend_SubDetectors.AddEntry(histo, det, "f") theLegend_SubDetectors.Draw() # text text_SubDetectors = TPaveText(0.180,0.727,0.402,0.787,"NDC") text_SubDetectors.SetFillColor(0) text_SubDetectors.SetBorderSize(0) text_SubDetectors.AddText("CMS Simulation") text_SubDetectors.SetTextAlign(11) text_SubDetectors.Draw() # Store can_SubDetectors.Update() if not checkFile_(theDirname): os.mkdir(theDirname) can_SubDetectors.SaveAs("%s/Tracker_SubDetectors_%s.pdf" % (theDirname, plot)) can_SubDetectors.SaveAs("%s/Tracker_SubDetectors_%s.root" % (theDirname, plot)) # Second Plot: BeamPipe + SEN + ELE + CAB + COL + SUP + OTH/AIR + # Outside stack stackTitle_Materials = "Tracker Material Budget;%s;%s" % (plots[plot].abscissa, plots[plot].ordinate) stack_X0_Materials = THStack("stack_X0",stackTitle_Materials) stack_X0_Materials.Add(hist_X0_detectors["BeamPipe"]) for label, [num, color, leg] in six.iteritems(hist_label_to_num): if label is 'SUM': continue stack_X0_Materials.Add(hist_X0_elements[label]) # canvas can_Materials = TCanvas("can_Materials","can_Materials",800,800) can_Materials.Range(0,0,25,25) can_Materials.SetFillColor(kWhite) # Draw stack_X0_Materials.SetMinimum(plots[plot].ymin) stack_X0_Materials.SetMaximum(plots[plot].ymax) stack_X0_Materials.Draw("HIST") stack_X0_Materials.GetXaxis().SetLimits(plots[plot].xmin, plots[plot].xmax) # Legenda theLegend_Materials = TLegend(0.180,0.8,0.95,0.92) theLegend_Materials.SetNColumns(3) theLegend_Materials.SetFillColor(0) theLegend_Materials.SetBorderSize(0) theLegend_Materials.AddEntry(hist_X0_detectors["BeamPipe"], "Beam Pipe", "f") for label, [num, color, leg] in six.iteritems(hist_label_to_num): if label is 'SUM': continue theLegend_Materials.AddEntry(hist_X0_elements[label], leg, "f") theLegend_Materials.Draw() # text text_Materials = TPaveText(0.180,0.727,0.402,0.787,"NDC") text_Materials.SetFillColor(0) text_Materials.SetBorderSize(0) text_Materials.AddText("CMS Simulation") text_Materials.SetTextAlign(11) text_Materials.Draw() # Store can_Materials.Update() can_Materials.SaveAs("%s/Tracker_Materials_%s.pdf" % (theDirname, plot)) can_Materials.SaveAs("%s/Tracker_Materials_%s.root" % (theDirname, plot)) return cumulative_matbdg
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))
if args.single: drawResoLin(histLin, legTitle, "#LT E_{pred}#GT/E_{true}", "lin_stage_" + str(st), False, 0.95, 1.05, "pe") else: drawResoLin(histLin, legTitle, "#LT E_{pred}#GT/E_{true}", "lin_stage_" + str(st), False, 0.95, 1.05, False) tfile.Close() r.gROOT.SetBatch(False) can = TCanvas("can", "") multi.Draw("nostack") multi.GetXaxis().SetTitle("E [GeV]") multi.GetYaxis().SetTitle("#sigma_{E_{pred}}/#LT E_{pred}#GT") multi.GetXaxis().SetRangeUser(0, 102) multi.SetMaximum(0.1) multi.Draw("nostack") leg.Draw() legT.Draw() can.Print("plots/allStages_reso.pdf") canLin = TCanvas("canLin", "") multiLin.Draw("nostack") multiLin.GetXaxis().SetTitle("E [GeV]") multiLin.GetYaxis().SetTitle("#LT E_{pred}#GT/E_{true}") multiLin.GetXaxis().SetRangeUser(0, 102) multiLin.SetMaximum(1.15) multiLin.SetMinimum(0.95) multiLin.Draw("nostack") leg.Draw() legT.Draw()
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 Draw_1D_Comp(rootfile_name, var, min, max, WP_list, leg, isTail=False): gStyle.SetErrorX(0.5) ## The TStack is created with min and max set stack = THStack("stack", var.name) stack.SetMinimum(min) stack.SetMaximum(max) for wp in WP_list: ## Loading the graph using its name and file location graph_name = "{}_{}".format(var.name, wp.name) if isTail: graph_name += "_cumulative" graph = GetGraphFromFile(rootfile_name, graph_name) if graph == -1: continue ## Setting the colors specific to the working point graph.SetLineColor(wp.colour) graph.SetMarkerColor(wp.colour) graph.SetMarkerStyle((wp.marker)) leg.AddEntry(graph, wp.name, "p") width = graph.GetBinWidth(0) ## We check if the legend requires values for statistics if leg.GetNColumns() == 2: ## Calculate the MEAN and RMSE and add to the legend mean = graph.GetMean() stdev = graph.GetStdDev() rms = np.sqrt(mean * mean + stdev * stdev) ## Adding the legend entry # leg.AddEntry( 0, "{:5.2f}".format(mean), "") leg.AddEntry(0, "{:5.2f}".format(rms), "") ## Adding the object to the stack stack.Add(graph) del graph ## Checking to see if any graphs were found for this variable if stack.GetNhists() == 0: print("\n\n\nNo graphs found for working point {}\n\n\n".format( wp.name)) return -1 ## Drawing the stack on the currrent canvas stack.Draw("nostack EP") leg.Draw() ## Setting axis labels if isTail: stack.GetXaxis().SetTitle(var.x_label + " threshold " + var.units) stack.GetYaxis().SetTitle("#it{f}_{tail}") else: stack_y_label = "Events per {:.0f} GeV".format( width) if width > 1 else "Events per GeV" stack.GetXaxis().SetTitle(var.x_label + " " + var.units) stack.GetYaxis().SetTitle(stack_y_label) ## Moving axis tick marks stack.GetYaxis().SetMaxDigits(3) stack.GetXaxis().SetLabelOffset(0.017) return stack
def plot_hist(histlist, labellist, norm, log, overflow, filename, options, scaling=[]): canv = TCanvas("c1", "c1", 800, 600) canv.SetTopMargin(10) canv.SetRightMargin(100) if log: gPad.SetLogy() histstack = THStack("stack", histlist[0].GetTitle()) legend = TLegend(0.76, 0.88 - 0.08 * len(histlist), 0.91, 0.88, '', 'NDC') colorlist = [4, 8, 2, 6, 1] if len(scaling) > 1 and scaling[1] == 0: scaling = [] if options: options += " NOSTACK" else: options = "NOSTACK" maximum = 0 for i in range(len(histlist)): entries = histlist[i].GetEntries() mean = histlist[i].GetMean() histlist[i].SetLineColorAlpha(colorlist[i], 0.65) histlist[i].SetLineWidth(3) nbins = histlist[i].GetNbinsX() legend.AddEntry( histlist[i], "#splitline{" + labellist[i] + "}{#splitline{%d entries}{mean=%.2f}}" % (entries, mean), "l") if overflow: histlist[i].SetBinContent( nbins, histlist[i].GetBinContent(nbins) + histlist[i].GetBinContent(nbins + 1)) #overflow histlist[i].SetBinContent(1, histlist[i].GetBinContent(0) + histlist[i].GetBinContent(1)) #underflow if entries and norm: histlist[i].Scale(1. / entries) if histlist[i].GetMaximum() > maximum: maximum = histlist[i].GetMaximum() histstack.Add(histlist[i]) histstack.SetMaximum(maximum * 1.4) histstack.Draw(options) histstack.GetXaxis().SetTitle(histlist[0].GetXaxis().GetTitle()) histstack.GetYaxis().SetTitle(histlist[0].GetYaxis().GetTitle()) xlimit = [ histlist[0].GetBinLowEdge(1), histlist[0].GetBinLowEdge(histlist[0].GetNbinsX()) + histlist[0].GetBinWidth(histlist[0].GetNbinsX()) ] if len(scaling) != 0: top_axis = TGaxis(xlimit[0], maximum * 1.4, xlimit[1], maximum * 1.4, (xlimit[0] - scaling[0]) / scaling[1], (xlimit[1] - scaling[0]) / scaling[1], 510, "-") top_axis.SetTitle("normalized scale") top_axis.SetTickSize(0) top_axis.Draw("SAME") legend.SetTextSize(0.02) legend.SetFillStyle(0) legend.SetBorderSize(0) legend.Draw("SAME") canv.SaveAs(filename) if log: gPad.Clear() canv.Clear() del canv
def plotFractionsOfBxId(self): ##BX right plotting pt canvasBxRightPt = TCanvas("cBxRightPt","cBxRightPt",1200,1200) canvasBxRightPt.cd().SetLeftMargin(0.15) hBxRightPt = self.fileHandler.getHistogram('BxRightGen_Pt').Clone() setPlotStyle() hBxRightPt.Rebin(50) hBxRightPt.GetXaxis().SetRangeUser(0,200) hBxRightPt.GetYaxis().SetTitle("normalized Entries / 5 GeV") hBxRightPt.GetXaxis().SetTitle("p_{T} Gen") hBxRightPt.GetYaxis().SetTitleOffset(2) hBxRightPt.SetTitle("Events with right BX ID vs. p_{T}") hBxRightPt.SetStats(0) hBxRightPt.SetLineWidth(2) hBxRightPt.Scale(1/hBxRightPt.Integral()) hBxRightPt.Draw() label = getLabelCmsPrivateSimulation() label.Draw() self.storeCanvas(canvasBxRightPt,"bxRightPt") ##BX wrong plotting pt canvasBxWrongPt = TCanvas("cBxWrongPt","cBxWrongPt",1200,1200) canvasBxWrongPt.cd().SetLeftMargin(0.15) hBxWrongPt = self.fileHandler.getHistogram('BxWrongGen_Pt').Clone() setPlotStyle() hBxWrongPt.Rebin(50) hBxWrongPt.GetXaxis().SetRangeUser(0,200) hBxWrongPt.GetYaxis().SetTitle("normalized Entries / 5 GeV") hBxWrongPt.GetXaxis().SetTitle("p_{T} Gen") hBxWrongPt.GetYaxis().SetTitleOffset(2) hBxWrongPt.SetTitle("Events with wrong BX ID vs. p_{T}") hBxWrongPt.SetStats(0) hBxWrongPt.SetLineWidth(2) hBxWrongPt.Scale(1/hBxWrongPt.Integral()) hBxWrongPt.DrawCopy() label = getLabelCmsPrivateSimulation() label.Draw() self.storeCanvas(canvasBxWrongPt,"bxWrongPt") #Plot the histogram stack canvasStack = TCanvas("cStacked","cStacked",1200,1200) canvasStack.cd().SetLeftMargin(0.15) hWrong = self.fileHandler.getHistogram('BxWrongGen_Pt') hRight = self.fileHandler.getHistogram('BxRightGen_Pt') hRightFraction = TH1D('hRightFraction','',100,0,500) hWrongFraction = TH1D('hWrongFraction','',100,0,500) #hWrong.Rebin(50) #hRight.Rebin(50) #Fill the histograms with the bin wise fractions for i in range(0,hRight.GetNbinsX()): nRight = hRight.GetBinContent(i+1) nWrong = hWrong.GetBinContent(i+1) if(nRight + nWrong == 0): continue hRightFraction.SetBinContent(i+1,nRight/(nRight+nWrong)) hWrongFraction.SetBinContent(i+1,nWrong/(nRight+nWrong)) #Create the stack stack = THStack("hstack","Fractions of events for BX ID correct and wrong") nRight = hRight.Integral() nWrong = hWrong.Integral() hRightFraction.SetLineColor(colorRwthDarkBlue) hRightFraction.SetFillColor(colorRwthDarkBlue) hRightFraction.SetFillStyle(3002) hWrongFraction.SetLineColor(colorRwthMagenta) hWrongFraction.SetFillColor(colorRwthMagenta) hWrongFraction.SetFillStyle(3002) stack.Add(hRightFraction) stack.Add(hWrongFraction) stack.Draw() stack.GetXaxis().SetRangeUser(0.5,201) stack.GetYaxis().SetTitle('rel. fraction / 5 GeV') stack.GetYaxis().SetTitleOffset(2) stack.GetXaxis().SetTitle('p_{T} Gen') stack.SetMinimum(0.9) stack.SetMaximum(1) legend = TLegend(0.6,0.75,0.9,0.9) legend.AddEntry(hRightFraction,"BX ID right","f") legend.AddEntry(hWrongFraction,"BX ID wrong","f") legend.Draw() label = getLabelCmsPrivateSimulation() label.Draw() canvasStack.Update() self.storeCanvas(canvasStack,"bxStacked")
def main(): from optparse import OptionParser parser = OptionParser() parser.add_option("-i", "--inputfile", dest="inputfile") parser.add_option("-N", "--multiplicity", dest="N", type="int", default=3) parser.add_option("-x", "--exclusive", action="store_true",\ dest="isExclusive", default=False) parser.add_option("-l", "--label", dest="label", type="string", default="") (options, args) = parser.parse_args() N = options.N isExclusive = options.isExclusive label_text = options.label if isExclusive and not (N == 2 or N == 3): parser.error("Exclusive plot only for N =2 or 3") import configurations as config from ROOT import TFile, TCanvas, THStack, TLegend, TPaveText, gStyle from ModelParser import ModelKey gStyle.SetPadTopMargin(0.05) gStyle.SetPadRightMargin(0.05) suffix = "" if not isExclusive: suffix = "up" sm_files = [] for model in config.sm_models: f = TFile("%s/%s.root" % (config.sm_dir, model), "READ") sm_files.append(f) bh_weights = [] bh_files = [] from BHXsec import BHXsec xsec = BHXsec() for model in config.bh_showcase: f = TFile("%s/%s.root" % (config.bh_dir, model), "READ") bh_files.append(f) h = f.Get("plotsNoCut/ST") nEvents = h.GetEntries() bh_weights.append( xsec.get(model) / nEvents * config.integrated_luminosity) c = TCanvas("ST_Mul%d%s" % (N, suffix), "ST_Mul%d%s" % (N, suffix), 500, 500) hs = THStack() infile = TFile(options.inputfile, "READ") hBkg = infile.Get("Background_N%d%s" % (N, suffix)) gBkg = infile.Get("BackgroundGraph_N%d%s" % (N, suffix)) hData = infile.Get("Data_N%d%s" % (N, suffix)) hBkg = infile.Get("Background_N%d%s" % (N, suffix)) hBkg.SetMarkerSize(0) hBkg_ = hBkg.Clone("BkgLine") hBkg.SetFillColor(33) hBkg.SetLineColor(33) hBkg_.SetLineWidth(3) hBkg_.SetLineColor(862) hs.Add(hBkg, "e3") legend = TLegend(0.3326613, 0.6419492, 0.9294355, 0.9216102) legend.SetTextSize(0.02966102) legend.SetTextFont(42) legend.SetFillColor(0) legend.SetLineColor(0) if isExclusive: legend.SetHeader("N = %d" % N) else: legend.SetHeader("N #geq %d" % N) legend.AddEntry(hData, "Data", "p") legend.AddEntry(hBkg_, "Background", "l") legend.AddEntry(hBkg, "Uncertainty", "f") legend_sm = TLegend(0.6471774, 0.7669492, 0.8508065, 0.8771186) legend_sm.SetTextSize(0.02966102) legend_sm.SetTextFont(42) legend_sm.SetFillColor(0) legend_sm.SetLineColor(0) for i, f in enumerate(bh_files): h = f.Get("plotsN%d%s/ST" % (N, suffix)) h.Rebin(config.rebin) h.Scale(bh_weights[i]) # Add background for ibin in range(h.GetNbinsX()): h.SetBinContent(ibin+1,\ h.GetBinContent(ibin+1)\ + hBkg.GetBinContent(ibin+1)) h.SetLineWidth(2) h.SetLineStyle(i + 2) hs.Add(h, "hist") model = ModelKey(config.bh_showcase[i]) bh_legend = "M_{D} = %.1f TeV, M_{BH}^{ min} = %.1f TeV, n = %d" % (\ model.parameter["MD"], model.parameter["M"], model.parameter["n"]) legend.AddEntry(h, bh_legend, "l") if isExclusive: for i, f in enumerate(sm_files): h = f.Get("plotsN%d%s/ST" % (N, suffix)) h.Rebin(config.rebin) h.Scale(config.integrated_luminosity) h.SetFillColor(config.sm_colors[i]) h.SetLineColor(config.sm_colors[i]) hs.Add(h, "hist") legend_sm.AddEntry(h, config.sm_models[i], "f") #hs.Add(hData, "e") hs.Draw("nostack") c.SetLogy(1) hs.GetXaxis().SetTitle("S_{T} (GeV)") hs.GetYaxis().SetTitle(hData.GetYaxis().GetTitle()) hs.GetYaxis().SetTitleOffset(1.2) ibin = 0 if isExclusive: hs.GetXaxis().SetRangeUser(config.fit_range[0], config.maxST) ibin = hData.FindBin(config.fit_range[0]) else: hs.GetXaxis().SetRangeUser(config.norm_range[0], config.maxST) ibin = hData.FindBin(config.norm_range[0]) from Styles import formatUncertainty formatUncertainty(gBkg) gBkg.Draw("LX") hData.Draw("esame") hs.SetMinimum(5e-2) if isExclusive: hs.SetMaximum(hData.GetBinContent(ibin) * 20) else: #hs.SetMaximum(4e4) hs.SetMaximum(hData.GetBinContent(ibin) * 20) legend.Draw("plain") if isExclusive: legend_sm.Draw("plain") if isExclusive: cmslabel = TPaveText(0.5544355, 0.5127119, 0.8991935, 0.6292373, "brNDC") else: cmslabel = TPaveText(0.1955645, 0.1631356, 0.5403226, 0.279661, "brNDC") cmslabel.AddText(config.cmsTitle) cmslabel.AddText(config.cmsSubtitle) cmslabel.SetFillColor(0) cmslabel.Draw("plain") label = TPaveText(0.6891129, 0.8644068, 0.9435484, 0.9258475, "brNDC") label.SetFillColor(0) label.SetTextSize(0.0529661) label.AddText(label_text) label.Draw("plain") c.Update() raw_input("Press Enter to continue...")
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 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 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, 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)
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) legend.AddEntry(rebinnedData, "Data", 'pe') legend.AddEntry(errorband, "Uncertainty", "f") for ih in rebinnedHist: legend.AddEntry(rebinnedHist[ih], ih, 'f')
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 main(): extension = "pdf" luminosity = 44307.4 ymin = 0 ymax = 0.024 data_set_names = [ (["SZee_all_susy_2l_0jets.root", "SZmumu_all_susy_2l_0jets.root"], "Z#rightarrowll", 860 + 0, 23), (["ZZ_1in3_susy_2l_0jets.root"], "ZZ#rightarrowll#nu#nu", 416 + 3, 43), (["WZ_1in3_susy_2l_0jets.root"], "WZ#rightarrowl#null", 416 - 8, 33), (["WW_1in3_susy_2l_0jets.root"], "WW#rightarrowl#nul#nu", 416 + 0, 20), ([ "ttbar_1in3_susy_2l_0jets.root", "top_1in3_susy_2l_0jets.root", "antitop_1in3_susy_2l_0jets.root" ], "Top", 800 + 4, 21), ] DATA_dir = os.path.join(os.environ["HOME_DIRECTORY"], "Data", "SR_SUSY") ## Creating the plots gROOT.SetStyle("ATLAS") gROOT.ForceStyle() gStyle.SetErrorX(0.5) canvas = TCanvas("canvas", 'A basic canvas', 800, 600) # canvas.SetLogy() ## Adding in the legend leg = Plotting.Create_Legend(0.60, 0.60, 0.95, 0.95, ncols=1) ## Creating the stack stack = THStack("stack", "stack") stack.SetMinimum(ymin) stack.SetMaximum(ymax) ## Cycling through the different datasets for datasets, label, colour, style in data_set_names: ## Creating the total histogram which will be filled myhist = TH1D(label, label, 50, 0, 150) myhist.SetStats(True) myhist.StatOverflows(True) for dataset in datasets: ## The root file is opened rootfile_name = os.path.join(DATA_dir, dataset) print(rootfile_name) root_file = TFile.Open(rootfile_name, 'read') tree = root_file.Get("mt2_Truth") ## Creating the current histogram which will be filled thishist = TH1D(label, label, 50, 0, 150) thishist.SetStats(True) thishist.StatOverflows(True) ## Drawing the tree and saving the hist to the matrix execution = "mt2>>{}".format(label) tree.Draw(execution, "", "goff") thishist.SetDirectory(0) myhist.Add(thishist) ## We are dont with the file root_file.Close() del root_file ## Changing the properties of the histogram myhist.Scale(1 / myhist.Integral("width")) myhist.SetLineColor(colour) myhist.SetMarkerColor(colour) myhist.SetMarkerStyle(style) myhist.SetMarkerSize(1.5) ## Adding the legend entry leg.AddEntry(myhist, label, "p") ## Adding the object to the stack stack.Add(myhist) del myhist ## Drawing the stack on the currrent canvas stack.Draw("NOSTACK HIST P") leg.Draw() ## Setting axis labels stack.GetXaxis().SetTitle("m_{T2} (True #it{E}_{T}^{miss}) [GeV]") stack.GetYaxis().SetTitle("Normalised Distributions") ## Moving axis tick marks stack.GetYaxis().SetMaxDigits(3) stack.GetXaxis().SetLabelOffset(0.017) ## Drawing all text left = 0.2 size = 1.0 shift = 0.06 pos = 0.88 Plotting.Draw_ATLASLabel(left, pos, "Simulation", scale=1.0) pos -= shift Plotting.Draw_Text(left, pos, "work in progress", scale=size) pos -= shift Plotting.Draw_Lumi(left, pos, 0, scale=size) pos -= shift ## Updating the canvas canvas.Update() out_file = "true_strans.{}".format(extension) canvas.Print(out_file) del canvas return 0
def plotDataVSMC(DataHist, MCHist, xtitle, legendNames, DataName, destination, year, ytitle_bottom='Data/MC', ylog=False): GeneralSettings() Canv = TCanvas("Canv" + destination, "Canv" + destination, 1000, 1000) #Set Histogram Styles for i, h in enumerate(MCHist): h.SetFillColor( TColor.GetColor(GetStackColorTauPOGbyName(legendNames[i]))) h.SetLineColor( TColor.GetColor(GetStackColorTauPOGbyName(legendNames[i]))) DataHist.SetMarkerColor(ROOT.kBlack) DataHist.SetLineColor(ROOT.kBlack) DataHist.SetMarkerStyle(20) #Add all MC samples to use in ratios totBkgr = MCHist[0].Clone("totBkgr") for h in MCHist[1:]: totBkgr.Add(h) DataOverMC = DataHist.Clone("DataOverMC") DataOverMC.Divide(totBkgr) #Errors predStatError = totBkgr.Clone("PredictedStatError") predSystError = totBkgr.Clone("PredictedSystError") predTotError = totBkgr.Clone("PredictedTotalError") for b in xrange(predSystError.GetNbinsX() + 1): predSystError.SetBinError(b, 0.3 * totBkgr.GetBinContent(b)) syst = predSystError.GetBinError(b) stat = predStatError.GetBinError(b) predTotError.SetBinError(b, np.sqrt(stat * stat + syst * syst)) #predTotError.SetFillStyle(3013) #predTotError.SetFillColor(ROOT.kGray+2) #predTotError.SetMarkerStyle(0) #predTotError.Draw("E2 Same") #First pad plotpad = TPad("plotpad", "plotpad", 0, .3, 1, 0.98) plotpad.SetBottomMargin(0.025) plotpad.Draw() plotpad.cd() #Create Stack (Change with most logical ordering) hs = THStack("hs", "hs") for h in MCHist: hs.Add(h) hs.Draw( "EHist" ) #Draw before using GetHistogram, see https://root-forum.cern.ch/t/thstack-gethistogram-null-pointer-error/12892/4 title = " ; ; Events / " + str(MCHist[0].GetBinWidth(1)) + " GeV" hs.SetTitle(title) # hs.GetHistogram().GetXaxis().SetTickLength(0) hs.GetHistogram().GetXaxis().SetLabelOffset(9999999) hs.GetHistogram().SetMaximum(1) #Set range overallMin = GetOverallMinimum(MCHist + [DataHist]) overallMax = GetOverallMaximum([totBkgr] + [DataHist]) if ylog: plotpad.SetLogy() hs.SetMinimum(0.3 * overallMin) hs.SetMaximum(10 * overallMax) else: hs.SetMinimum(0.5 * overallMin) hs.SetMaximum(1.7 * overallMax) DataHist.Draw("EPSame") predTotError.SetFillStyle(3013) predTotError.SetFillColor(ROOT.kGray + 2) predTotError.SetMarkerStyle(0) predTotError.Draw("E2 Same") #Create Legend legend = TLegend(0.7, .7, .9, .9) for h, n in zip(MCHist, legendNames): legend.AddEntry(h, n) legend.AddEntry(DataHist, DataName) legend.SetFillStyle(0) legend.SetBorderSize(0) legend.Draw() #Return to canvas Canv.cd() #Second pad ratiopad = TPad("ratiopad", "ratiopad", 0, 0.05, 1, .3) ratiopad.SetTopMargin(0.05) ratiopad.SetBottomMargin(0.25) ratiopad.Draw() ratiopad.cd() #Errors StatErrorRatio = predStatError.Clone("StatErrorRatio") StatErrorRatio.SetFillStyle(1001) StatErrorRatio.SetFillColor(TColor.GetColor('#6EF9F5')) TotErrorRatio = predTotError.Clone("SystErrorRatio") TotErrorRatio.SetFillColor(TColor.GetColor('#63E2C6')) TotErrorRatio.SetFillStyle(1001) for b in xrange(StatErrorRatio.GetNbinsX() + 1): if (StatErrorRatio.GetBinContent(b) != 0): StatErrorRatio.SetBinError( b, StatErrorRatio.GetBinError(b) / StatErrorRatio.GetBinContent(b)) TotErrorRatio.SetBinError( b, TotErrorRatio.GetBinError(b) / TotErrorRatio.GetBinContent(b)) StatErrorRatio.SetBinContent(b, 1.) TotErrorRatio.SetBinContent(b, 1.) else: StatErrorRatio.SetBinContent(b, 0) TotErrorRatio.SetBinContent(b, 0) #Set Style for bottom plot DataOverMC.SetTitle(";" + xtitle + "; " + ytitle_bottom) DataOverMC.GetXaxis().SetTitleSize(.12) DataOverMC.GetYaxis().SetTitleSize(.12) DataOverMC.GetYaxis().SetTitleOffset(.6) DataOverMC.GetXaxis().SetLabelSize(.12) DataOverMC.GetYaxis().SetLabelSize(.12) DataOverMC.SetMinimum(0.3) DataOverMC.SetMaximum(1.7) DataOverMC.Draw("EP") TotErrorRatio.Draw("E2 same") StatErrorRatio.Draw("E2 same") DataOverMC.Draw("EPsame") #Draw a guide for the eye line = TLine(DataOverMC.GetXaxis().GetXmin(), 1, DataOverMC.GetXaxis().GetXmax(), 1) line.SetLineColor(ROOT.kRed) line.SetLineWidth(1) line.SetLineStyle(1) line.Draw("Same") #Create Legend legend_bottom = TLegend(0.2, .8, .9, .9) legend_bottom.SetNColumns(3) legend_bottom.AddEntry(DataOverMC, "Obs./Pred.") legend_bottom.AddEntry(StatErrorRatio, "Stat. Unc.") legend_bottom.AddEntry(TotErrorRatio, "Tot. Unc.") legend_bottom.SetFillStyle(0) legend_bottom.SetBorderSize(0) legend_bottom.Draw() #Throw CMs lumi at it cl.CMS_lumi(Canv, 4, 11, year, 'Preliminary', True) print 'save' #Save everything savePlots(Canv, destination) print 'saved'
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))
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]
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 plotStack(): inputfile = TFile(filename, "read") if inputfile.IsZombie(): print("inputfile is Zombie") sys.exit() # loop over features for feature, values in features.items(): file = open( "%s%s_%s_isNorm%s_wtStat%s_isBlind%s.txt" % (outputdir, feature, plotname, normalization, showStats, blind), "w") file.write( "\\begin{table}[]\n\\resizebox{!}{.33\\paperheight}{\n \\begin{tabular}{|l|l|l|}\n\\hline\nProcess & Yield & Entries \\\\ \\hline \n" ) # set up legend legend = TLegend(0.2, 0.6, 0.7, 0.88) legend.SetHeader("%i %s" % (year, region)) legend.SetNColumns(4) legend.SetBorderSize(0) c, pad1, pad2 = createCanvasPads() hstack = THStack("hstack", "hstack") hstack.SetTitle( "#scale[0.9]{#font[22]{CMS} #font[12]{Preliminary} %i at %.2f fb^{-1}(13TeV)}" % (year, luminosity[year])) histName = "TTH_" + feature # assuming TTH is always there if not inputfile.GetListOfKeys().Contains(histName): print("%s doesn't have histogram %s, please use another hist " % (inputfile, histName)) sys.exit() h0 = inputfile.Get(histName) h_totalsig = h0.Clone("h_totalsig") h_totalsig.SetDirectory(0) h_totalsig.Reset() h_totalsig.SetMarkerStyle(20) h_totalsig.Sumw2() h_totalbkg = h0.Clone("h_totalbkg") h_totalbkg.SetDirectory(0) h_totalbkg.Reset() h_totalbkg.SetMarkerStyle(20) h_totalbkg.Sumw2() h_totalmc = h0.Clone("h_totalmc") h_totalmc.SetDirectory(0) h_totalmc.Reset() h_totalmc.SetLineColor(kBlack) h_totalmc.SetFillColor(kGray + 3) h_totalmc.SetFillStyle(3001) h_totalmc.SetTitle("") #h_totalmc.SetMinimum(0.8) #h_totalmc.SetMaximum(1.35) h_totalmc.Sumw2() h_totalmc.SetStats(0) h_dataobs = h0.Clone("h_dataobs") h_dataobs.SetDirectory(0) h_dataobs.Reset() h_dataobs.SetMarkerStyle(20) # loop over samples for sample in Samples: hist = h_totalmc.Clone(sample) hist.SetDirectory(0) hist.Reset() if sample not in Process: print("sample %s is not in Process " % sample) continue # loop over data: if sample == "Data" or sample == "data": for p in Process[sample]: if p not in sampleName: print("process %s is not in sampleName " % s) continue hist_name = p + "_" + feature if not inputfile.GetListOfKeys().Contains(hist_name): print("%s doesn't have histogram %s" % (inputfile, hist_name)) continue h1 = inputfile.Get(hist_name).Clone(hist_name) h1.SetDirectory(0) h_dataobs.Add(h1) error = Double(0) h1.IntegralAndError(0, h1.GetNbinsX(), error) if not blind: file.write( "%s & %.2f +/- %.2f & %i \\\\ \\hline \n" % (p.replace('_', '\\_'), h1.Integral(), error, h1.GetEntries())) # loop over mc # loop over signal elif sample in Signals: for p in Process[sample]: if p not in sampleName: print("process %s is not in sampleName " % s) continue hist_name = p + "_" + feature if not inputfile.GetListOfKeys().Contains(hist_name): print("%s doesn't have histogram %s" % (filename, hist_name)) continue h1 = inputfile.Get(hist_name).Clone(hist_name) h1.SetDirectory(0) if p == "FakeSub" and sample == "Fakes": hist.Add(h1, -1) h_totalsig.Add(h1, -1) h_totalmc.Add(h1, -1) else: hist.Add(h1) h_totalsig.Add(h1) h_totalmc.Add(h1) error = Double(0) h1.IntegralAndError(0, h1.GetNbinsX(), error) if h1.Integral() < 0.05 or h1.GetEntries() < 100: file.write( "\\textcolor{red}{%s} & %.2f +/- %.2f & %i \\\\ \\hline \n" % (p.replace('_', '\\_'), h1.Integral(), error, h1.GetEntries())) else: file.write( "%s & %.2f +/- %.2f & %i \\\\ \\hline \n" % (p.replace('_', '\\_'), h1.Integral(), error, h1.GetEntries())) hist.SetFillColor(Color[sample]) hist.SetLineColor(kBlack) hist.SetFillStyle(Style[sample]) if sample == "TH" and tH != 1: hist.Scale(tH) hist.SetFillColor(Color[sample]) hist.SetLineColor(kBlack) hist.SetFillStyle(Style[sample]) hstack.Add(hist) legend.AddEntry(hist, "%s * %i" % (sample, tH), "f") else: hstack.Add(hist) legend.AddEntry(hist, sample, "f") # create required parts # loop over bkg else: for p in Process[sample]: if p not in sampleName: print("process %s is not in sampleName " % p) continue hist_name = p + "_" + feature if not inputfile.GetListOfKeys().Contains(hist_name): print("%s doesn't have histogram %s" % (filename, hist_name)) continue h1 = inputfile.Get(hist_name).Clone(hist_name) h1.SetDirectory(0) if p == "FakeSub" and sample == "Fakes": hist.Add(h1, -1) h_totalmc.Add(h1, -1) h_totalbkg.Add(h1, -1) else: hist.Add(h1) h_totalmc.Add(h1) h_totalbkg.Add(h1) error = Double(0) h1.IntegralAndError(0, h1.GetNbinsX(), error) if h1.Integral() < 0.05 or h1.GetEntries() < 100: file.write( "\\textcolor{red}{%s} & %.2f +/- %.2f & %i \\\\ \\hline \n" % (p.replace('_', '\\_'), h1.Integral(), error, h1.GetEntries())) else: file.write( "%s & %.2f +/- %.2f & %i \\\\ \\hline \n" % (p.replace('_', '\\_'), h1.Integral(), error, h1.GetEntries())) hist.SetFillColor(Color[sample]) hist.SetLineColor(kBlack) hist.SetFillStyle(Style[sample]) if sample == "TH" and tH != 1: hist.Scale(tH) hist.SetFillColor(Color[sample]) hist.SetLineColor(kBlack) hist.SetFillStyle(Style[sample]) hstack.Add(hist) legend.AddEntry(hist, "%s * %i" % (sample, tH), "f") else: hstack.Add(hist) legend.AddEntry(hist, sample, "f") error = Double(0) h_totalsig.IntegralAndError(0, h_totalsig.GetNbinsX(), error) file.write("signal & %.2f +/- %.2f & %i \\\\ \\hline \n" % (h_totalsig.Integral(), error, h_totalsig.GetEntries())) error = Double(0) h_totalbkg.IntegralAndError(0, h_totalbkg.GetNbinsX(), error) file.write("bkg & %.2f +/- %.2f & %i \\\\ \\hline \n" % (h_totalbkg.Integral(), error, h_totalbkg.GetEntries())) # create required parts if blind: h_sqrtB = createSqrt(h_totalbkg) h_MCerr = createTotalMCErr(h_sqrtB, values["xlabel"]) h_ratio = createRatio(h_totalsig, h_sqrtB, values["xlabel"], normalization) else: h_MCerr = createTotalMCErr(h_totalmc, feature) h_ratio = createRatio(h_dataobs, h_totalmc, values["xlabel"], normalization) legend.AddEntry(h_dataobs, "observed", "lep") legend.AddEntry(h_totalmc, "Uncertainty", "f") # draw everything pad1.cd() if values["logy"] == 1: pad1.SetLogy() maximum = h_dataobs.GetMaximum() upperbound = 2. * maximum lowerbound = -maximum / 40. if values["logy"] == 1: upperbound = 1000 * maximum lowerbound = 0.1 hstack.SetMinimum(lowerbound) hstack.SetMaximum(upperbound) hstack.Draw("HISTY") # Adjust y-axis settings y = hstack.GetYaxis() y.SetTitle("Events ") y.SetTitleSize(25) y.SetTitleFont(43) y.SetTitleOffset(1.55) y.SetLabelFont(43) y.SetLabelSize(20) nbins = h_ratio.GetNbinsX() #hstack.GetXaxis().SetRange(0, nbins+1) hstack.GetXaxis().SetRangeUser(values["min"], values["max"]) h_totalmc.Draw("e2same") if not blind: h_dataobs.Draw("same") legend.Draw("same") pad2.cd() if blind: h_ratio.SetMinimum(0.) #maximum = h_ratio.GetMaximum() #upperbound = 1.5*maximum #h_ratio.SetMaximum(upperbound) h_ratio.SetMaximum(3.) h_ratio.GetXaxis().SetRangeUser(values["min"], values["max"]) h_ratio.Draw("") else: h_MCerr.SetMinimum(0.5) h_MCerr.SetMaximum(1.8) h_MCerr.GetXaxis().SetRangeUser(values["min"], values["max"]) h_MCerr.Draw("e2") h_ratio.Draw("same") c.SaveAs( "%s%s_%s_isNorm%s_wtStat%s_isBlind%s_stack.png" % (outputdir, feature, plotname, normalization, showStats, blind)) file.write("\\end{tabular}\n}\n\\end{table}\n") file.close() inputfile.Close()
def calcAndDrawSignificance(SignalHist, BkgrHist, xtitle, legendNames, DataName, destination, year, ylog=False, customLabels=None, extraText=None, scaleSignalToBkgr=False, DivideByLine=None): GeneralSettings() #Make sure the code works for single backgrounds if not isinstance(BkgrHist, (list, )): BkgrHist = [BkgrHist] if not isinstance(SignalHist, (list, )): SignalHist = [SignalHist] BkgrHist, legendNames = orderHist(BkgrHist, legendNames, True) #Add all backgrounds totBkgr = BkgrHist[0].Clone("TotBkgr") for h in BkgrHist[1:]: totBkgr.Add(h) #Normalize signal to background if needed if scaleSignalToBkgr: for h in SignalHist: h.scale(totBkgr.GetSumOfWeights() / h.GetSumOfWeights) #Define a canvas Canv = TCanvas("Canv" + destination, "Canv" + destination, 1500, 1000) #Set Histogram Styles for h, n in zip(BkgrHist, legendNames): h.SetFillColor(TColor.GetColor(GetStackColorTauPOGbyName(n))) h.SetLineColor(TColor.GetColor(GetStackColorTauPOGbyName(n))) for i, h in enumerate(SignalHist): h.SetMarkerColor(TColor.GetColor(GetLineColor(i))) h.SetLineColor(TColor.GetColor(GetLineColor(i))) h.SetMarkerStyle(GetMarker(i)) list_of_significance_hists = [] for i, sh in enumerate(SignalHist): #Calculate significance total = totBkgr.Clone("Total") total.Add(sh) sqrt_total = total.Clone('Sqrt_Total') for xbin in xrange( 1, total.GetSize() - 1 ): #GetSize returns nbins + 2 (for overflow and underflow bin) sqrt_x = np.sqrt(total.GetBinContent(xbin)) sqrt_total.SetBinContent(xbin, sqrt_x) sqrt_total.SetBinError(xbin, 0.5 * total.GetBinError(xbin) / sqrt_x) significance = sh.Clone('Signal' + str(i)) significance.Divide(sqrt_total) list_of_significance_hists.append(significance) #First pad plotpad = TPad("plotpad", "plotpad", 0, .3, 1, 0.98) plotpad.SetBottomMargin(0.025) plotpad.Draw() plotpad.cd() #Create Stack (Change with most logical ordering) hs = THStack("hs", "hs") for h in BkgrHist: hs.Add(h) hs.Draw( "EHist" ) #Draw before using GetHistogram, see https://root-forum.cern.ch/t/thstack-gethistogram-null-pointer-error/12892/4 title = " ; ; Events" hs.SetTitle(title) # hs.GetHistogram().GetXaxis().SetTickLength(0) hs.GetHistogram().GetXaxis().SetLabelOffset(9999999) #hs.GetHistogram().SetMaximum(1) #Set range overallMin = GetOverallMinimum(BkgrHist + SignalHist, True) overallMax = GetOverallMaximum([totBkgr] + SignalHist) if ylog: if overallMin == 0.: overallMin = 0.1 ymin = 0.3 * overallMin ymax = 30 * overallMax plotpad.SetLogy() else: ymin = 0.7 * overallMin ymax = 1.3 * overallMax hs.SetMinimum(ymin) hs.SetMaximum(ymax) for h in SignalHist: h.Draw("EPSame") #Create Legend legend = TLegend(0.7, .7, .9, .9) for h, n in zip(BkgrHist, legendNames): legend.AddEntry(h, n) for h, n in zip(SignalHist, DataName): legend.AddEntry(h, n) legend.SetFillStyle(0) legend.SetBorderSize(0) legend.Draw() #Draw lines if needed if DivideByLine is not None: tdrStyle_Left_Margin = 0.16 tdrStyle_Right_Margin = 0.02 plot_size_hor = 1 - tdrStyle_Left_Margin - tdrStyle_Right_Margin #Option one, user provides the number of divisions and we divide equally if isinstance(DivideByLine[0], int): x_pos = np.linspace(totBkgr.GetXaxis().GetXmin(), totBkgr.GetXaxis().GetXmax(), DivideByLine[0] + 1) #Option two, user provides the specific boundaries if isinstance(DivideByLine[0], (list, )): x_pos = DivideByLine[0] #Draw the lines lines = [] for i, x in enumerate(x_pos[1:-1]): lines.append(TLine(x, ymin, x, ymax)) lines[i].SetLineColor(ROOT.kRed) lines[i].SetLineStyle(10) for line in lines: line.Draw('same') #Add extra text for i, name in enumerate(DivideByLine[1]): x = ((x_pos[i + 1] + x_pos[i]) / (2 * (x_pos[-1] - x_pos[0]) / plot_size_hor)) + tdrStyle_Left_Margin extraText.append(extraTextFormat(name, x, 0.1, None, 22)) #Draw extra text if needed if extraText is not None: DrawExtraText(plotpad, extraText) #Return to canvas Canv.cd() #Second pad ratiopad = TPad("ratiopad", "ratiopad", 0, 0.05, 1, .3) ratiopad.SetTopMargin(0.05) ratiopad.SetBottomMargin(0.25) ratiopad.Draw() ratiopad.cd() #print list_of_significance_hists[0].GetMaximum(), list_of_significance_hists[1].GetMaximum(), list_of_significance_hists[2].GetMaximum() overallMin = GetOverallMinimum(list_of_significance_hists) overallMax = GetOverallMaximum(list_of_significance_hists) significance = list_of_significance_hists[0] #Prepare lines before changing maximum lines_bottom = [] for i, sig in enumerate(list_of_significance_hists): lines_bottom.append( TLine(sig.GetXaxis().GetXmin(), sig.GetMaximum(), sig.GetXaxis().GetXmax(), sig.GetMaximum())) lines_bottom[i].SetLineColor(TColor.GetColor(GetLineColor(i))) lines_bottom[i].SetLineStyle(3) #Set Style for bottom plot significance.SetTitle(";" + xtitle + "; S/#sqrt{S+B}") significance.GetXaxis().SetTitleSize(.12) significance.GetYaxis().SetTitleSize(.12) significance.GetYaxis().SetTitleOffset(.6) significance.GetXaxis().SetLabelSize(.12) significance.GetYaxis().SetLabelSize(.12) significance.SetMinimum(0.) significance.SetMaximum(1.3 * overallMax) significance.Draw("EP") for sig in list_of_significance_hists[1:]: sig.Draw('EPSame') for line in lines_bottom: line.Draw("same") #Set custom x labels xaxis = significance.GetXaxis() if customLabels != None: number_of_bins = significance.GetNbinsX() if number_of_bins != len(customLabels): if DivideByLine is not None: for i in range(number_of_bins): xaxis.SetBinLabel( i + 1, customLabels[i % len(customLabels)] ) #Only works when DivideByLine[0] is an integer else: print 'Please provide ' + str( number_of_bins) + ' labels instead of ' + str( len(customLabels)) return else: for i, label in zip(range(number_of_bins), customLabels): xaxis.SetBinLabel(i + 1, label) #Throw CMs lumi at it cl.CMS_lumi(Canv, 4, 11, year, 'Simulation Preliminary', True) #Save everything savePlots(Canv, destination) ROOT.SetOwnership( Canv, False ) #https://root-forum.cern.ch/t/tlatex-crashing-in-pyroot-after-many-uses/21638/4 return
def 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 createPlots_(plot, compounddetectorname): """Cumulative material budget from simulation. Internal function that will produce a cumulative profile of the material budget inferred from the simulation starting from the single detectors that compose the tracker. It will iterate over all existing detectors contained in the DETECTORS dictionary. The function will automatically skip non-existent detectors. """ theDirname = "Figures" hist_X0_detectors = OrderedDict() if plot not in plots.keys(): print("Error: chosen plot name not known %s" % plot) return # We need to keep the file content alive for the lifetime of the # full function.... subDetectorFiles = [] hist_X0_elements = OrderedDict() prof_X0_elements = OrderedDict() for subDetector, color in DETECTORS.iteritems(): subDetectorFilename = "matbdg_%s.root" % subDetector if not checkFile_(subDetectorFilename): print("Error opening file: %s" % subDetectorFilename) continue subDetectorFiles.append(TFile(subDetectorFilename)) subDetectorFile = subDetectorFiles[-1] print("Opening file: %s" % subDetectorFilename) prof_X0_XXX = subDetectorFile.Get("%d" % plots[plot].plotNumber) hist_X0_detectors[subDetector] = prof_X0_XXX.ProjectionX() # category profiles for label, [num, color, leg] in hist_label_to_num.iteritems(): prof_X0_elements[label] = subDetectorFile.Get( "%d" % (num + plots[plot].plotNumber)) hist_X0_elements[label] = assignOrAddIfExists_( hist_X0_elements.setdefault(label, None), prof_X0_elements[label]) cumulative_matbdg = TH1D( "CumulativeSimulMatBdg", "CumulativeSimulMatBdg", hist_X0_detectors["BeamPipe"].GetNbinsX(), hist_X0_detectors["BeamPipe"].GetXaxis().GetXmin(), hist_X0_detectors["BeamPipe"].GetXaxis().GetXmax()) cumulative_matbdg.SetDirectory(0) # colors for det, color in DETECTORS.iteritems(): setColorIfExists_(hist_X0_detectors, det, color) for label, [num, color, leg] in hist_label_to_num.iteritems(): hist_X0_elements[label].SetFillColor(color) # First Plot: BeamPipe + Tracker + ECAL + HCal + HGCal + MB + MGNT # stack stackTitle_SubDetectors = "Material Budget;%s;%s" % (plots[plot].abscissa, plots[plot].ordinate) stack_X0_SubDetectors = THStack("stack_X0", stackTitle_SubDetectors) for det, histo in hist_X0_detectors.iteritems(): stack_X0_SubDetectors.Add(histo) cumulative_matbdg.Add(histo, 1) # canvas can_SubDetectors = TCanvas("can_SubDetectors", "can_SubDetectors", 800, 800) #can_SubDetectors.Range(0,0,25,25) can_SubDetectors.SetFillColor(kWhite) # Draw stack_X0_SubDetectors.SetMinimum(plots[plot].ymin) stack_X0_SubDetectors.SetMaximum(plots[plot].ymax) stack_X0_SubDetectors.Draw("HIST") #stack_X0_SubDetectors.GetXaxis().SetLimits(plots[plot].xmin, plots[plot].xmax) # Legenda theLegend_SubDetectors = TLegend(0.130, 0.7, 0.93, 0.90) #(0.180,0.8,0.98,0.90) theLegend_SubDetectors.SetNColumns(2) theLegend_SubDetectors.SetFillColor(0) theLegend_SubDetectors.SetFillStyle(0) theLegend_SubDetectors.SetBorderSize(0) for det, histo in hist_X0_detectors.iteritems(): theLegend_SubDetectors.AddEntry(histo, det, "f") theLegend_SubDetectors.Draw() # text text_SubDetectors = TPaveText(0.130, 0.627, 0.352, 0.687, "NDC") #(0.180,0.727,0.402,0.787,"NDC") text_SubDetectors.SetFillColor(0) text_SubDetectors.SetBorderSize(0) text_SubDetectors.AddText("CMS Simulation") text_SubDetectors.SetTextAlign(11) text_SubDetectors.Draw() # Store can_SubDetectors.Update() if not checkFile_(theDirname): os.mkdir(theDirname) can_SubDetectors.SaveAs("%s/MaterialBdg_%s_%s.pdf" % (theDirname, compounddetectorname, plot)) can_SubDetectors.SaveAs("%s/MaterialBdg_%s_%s.png" % (theDirname, compounddetectorname, plot)) can_SubDetectors.SaveAs("%s/MaterialBdg_%s_%s.root" % (theDirname, compounddetectorname, plot)) if plot == "x_vs_eta" or plot == "l_vs_eta": canname = "MBCan_1D_%s_%s_total" % (compounddetectorname, plot) can2 = TCanvas(canname, canname, 800, 800) can2.Range(0, 0, 25, 25) can2.SetFillColor(kWhite) gStyle.SetOptStat(0) gStyle.SetOptTitle(0) #title = TPaveLabel(.11,.95,.35,.99,"Total accumulated material budget","brndc") stack_X0_SubDetectors.GetStack().Last().SetMarkerStyle(34) stack_X0_SubDetectors.GetStack().Last().GetXaxis().SetRangeUser( 1.0, 3.5) stack_X0_SubDetectors.GetStack().Last().Draw() stack_X0_SubDetectors.GetYaxis().SetTitleOffset(1.15) can2.Update() can2.Modified() can2.SaveAs("%s/%s_%s_total_Zplus.pdf" % (theDirname, compounddetectorname, plot)) can2.SaveAs("%s/%s_%s_total_Zplus.png" % (theDirname, compounddetectorname, plot)) stack_X0_SubDetectors.GetStack().Last().GetXaxis().SetRangeUser( -3.5, -1.0) stack_X0_SubDetectors.GetStack().Last().Draw() stack_X0_SubDetectors.GetYaxis().SetTitleOffset(1.15) can2.Update() can2.Modified() can2.SaveAs("%s/%s_%s_total_Zminus.pdf" % (theDirname, compounddetectorname, plot)) can2.SaveAs("%s/%s_%s_total_Zminus.png" % (theDirname, compounddetectorname, plot)) #Also print them to give them exact numbers etavalues = [] matbudginX0 = [] matbudginIntLen = [] for binx in range( 0, stack_X0_SubDetectors.GetStack().Last().GetXaxis().GetNbins()): bincontent = stack_X0_SubDetectors.GetStack().Last().GetBinContent( binx) if bincontent == 0: continue etavalues.append( stack_X0_SubDetectors.GetStack().Last().GetBinCenter(binx)) if plot == "x_vs_eta": matbudginX0.append(bincontent) d1 = {'Eta': etavalues, 'MatBudInX0': matbudginX0} df1 = pd.DataFrame(data=d1).round(2) df1.to_csv( r'/afs/cern.ch/work/a/apsallid/CMS/PFCalStudies/CMS-HGCAL/matbudV10fromVertexToBackofHGCal/CMSSW_11_0_X_2019-06-04-2300/src/Validation/Geometry/test/EtavsMatBudinXo.txt', sep=' ', index=False, header=False) #print df1 if plot == "l_vs_eta": matbudginIntLen.append(bincontent) d2 = {'Eta': etavalues, 'MatBudInIntLen': matbudginIntLen} df2 = pd.DataFrame(data=d2).round(2) df2.to_csv( r'/afs/cern.ch/work/a/apsallid/CMS/PFCalStudies/CMS-HGCAL/matbudV10fromVertexToBackofHGCal/CMSSW_11_0_X_2019-06-04-2300/src/Validation/Geometry/test/EtavsMatBudInIntLen.txt', sep=' ', index=False, header=False) #print df2 return cumulative_matbdg
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)
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 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...")