def sobWeightedPlot(self, fileName, datasetName, channel, cat, log, mass, tanb, blind, sob=False): # print 'yuta', channel, cat c = TCanvas(fileName, '', 600, 600) c.cd() if log: c.SetLogy(1) f = self.openTFile('Plot_' + fileName + '.root') isEMSM = fileName.find('SM') != -1 and fileName.find('em') != -1 isETSM = fileName.find('SM') != -1 and fileName.find('et') != -1 samples = ['ggH', 'Ztt', 'signal', 'data_obs', 'ttbar', 'EWK', 'Fakes'] if isEMSM: samples.append('ggH_hww') if isETSM: samples.append('Zee') dataGraph = self.tfileGet(f, 'Graph_from_data_obs') histDict = {} for sample in samples: histDict[sample] = self.tfileGet(f, sample) # print 'check :', sample, histDict[sample].GetSumOfWeights() if not histDict[sample]: print 'Missing histogram', sample, 'in file', 'Plot_' + fileName + '.root' # original for plots xminInset = 60 # 0 xmaxInset = 179 # 340 (for full range) # all range # xminInset = 0 # 0 # xmaxInset = 350 # 340 (for full range) # xminInset = 40 # 0 # xmaxInset = 200 # 340 (for full range) # xminInset = 120 # 0 # xmaxInset = 251 # 340 (for full range) if tanb > 0: xminInset = mass - 100 xmaxInset = mass + 100 if sob: xminInset = 0.4 xmaxInset = 0.7 ztt = histDict['Ztt'] ggH = histDict['ggH'] data = histDict['data_obs'] # This is to fix a weird plotting bug if sob: new_data = TH1F('new_data', '', ggH.GetNbinsX(), 0., 0.7) for i in range(1, new_data.GetNbinsX() + 1): new_data.SetBinContent(i, data.GetBinContent(i)) # print data.GetBinContent(i) data = new_data ggH_hww = 0 zee = 0 signal = histDict['signal'] if isEMSM: ggH_hww = histDict['ggH_hww'] if isETSM: print 'retrieve Zee' zee = histDict['Zee'] tt = histDict['ttbar'] ewk = histDict['EWK'] fakes = histDict['Fakes'] ztt.GetYaxis().SetRangeUser(0., 1.3 * self.findMaxY(data, 0)) if log: ztt.GetYaxis().SetRangeUser(0.001, 50. * self.findMaxY(data, 0)) ztt.GetXaxis().SetTitle('#bf{m_{#tau#tau} [GeV]}') ztt.GetYaxis().SetTitle('#bf{S/B Weighted dN/dm_{#tau#tau} [1/GeV]}') if tanb > 0. and not log: ztt.GetXaxis().SetRangeUser(0., mass + 200.) if sob: ztt.GetXaxis().SetTitle('S/(S+B)') ztt.GetYaxis().SetTitle('Events') ztt.SetTitleOffset(1.3, 'Y') ztt.SetTitleOffset(1., 'X') ztt.GetYaxis().SetNdivisions(505) ztt.SetNdivisions(505) for b in range(0, signal.GetNbinsX() + 2): if signal.GetBinCenter( b) < xminInset or xmaxInset < signal.GetBinCenter(b): signal.SetBinContent(b, 0.) signal.SetBinError(b, 0.) signal.SetName('sig') signal.SetFillStyle(3353) # 1001=solid , 3004,3005=diagonal signal.SetFillColor(2) signal.SetLineColor(2) signal.SetLineStyle(1) signal.SetLineWidth(0) ggH.SetBinContent(0, 0) # remove red line on top of y axis in plot ggH.SetBinContent(ggH.GetNbinsX() + 1, 0) ggH.SetBinError(0, 0) ggH.SetBinError(ggH.GetNbinsX() + 1, 0) ggH.SetName('ggH') ggH.SetFillStyle(3353) # 1001=solid , 3004,3005=diagonal ggH.SetFillColor(2) ggH.SetLineColor(2) ggH.SetLineStyle(1) ggH.SetLineWidth(0) if isEMSM: errorBand = TH1F(ggH_hww) else: errorBand = TH1F(ztt) errorBand.SetName("errorBand") errorBand.SetMarkerSize(0) errorBand.SetFillColor(1) errorBand.SetFillStyle(3013) errorBand.SetLineWidth(1) legend = TLegend() mssmLabel = '' if tanb > 0: mssmLabel = "tan#beta={tanb}".format(tanb=tanb) higgsLabel = "H(125 GeV)#rightarrow#tau#tau" if tanb > 0: higgsLabel = "H(125 GeV)#rightarrow#tau#tau" legend.SetFillStyle(0) legend.SetFillColor(0) legend.SetBorderSize(0) legend.AddEntry(ggH, higgsLabel, "F") if tanb > 0: legend.AddEntry(TObject(0), mssmLabel, "") legend.AddEntry(data, "observed", "LP") if isEMSM: legend.AddEntry(ggH_hww, "H(125 GeV)#rightarrowWW", "F") legend.AddEntry(ztt, "Z#rightarrow#tau#tau", "F") legend.AddEntry(tt, "t#bar{t}", "F") if isETSM: legend.AddEntry(zee, "Z#rightarrowee", "F") legend.AddEntry(ewk, "electroweak", "F") legend.AddEntry(fakes, "QCD", "F") legend.SetX1NDC(0.63) legend.SetX2NDC(1.05) legend.SetY1NDC(0.25) legend.SetY2NDC(0.46) if log: legend.SetX1NDC(0.18) legend.SetX2NDC(0.60) legend.SetY1NDC(0.17) legend.SetY2NDC(0.38) legend.SetTextSize(.028) legend.SetTextAlign(12) if isEMSM: dataDiff = self.diffPlot(data, ggH_hww, 1) dataDiffGraph = self.diffGraph(dataGraph, ggH_hww, 1) errBand = self.getErrorBand(ggH_hww) else: dataDiff = self.diffPlot(data, ztt, 1) dataDiffGraph = self.diffGraph(dataGraph, ztt, 1) errBand = self.getErrorBand(ztt) errBand.SetFillStyle( 3013 ) # 1001=solid , 3004,3005=diagonal, 3013=hatched official for H.tau tau errBand.SetFillColor(1) errBand.SetLineStyle(1) errBand.SetLineColor(1) errBand.SetLineWidth(1) errBandFrame = TH1F( 'errBandFrame', '', int((xmaxInset - xminInset) / dataDiff.GetBinWidth(1)), xminInset, xmaxInset) errBandFrame.GetYaxis().SetTitle("") errBandFrame.GetYaxis().SetRangeUser( -1.1 * self.findMinY(dataDiff, blind, 0, xminInset, xmaxInset), 2.0 * self.findMaxY(dataDiff, blind, 0, xminInset, xmaxInset)) # errBandFrame.GetYaxis().SetRangeUser(-1.*self.findMinY(dataDiff,blind,0,xminInset,xmaxInset),1.1*self.findMaxY(dataDiff,blind,0,xminInset,xmaxInset)) # good ! # errBandFrame.GetYaxis().SetRangeUser(-0.2*self.findMinY(dataDiff,blind,0,xminInset,xmaxInset),0.5*self.findMaxY(dataDiff,blind,0,xminInset,xmaxInset)) print 'Yuta', channel, cat if (channel == 'e#tau_{h}' and cat == 'vbf') or (channel == 'e#tau_{h}' and cat == ''): print 'enter' errBandFrame.GetYaxis().SetRangeUser( -2. * self.findMinY(dataDiff, blind, 0, xminInset, xmaxInset), 2.0 * self.findMaxY(dataDiff, blind, 0, xminInset, xmaxInset)) errBandFrame.GetYaxis().SetNdivisions(5) errBandFrame.GetYaxis().SetLabelSize(0.06) errBandFrame.GetXaxis().SetTitle("#bf{m_{#tau#tau} [GeV]} ") errBandFrame.GetXaxis().SetTitleColor(kBlack) errBandFrame.GetXaxis().SetTitleSize(0.07) errBandFrame.GetXaxis().SetTitleOffset(0.85) errBandFrame.GetXaxis().SetLabelSize(0.06) errBandFrame.GetXaxis().SetNdivisions(506) # errBandFrame.SetNdivisions(505) legendDiff = TLegend() legendDiff.SetFillStyle(0) legendDiff.SetFillColor(0) legendDiff.SetBorderSize(0) legendDiff.AddEntry(signal, higgsLabel, "F") if tanb > 0: legendDiff.AddEntry(TObject(0), mssmLabel, '') # That might not work in python # legendDiff.AddEntry(dataDiff,"Data - Background","LP") legendDiff.AddEntry(dataDiffGraph, "Data - Background", "LEP") legendDiff.AddEntry(errBand, "Bkg. Uncertainty", "F") legendDiff.SetX1NDC(0.45) legendDiff.SetX2NDC(0.88) legendDiff.SetY1NDC(0.67) legendDiff.SetY2NDC(0.88) if dataDiff.GetBinContent(dataDiff.FindBin(mass)) < 0.: legendDiff.SetX1NDC(0.45) legendDiff.SetX2NDC(0.88) legendDiff.SetY1NDC(0.24) legendDiff.SetY2NDC(0.45) legendDiff.SetTextSize(.045) legendDiff.SetTextAlign(12) padBack = TPad( "padBack", "padBack", 0.57, 0.58, 0.975, 0.956) # TPad must be created after TCanvas otherwise ROOT crashes padBack.SetFillColor(0) pad = TPad( "diff", "diff", 0.45, 0.5, 0.9765, 0.957) # TPad must be created after TCanvas otherwise ROOT crashes pad.cd() pad.SetFillColor(0) pad.SetFillStyle(0) errBandFrame.Draw() errBand.Draw("e2lsame") signal.Draw("histsame") line = TLine() line.DrawLine(xminInset, 0, xmaxInset, 0) # dataDiff.Draw("pe same") if blind == False: self.HideBin(dataDiffGraph) dataDiffGraph.SetMarkerSize(0.5) dataDiffGraph.Draw('pe same') for ibin in range(0, dataDiffGraph.GetN()): x = Double(0.) y = Double(0.) dataDiffGraph.GetPoint(ibin, x, y) print 'Yuta_bin=', ibin, 'x=', x, 'y=', y, dataDiffGraph.GetErrorYhigh( ibin), dataDiffGraph.GetErrorYlow(ibin) print 'Yuta_error=', ibin, errBand.GetXaxis().GetBinCenter( ibin + 1), errBand.GetBinError(ibin + 1) legendDiff.Draw() pad.RedrawAxis() c.cd() ztt.Draw("hist") ggH.Draw("hist same") if isEMSM: ggH_hww.Draw("hist same") ztt.Draw("hist same") errorBand.Draw("e2 same") tt.Draw("hist same") if isETSM: zee.Draw("hist same") ewk.Draw("hist same") fakes.Draw("hist same") # data.Draw("pe same") dataGraph.SetMarkerSize(1) dataGraph.Draw('PE same') if blind == False: self.HideBin(dataGraph) print '#####', data.Integral(), data.GetBinContent(1) legend.Draw() c.RedrawAxis() padBack.Draw() # clear the background axe pad.Draw() if log: c.SetLogy(1) self.CMSPrelim(c, datasetName, channel, cat) savepath = 'figure/Plot_' + fileName if cat == '': savepath = savepath + '.pdf' else: savepath = savepath + '_' + cat + '.pdf' # c.Print('figure/Plot_'+fileName+".eps") # c.Print('figure/Plot_'+fileName+".png") # c.Print('figure/Plot_'+fileName+".pdf") c.Print(savepath) c.Close()
def saveRatio(self, legend, isData, log, lumi, hdata, hMC, r_ymin=0, r_ymax=2, label ="Data/Prediction", outputDir = 'plots/'): self.myCanvas.cd() pad1 = TPad("pad1", "pad1", 0, 0.25, 1, 1.0) pad1.SetBottomMargin(0.12) pad1.Draw() pad2 = TPad("pad2", "pad2", 0, 0.05, 1, 0.25) pad2.SetTopMargin(0.1); pad2.SetBottomMargin(0.3); pad2.Draw(); pad1.cd() if(log): pad1.SetLogy(1) for i in range(0, len(self.histos)): if(self.ToDraw[i] != 0): #self.histos[i].SetMinimum(0.00001) self.histos[i].SetMinimum(0.1) #self.histos[i].SetMinimum(0.0001) #self.histos[i].SetMaximum(0.5) self.histos[i].Draw(self.options[i]) if(legend): self.makeLegend() self.myLegend.SetTextSize(0.035) # Modify the legend size self.myLegend.Draw() for band in self.bands: band.Draw('f') for line in self.lines: line.Draw() for arrow in self.arrows: arrow.Draw() for latex in self.latexs: lat = TLatex() lat.SetNDC() lat.SetTextSize(latex[-1]) lat.SetTextFont(latex[-2]) lat.DrawLatex(latex[0], latex[1], latex[2]) if type(hMC) != list: hMClist = [hMC] else: hMClist = hMC ratios = [] for tmp_hMC in hMClist: ind = hMClist.index(tmp_hMC) tmp_ratio = hdata.Clone(tmp_hMC.GetName()+'_ratio') tmp_ratio.Divide(tmp_hMC) tmp_ratio.SetTitle("") tmp_ratio.GetYaxis().SetRangeUser(r_ymin, r_ymax); tmp_ratio.GetYaxis().SetTitle(label); tmp_ratio.GetYaxis().CenterTitle(); tmp_ratio.GetYaxis().SetLabelSize(0.12); tmp_ratio.GetXaxis().SetLabelSize(0.12); tmp_ratio.GetYaxis().SetTitleOffset(0.3); tmp_ratio.GetYaxis().SetNdivisions(4); tmp_ratio.GetYaxis().SetTitleSize(0.12); tmp_ratio.GetXaxis().SetTitleSize(0.12); tmp_ratio.GetXaxis().SetLabelOffset(0.08); tmp_ratio.GetXaxis().SetTitle(''); tmp_ratio.SetMarkerStyle(tmp_hMC.GetMarkerStyle()); tmp_ratio.SetFillColorAlpha(r.kBlue-3,0.9) tmp_ratio.SetFillStyle(3017) tmp_ratio.SetMarkerColor(r.kBlack); tmp_ratio.SetMarkerSize(0.6); #tmp_ratio.SetMarkerColor(r.kBlack if len(hMClist) == 1 else tmp_hMC.GetMarkerColor()); #tmp_ratio.SetLineColor (r.kBlack if len(hMClist) == 1 else tmp_hMC.GetLineColor ()); tmp_ratio.SetLineColor (tmp_hMC.GetLineColor()); tmp_ratio.SetLineStyle(tmp_hMC.GetLineStyle()) ratios.append(tmp_ratio) xmin = tmp_ratio.GetBinLowEdge(1) xmax = tmp_ratio.GetBinLowEdge(tmp_ratio.GetNbinsX()+1) #tmp_ratio.Draw("E,SAME"); pad2.cd(); for rat in ratios: rat.Draw('PE2,same'); line = TLine(xmin, 1, xmax, 1) line.SetLineColor(r.kGray+2); line.Draw(''); pad1.cd() self.banner2(isData, lumi) if not outputDir[-1] == '/': dirName = outputDir + '/' else: dirName = outputDir for i,plotName in enumerate(self.plotNames): pad1.cd() pad1.SetLogy(0) path = dirName+plotName pathlog = dirName+self.plotNamesLog[i] self.ensurePath(path) self.myCanvas.SaveAs(path) if not '.root' in pathlog: pad1.cd() pad1.SetLogy() self.myCanvas.SaveAs(pathlog) pad1.IsA().Destructor(pad1) pad2.IsA().Destructor(pad2) self.myLegend.IsA().Destructor(self.myLegend) self.myCanvas.IsA().Destructor(self.myCanvas)
def drawLine(x1, y1, x2, y2): line = TLine(x1, y1, x2, y2) line.SetLineStyle(2) line.SetLineWidth(2) line.Draw() return line
def drawHline(yval, col): lines.append(TLine(-0.2, yval, 1, yval)) lines[-1].SetLineColor(col) lines[-1].SetLineWidth(2) lines[-1].Draw()
kkTot.paramOn(kkFrame, RooFit.Layout(0.57, 0.99, 0.65)) kkFrame.Draw() pullpad.cd() hpull = kkFrame.pullHist("Data", "Pdf") pullframe = mmtt_mass.frame(Title("Pull Distribution"), Range(fitphimin, fitphimax)) pullframe.SetAxisRange(-5.0, 5.0, "Y") #pullframe.GetXaxis().SetTitleSize(0.04) #pullframe.GetYaxis().SetTitleSize(0.03) gStyle.SetTitleFontSize(0.07) pullframe.addPlotable(hpull, "P") pullframe.Draw() lineup = TLine(fitphimin, 4.0, fitphimax, 4.0) lineup.SetLineColor(kRed) lineup.SetLineStyle(kDashed) lineup.Draw() linedw = TLine(fitphimin, -4.0, fitphimax, -4.0) linedw.SetLineColor(kRed) linedw.SetLineStyle(kDashed) linedw.Draw() kcanvas.SaveAs(region + "/kk_Phi_fit_" + region + ".png") kcanvas.SaveAs(region + "/kk_Phi_fit_" + region + ".root") kcanvas.Clear() signalhist.SetFillColor(kBlue) signalhist.SetName("#mu#muKK Candidates Mass - " + region)
def plot_fits(canvas, histos, x_range, x_bin_step, title_formatter, save_name, label, y_fit_range, y_range=None, title=None, xtitle=None, ytitle=None, hline=None): canvas.Clear() canvas.Divide(2, 3) root_is_dumb = [] for i in range(1, 7): canvas.cd(i) title = title_formatter.format(i) graph, slices, fits = fit_slices(histos.get(title, default_histo2d), x_range, x_bin_step, y_fit_range=y_fit_range) graph.SetMarkerStyle(8) graph.SetMarkerSize(1) if y_range: graph.GetHistogram().SetMinimum(y_range[0]) graph.GetHistogram().SetMaximum(y_range[1]) graph.Draw('AP') root_is_dumb.append(graph) else: graph.Draw('AP') root_is_dumb.append(graph) if hline: line = TLine(x_range[0], hline, x_range[1], hline) line.SetLineStyle(8) line.SetLineWidth(1) line.Draw() root_is_dumb.append(line) if title: label.DrawLatex(0.1, 0.925, title) if xtitle: label.DrawLatex(0.5, 0.015, xtitle) if ytitle: label.SetTextAngle(90) label.DrawLatex(0.035, 0.5, ytitle) label.SetTextAngle(0) canvas.Print(save_name) # For the slices slice_can = TCanvas('slice_can', 'slice_can', 1200, 1600) slice_pdfname = title_formatter.split('_{}')[0] + '_slices.pdf' slice_can.Print(slice_pdfname + '[') for i in range(1, 7): title = title_formatter.format(i) graph, slices, fits = fit_slices(histos.get(title, default_histo2d), x_range, x_bin_step, y_fit_range) # Size of slices page nrows = 5 ncols = int(np.ceil(len(slices) / nrows) + 1) slice_can.Clear() slice_can.Divide(ncols, nrows) for j, (s, f) in enumerate(zip(slices, fits)): slice_can.cd(j + 1) s.Draw() lab.DrawLatex( 0.15, 0.88, '#mu = {0:6.4f}, #sigma = {1:6.4f}'.format( f.GetParameter(1), f.GetParameter(2))) slice_can.Print(slice_pdfname) slice_can.Print(slice_pdfname + ']')
tnt.SetTextAlign(22) tnt.SetTextSize(0.030) tree.AddText('fScanField') tree.AddText('fMaxEventLoop') tree.AddText('fMaxVirtualSize') tree.AddText('fEntries') tree.AddText('fDimension') tree.AddText('fSelectedRows') tree.Draw() farm = TPavesText(.01, 1.02, .15, 1.1, 9, 'tr') tfarm = farm.AddText('CHAIN') tfarm.SetTextSize(0.024) farm.AddText('Collection') farm.AddText('of Trees') farm.Draw() link = TLine(.15, .92, .80, .92) link.SetLineWidth(2) link.SetLineColor(1) link.Draw() link.DrawLine(.21, .87, .21, .275) link.DrawLine(.23, .87, .23, .375) link.DrawLine(.25, .87, .25, .775) link.DrawLine(.41, .25, .41, -.025) link.DrawLine(.43, .25, .43, .075) link.DrawLine(.45, .25, .45, .175) branch0 = TPaveLabel(.20, .87, .35, .97, 'Branch 0') branch0.SetTextSize(0.35) branch0.SetFillColor(branchcolor) branch0.Draw() branch1 = TPaveLabel(.40, .87, .55, .97, 'Branch 1') branch1.SetTextSize(0.35)
def doMCFit(inputfile_name, mass_chib, cuts, output_name='ChiB', plotTitle="#Chi_{b}", fittedVariable='qValue', returnOnlyFitResult=False, useOtherSignalParametrization=False, drawPulls=False, legendOnPlot=True): mass_error = 0.15 print "Creating DataSet from file " + str(inputfile_name) dataSet = makeRooDataset(inputfile_name) if (fittedVariable == 'refittedMass'): x_var = 'rf1S_chib_mass' output_suffix = '_refit' x_axis_label = 'm_{#mu^{+} #mu^{-} #gamma} [GeV]' else: x_var = 'invm1S' output_suffix = '_qValue' x_axis_label = 'm_{#gamma #mu^{+} #mu^{-}} - m_{#mu^{+} #mu^{-}} + m^{PDG}_{#Upsilon} [GeV]' cuts_str = str(cuts) #cuts_str = quality_cut +"photon_pt > 0.5 && abs(photon_eta) < 1.0 && abs(dimuon_rapidity) < 1.0 && dimuon_pt>5.0 && pi0_abs_mass > 0.025 && fabs(dz) < 0.1 "#&& numPrimaryVertices < 16" data = dataSet.reduce(RooFit.Cut(cuts_str)) print 'Creating pdf' x = RooRealVar(x_var, 'm(#mu #mu #gamma) - m(#mu #mu) + m_{#Upsilon}', 9.8, 9.96) #9.7,10.1,'GeV') numBins = 32 # define here so that if I change it also the ndof change accordingly x.setBins(numBins) # Double sided Crystal Ball mean = RooRealVar("#mu", "mean ChiB", mass_chib, mass_chib - mass_error, mass_chib + mass_error, "GeV") sigma = RooRealVar("#sigma", "sigma ChiB", 0.006, 0, 0.2, 'GeV') a1 = RooRealVar('#alpha1', '#alpha1', 0.75, 0, 3) a2 = RooRealVar('#alpha2', '#alpha2', 1.6, 0, 3) n1 = RooRealVar('n1', 'n1', 2.8) #, 1.0,4.0) # 2 per 2S n2 = RooRealVar('n2', 'n2', 3) #, 1.,4.0) # 1 per 2S parameters = RooArgSet(mean, sigma, a1, a2, n1, n2) cb_pdf = My_double_CB('chib', 'chib', x, mean, sigma, a1, n1, a2, n2) #cb_pdf = RooCBShape('chib', 'chib', x, mean, sigma, a1, n1) # ndof floatPars = parameters.selectByAttrib("Constant", ROOT.kFALSE) ndof = numBins - floatPars.getSize() - 1 if useOtherSignalParametrization: # In this case I redefine cb_pdf n1 = RooRealVar('n1', 'n1', 2) cb = RooCBShape('cb1', 'cb1', x, mean, sigma, a1, n1) # I use a2 as the sigma of my second CB a2 = RooRealVar('#alpha2', '#alpha2', 0.5, 0, 3) gauss = RooCBShape('cb2', 'cb2', x, mean, a2, a1, n1) # I use n2 as the ratio of cb1 with respect to cb2 n2 = RooRealVar('n2', 'n2', 0., 1.) cb_pdf = RooAddPdf('chib', 'chib', RooArgList(cb, gauss), RooArgList(n2)) #cb_pdf = cb print 'Fitting to data' fit_region = x.setRange("fit_region", 9.8, 9.96) result = cb_pdf.fitTo(data, RooFit.Save(), RooFit.Range("fit_region")) # a1_val = a1.getVal() # a2_val = a2.getVal() # a1 = RooRealVar('#alpha1', '#alpha1', a1_val) # a2 = RooRealVar('#alpha2', '#alpha2', a2_val) # n1 = RooRealVar('n1', 'n1', 1.7,1.0,5.) # n2 = RooRealVar('n2', 'n2', 1.7,0.,4.) # cb_pdf = My_double_CB('chib', 'chib', x, mean, sigma, a1, n1, a2, n2) # result = cb_pdf.fitTo(data, RooFit.Save()) if returnOnlyFitResult: return result # define frame frame = x.frame() frame.SetNameTitle("fit_resonance", "Fit Resonanace") frame.GetXaxis().SetTitle(x_axis_label) frame.GetYaxis().SetTitle("Events/5 MeV ") frame.GetXaxis().SetTitleSize(0.04) frame.GetYaxis().SetTitleSize(0.04) frame.GetXaxis().SetTitleOffset(1.1) frame.GetXaxis().SetLabelSize(0.04) frame.GetYaxis().SetLabelSize(0.04) frame.SetLineWidth(1) frame.SetTitle(plotTitle) # plot things on frame data.plotOn(frame, RooFit.MarkerSize(0.7)) cb_pdf.plotOn(frame, RooFit.LineWidth(2)) # chiSquare legend chi2 = frame.chiSquare() probChi2 = TMath.Prob(chi2 * ndof, ndof) chi2 = round(chi2, 2) probChi2 = round(probChi2, 2) leg = TLegend(0.3, 0, .10, .10) leg.SetBorderSize(0) leg.SetFillStyle(0) cb_pdf.paramOn(frame, RooFit.Layout(0.17, 0.56, 0.93)) leg.AddEntry(0, '#chi^{2} =' + str(chi2), '') leg.AddEntry(0, 'Prob #chi^{2} = ' + str(probChi2), '') leg.SetTextSize(0.04) frame.addObject(leg) if legendOnPlot: legend = TLegend(.08, .5, .55, .7) #legend.SetTextSize(0.04) legend.SetFillStyle(0) legend.SetBorderSize(0) #legend.AddEntry(0,'CMS','') legend.AddEntry( 0, str(cuts.upsilon_pt_lcut) + ' GeV < p_{T}(#Upsilon) < ' + str(cuts.upsilon_pt_hcut) + ' GeV', '') #legend.AddEntry(0,'p_{T}(#Upsilon)<'+str(cuts.upsilon_pt_hcut),'') frame.addObject(legend) title = TLegend(.8, .75, .9, .93) title.SetTextSize(0.15) title.SetFillStyle(0) title.SetBorderSize(0) title.AddEntry(0, plotTitle, '') frame.addObject(title) # Canvas c1 = TCanvas(output_name + output_suffix, output_name + output_suffix) frame.Draw() if drawPulls: #c1=TCanvas(output_name+output_suffix,output_name+output_suffix,700, 625) hpull = frame.pullHist() framePulls = x.frame() framePulls.SetTitle(';;Pulls') framePulls.GetYaxis().SetLabelSize(0.18) framePulls.GetYaxis().SetTitle('Pulls') framePulls.GetYaxis().SetTitleSize(0.18) framePulls.GetYaxis().SetTitleOffset(0.15) framePulls.GetYaxis().SetNdivisions(005) framePulls.GetXaxis().SetLabelSize(0.16) framePulls.GetXaxis().SetTitle('') line0 = TLine(9.8, 0, 9.96, 0) line0.SetLineColor(ROOT.kBlue) line0.SetLineWidth(2) framePulls.addObject(line0) framePulls.addPlotable(hpull, "P") framePulls.SetMaximum(5) framePulls.SetMinimum(-5) pad1 = TPad("pad1", "The pad 80% of the height", 0.0, 0.2, 1.0, 1.0) pad1.cd() frame.Draw() pad2 = TPad("pad2", "The pad 20% of the height", 0.0, 0.01, 1.0, 0.2) pad2.cd() framePulls.Draw() c1.cd() pad1.Draw() pad2.Draw() #c1.SaveAs(output_name+output_suffix+'.png') print 'Chi2 = ' + str(frame.chiSquare()) pdf_parameters = CB_parameters(mean=mean.getVal(), sigma=sigma.getVal(), n1=n1.getVal(), n2=n2.getVal(), a1=a1.getVal(), a2=a2.getVal(), s_mean=mean.getError(), s_sigma=sigma.getError(), s_n1=n1.getError(), s_n2=n2.getError(), s_a1=a1.getError(), s_a2=a2.getError(), chiSquare=frame.chiSquare()) #pdf_parameters.saveToFile("CB_"+output_name+output_suffix+".txt") return pdf_parameters, c1
def stackHistograms(t_plots, t_processList, l_histoList, l_legendList, l_textList, l_axisList, saveAs,l_ratioList, saveString, tagText): ''' PURPOSE: Function to create stacked plots and save them to the local disk. This function will: * Create a stacked plot * Create a ratio plot * Allow for Blinding * Save the canvas as requested ''' # Release the variables from the lists h_st, location_suf, name, c_x, c_y, v_rebin, xMin, xMax, doBlinding, b_low, b_high = l_histoList l_st, l_x1, l_y1, l_x2, l_y2, l_textSize = l_legendList t_st, plotText, t_textSize, t_alignment, t_start, t_gap, t_x = l_textList a_st, xLabel, yLabel, xOffset, yOffset, a_labelSize, a_textSize, y_scale = l_axisList r_st, doRatio, r_yLabel, r_xOffset, r_yOffset, r_labelSize, r_textSize = l_ratioList len_plots = len(t_plots) plotText = plotText + tagText l_overlay = [] l_data = [] sh = THStack('sh', '') t_legend = [] listMC = TList() for i in xrange(len_plots): process, location_pre, v_colour, v_scale, ovack, sigrouta, l_marker, sel = t_processList[i] histogram = rebin(t_plots[i][0], v_rebin) histogram.Scale(float(v_scale)) histogram.SetLineWidth(1) histogram.SetLineColor(int(v_colour)) l_legendLine = [t_plots[i][0], process, l_marker] t_legend.append(l_legendLine) if sigrouta == "DATA" and int(doBlinding): histogram = blindingPlots(histogram, b_low, b_high) if ovack == "STACK": if sigrouta == "BACKGROUND": listMC.Add(histogram) histogram.SetFillColor(int(v_colour)) sh.Add(histogram) elif ovack == "OVERLAY" and sigrouta != "DATA": l_overlay.append(histogram) elif ovack == "OVERLAY" and sigrouta == "DATA": histogram.SetMarkerStyle(8) histogram.SetMarkerColor(1) l_data.append(histogram) else: print "\n%s or %s are not a valid options" % (sigrouta, ovack) sys.exit(1) mergeMC = histogram.Clone('mergeMC') mergeMC.Reset() mergeMC.Merge(listMC) gROOT.SetBatch(1) c = TCanvas('c', 'c', int(c_x), int(c_y)) gStyle.SetOptStat(0) if int(doRatio): m_Pad = TPad('m_pad', 'm_pad', 0, 0.30, 1, 1) r_Pad = TPad('r_pad', 'r_pad', 0, 0, 1, 0.30) m_Pad.Draw() r_Pad.Draw() m_Pad.SetTopMargin(0.05) m_Pad.SetBottomMargin(0.01) r_Pad.SetTopMargin(0) r_Pad.SetBottomMargin(0.3) m_Pad.cd() m_Pad.SetTicks(1) m_Pad.Update() else: c.SetTicks(1) c.Update # Draw our plots we defined earlier. First the stacked plot, then any overlaid plots and finally data sh.Draw() if l_overlay: for i in xrange(len(l_overlay)): l_overlay[i].Draw('hist same') h_MCerr = getStatUncert(mergeMC) h_MCerr.SetMarkerSize(0) h_MCerr.SetFillColor(921) h_MCerr.SetFillStyle(3344) h_MCerr.Draw('e2s same') t_legend.append([h_MCerr, 'Stat Uncert.', 'f']) if l_data: h_data = mergeData(l_data, doBlinding, b_low, b_high) h_data.Draw('epsames') ## Next up is to add the styling: ## 1, Axis labels ## 2. Text on the plot ## 3. Legend if not int(doRatio): setupAxes(sh, xLabel, yLabel, xOffset, 0.8, a_textSize, xMin, xMax, y_scale) else: sh.SetMinimum(0.001) setupAxes(sh, "", yLabel, -999, yOffset, a_textSize, xMin, xMax, y_scale) setupLegend(t_legend, l_x1, l_y1, l_x2, l_y2, l_textSize) setupTextOnPlot(plotText, t_textSize, t_alignment, t_x, t_start, t_gap) if int(doRatio): r_Pad.cd() r_Pad.SetTicks(1) r_Pad.Update() l_mc = TList() l_data = TList() for i in xrange(len_plots): l_histogram = rebin(t_plots[i][0], v_rebin) process, location_pre, v_colour, v_scale, ovack, sigrouta, l_marker, tag = t_processList[i] if sigrouta == "SIGNAL": l_mc.Add(l_histogram) elif sigrouta == "BACKGROUND": l_mc.Add(l_histogram) elif sigrouta == "DATA": l_data.Add(l_histogram) elif sigrouta == "OVERLAY": pass else: print "\nOption %s not available" % (sigrouta) mh_MC = l_histogram.Clone('mh_MC') mh_MC.Merge(l_mc) h_statMC = getRelError(mh_MC) h_statMC.SetMarkerSize(0) h_statMC.SetFillColor(921) h_statMC.SetFillStyle(3344) h_statMC.Draw('e2s') setupAxes(h_statMC, xLabel, r_yLabel, r_xOffset, r_yOffset, r_textSize, xMin, xMax, 1) h_statMC.GetYaxis().SetRangeUser(-0.38, 0.38) mh_data = l_histogram.Clone('mh_data') mh_data.Merge(l_data) h_dataMC = getRatio(mh_data, mh_MC, doBlinding, b_low, b_high) h_dataMC.Draw('epsames') h_line = TLine(float(xMin), 0, float(xMax), 0) h_line.SetLineWidth(2) h_line.SetLineColor(1) h_line.SetLineStyle(2) h_line.Draw('same') savePlots(c, saveString, saveAs)
neupt_nomad.Fill(neu_nomad.Pt(),weight_nomad) neueta_nomad.Fill(neu_nomad.Eta(),weight_nomad) lphi_nomad.Scale(1./lphi_nomad.Integral()) lpt_nomad.Scale(1./lpt_nomad.Integral()) leta_nomad.Scale(1./leta_nomad.Integral()) neuphi_nomad.Scale(1./neuphi_nomad.Integral()) neupt_nomad.Scale(1./neupt_nomad.Integral()) neueta_nomad.Scale(1./neueta_nomad.Integral()) lphi_nomad.SetMaximum(1.4*lphi_nomad.GetMaximum()) lpt_nomad.SetMaximum(1.4*lpt_nomad.GetMaximum()) leta_nomad.SetMaximum(1.4*leta_nomad.GetMaximum()) neuphi_nomad.SetMaximum(1.4*neuphi_nomad.GetMaximum()) neupt_nomad.SetMaximum(1.4*neupt_nomad.GetMaximum()) neueta_nomad.SetMaximum(1.4*neueta_nomad.GetMaximum()) tline1 = TLine(-3,1,3,1) tline1.SetLineColor(kRed) tline2 = TLine(0,1,200,1) tline2.SetLineColor(kRed) lphi_ratio = lphi_nomad.Clone() lphi_ratio.Divide(lphi_mad) lphi_ratio.SetMaximum(1.5) lphi_ratio.SetMinimum(0.5) lphi_ratio.GetYaxis().SetNdivisions(2,kFALSE); lphi_ratio.GetXaxis().SetTitle('lep phi') lphi_ratio.GetXaxis().SetTitleSize(0.15); lphi_ratio.GetXaxis().SetTitleOffset(0.75); lphi_ratio.GetXaxis().SetLabelSize(0.13);
metTriggerEfficiency_ff_H_WW_enuenu_1000events.Draw("AP") metTriggerEfficiency_ff_H_WW_enuenu_1000events.GetXaxis().SetTitle("MET [GeV]") metTriggerEfficiency_ff_H_WW_enuenu_1000events.GetXaxis().SetRangeUser(0, 150) metTriggerEfficiency_ff_H_WW_enuenu_1000events.GetYaxis().SetTitle("% accepted events") metTriggerEfficiency_ff_H_WW_enuenu_1000events.GetYaxis().SetTitleOffset(1.2) metTriggerEfficiency_ff_H_WW_enuenu_1000events.GetYaxis().SetRangeUser(0, 1.1) text.Draw() canvas.Update() canvas.Draw() canvas.Print("metTriggerEfficiency_ff_H_WW_enuenu_1000events.svg", "svg") canvas.Print("metTriggerEfficiency_ff_H_WW_enuenu_1000events.png", "png") canvas.Print("metTriggerEfficiency_ff_H_WW_enuenu_1000events.pdf", "pdf") label_200kHz = TLatex(220000, 0.9, "110 GeV - 200 kHz") label_200kHz.SetTextSize(0.03) line_200kHz = TLine(200000, 0, 200000, 1.1) line_200kHz.SetLineColor(2) line_200kHz.SetLineStyle(2) canvas.SetLogx(1) canvas.SetLogy(0) text.SetX1NDC(0.12) text.SetX2NDC(0.52) efficiencyPlotWithRate_ff_H_WW_enuenu_1000events = TGraphErrors(14) for x in xrange(1, 15): efficiencyPlotWithRate_ff_H_WW_enuenu_1000events.SetPoint(x - 1, jetToMETTriggerRate.GetY()[x], metTriggerEfficiency_ff_H_WW_enuenu_1000events.GetY()[x]) efficiencyPlotWithRate_ff_H_WW_enuenu_1000events.SetPointError(x - 1, jetToMETTriggerRate.GetEY()[x], metTriggerEfficiency_ff_H_WW_enuenu_1000events.GetEY()[x]) efficiencyPlotWithRate_ff_H_WW_enuenu_1000events.SetTitle("ff_H_WW_enuenu_1000events") efficiencyPlotWithRate_ff_H_WW_enuenu_1000events.SetName("efficiencyPlotWithRate_ff_H_WW_enuenu_1000events") efficiencyPlotWithRate_ff_H_WW_enuenu_1000events.GetYaxis().SetTitle("% accepted events") efficiencyPlotWithRate_ff_H_WW_enuenu_1000events.GetYaxis().SetTitleOffset(1.2)
def plotSysts(): inputfile = TFile(filename, "read") if inputfile.IsZombie(): print("inputfile is Zombie") sys.exit() # loop over samples file = open( "%s%s_isNorm%s_wtStat%s.txt" % (outputdir, plotname, normalization, showStats), "w") # loop over features for feature, values in features.items(): # get nominal histograms hist_nom_name = "TT_mcFakes_" + feature + "_" + region + "Fakes" if not inputfile.GetListOfKeys().Contains(hist_nom_name): print("%s doesn't have histogram %s" % (filename, hist_nom_name)) continue hist_nom = inputfile.Get(hist_nom_name) hist_nom.SetFillColor(0) hist_nom.SetLineColor(Color["nominal"]) hist_nom.SetLineWidth(2) hist_nom.SetMarkerColor(Color["nominal"]) #h_ratio = createRatio(hist_nom, hist_nom, values["xlabel"], Color["nominal"],normalization) h_ratio = createRatio(hist_nom, hist_nom, values["xlabel"], normalization) # loop over variations for syst in systematics: if syst == "nominal": continue file.write(" sample TT mcFakes, feature %s, nominal yield %f\n" % (feature, hist_nom.Integral())) # set up legend legend = TLegend(0.5, 0.7, 0.8, 0.88) #legend.SetHeader("CMS preliminary %i %s"%(year,region)) #legend.SetNColumns(3) legend.SetBorderSize(0) legend.AddEntry(hist_nom, "TT_mcFakes_%s" % region, "l") c, pad1, pad2 = createCanvasPads() hist_vars = [] hist_ratio_vars = [] for var in upDown: hist_name = "TT_ddFakes_" + feature + "_" + syst + "_" + region + var if not inputfile.GetListOfKeys().Contains(hist_name): print("%s doesn't have histogram %s" % (filename, hist_name)) continue hist_var = inputfile.Get(hist_name) hist_var.SetFillColor(0) hist_var.SetLineColor(Color[var]) hist_var.SetLineWidth(2) hist_var.SetMarkerColor(Color[var]) hist_vars.append(hist_var) var_yield = hist_var.Integral() delta = (100. * (var_yield / hist_nom.Integral() - 1.)) file.write( " sample TT ddFakes, feature {}, {}{} yield {} diff {}% \n" .format(feature, syst, var, var_yield, delta)) h_ratio_var = createRatio(hist_var, hist_nom, values["xlabel"], normalization) hist_ratio_vars.append(h_ratio_var) legend.AddEntry(h_ratio_var, "FR_%s_%s" % (var, region), "l") # draw everything pad1.cd() #pad1.SetGridx() #pad1.SetGridy() # set bounds maximum = 0 for hist in hist_vars: if normalization: hist.Scale(1. / hist.Integral()) if hist.GetMaximum() > maximum: maximum = hist.GetMaximum() upperbound = 1.8 * maximum lowerbound = -maximum / 40. Y_name = "Events" if normalization: hist_nom.Scale(1. / hist_nom.Integral()) Y_name = " Unit " if showStats: hist_nom.SetStats(1) else: hist_nom.SetStats(0) hist_nom.SetMaximum(upperbound) hist_nom.SetMinimum(lowerbound) # Adjust y-axis settings y = hist_nom.GetYaxis() y.SetTitleSize(30) y.SetTitleFont(43) y.SetTitleOffset(1.3) y.SetLabelFont(43) y.SetLabelSize(20) y.SetTitle(Y_name) # Adjust x-axis settings x = hist_nom.GetXaxis() x.SetTitleSize(25) x.SetTitleFont(43) x.SetTitleOffset(1.55) x.SetLabelFont(43) x.SetLabelSize(20) x.SetTitle(values["xlabel"]) hist_nom.SetTitle("#scale[1.0]{%i at %.2f fb^{-1}(13TeV)}" % (year, luminosity[year])) hist_nom.GetXaxis().SetRangeUser(values["min"], values["max"]) hist_nom.Draw("EP") for hist in hist_vars: hist.Draw("EPsame") legend.Draw("same") pad2.cd() #pad2.SetGridx(2) #pad2.SetGridy(2) bins = h_ratio.GetNbinsX() LowEdge = h_ratio.GetBinLowEdge(1) HighEdge = h_ratio.GetBinLowEdge(bins + 1) #LowEdge = h_ratio.GetBinLowEdge(0) #HighEdge = h_ratio.GetBinLowEdge(bins+2) line = TLine(LowEdge, 1, HighEdge, 1) line.SetLineColor(kBlack) h_ratio.GetXaxis().SetRangeUser(values["min"], values["max"]) h_ratio.SetFillColor(kGray + 3) h_ratio.SetFillStyle(3001) h_ratio.Draw("E2") h_ratio.SetMinimum(0.0) h_ratio.SetMaximum(2.0) for i in range(len(hist_ratio_vars)): hist_ratio_vars[i].Draw("EPsame") line.Draw("same") c.SaveAs("%s%s_%s_SF%s_isNorm%s_wtStat%s.png" % (outputdir, plotname, hist_nom_name, syst, normalization, showStats)) file.close()
leg.Draw() hFrame = cFracs.cd(2).DrawFrame( ptMin, 0., ptMax, 0.2, ';#it{p}_{T} (GeV/#it{c});#it{f}_{non-prompt}' ) hFrame.GetYaxis().SetDecimals() hFrame.GetYaxis().SetNdivisions(505) for histo, graph in zip(hFracNonPrompt, gFracNonPrompt): graph.Draw('2') histo.DrawCopy('same') line = TLine(ptMin, 1., ptMax, 1.) line.SetLineWidth(2) line.SetLineColor(GetROOTColor('kGrey+2')) line.SetLineStyle(9) hFrame = cFracs.cd(3).DrawFrame( ptMin, 0.9, ptMax, 1.1, f';#it{{p}}_{{T}} (GeV/#it{{c}});#it{{f}}_{{prompt}} / #it{{f}}_{{prompt}}^{{{ titles[0]}}}' ) hFrame.GetYaxis().SetDecimals() line.Draw() for histo in hRatioFracPrompt: if histo:
def pulls(fileName): with open(fileName) as f: content = f.readlines() content_nostat = [x for x in content if not 'CMS_stat' in x] nbins, off = len(content_nostat), 0.10 b_pulls = TH1F("b_pulls", ";;Pulls", nbins, 0. - off, nbins - off) s_pulls = TH1F("s_pulls", ";;Pulls", nbins, 0. + off, nbins + off) # for i, s in enumerate(content_nostat): l = s.split() b_pulls.GetXaxis().SetBinLabel(i + 1, l[0]) s_pulls.GetXaxis().SetBinLabel(i + 1, l[0]) b_pulls.SetBinContent(i + 1, float(l[1])) b_pulls.SetBinError(i + 1, float(l[2])) s_pulls.SetBinContent(i + 1, float(l[3])) s_pulls.SetBinError(i + 1, float(l[4])) b_pulls.SetFillStyle(3005) b_pulls.SetFillColor(923) b_pulls.SetLineColor(923) b_pulls.SetLineWidth(2) b_pulls.SetMarkerStyle(20) b_pulls.SetMarkerSize(1.25) s_pulls.SetLineColor(602) s_pulls.SetMarkerColor(602) s_pulls.SetMarkerStyle(24) #24 s_pulls.SetLineWidth(2) b_pulls.GetYaxis().SetRangeUser(-2.5, 2.5) c1 = TCanvas("c1", "Pulls", 1600, 800) c1.cd() c1.GetPad(0).SetTopMargin(0.06) c1.GetPad(0).SetRightMargin(0.05) c1.GetPad(0).SetBottomMargin(0.15) c1.GetPad(0).SetTicks(1, 1) # box = TBox(950., 105., 2000., 200.) # box.SetFillStyle(3354) # #box.SetFillStyle(0) # box.SetFillColor(1) # box.SetLineWidth(2) # box.SetLineStyle(2) # box.SetLineColor(1) # box.Draw() # Draw b_pulls.Draw("PE1") #b_pulls.Draw("B") s_pulls.Draw("SAME, PE1") leg = TLegend(0.25, 0.95, 0.75, 0.995) leg.SetBorderSize(0) leg.SetFillStyle(0) leg.SetFillColor(0) leg.SetNColumns(2) leg.AddEntry(b_pulls, "background-only fit", "flp") leg.AddEntry(s_pulls, "signal+background fit", "lp") line = TLine() line.DrawLine(0., 0., nbins, 0.) line.SetLineStyle(7) line.SetLineWidth(2) line.SetLineColor(417) line.DrawLine(0., 1., nbins, 1.) line.DrawLine(0., -1., nbins, -1.) line.SetLineColor(800) line.DrawLine(0., 2., nbins, 2.) line.DrawLine(0., -2., nbins, -2.) leg.Draw() # drawCMS(LUMI, "Simulation") # drawAnalysis("DM") # drawRegion(channel) # c1.Print(outName+".jpg") c1.Print(outName + ".png") c1.Print(outName + ".pdf") if not gROOT.IsBatch(): raw_input("Press Enter to continue...")
def addLine(theta, centerx, centery): line = TLine(centerx, centery, centerx + 200 * np.cos(theta), centery + 200 * np.sin(theta)) line.SetLineColor(2) return line
def printSystematic(self): fakeRate3, fakeRate3Error, ratio3, ratio3Error = self.printFakeRateRatio( 3) fakeRate4, fakeRate4Error, ratio4, ratio4Error = self.printFakeRateRatio( 4) fakeRate5, fakeRate5Error, ratio5, ratio5Error = self.printFakeRateRatio( 5) fakeRate6, fakeRate6Error, ratio6, ratio6Error = self.printFakeRateRatio( 6) print "systematic uncertainty: " + str( (abs(ratio5 - 1.0) + ratio5Error) * 100.0) + "%" basicFakeRate = TH1D("basicFakeRate", ";number of hits", 400, 2.5, 6.5) zToMuMuFakeRate = TH1D("zToMuMuFakeRate", ";number of hits", 400, 2.5, 6.5) ratio = TH1D("ratio", ";number of hits", 400, 2.5, 6.5) basicFakeRate.SetBinContent(basicFakeRate.FindBin(3.0), fakeRate3[0]) basicFakeRate.SetBinError(basicFakeRate.FindBin(3.0), fakeRate3Error[0]) basicFakeRate.SetBinContent(basicFakeRate.FindBin(4.0), fakeRate4[0]) basicFakeRate.SetBinError(basicFakeRate.FindBin(4.0), fakeRate4Error[0]) basicFakeRate.SetBinContent(basicFakeRate.FindBin(5.0), fakeRate5[0]) basicFakeRate.SetBinError(basicFakeRate.FindBin(5.0), fakeRate5Error[0]) basicFakeRate.SetBinContent(basicFakeRate.FindBin(6.0), fakeRate6[0]) basicFakeRate.SetBinError(basicFakeRate.FindBin(6.0), fakeRate6Error[0]) zToMuMuFakeRate.SetBinContent(zToMuMuFakeRate.FindBin(3.0), fakeRate3[1]) zToMuMuFakeRate.SetBinError(zToMuMuFakeRate.FindBin(3.0), fakeRate3Error[1]) zToMuMuFakeRate.SetBinContent(zToMuMuFakeRate.FindBin(4.0), fakeRate4[1]) zToMuMuFakeRate.SetBinError(zToMuMuFakeRate.FindBin(4.0), fakeRate4Error[1]) zToMuMuFakeRate.SetBinContent(zToMuMuFakeRate.FindBin(5.0), fakeRate5[1]) zToMuMuFakeRate.SetBinError(zToMuMuFakeRate.FindBin(5.0), fakeRate5Error[1]) zToMuMuFakeRate.SetBinContent(zToMuMuFakeRate.FindBin(6.0), fakeRate6[1]) zToMuMuFakeRate.SetBinError(zToMuMuFakeRate.FindBin(6.0), fakeRate6Error[1]) ratio.SetBinContent(ratio.FindBin(3.0), ratio3) ratio.SetBinError(ratio.FindBin(3.0), ratio3Error) ratio.SetBinContent(ratio.FindBin(4.0), ratio4) ratio.SetBinError(ratio.FindBin(4.0), ratio4Error) ratio.SetBinContent(ratio.FindBin(5.0), ratio5) ratio.SetBinError(ratio.FindBin(5.0), ratio5Error) ratio.SetBinContent(ratio.FindBin(6.0), ratio6) ratio.SetBinError(ratio.FindBin(6.0), ratio6Error) cmsLabel = TPaveText(0.134085, 0.937984, 0.418546, 0.984496, "brNDC") cmsLabel.SetBorderSize(0) cmsLabel.SetFillStyle(0) cmsLabel.SetTextFont(62) cmsLabel.SetTextSize(0.0387597) cmsLabel.AddText("CMS Preliminary") lumiLabel = TPaveText(0.66416, 0.937339, 0.962406, 0.992894, "brNDC") lumiLabel.SetBorderSize(0) lumiLabel.SetFillStyle(0) lumiLabel.SetTextFont(42) lumiLabel.SetTextSize(0.0387597) lumiLabel.AddText(str(self._luminosityLabel)) leg = TLegend(0.7550251, 0.7759067, 0.9459799, 0.8795337) leg.SetBorderSize(0) leg.SetTextSize(0.0388601) leg.SetTextFont(42) leg.SetLineColor(1) leg.SetLineStyle(1) leg.SetLineWidth(1) leg.SetFillColor(0) leg.SetFillStyle(0) leg.AddEntry(zToMuMuFakeRate, "Z#rightarrow#mu#mu", "p") leg.AddEntry(basicFakeRate, "basic", "p") setStyle(basicFakeRate, 632) setStyle(zToMuMuFakeRate, 600) setAxisStyle(basicFakeRate, yTitle="P_{fake}") setAxisStyle(zToMuMuFakeRate, yTitle="P_{fake}") self._canvas.cd() self._canvas.SetLogy() zToMuMuFakeRate.Draw() basicFakeRate.Draw("same") leg.Draw("same") cmsLabel.Draw("same") lumiLabel.Draw("same") self._fout.cd() self._canvas.Write("fakeRate") line = TLine(2.5, 1.0, 6.5, 1.0) line.SetLineStyle(2) line.SetLineWidth(2) line.SetLineColor(1) setStyle(ratio) setAxisStyle( ratio, yTitle=("P_{fake}^{Z#rightarrow#mu#mu} / P_{fake}^{basic}" if not self._plotDiff else "P_{fake}^{Z#rightarrow#mu#mu} - P_{fake}^{basic}")) self._canvas.cd() self._canvas.SetLogy(False) ratio.Draw() line.Draw("same") cmsLabel.Draw("same") lumiLabel.Draw("same") self._fout.cd() self._canvas.Write("fakeRateRatio")
pxlVsThr.append([item[ipix] for item in hitArray]) # Generate graphs for each pixel graphs = [] for ipixScan in pxlVsThr: graphs.append( TGraph(len(thrArray), array('d', thrArray), array('d', ipixScan))) # Draw graphs on canvas c1 = TCanvas("graph", "graph", 1024, 768) c1.cd() for i, graph in enumerate(graphs): if i == 0: graph.SetTitle('Threshold Scan;Threshold (DAC);Number of Hits') graph.GetYaxis().SetRangeUser(0, max(eventArray) * 1.1) graph.Draw("APL") else: graph.Draw("PL") # Add line for nMax line = TLine(0, max(eventArray), graphs[0].GetXaxis().GetXmax(), max(eventArray)) line.SetLineColor(2) line.Draw() print "Max number of events during scan: %s" % max(eventArray) raw_input("Press any key to exit")
def saveSigmaDev(self, legend, isData, log, lumi, hdata, hMC, r_ymin=-8, r_ymax=8, label="(Data - MC)/#sigma(MC)", outputDir='plots/', xlog=False): self.myCanvas.cd() pad1 = TPad("pad1", "pad1", 0, 0.25, 1, 1.0) pad1.SetBottomMargin(0.12) pad1.Draw() pad2 = TPad("pad2", "pad2", 0, 0.05, 1, 0.25) pad2.SetTopMargin(0.1) pad2.SetBottomMargin(0.3) pad2.Draw() pad1.cd() if (log): pad1.SetLogy(1) if (xlog): pad1.SetLogx(1) pad2.SetLogx(1) for i in range(0, len(self.histos)): if (self.ToDraw[i] != 0): if str(type(self.histos[i])) == "<class 'ROOT.TEfficiency'>": self.makeRate(self.histos[i], self.options[i]) else: self.histos[i].Draw(self.options[i]) if (legend): self.makeLegend() self.myLegend.SetTextSize(0.035) # Modify the legend size self.myLegend.Draw() for band in self.bands: band.Draw('f') for line in self.lines: line.Draw() for arrow in self.arrows: arrow.Draw() for latex in self.latexs: lat = TLatex() lat.SetNDC() lat.SetTextAlign(latex[-1]) lat.SetTextSize(latex[-2]) lat.SetTextFont(latex[-3]) lat.DrawLatex(latex[0], latex[1], latex[2]) if type(hMC) != list: hMClist = [hMC] else: hMClist = hMC devs = [] for tmp_hMC in hMClist: ind = hMClist.index(tmp_hMC) tmp_dev = hdata.Clone(tmp_hMC.GetName() + '_ratio') for n in range(1, tmp_dev.GetNbinsX() + 1): data_value = hdata.GetBinContent(n) MC_value = tmp_hMC.GetBinContent(n) MC_err = tmp_hMC.GetBinError(n) tmp_dev.SetBinContent(n, (data_value - MC_value) / MC_err) tmp_dev.SetTitle("") tmp_dev.GetYaxis().SetRangeUser(r_ymin, r_ymax) tmp_dev.GetYaxis().SetTitle(label) tmp_dev.GetYaxis().CenterTitle() tmp_dev.GetYaxis().SetLabelSize(0.12) tmp_dev.GetXaxis().SetLabelSize(0.12) tmp_dev.GetYaxis().SetTitleOffset(0.3) tmp_dev.GetYaxis().SetNdivisions(4) tmp_dev.GetYaxis().SetTitleSize(0.12) tmp_dev.GetXaxis().SetTitleSize(0.12) tmp_dev.GetXaxis().SetLabelOffset(0.08) tmp_dev.GetXaxis().SetTitle('') tmp_dev.SetFillColor(r.kRed + 1) tmp_dev.SetLineColor(r.kBlack) devs.append(tmp_dev) xmin = tmp_dev.GetBinLowEdge(1) xmax = tmp_dev.GetBinLowEdge(tmp_dev.GetNbinsX() + 1) #tmp_ratio.Draw("E,SAME"); pad2.cd() for dev in devs: dev.Draw('hist,same') line = TLine(xmin, 0, xmax, 0) line.SetLineColor(r.kGray + 2) line.Draw('') pad1.cd() self.banner2(isData, lumi) if not outputDir[-1] == '/': dirName = outputDir + '/' else: dirName = outputDir for i, plotName in enumerate(self.plotNames): pad1.cd() pad1.SetLogy(0) path = dirName + plotName pathlog = dirName + self.plotNamesLog[i] self.ensurePath(path) self.myCanvas.SaveAs(path) """ if not '.root' in pathlog: pad1.cd() pad1.SetLogy() self.myCanvas.SaveAs(pathlog) """ pad1.IsA().Destructor(pad1) pad2.IsA().Destructor(pad2) self.myLegend.IsA().Destructor(self.myLegend) self.myCanvas.IsA().Destructor(self.myCanvas)
def plot_sector_page(canvas, histos, title_formatter, label, save_name, xtitle=None, ytitle=None, title=None, log=False, y_fit_range=None, landscape=False, x_range=None, vline=None, hline=None): root_garbage_can = [] canvas.Clear() if landscape: canvas.Divide(3, 2) else: canvas.Divide(2, 3) for i in range(1, 7): canvas.cd(i) #if isinstance(histos[title_formatter.format(i)], TH1F): if isinstance(histos.get(title_formatter.format(i), default_histo), TH1F): if y_fit_range: fit = TF1(title_formatter.format(i) + '_fit', 'gaus') histos.get(title_formatter.format(i), default_histo).Fit(fit, '', 'R', y_fit_range[0], y_fit_range[1]) if x_range: histos.get(title_formatter.format(i), default_histo).GetXaxis().SetRangeUser( x_range[0], x_range[1]) histos.get(title_formatter.format(i), default_histo).SetFillColorAlpha(55, 0.65) histos.get(title_formatter.format(i), default_histo).Draw() if y_fit_range: label.DrawLatex( 0.15, 0.86, '#mu = {0:6.4f}, #sigma = {1:6.4f}'.format( fit.GetParameter(1), fit.GetParameter(2))) #elif isinstance(histos[title_formatter.format(i)], TH2F): elif isinstance(histos.get(title_formatter.format(i), default_histo), TH2F): # histos[title_formatter.format(i)].Draw('colz') histos.get(title_formatter.format(i), default_histo).Draw('colz') if log: gPad.SetLogz() else: #raise NotImplementedException('plot_sector_page only supports TH1F, TH2F') pass if vline: line = TLine( vline, histos.get(title_formatter.format(i), default_histo).GetYaxis().GetXmin(), vline, histos.get(title_formatter.format(i), default_histo).GetYaxis().GetXmax()) line.SetLineColor(1) line.SetLineStyle(1) line.Draw('same') root_garbage_can.append(line) if hline: xmin = histos.get(title_formatter.format(i)).GetXaxis().GetXmin() xmax = histos.get(title_formatter.format(i)).GetXaxis().GetXmax() line = TLine(xmin, hline, xmax, hline) line.SetLineColor(1) line.SetLineStyle(1) line.Draw('same') root_garbage_can.append(line) if title: label.DrawLatex(0.1, 0.925, title) if xtitle: label.DrawLatex(0.5, 0.015, xtitle) if ytitle: label.SetTextAngle(90) label.DrawLatex(0.04, 0.5, ytitle) label.SetTextAngle(0) canvas.Print(save_name)
sig1box7 = TPolyLine(4, sigboxX7, sig1boxY7) sig1box8 = TPolyLine(4, sigboxX8, sig1boxY8) sig1box = [ sig1box1, sig1box2, sig1box3, sig1box4, sig1box5, sig1box6, sig1box7, sig1box8 ] for box1 in sig1box: box1.SetLineColor(3) box1.SetFillColor(3) box1.Draw('f same') ################################# observed = [0.0777, 0.1223, 0.0791, 0.0597, 0.1496, 0.1103, 0.0890, 0.0726] expected = [0.1362, 0.0977, 0.1187, 0.1001, 0.1460, 0.1118, 0.1396, 0.1177] obs_hct_keras = TLine(0, xsec * observed[0], 1, xsec * observed[0]) obs_hct_bdt = TLine(1, xsec * observed[1], 2, xsec * observed[1]) obs_hct_keras_mat = TLine(2, xsec * observed[2], 3, xsec * observed[2]) obs_hct_bdt_mat = TLine(3, xsec * observed[3], 4, xsec * observed[3]) obs_hut_keras = TLine(4, xsec * observed[4], 5, xsec * observed[4]) obs_hut_bdt = TLine(5, xsec * observed[5], 6, xsec * observed[5]) obs_hut_keras_mat = TLine(6, xsec * observed[6], 7, xsec * observed[6]) obs_hut_bdt_mat = TLine(7, xsec * observed[7], 8, xsec * observed[7]) obs = [ obs_hct_keras, obs_hct_bdt, obs_hct_keras_mat, obs_hct_bdt_mat, obs_hut_keras, obs_hut_bdt, obs_hut_keras_mat, obs_hut_bdt_mat ] for lines in obs: lines.SetLineColor(2) lines.SetLineWidth(2) lines.Draw('same')
def main(): # pylint: disable=too-many-locals, too-many-statements, too-many-branches """ Main plotting function """ gROOT.SetBatch(True) # pylint: disable=unused-variable parser = argparse.ArgumentParser() parser.add_argument("--database-analysis", "-d", dest="database_analysis", help="analysis database to be used", required=True) parser.add_argument("--analysis", "-a", dest="type_ana", help="choose type of analysis", required=True) parser.add_argument("--input", "-i", dest="input_file", help="results input file", required=True) args = parser.parse_args() typean = args.type_ana shape = typean[len("jet_"):] print("Shape:", shape) file_in = args.input_file with open(args.database_analysis, "r") as file_db: data_param = yaml.safe_load(file_db) case = list(data_param.keys())[0] datap = data_param[case] logger = get_logger() i_cut = file_in.rfind("/") rootpath = file_in[:i_cut] # plotting # LaTeX string p_latexnhadron = datap["analysis"][typean]["latexnamehadron"] p_latexbin2var = datap["analysis"][typean]["latexbin2var"] v_varshape_latex = datap["analysis"][typean]["var_shape_latex"] # first variable (hadron pt) lpt_finbinmin = datap["analysis"][typean]["sel_an_binmin"] lpt_finbinmax = datap["analysis"][typean]["sel_an_binmax"] var1ranges = lpt_finbinmin.copy() var1ranges.append(lpt_finbinmax[-1]) # second variable (jet pt) v_var2_binning = datap["analysis"][typean]["var_binning2"] # name lvar2_binmin_reco = datap["analysis"][typean].get("sel_binmin2_reco", None) lvar2_binmax_reco = datap["analysis"][typean].get("sel_binmax2_reco", None) p_nbin2_reco = len(lvar2_binmin_reco) # number of reco bins lvar2_binmin_gen = datap["analysis"][typean].get("sel_binmin2_gen", None) lvar2_binmax_gen = datap["analysis"][typean].get("sel_binmax2_gen", None) p_nbin2_gen = len(lvar2_binmin_gen) # number of gen bins var2ranges_reco = lvar2_binmin_reco.copy() var2ranges_reco.append(lvar2_binmax_reco[-1]) var2binarray_reco = array( "d", var2ranges_reco) # array of bin edges to use in histogram constructors var2ranges_gen = lvar2_binmin_gen.copy() var2ranges_gen.append(lvar2_binmax_gen[-1]) var2binarray_gen = array( "d", var2ranges_gen) # array of bin edges to use in histogram constructors # observable (z, shape,...) v_varshape_binning = datap["analysis"][typean][ "var_binningshape"] # name (reco) v_varshape_binning_gen = datap["analysis"][typean][ "var_binningshape_gen"] # name (gen) lvarshape_binmin_reco = \ datap["analysis"][typean].get("sel_binminshape_reco", None) lvarshape_binmax_reco = \ datap["analysis"][typean].get("sel_binmaxshape_reco", None) p_nbinshape_reco = len(lvarshape_binmin_reco) # number of reco bins lvarshape_binmin_gen = \ datap["analysis"][typean].get("sel_binminshape_gen", None) lvarshape_binmax_gen = \ datap["analysis"][typean].get("sel_binmaxshape_gen", None) p_nbinshape_gen = len(lvarshape_binmin_gen) # number of gen bins varshaperanges_reco = lvarshape_binmin_reco.copy() varshaperanges_reco.append(lvarshape_binmax_reco[-1]) varshapebinarray_reco = array( "d", varshaperanges_reco ) # array of bin edges to use in histogram constructors varshaperanges_gen = lvarshape_binmin_gen.copy() varshaperanges_gen.append(lvarshape_binmax_gen[-1]) varshapebinarray_gen = array( "d", varshaperanges_gen ) # array of bin edges to use in histogram constructors file_results = TFile.Open(file_in) if not file_results: logger.fatal(make_message_notfound(file_in)) ibin2 = 1 suffix = "%s_%g_%g" % (v_var2_binning, lvar2_binmin_gen[ibin2], lvar2_binmax_gen[ibin2]) # HF data nameobj = "%s_hf_data_%d_stat" % (shape, ibin2) hf_data_stat = file_results.Get(nameobj) if not hf_data_stat: logger.fatal(make_message_notfound(nameobj, file_in)) nameobj = "%s_hf_data_%d_syst" % (shape, ibin2) hf_data_syst = file_results.Get(nameobj) if not hf_data_syst: logger.fatal(make_message_notfound(nameobj, file_in)) # HF PYTHIA nameobj = "%s_hf_pythia_%d_stat" % (shape, ibin2) hf_pythia_stat = file_results.Get(nameobj) if not hf_pythia_stat: logger.fatal(make_message_notfound(nameobj, file_in)) # HF ratio nameobj = "%s_hf_ratio_%d_stat" % (shape, ibin2) hf_ratio_stat = file_results.Get(nameobj) if not hf_ratio_stat: logger.fatal(make_message_notfound(nameobj, file_in)) nameobj = "%s_hf_ratio_%d_syst" % (shape, ibin2) hf_ratio_syst = file_results.Get(nameobj) if not hf_ratio_syst: logger.fatal(make_message_notfound(nameobj, file_in)) # inclusive data nameobj = "%s_incl_data_%d_stat" % (shape, ibin2) incl_data_stat = file_results.Get(nameobj) if not incl_data_stat: logger.fatal(make_message_notfound(nameobj, file_in)) nameobj = "%s_incl_data_%d_syst" % (shape, ibin2) incl_data_syst = file_results.Get(nameobj) if not incl_data_syst: logger.fatal(make_message_notfound(nameobj, file_in)) # inclusive PYTHIA nameobj = "%s_incl_pythia_%d_stat" % (shape, ibin2) incl_pythia_stat = file_results.Get(nameobj) if not incl_pythia_stat: logger.fatal(make_message_notfound(nameobj, file_in)) nameobj = "%s_incl_pythia_%d_syst" % (shape, ibin2) incl_pythia_syst = file_results.Get(nameobj) if not incl_pythia_syst: logger.fatal(make_message_notfound(nameobj, file_in)) # inclusive ratio nameobj = "%s_incl_ratio_%d_stat" % (shape, ibin2) incl_ratio_stat = file_results.Get(nameobj) if not incl_ratio_stat: logger.fatal(make_message_notfound(nameobj, file_in)) nameobj = "%s_incl_ratio_%d_syst" % (shape, ibin2) incl_ratio_syst = file_results.Get(nameobj) if not incl_ratio_syst: logger.fatal(make_message_notfound(nameobj, file_in)) # quark PYTHIA nameobj = "%s_quark_pythia_%d_stat" % (shape, ibin2) quark_pythia_stat = file_results.Get(nameobj) if not quark_pythia_stat: logger.fatal(make_message_notfound(nameobj, file_in)) nameobj = "%s_quark_pythia_%d_syst" % (shape, ibin2) quark_pythia_syst = file_results.Get(nameobj) if not quark_pythia_syst: logger.fatal(make_message_notfound(nameobj, file_in)) # gluon PYTHIA nameobj = "%s_gluon_pythia_%d_stat" % (shape, ibin2) gluon_pythia_stat = file_results.Get(nameobj) if not gluon_pythia_stat: logger.fatal(make_message_notfound(nameobj, file_in)) nameobj = "%s_gluon_pythia_%d_syst" % (shape, ibin2) gluon_pythia_syst = file_results.Get(nameobj) if not gluon_pythia_syst: logger.fatal(make_message_notfound(nameobj, file_in)) # plot the results with systematic uncertainties and models size_can = [800, 800] offsets_axes = [0.8, 1.1] margins_can = [0.1, 0.13, 0.1, 0.03] size_thg = 0.05 offset_thg = 0.85 gStyle.SetErrorX(0) # do not plot horizontal error bars of histograms fontsize = 0.035 opt_leg_g = "FP" opt_plot_g = "2" list_new = [] # list to avoid loosing objects created in loops # labels x_latex = 0.16 y_latex_top = 0.83 y_step = 0.055 title_x = v_varshape_latex title_y = "(1/#it{N}_{jet}) d#it{N}/d%s" % v_varshape_latex title_full = ";%s;%s" % (title_x, title_y) title_full_ratio = ";%s;data/MC: ratio of %s" % (title_x, title_y) text_alice = "#bf{ALICE} Preliminary, pp, #sqrt{#it{s}} = 13 TeV" text_alice_sim = "#bf{ALICE} Simulation, pp, #sqrt{#it{s}} = 13 TeV" text_pythia = "PYTHIA 8 (Monash)" text_pythia_split = "#splitline{PYTHIA 8}{(Monash)}" text_jets = "charged jets, anti-#it{k}_{T}, #it{R} = 0.4" text_ptjet = "%g #leq %s < %g GeV/#it{c}, #left|#it{#eta}_{jet}#right| #leq 0.5" % ( lvar2_binmin_reco[ibin2], p_latexbin2var, lvar2_binmax_reco[ibin2]) text_pth = "%g #leq #it{p}_{T}^{%s} < %g GeV/#it{c}, #left|#it{y}_{%s}#right| #leq 0.8" % ( lpt_finbinmin[0], p_latexnhadron, min(lpt_finbinmax[-1], lvar2_binmax_reco[ibin2]), p_latexnhadron) text_ptcut = "#it{p}_{T, incl. ch. jet}^{leading track} #geq 5.33 GeV/#it{c}" text_ptcut_sim = "#it{p}_{T, incl. ch. jet}^{leading h^{#pm}} #geq 5.33 GeV/#it{c} (varied)" text_sd = "Soft Drop (#it{z}_{cut} = 0.1, #it{#beta} = 0)" title_thetag = "#it{#theta}_{g} = #it{R}_{g}/#it{R}" radius_jet = 0.4 # colour and marker indeces c_hf_data = 0 c_incl_data = 1 c_hf_mc = 2 c_incl_mc = 6 c_quark_mc = 5 c_gluon_mc = 0 # markers m_hf_data = get_marker(0) m_incl_data = get_marker(1) m_hf_mc = get_marker(0, 2) m_incl_mc = get_marker(1, 2) m_quark_mc = get_marker(2) m_gluon_mc = get_marker(3) # make the horizontal error bars smaller if shape == "nsd": for gr in [ hf_data_syst, incl_data_syst, hf_ratio_syst, incl_ratio_syst, incl_pythia_syst, quark_pythia_syst, gluon_pythia_syst ]: for i in range(gr.GetN()): gr.SetPointEXlow(i, 0.1) gr.SetPointEXhigh(i, 0.1) # data, HF and inclusive hf_data_syst_cl = hf_data_syst.Clone() leg_pos = [.72, .75, .85, .85] list_obj = [hf_data_syst, incl_data_syst, hf_data_stat, incl_data_stat] labels_obj = ["%s-tagged" % p_latexnhadron, "inclusive", "", ""] colours = [ get_colour(i, j) for i, j in zip((c_hf_data, c_incl_data, c_hf_data, c_incl_data), (2, 2, 1, 1)) ] markers = [m_hf_data, m_incl_data, m_hf_data, m_incl_data] y_margin_up = 0.46 y_margin_down = 0.05 cshape_data, list_obj_data_new = make_plot("cshape_data_" + suffix, size=size_can, \ list_obj=list_obj, labels_obj=labels_obj, opt_leg_g=opt_leg_g, opt_plot_g=opt_plot_g, offsets_xy=offsets_axes, \ colours=colours, markers=markers, leg_pos=leg_pos, margins_y=[y_margin_down, y_margin_up], margins_c=margins_can, \ title=title_full) for gr, c in zip((hf_data_syst, incl_data_syst), (c_hf_data, c_incl_data)): gr.SetMarkerColor(get_colour(c)) list_obj_data_new[0].SetTextSize(fontsize) if shape == "nsd": hf_data_syst.GetXaxis().SetNdivisions(5) # Draw a line through the points. if shape == "nsd": for h in (hf_data_stat, incl_data_stat): h_line = h.Clone(h.GetName() + "_line") h_line.SetLineStyle(2) h_line.Draw("l hist same") list_new.append(h_line) cshape_data.Update() if shape == "rg": # plot the theta_g axis gr_frame = hf_data_syst axis_rg = gr_frame.GetXaxis() rg_min = axis_rg.GetBinLowEdge(axis_rg.GetFirst()) rg_max = axis_rg.GetBinUpEdge(axis_rg.GetLast()) thetag_min = rg_min / radius_jet thetag_max = rg_max / radius_jet y_axis = cshape_data.GetUymax() axis_thetag = TGaxis(rg_min, y_axis, rg_max, y_axis, thetag_min, thetag_max, 510, "-") axis_thetag.SetTitle(title_thetag) axis_thetag.SetTitleSize(size_thg) axis_thetag.SetLabelSize(0.036) axis_thetag.SetTitleFont(42) axis_thetag.SetLabelFont(42) axis_thetag.SetLabelOffset(0) axis_thetag.SetTitleOffset(offset_thg) cshape_data.SetTickx(0) axis_thetag.Draw("same") # Draw LaTeX y_latex = y_latex_top list_latex_data = [] for text_latex in [ text_alice, text_jets, text_ptjet, text_pth, text_ptcut, text_sd ]: latex = TLatex(x_latex, y_latex, text_latex) list_latex_data.append(latex) draw_latex(latex, textsize=fontsize) y_latex -= y_step cshape_data.Update() cshape_data.SaveAs("%s/%s_data_%s.pdf" % (rootpath, shape, suffix)) # data and PYTHIA, HF leg_pos = [.72, .65, .85, .85] list_obj = [hf_data_syst_cl, hf_data_stat, hf_pythia_stat] labels_obj = ["data", "", text_pythia_split] colours = [ get_colour(i, j) for i, j in zip((c_hf_data, c_hf_data, c_hf_mc), (2, 1, 1)) ] markers = [m_hf_data, m_hf_data, m_hf_mc] y_margin_up = 0.4 y_margin_down = 0.05 cshape_data_mc_hf, list_obj_data_mc_hf_new = make_plot("cshape_data_mc_hf_" + suffix, size=size_can, \ list_obj=list_obj, labels_obj=labels_obj, opt_leg_g=opt_leg_g, opt_plot_g=opt_plot_g, offsets_xy=offsets_axes, \ colours=colours, markers=markers, leg_pos=leg_pos, margins_y=[y_margin_down, y_margin_up], margins_c=margins_can, \ title=title_full) for gr, c in zip([hf_data_syst_cl], [c_hf_data]): gr.SetMarkerColor(get_colour(c)) leg_data_mc_hf = list_obj_data_mc_hf_new[0] leg_data_mc_hf.SetHeader("%s-tagged" % p_latexnhadron) leg_data_mc_hf.SetTextSize(fontsize) if shape == "nsd": hf_data_syst_cl.GetXaxis().SetNdivisions(5) #axis_nsd = hf_data_syst_cl.GetHistogram().GetXaxis() #x1 = axis_nsd.GetBinLowEdge(1) #x2 = axis_nsd.GetBinUpEdge(axis_nsd.GetNbins()) #axis_nsd.Set(5, x1, x2) #for ibin in range(axis_nsd.GetNbins()): # axis_nsd.SetBinLabel(ibin + 1, "%d" % ibin) #axis_nsd.SetNdivisions(5) cshape_data_mc_hf.Update() if shape == "rg": # plot the theta_g axis axis_rg = hf_data_stat.GetXaxis() rg_min = axis_rg.GetBinLowEdge(axis_rg.GetFirst()) rg_max = axis_rg.GetBinUpEdge(axis_rg.GetLast()) thetag_min = rg_min / radius_jet thetag_max = rg_max / radius_jet y_axis = cshape_data_mc_hf.GetUymax() axis_thetag = TGaxis(rg_min, y_axis, rg_max, y_axis, thetag_min, thetag_max, 510, "-") axis_thetag.SetTitle(title_thetag) axis_thetag.SetTitleSize(size_thg) axis_thetag.SetLabelSize(0.036) axis_thetag.SetTitleFont(42) axis_thetag.SetLabelFont(42) axis_thetag.SetLabelOffset(0) axis_thetag.SetTitleOffset(offset_thg) cshape_data_mc_hf.SetTickx(0) axis_thetag.Draw("same") # Draw LaTeX y_latex = y_latex_top list_latex_data_mc_hf = [] for text_latex in [text_alice, text_jets, text_ptjet, text_pth, text_sd]: latex = TLatex(x_latex, y_latex, text_latex) list_latex_data_mc_hf.append(latex) draw_latex(latex, textsize=fontsize) y_latex -= y_step cshape_data_mc_hf.Update() cshape_data_mc_hf.SaveAs("%s/%s_data_mc_hf_%s.pdf" % (rootpath, shape, suffix)) # data and PYTHIA, inclusive #leg_pos = [.68, .65, .85, .85] list_obj = [ incl_data_syst, incl_pythia_syst, incl_data_stat, incl_pythia_stat ] labels_obj = ["data", text_pythia_split] colours = [ get_colour(i, j) for i, j in zip((c_incl_data, c_incl_mc, c_incl_data, c_incl_mc), (2, 2, 1, 1)) ] markers = [m_incl_data, m_incl_mc, m_incl_data, m_incl_mc] y_margin_up = 0.4 y_margin_down = 0.05 cshape_data_mc_incl, list_obj_data_mc_incl_new = make_plot("cshape_data_mc_incl_" + suffix, size=size_can, \ list_obj=list_obj, labels_obj=labels_obj, opt_leg_g=opt_leg_g, opt_plot_g=opt_plot_g, offsets_xy=offsets_axes, \ colours=colours, markers=markers, leg_pos=leg_pos, margins_y=[y_margin_down, y_margin_up], margins_c=margins_can, \ title=title_full) for gr, c in zip([incl_data_syst, incl_pythia_syst], [c_incl_data, c_incl_mc]): gr.SetMarkerColor(get_colour(c)) leg_data_mc_incl = list_obj_data_mc_incl_new[0] leg_data_mc_incl.SetHeader("inclusive") leg_data_mc_incl.SetTextSize(fontsize) if shape == "nsd": incl_data_syst.GetXaxis().SetNdivisions(5) cshape_data_mc_incl.Update() if shape == "rg": # plot the theta_g axis axis_rg = incl_data_stat.GetXaxis() rg_min = axis_rg.GetBinLowEdge(axis_rg.GetFirst()) rg_max = axis_rg.GetBinUpEdge(axis_rg.GetLast()) thetag_min = rg_min / radius_jet thetag_max = rg_max / radius_jet y_axis = cshape_data_mc_incl.GetUymax() axis_thetag = TGaxis(rg_min, y_axis, rg_max, y_axis, thetag_min, thetag_max, 510, "-") axis_thetag.SetTitle(title_thetag) axis_thetag.SetTitleSize(size_thg) axis_thetag.SetLabelSize(0.036) axis_thetag.SetTitleFont(42) axis_thetag.SetLabelFont(42) axis_thetag.SetLabelOffset(0) axis_thetag.SetTitleOffset(offset_thg) cshape_data_mc_incl.SetTickx(0) axis_thetag.Draw("same") # Draw LaTeX y_latex = y_latex_top list_latex_data_mc_incl = [] for text_latex in [text_alice, text_jets, text_ptjet, text_ptcut, text_sd]: latex = TLatex(x_latex, y_latex, text_latex) list_latex_data_mc_incl.append(latex) draw_latex(latex, textsize=fontsize) y_latex -= y_step cshape_data_mc_incl.Update() cshape_data_mc_incl.SaveAs("%s/%s_data_mc_incl_%s.pdf" % (rootpath, shape, suffix)) # Ratios data/MC, HF and inclusive line_1 = TLine(lvarshape_binmin_reco[0], 1, lvarshape_binmax_reco[-1], 1) line_1.SetLineStyle(9) line_1.SetLineColor(1) line_1.SetLineWidth(3) #leg_pos = [.72, .7, .85, .85] # with header leg_pos = [.72, .75, .85, .85] # without header list_obj = [ hf_ratio_syst, line_1, incl_ratio_syst, hf_ratio_stat, incl_ratio_stat ] labels_obj = ["%s-tagged" % p_latexnhadron, "inclusive"] colours = [ get_colour(i, j) for i, j in zip((c_hf_data, c_incl_data, c_hf_data, c_incl_data), (2, 2, 1, 1)) ] markers = [m_hf_data, m_incl_data, m_hf_data, m_incl_data] y_margin_up = 0.52 y_margin_down = 0.05 if shape == "nsd": y_margin_up = 0.22 cshape_ratio, list_obj_ratio_new = make_plot("cshape_ratio_" + suffix, size=size_can, \ list_obj=list_obj, labels_obj=labels_obj, opt_leg_g=opt_leg_g, opt_plot_g=opt_plot_g, offsets_xy=offsets_axes, \ colours=colours, markers=markers, leg_pos=leg_pos, margins_y=[y_margin_down, y_margin_up], margins_c=margins_can, \ title=title_full_ratio) cshape_ratio.Update() for gr, c in zip((hf_ratio_syst, incl_ratio_syst), (c_hf_data, c_incl_data)): gr.SetMarkerColor(get_colour(c)) leg_ratio = list_obj_ratio_new[0] leg_ratio.SetTextSize(fontsize) #leg_ratio.SetHeader("data/MC") if shape == "nsd": hf_ratio_syst.GetXaxis().SetNdivisions(5) cshape_ratio.Update() if shape == "rg": # plot the theta_g axis gr_frame = hf_ratio_syst axis_rg = gr_frame.GetXaxis() rg_min = axis_rg.GetBinLowEdge(axis_rg.GetFirst()) rg_max = axis_rg.GetBinUpEdge(axis_rg.GetLast()) thetag_min = rg_min / radius_jet thetag_max = rg_max / radius_jet y_axis = cshape_ratio.GetUymax() axis_thetag = TGaxis(rg_min, y_axis, rg_max, y_axis, thetag_min, thetag_max, 510, "-") axis_thetag.SetTitle(title_thetag) axis_thetag.SetTitleSize(size_thg) axis_thetag.SetLabelSize(0.036) axis_thetag.SetTitleFont(42) axis_thetag.SetLabelFont(42) axis_thetag.SetLabelOffset(0) axis_thetag.SetTitleOffset(offset_thg) cshape_ratio.SetTickx(0) axis_thetag.Draw("same") # Draw LaTeX y_latex = y_latex_top list_latex_ratio = [] for text_latex in [ text_alice, text_jets, text_ptjet, text_pth, text_ptcut, text_sd, text_pythia ]: latex = TLatex(x_latex, y_latex, text_latex) list_latex_ratio.append(latex) draw_latex(latex, textsize=fontsize) y_latex -= y_step cshape_ratio.Update() cshape_ratio.SaveAs("%s/%s_ratio_%s.pdf" % (rootpath, shape, suffix)) # PYTHIA, HF, inclusive, quark, gluon incl_pythia_syst_cl = incl_pythia_syst.Clone() y_min_h, y_max_h = get_y_window_his([ hf_pythia_stat, incl_pythia_stat, quark_pythia_stat, gluon_pythia_stat ]) y_min_g, y_max_g = get_y_window_gr( [incl_pythia_syst, quark_pythia_syst, gluon_pythia_syst]) y_min = min(y_min_h, y_min_g) y_max = max(y_max_h, y_max_g) y_margin_up = 0.46 y_margin_down = 0.05 y_min_plot, y_max_plot = get_plot_range(y_min, y_max, y_margin_down, y_margin_up) #leg_pos = [.6, .65, .75, .85] leg_pos = [.72, .55, .85, .85] list_obj = [ incl_pythia_syst, quark_pythia_syst, gluon_pythia_syst, hf_pythia_stat, incl_pythia_stat, quark_pythia_stat, gluon_pythia_stat ] labels_obj = ["inclusive", "quark", "gluon", "%s-tagged" % p_latexnhadron] colours = [ get_colour(i, j) for i, j in zip((c_incl_mc, c_quark_mc, c_gluon_mc, c_hf_mc, c_incl_mc, c_quark_mc, c_gluon_mc), (2, 2, 2, 1, 1, 1, 1)) ] markers = [ m_incl_mc, m_quark_mc, m_gluon_mc, m_hf_mc, m_incl_mc, m_quark_mc, m_gluon_mc ] y_margin_up = 0.46 y_margin_down = 0.05 cshape_mc, list_obj_mc_new = make_plot("cshape_mc_" + suffix, size=size_can, \ list_obj=list_obj, labels_obj=labels_obj, opt_leg_g=opt_leg_g, opt_plot_g=opt_plot_g, offsets_xy=offsets_axes, \ colours=colours, markers=markers, leg_pos=leg_pos, range_y=[y_min_plot, y_max_plot], margins_c=margins_can, \ title=title_full) cshape_mc.Update() for gr, c in zip((incl_pythia_syst, quark_pythia_syst, gluon_pythia_syst), (c_incl_mc, c_quark_mc, c_gluon_mc)): gr.SetMarkerColor(get_colour(c)) leg_mc = list_obj_mc_new[0] leg_mc.SetTextSize(fontsize) leg_mc.SetHeader(text_pythia_split) if shape == "nsd": incl_pythia_syst.GetXaxis().SetNdivisions(5) cshape_mc.Update() if shape == "rg": # plot the theta_g axis axis_rg = hf_pythia_stat.GetXaxis() rg_min = axis_rg.GetBinLowEdge(axis_rg.GetFirst()) rg_max = axis_rg.GetBinUpEdge(axis_rg.GetLast()) thetag_min = rg_min / radius_jet thetag_max = rg_max / radius_jet y_axis = cshape_mc.GetUymax() axis_thetag = TGaxis(rg_min, y_axis, rg_max, y_axis, thetag_min, thetag_max, 510, "-") axis_thetag.SetTitle(title_thetag) axis_thetag.SetTitleSize(size_thg) axis_thetag.SetLabelSize(0.036) axis_thetag.SetTitleFont(42) axis_thetag.SetLabelFont(42) axis_thetag.SetLabelOffset(0) axis_thetag.SetTitleOffset(offset_thg) cshape_mc.SetTickx(0) axis_thetag.Draw("same") # Draw LaTeX y_latex = y_latex_top list_latex_mc = [] for text_latex in [ text_alice_sim, text_jets, text_ptjet, text_pth, text_ptcut_sim, text_sd ]: latex = TLatex(x_latex, y_latex, text_latex) list_latex_mc.append(latex) draw_latex(latex, textsize=fontsize) y_latex -= y_step cshape_mc.Update() cshape_mc.SaveAs("%s/%s_mc_%s.pdf" % (rootpath, shape, suffix)) # PYTHIA, HF, quark, gluon #leg_pos = [.6, .65, .75, .85] leg_pos = [.72, .61, .85, .85] list_obj = [ quark_pythia_syst, gluon_pythia_syst, hf_pythia_stat, quark_pythia_stat, gluon_pythia_stat ] labels_obj = ["quark", "gluon", "%s-tagged" % p_latexnhadron] colours = [ get_colour(i, j) for i, j in zip((c_quark_mc, c_gluon_mc, c_hf_mc, c_quark_mc, c_gluon_mc), (2, 2, 1, 1, 1)) ] markers = [m_quark_mc, m_gluon_mc, m_hf_mc, m_quark_mc, m_gluon_mc] y_margin_up = 0.46 y_margin_down = 0.05 cshape_mc, list_obj_mc_new = make_plot("cshape_mc_qgd_" + suffix, size=size_can, \ list_obj=list_obj, labels_obj=labels_obj, opt_leg_g=opt_leg_g, opt_plot_g=opt_plot_g, offsets_xy=offsets_axes, \ colours=colours, markers=markers, leg_pos=leg_pos, range_y=[y_min_plot, y_max_plot], margins_c=margins_can, \ title=title_full) cshape_mc.Update() for gr, c in zip((quark_pythia_syst, gluon_pythia_syst), (c_quark_mc, c_gluon_mc)): gr.SetMarkerColor(get_colour(c)) leg_mc = list_obj_mc_new[0] leg_mc.SetTextSize(fontsize) leg_mc.SetHeader(text_pythia_split) if shape == "nsd": quark_pythia_syst.GetXaxis().SetNdivisions(5) cshape_mc.Update() if shape == "rg": # plot the theta_g axis axis_rg = hf_pythia_stat.GetXaxis() rg_min = axis_rg.GetBinLowEdge(axis_rg.GetFirst()) rg_max = axis_rg.GetBinUpEdge(axis_rg.GetLast()) thetag_min = rg_min / radius_jet thetag_max = rg_max / radius_jet y_axis = cshape_mc.GetUymax() axis_thetag = TGaxis(rg_min, y_axis, rg_max, y_axis, thetag_min, thetag_max, 510, "-") axis_thetag.SetTitle(title_thetag) axis_thetag.SetTitleSize(size_thg) axis_thetag.SetLabelSize(0.036) axis_thetag.SetTitleFont(42) axis_thetag.SetLabelFont(42) axis_thetag.SetLabelOffset(0) axis_thetag.SetTitleOffset(offset_thg) cshape_mc.SetTickx(0) axis_thetag.Draw("same") # Draw LaTeX y_latex = y_latex_top list_latex_mc = [] for text_latex in [ text_alice_sim, text_jets, text_ptjet, text_pth, text_ptcut_sim, text_sd ]: latex = TLatex(x_latex, y_latex, text_latex) list_latex_mc.append(latex) draw_latex(latex, textsize=fontsize) y_latex -= y_step cshape_mc.Update() cshape_mc.SaveAs("%s/%s_mc_qgd_%s.pdf" % (rootpath, shape, suffix)) # PYTHIA, HF, inclusive #leg_pos = [.6, .65, .75, .85] leg_pos = [.72, .67, .85, .85] list_obj = [incl_pythia_syst_cl, incl_pythia_stat, hf_pythia_stat] labels_obj = ["inclusive", "", "%s-tagged" % p_latexnhadron] colours = [ get_colour(i, j) for i, j in zip((c_incl_mc, c_incl_mc, c_hf_mc), (2, 1, 1)) ] markers = [m_incl_mc, m_incl_mc, m_hf_mc] y_margin_up = 0.46 y_margin_down = 0.05 cshape_mc, list_obj_mc_new = make_plot("cshape_mc_id_" + suffix, size=size_can, \ list_obj=list_obj, labels_obj=labels_obj, opt_leg_g=opt_leg_g, opt_plot_g=opt_plot_g, offsets_xy=offsets_axes, \ colours=colours, markers=markers, leg_pos=leg_pos, range_y=[y_min_plot, y_max_plot], margins_c=margins_can, \ title=title_full) # Draw a line through the points. if shape == "nsd": for h in (incl_pythia_stat, hf_pythia_stat): h_line = h.Clone(h.GetName() + "_line") h_line.SetLineStyle(2) h_line.Draw("l hist same") list_new.append(h_line) cshape_mc.Update() incl_pythia_syst_cl.SetMarkerColor(get_colour(c_incl_mc)) leg_mc = list_obj_mc_new[0] leg_mc.SetTextSize(fontsize) leg_mc.SetHeader(text_pythia_split) if shape == "nsd": incl_pythia_syst_cl.GetXaxis().SetNdivisions(5) cshape_mc.Update() if shape == "rg": # plot the theta_g axis axis_rg = hf_pythia_stat.GetXaxis() rg_min = axis_rg.GetBinLowEdge(axis_rg.GetFirst()) rg_max = axis_rg.GetBinUpEdge(axis_rg.GetLast()) thetag_min = rg_min / radius_jet thetag_max = rg_max / radius_jet y_axis = cshape_mc.GetUymax() axis_thetag = TGaxis(rg_min, y_axis, rg_max, y_axis, thetag_min, thetag_max, 510, "-") axis_thetag.SetTitle(title_thetag) axis_thetag.SetTitleSize(size_thg) axis_thetag.SetLabelSize(0.036) axis_thetag.SetTitleFont(42) axis_thetag.SetLabelFont(42) axis_thetag.SetLabelOffset(0) axis_thetag.SetTitleOffset(offset_thg) cshape_mc.SetTickx(0) axis_thetag.Draw("same") # Draw LaTeX y_latex = y_latex_top list_latex_mc = [] for text_latex in [ text_alice_sim, text_jets, text_ptjet, text_pth, text_ptcut_sim, text_sd ]: latex = TLatex(x_latex, y_latex, text_latex) list_latex_mc.append(latex) draw_latex(latex, textsize=fontsize) y_latex -= y_step cshape_mc.Update() cshape_mc.SaveAs("%s/%s_mc_id_%s.pdf" % (rootpath, shape, suffix)) # data inclusive vs PYTHIA, quark, gluon #leg_pos = [.6, .65, .75, .85] #leg_pos = [.72, .55, .85, .85] leg_pos = [.6, .7, .85, .85] list_obj = [ incl_data_syst, quark_pythia_syst, gluon_pythia_syst, incl_data_stat, quark_pythia_stat, gluon_pythia_stat ] labels_obj = ["inclusive (data)", "quark (PYTHIA 8)", "gluon (PYTHIA 8)"] colours = [ get_colour(i, j) for i, j in zip((c_incl_data, c_quark_mc, c_gluon_mc, c_incl_data, c_quark_mc, c_gluon_mc), (2, 2, 2, 1, 1, 1)) ] markers = [ m_incl_data, m_quark_mc, m_gluon_mc, m_incl_data, m_quark_mc, m_gluon_mc ] y_margin_up = 0.3 y_margin_down = 0.05 cshape_mc, list_obj_mc_new = make_plot("cshape_mc_data_iqg" + suffix, size=size_can, \ list_obj=list_obj, labels_obj=labels_obj, opt_leg_g=opt_leg_g, opt_plot_g=opt_plot_g, offsets_xy=offsets_axes, \ colours=colours, markers=markers, leg_pos=leg_pos, margins_y=[y_margin_down, y_margin_up], margins_c=margins_can, \ title=title_full) for gr, c in zip((incl_data_syst, quark_pythia_syst, gluon_pythia_syst), (c_incl_data, c_quark_mc, c_gluon_mc)): gr.SetMarkerColor(get_colour(c)) leg_mc = list_obj_mc_new[0] leg_mc.SetTextSize(fontsize) cshape_mc.Update() cshape_mc.SaveAs("%s/%s_data_i_mc_qg_%s.pdf" % (rootpath, shape, suffix))
def plot_2(var,cuts): for s in attr: c1 = TCanvas("c1", "Signals", 1200, 800) if log_y == 1: c1.SetLogy() c1.SetTopMargin(0.08)#0.12 c1.SetBottomMargin(0.11)#0.12 c1.SetLeftMargin(0.14) c1.SetRightMargin(0.14)#0.24 c1.cd() #c1.SetGrid() gStyle.SetTitleFontSize(0.04) if ct_dep == 0: if s in ('elf','muf','cm','nm','chm'): c1.SetLogx() for cc in channel: #hist[cc][s].SetMaximum(0.44) if 'combind' in cc: fc = 30 #hist[cc][s].SetFillStyle()#3005) elif 'VBF' in cc: fc = 38 hist[cc][s].SetFillStyle(3444) elif 'HT50' in cc: fc = 7 hist[cc][s].SetFillStyle(3001) elif 'HT100' in cc: fc = 4 hist[cc][s].SetFillStyle(3002) elif 'HT200' in cc: fc = 6 hist[cc][s].SetFillStyle(3003) elif 'HT300' in cc: fc = 9 hist[cc][s].SetFillStyle(3004) if histFillColOn == 1: pass #hist[cc][s].SetFillColor(fc) hist[cc][s].Draw(histStyl) #legend = TLegend(0.76, 0.56, 0.99, 0.88) legend = TLegend(0.60, 0.9-0.04*2, 0.85, 0.9) #x_left y_bottom x_right y_top legend.SetBorderSize(0) legend.SetFillStyle(0)#1001 legend.SetFillColor(0) #legend.SetHeader( entry['entries'] ) for cc in channel: legend.AddEntry(hist[cc][s],cc) legend.Draw() for ct in cut_text: cut_text[ct].Draw() #>>>>>>>>>>>>>>>>>>>>>>>>>>>>>Line for critical value if s == 'chm': l = TLine(11.4,0.0,11.4,0.084) elif s == 'cHadEFrac': l = TLine(0.38,0.0,0.38,0.027) elif s == 'FracCal': l = TLine(30,0.0,30,0.44) #l.SetLineColor(2) #l.SetLineWidth(3) if critical_line == 1: l.SetLineColor(46)#4,2 l.SetLineWidth(3) l.Draw('same') c1.Print(path1 + s + var + cuts.replace('(','_').replace(')','_').replace('&&','_').replace('>','LG').replace('<','LS').replace('=','EQ').replace('.','P').replace('-','N').replace('Jet','J').replace('GenBquark','GBQ') + ".pdf") elif ct_dep == 1: eac0 = str( entries_after_cut['ct0'][s] ) c1.SetLogx() #gr = TGraph( len_of_lt , x , yy['sgn'][s] ) gr = TGraphErrors( len_of_lt , x , yy['sgn'][s] , ex , ey['sgn'][s] ) gr.SetMarkerSize(1.5) gr.SetMarkerStyle(1) gr.GetYaxis().SetTitleOffset(1.6) gr.SetLineColor(4) gr.SetLineWidth(4) gr.SetTitle('mean ' + s ) gr.GetXaxis().SetTitle('decaying length (mm)') gr.GetYaxis().SetTitle('mean normalized number of events') gr.GetXaxis().SetTitleOffset(1.4) gr.SetMaximum( plotrange[s] * 1.12 ) gr.SetName('sgn') gr.Draw('ACP') # '' sets up the scattering style gr1 = TGraphErrors( len_of_lt , x , yy['QCD'][s] , ex , ey['QCD'][s] ) gr1.SetMarkerSize(1.0) gr1.SetMarkerStyle(1) gr.GetYaxis().SetTitleOffset(1.6) gr1.SetLineColor(2) gr1.SetLineWidth(2) gr1.SetName('QCD') #gr1.SetTitle('averaged ' + s) #gr1.GetXaxis().SetTitle('decaying length (mm)') #gr1.GetYaxis().SetTitle('mean frequency') gr1.Draw('CP') # '' sets up the scattering style legend = TLegend(0.76, 0.56, 0.99, 0.88) legend.SetHeader( 'Entries: ' + eac0 ) legend.AddEntry('QCD', legendb, 'l') legend.AddEntry('sgn', legends, 'l') legend.Draw() for ct in cut_text: cut_text[ct].Draw() c1.Print(path1 + 'mean_' + s + var + cuts.replace('(','_').replace(')','_').replace('&&','_').replace('>','LG').replace('<','LS').replace('=','EQ').replace('.','P').replace('-','N').replace('Jet','J').replace('GenBquark','GBQ') + ".pdf") c1.Update() c1.Close() print('|||||||||||||||||||||||||||||||||||||||||||||||||||')
def plotDeltaTime(self): hDeltaTAllHo = self.fileHandler.getHistogram('L1MuonPresentHoMatch_DeltaTime') hDeltaTCleanHo = self.fileHandler.getHistogram('timingSupport_UnmatchedDtHo_DeltaTime') c = TCanvas("c","Delta Time",1200,1200) c.SetLogy() hDeltaTAllHo.SetLineColor(colorRwthDarkBlue) hDeltaTAllHo.SetLineWidth(3) hDeltaTAllHo.SetFillColor(colorRwthDarkBlue) hDeltaTAllHo.SetFillStyle(3017) hDeltaTAllHo.SetTitle("#Delta time") hDeltaTAllHo.SetStats(0) hDeltaTCleanHo.SetLineColor(8) hDeltaTCleanHo.SetFillColor(8) hDeltaTCleanHo.SetLineWidth(3) hDeltaTCleanHo.SetFillStyle(3002) #hDeltaTAllHo.Scale(1/hDeltaTAllHo.Integral()) #hDeltaTCleanHo.Scale(1/hDeltaTCleanHo.Integral()) print hDeltaTCleanHo.Integral(),hDeltaTAllHo.Integral() fitFirstMin = TF1("fitFirstMin","[0]+x*[1]+[2]*x**2") fitSecondMin = TF1("fitsecondMin","[0]+x*[1]+[2]*x**2",10,20) hDeltaTCleanHo.Fit(fitFirstMin,"+q","",-20,-10) hDeltaTCleanHo.Fit(fitSecondMin,"R+q","") hDeltaTAllHo.Draw() legend = TLegend(0.6,0.75,0.9,0.9) legend.AddEntry(hDeltaTAllHo,"L1Muon matched to any HO","le") legend.Draw() label = getLabelCmsPrivateSimulation() label.Draw() c.Update() self.storeCanvas(c,"deltaTimeAllHo") hDeltaTCleanHo.Draw('same') fitFirstMin.SetRange(-50,50) fitSecondMin.SetRange(-50,50) #fitFirstMin.Draw('lSame') #fitSecondMin.Draw('lSame') lineFirstMin = TLine(fitFirstMin.GetMinimumX(-20,-10),hDeltaTAllHo.GetMinimum(),fitFirstMin.GetMinimumX(-20,-10),hDeltaTAllHo.GetMaximum()) lineFirstMin.SetLineWidth(3) lineFirstMin.SetLineColor(colorRwthRot) lineFirstMin.Draw() lineSecondMin = TLine(fitSecondMin.GetMinimumX(10,20),hDeltaTAllHo.GetMinimum(),fitSecondMin.GetMinimumX(10,20),hDeltaTAllHo.GetMaximum()) lineSecondMin.SetLineWidth(3) lineSecondMin.SetLineColor(colorRwthRot) lineSecondMin.Draw() legend.AddEntry(hDeltaTCleanHo,"L1Muon matched to HO > 0.2 GeV","le") legend.AddEntry(lineFirstMin,"Integral boundaries","e") legend.Draw() integralCenter = hDeltaTCleanHo.Integral(hDeltaTCleanHo.FindBin(fitFirstMin.GetMinimumX(-20,-10)),hDeltaTCleanHo.FindBin(fitSecondMin.GetMinimumX(10,20))) integralCenterAll = hDeltaTAllHo.Integral(hDeltaTAllHo.FindBin(fitFirstMin.GetMinimumX(-20,-10)),hDeltaTAllHo.FindBin(fitSecondMin.GetMinimumX(10,20))) self.debug(80*'#') self.debug('Integral of center area in clean histogram :%d' % integralCenter) self.debug('==> %.2f%% +/- %.2f%%' % (integralCenter/hDeltaTCleanHo.Integral()*100 ,calcSigma(integralCenter, hDeltaTCleanHo.Integral())*100)) self.debug('Integral of center area in all matched HO events:%d' % integralCenterAll) self.debug('==> %.2f%% +/- %.2f%%' % (integralCenterAll/hDeltaTAllHo.Integral()*100 ,calcSigma(integralCenterAll, hDeltaTAllHo.Integral())*100)) self.debug(80*'#') paveText = TPaveText(0.6,0.7,0.9,0.75,'NDC') paveText.AddText('%s' % ('Central peak contains (filtered hist.)')) paveText.AddText('%.2f%% +/- %.2f%%' % (integralCenter/hDeltaTCleanHo.Integral()*100,calcSigma(integralCenter, hDeltaTCleanHo.Integral())*100)) paveText.SetBorderSize(1) paveText.Draw() label = getLabelCmsPrivateSimulation() label.Draw() c.Update() self.storeCanvas(c,"deltaTime") return c, hDeltaTCleanHo
def Plot2DCorrection(hist2D, graph, f1, etBin=None, etaBin=None, outname=None, xlabel='N_{vtx}', runLabel=None, legends=None, extraText1=None, legendX1=.5, etidx=None, etaidx=None, etlist=None, etalist=None): import array as ar from ROOT import TCanvas, gStyle, TLegend, kRed, kBlue, kBlack, TLine, kBird, kOrange from ROOT import TGraphErrors, TF1, TColor pileup_max = hist2D.GetYaxis().GetXmax() pileup_min = hist2D.GetYaxis().GetXmin() # Retrieve some usefull information gStyle.SetPalette(kBird) canvas = TCanvas('canvas', 'canvas', 500, 500) #FormatCanvasAxes(canvas, XLabelSize=18, YLabelSize=18, XTitleOffset=0.87, YTitleOffset=1.5) canvas.SetRightMargin(0.12) canvas.SetLeftMargin(0.10) hist2D.Draw('colz') hist2D.GetZaxis().SetTitle("Entries") canvas.SetLogz() AddTopLabels(canvas, legends, runLabel=runLabel, legOpt='p', etlist=etlist, etalist=etalist, etidx=etidx, etaidx=etaidx) FormatCanvasAxes(canvas, XLabelSize=12, YLabelSize=12, XTitleOffset=0.87, ZLabelSize=12, ZTitleSize=14, YTitleOffset=0.87, ZTitleOffset=0.67) SetAxisLabels(canvas, 'Neural Network output (Discriminant)', xlabel) # Invert graph import array x = graph.GetX() x.SetSize(graph.GetN()) ex = graph.GetEX() ex.SetSize(graph.GetN()) y = graph.GetY() y.SetSize(graph.GetN()) ey = graph.GetEY() ey.SetSize(graph.GetN()) nvtx_points = array.array('d', x) nvtx_error_points = array.array('d', ex) discr_points = array.array('d', y) discr_error_points = array.array('d', ey) g1 = TGraphErrors(len(discr_points), discr_points, nvtx_points, discr_error_points, nvtx_error_points) g1.SetLineWidth(1) #g1.SetLineColor(kBlack) g1.SetMarkerColor(kBlue + 1) g1.SetMarkerSize(.6) g1.Draw("P same") tobject_collector.append(g1) #l2 = TLine(eff_uncorr.thres,miny,eff_uncorr.thres,maxy) #l2.SetLineColor(kRed) #l2.SetLineWidth(2) #l2.Draw("l,same") #tobject_collector.append(l2) #f1 = eff.f1 if type(f1) is not list: f1 = [f1] for idx, f in enumerate(f1): l3 = TLine(f.Eval(pileup_min), pileup_min, f.Eval(pileup_max), pileup_max) if idx > 0: l3.SetLineColor(GetTransparent(kRed)) else: l3.SetLineColor(kBlack) l3.SetLineWidth(2) l3.Draw("l,same") tobject_collector.append(l3) if outname: canvas.SaveAs(outname)
def outputErrors(self): # Output all kinds of info to a file rootFileName = "%s/CertificationSummaries.root" % (self.saveDirectory) rootFile = TFile(rootFileName, "RECREATE") print "\nWriting summary root file %s" % (rootFileName) sortedRuns = sorted(self.run_trig_ls) try: fileName = "CertificationSummary_run" + str( sortedRuns[0]) + "_run" + str(sortedRuns[-1]) + ".txt" file = open( self.saveDirectory + "/" + fileName, 'w') # come up with a name based on something about the runs print "\nCertification Summary txt file: %s/%s \n" % ( self.saveDirectory, fileName) except: print "Error writing certification summary ." return for runNumber in sortedRuns: file.write("Run Number: %s\n" % (runNumber)) file.write("\n") file.write(" TRIGGERS: BAD LUMIECTION(S) \n") file.write("\n") totalErrs = 0 badLumiList = {} badLumiListSorted = {} for triggerName in sorted(self.run_trig_ls[runNumber]): file.write(" %s: " % (triggerName)) list = formatJSON( sorted(self.run_trig_ls[runNumber][triggerName])) file.write(list + "\n") for LS in sorted(self.run_trig_ls[runNumber][triggerName]): if badLumiList.has_key(LS): badLumiList[LS] += 1 else: badLumiList[LS] = 1 file.write("\n") totalLumis = len( self.run_allLs[runNumber][self.run_allLs[runNumber].keys()[0]]) minLumi = min( self.run_allLs[runNumber][self.run_allLs[runNumber].keys()[0]]) maxLumi = max( self.run_allLs[runNumber][self.run_allLs[runNumber].keys()[0]]) # maxNumBadPaths = sorted(badLumiListSorted.keys(), reverse =True)[0] maxNumBadPaths = len(self.run_allLs[runNumber]) canvas = TCanvas("can", "can", 1000, 600) canvas.SetName("Certification Summary of Run %s" % runNumber) canvas.SetGridx(1) canvas.SetGridy(1) summaryHist = TH1D("Certification_Summary_of_Run%s" % (runNumber), "Run %s" % (runNumber), (totalLumis + 2), (minLumi - 1), (maxLumi + 1)) summaryHist.GetXaxis().SetTitle("LS") summaryHist.GetYaxis().SetTitle("Number of bad paths") summaryHist.SetMaximum(1.2 * maxNumBadPaths) #sort the dict so the number of bad triggers is now the key for LS in sorted(badLumiList.keys(), key=badLumiList.__getitem__, reverse=True): summaryHist.Fill(LS, badLumiList[LS]) if badLumiListSorted.has_key(badLumiList[LS]): badLumiListSorted[badLumiList[LS]].append(LS) else: badLumiListSorted[badLumiList[LS]] = [LS] testVariable = 0 file.write(" # OF BAD PATHS : LUMISECTION(S)\n") file.write("\n") for numBadTrigs in sorted(badLumiListSorted.keys(), reverse=True): testVariable += numBadTrigs * (len( sorted(badLumiListSorted[numBadTrigs]))) file.write( " %s : %s\n" % (numBadTrigs, sorted(badLumiListSorted[numBadTrigs]))) totalErrs += len(sorted(badLumiListSorted[numBadTrigs])) maxLine = TLine(minLumi - 1, maxNumBadPaths, maxLumi + 1, maxNumBadPaths) maxLine.SetLineStyle(9) maxLine.SetLineColor(2) maxLine.SetLineWidth(2) summaryHist.Draw("hist") summaryHist.SetLineColor(4) summaryHist.SetFillColor(4) summaryHist.SetFillStyle(3004) canvas.Update() latex = TLatex() latex.SetNDC() latex.SetTextColor(1) latex.SetTextAlign(11) latex.SetTextFont(62) latex.SetTextSize(0.05) latex.DrawLatex(0.15, 0.84, "CMS") latex.SetTextSize(0.035) latex.SetTextFont(52) latex.DrawLatex(0.15, 0.80, "Rate Monitoring") canvas.Update() maxLine.Draw("same") canvas.Update() canvas.Modified() canvas.Write() canvas.Print( "%s/CertificationSummary_run%s.png" % (self.saveDirectory, runNumber), "png") fractionBadLumis = 100. * float(totalErrs) / float(totalLumis) fractionBadRun = 100. * summaryHist.Integral() / float( (totalLumis + 2) * maxNumBadPaths) file.write("\n") file.write("BAD LS SUMMARY: \n") file.write( "\n---- Total bad LS: %s ( bad LS: >= 1 trigger(s) deviating more than 3 sigma from prediction )\n" % (totalErrs)) file.write("---- Total LS: %s\n" % (totalLumis)) file.write("---- Fraction bad LS: %s\n" % (fractionBadLumis)) fractionBadpaths = (100. * (float(testVariable) / (float(totalLumis * maxNumBadPaths)))) totalPossPaths = float(totalLumis * maxNumBadPaths) totalBadPaths = float(testVariable) file.write("\n") file.write("BAD PATH SUMMARY: \n") file.write("\n") file.write("---- Total Bad Paths: %.1f\n" % (totalBadPaths)) file.write("---- Total Possible Paths: %.1f\n" % (totalPossPaths)) file.write("---- Fraction that are Bad Paths: %.1f\n" % (float(fractionBadpaths))) file.write("\n") file.write( "----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------\n" ) file.close() rootFile.Close()
# h_pionplus_long_trans.GetYaxis().SetTitleFont(12) h_pionplus_long_trans.GetXaxis().SetRangeUser(0, 130) h_pionplus_long_trans.GetYaxis().SetRangeUser(0, 5) h_pionplus_long_trans.GetXaxis().SetLabelSize(0.05) h_pionplus_long_trans.GetXaxis().SetTitleSize(0.05) h_pionplus_long_trans.GetYaxis().SetLabelSize(0.05) h_pionplus_long_trans.GetYaxis().SetTitleSize(0.05) cpionplus_long_trans.SetLeftMargin(0.15) cpionplus_long_trans.SetBottomMargin(0.12) cpionplus_long_trans.SetRightMargin(0.14) gStyle.SetTitleH(0.07) h_pionplus_long_trans.Draw("colz") # Seun's K/pi measurements (MIPP, thick target, so with tptype particle) [FERMILAB-THESIS-2007-61] line1 = TLine(20, 0, 20, 1) line2 = TLine(20, 1, 24, 1) line3 = TLine(24, 1, 24, 1.2) line4 = TLine(24, 1.2, 31, 1.2) line5 = TLine(31, 1.2, 31, 1.55) line6 = TLine(31, 1.55, 42, 1.55) line7 = TLine(42, 1.55, 42, 2) line8 = TLine(42, 2, 60, 2) line9 = TLine(60, 2, 90, 2) line10 = TLine(90, 2, 90, 0) line11 = TLine(90, 0, 20, 0) lineVector = [ line1, line2, line3, line4, line5, line6, line7, line8, line9, line10, line11 ]
# ______________________________________________________________________________ if __name__ == '__main__': from ROOT import gROOT, gPad, gStyle, TFile, TCanvas, TH1F, TH2F, TPolyLine, TLatex, TColor, TEfficiency, TLine, TLatex, TGraph, TGraphAsymmErrors # ____________________________________________________________________________ # Setup basic drawer gROOT.LoadMacro("tdrstyle.C") gROOT.ProcessLine("setTDRStyle();") #gROOT.SetBatch(True) gStyle.SetPadGridX(True) gStyle.SetPadGridY(True) gStyle.SetMarkerStyle(1) gStyle.SetEndErrorSize(0) gROOT.ForceStyle() tline = TLine() tline.SetLineColor(920 + 2) # kGray+2 tline.SetLineStyle(2) tlatexCMS1 = TLatex() tlatexCMS1.SetNDC() tlatexCMS1.SetTextFont(61) tlatexCMS1.SetTextSize(0.75 * 0.05) tlatexCMS2 = TLatex() tlatexCMS2.SetNDC() tlatexCMS2.SetTextFont(52) tlatexCMS2.SetTextSize(0.60 * 0.05) tlatexCMS3 = TLatex() tlatexCMS3.SetNDC()
gr1.GetXaxis().SetLimits(math.pow(10, 10 + 0 * 0.5), math.pow(10, 10 + 16 * 0.5)) leg1 = TLegend(0.2, 0.7, 0.5, 0.9) leg1.SetFillColor(0) leg1.SetFillStyle(0) leg1.SetTextSize(0.05) leg1.SetBorderSize(0) leg1.SetTextFont(22) leg1.AddEntry("", "GeIA group", "") leg1.AddEntry("", "Avalanche region:", "") leg1.AddEntry(gr, str(Avalanche_region) + "cm(Square)", "lp") leg1.AddEntry(gr1, str(Avalanche_region1) + "cm(Circle)", "lp") line = TLine( math.pow(10, 15), 0, math.pow(10, 15), Number_of_Atom(Avalanche_region, math.pow(math.pow(10, 15), 0.33))) line1 = TLine( math.pow(10, 16), 0, math.pow(10, 16), Number_of_Atom(Avalanche_region, math.pow(math.pow(10, 16), 0.33))) line3 = TLine(math.pow(10, 15), 0, math.pow(10, 16), 0) line3.SetLineWidth(10) gr1.Draw("ALP") gr.Draw("LPsame") line.Draw("Lsame") line1.Draw("Lsame") c.SetLogx() #c.SetLogy() c.Draw() leg1.Draw()
def drawCut(cut, ymin, ymax): line = TLine() line.SetLineWidth(2) line.SetLineStyle(7) line.SetLineColor(1) line.PaintLineNDC(cut, ymin, cut, ymax)
def __applyThresholdCorrection( self, refValue, sgn_hist2D, bkg_hist2D, partition_name, output_name, **kwargs): legend_position = retrieve_kw( kwargs, 'legend_position', (0.36,0.20,0.66,0.40)) useNoActivationFunctionInTheLastLayer=retrieve_kw(kwargs,'useNoActivationFunctionInTheLastLayer',False) xname = retrieve_kw( kwargs, 'xname', 'n_{vtx}' ) draw = retrieve_kw( kwargs, 'draw', False) limits = retrieve_kw( kwargs, 'limits', [0,10,20]) dovertical = retrieve_kw( kwargs, 'dovertical' , False) mumin = limits[0]; mumax=limits[-1] mubins = mumax-mumin from TrigEgammaDevelopments.helper.util import * sgn_hist2D = copy2DRegion(sgn_hist2D,1000,-12,7,mubins,mumin,mumax) bkg_hist2D = copy2DRegion(bkg_hist2D,1000,-12,7,mubins,mumin,mumax) from copy import deepcopy refValue_requested = refValue false_alarm = 1.0 false_alarm_limit = 0.20 while false_alarm > false_alarm_limit: # Calculate the original threshold b0, error = find_threshold(sgn_hist2D.ProjectionX(), refValue ) # Take eff points using uncorrection threshold discr_points, nvtx_points, error_points = calculate_dependent_discr_points(sgn_hist2D , refValue ) # Calculate eff without correction sgn_histNum, sgn_histDen, sgn_histEff, det0 = calculate_efficiency(sgn_hist2D, refValue, b0, 0, doCorrection=False) # Generate correction parameters and produce fixed plots sgn_histNum_corr, sgn_histDen_corr, sgn_histEff_corr, detection ,b, a = calculate_efficiency( sgn_hist2D, refValue, b0, 0, limits = limits, doCorretion=True) # Calculate eff without correction bkg_histNum, bkg_histDen, bkg_histEff, _ = calculate_efficiency(bkg_hist2D, refValue, b0, 0, doCorrection=False) # Calculate eff using the correction from signal bkg_histNum_corr, bkg_histDen_corr, bkg_histEff_corr, false_alarm = calculate_efficiency(bkg_hist2D, refValue, b, a, doCorrection=False) if false_alarm > false_alarm_limit: refValue-=0.025 # To np.array discr_points = np.array(discr_points) # Plot correction if draw: # Retrieve some usefull information y_max = sgn_hist2D.GetYaxis().GetXmax() y_min = sgn_hist2D.GetYaxis().GetXmin() x_min = y_min; x_max = y_max from ROOT import TCanvas, gStyle, TLegend, kRed, kBlue, kBlack,TLine from ROOT import TGraphErrors,TF1 gStyle.SetPalette(107) if dovertical: canvas = TCanvas('canvas','canvas',1600,2000) canvas.Divide(2,3) else: canvas = TCanvas('canvas','canvas',2800,1600) canvas.Divide(3,2) pad1= canvas.cd(1) sgn_histEff.SetTitle('Signal Efficiency in: '+partition_name) sgn_histEff.SetLineColor(kRed) sgn_histEff.SetMarkerColor(kRed) sgn_histEff.GetYaxis().SetTitle('#epsilon('+xname+')') sgn_histEff.GetXaxis().SetTitle(xname) sgn_histEff.GetYaxis().SetRangeUser( 0.6, 1.1 ) sgn_histEff.Draw() sgn_histEff_corr.SetLineColor(kBlack) sgn_histEff_corr.SetMarkerColor(kBlack) sgn_histEff_corr.Draw('sames') l0 = TLine(x_min,refValue_requested,x_max,refValue_requested) l0.SetLineColor(kBlack) l0.Draw() l1 = TLine(x_min,refValue,x_max,refValue) l1.SetLineColor(kBlack) l1.SetLineStyle(9) l1.Draw() leg1 = TLegend(legend_position[0],legend_position[1], legend_position[2],legend_position[3]) setLegend1(leg1) leg1.SetHeader('Signal efficiency in '+partition_name) leg1.AddEntry(sgn_histEff,('Old: d = %1.3f')%(b0),'p' ) lg1 = leg1.AddEntry(sgn_histEff_corr,('New: d = %1.3f + %s %1.3f')%(b,xname,a),'p' ) lg1.SetTextColor(kRed) leg1.AddEntry(l1,('Reference: %1.3f')%(refValue) ,'l') leg1.SetTextSize(0.03) leg1.SetBorderSize(0) leg1.Draw() atlas_template(pad1,**kwargs) pad2 = canvas.cd(2) if dovertical else canvas.cd(4) bkg_histEff.SetTitle('Background rejection in: '+partition_name) bkg_histEff.SetLineColor(kRed) bkg_histEff.SetMarkerColor(kRed) bkg_histEff.GetYaxis().SetTitle('#epsilon('+xname+')') bkg_histEff.GetXaxis().SetTitle(xname) bkg_histEff.Draw() bkg_histEff_corr.SetLineColor(kBlack) bkg_histEff_corr.SetMarkerColor(kBlack) bkg_histEff_corr.Draw('sames') l0.Draw() l1.Draw() leg2 = TLegend(legend_position[0],legend_position[1]+0.4, legend_position[2],legend_position[3]+0.4) setLegend1(leg2) leg2.SetHeader('Background rejection in '+partition_name) leg2.AddEntry(sgn_histEff,('Old: d = %1.3f')%(b0),'p' ) lg2 = leg2.AddEntry(sgn_histEff_corr,('New: d = %1.3f + %s %1.3f')%(b,xname,a),'p' ) lg2.SetTextColor(kRed) leg2.SetTextSize(0.03) leg2.SetBorderSize(0) leg2.Draw() atlas_template(pad2,**kwargs) pad3 = canvas.cd(3) if dovertical else canvas.cd(2) sgn_hist2D.SetTitle('Neural Network output as a function fo nvtx, '+partition_name) sgn_hist2D.GetXaxis().SetTitle('Neural Network output (Discriminant)') sgn_hist2D.GetYaxis().SetTitle(xname) sgn_hist2D.GetZaxis().SetTitle('') if not useNoActivationFunctionInTheLastLayer: sgn_hist2D.SetAxisRange(-1,1, 'X' ) sgn_hist2D.Draw('colz') pad3.SetLogz() # Add points g1 = TGraphErrors(len(discr_points), discr_points, np.array(nvtx_points)+limits[0], np.array(error_points), np.zeros(discr_points.shape)) g1.SetLineWidth(1) g1.SetLineColor(kBlue) g1.SetMarkerColor(kBlue) g1.Draw("P same") # Old threshold line l2 = TLine(b0,y_min,b0,y_max) l2.SetLineColor(kRed) l2.SetLineWidth(2) l2.Draw() # New threshold line l3 = TLine(b,y_min, a*y_max+b, y_max) l3.SetLineColor(kBlack) l3.SetLineWidth(2) l3.Draw() atlas_template(pad3,**kwargs) pad4 = canvas.cd(4) if dovertical else canvas.cd(5) bkg_hist2D.SetTitle('Neural Network output as a function fo nvtx, '+partition_name) bkg_hist2D.GetXaxis().SetTitle('Neural Network output (Discriminant)') bkg_hist2D.GetYaxis().SetTitle(xname) bkg_hist2D.GetZaxis().SetTitle('') if not useNoActivationFunctionInTheLastLayer: bkg_hist2D.SetAxisRange(-1,1, 'X' ) #sgn_hist2D.SetAxisRange(b+y_max*a-0.2,1, 'X' ) bkg_hist2D.Draw('colz') pad4.SetLogz() # Add points g2 = TGraphErrors(len(discr_points), discr_points, np.array(nvtx_points)+limits[0], np.array(error_points), np.zeros(discr_points.shape)) g2.SetLineWidth(1) g2.SetLineColor(kBlue) g2.SetMarkerColor(kBlue) g2.Draw("P same") # Old threshold line l4 = TLine(b0,y_min,b0,y_max) l4.SetLineColor(kRed) l4.SetLineWidth(2) l4.Draw() # New threshold line l5 = TLine(b,y_min, a*y_max+b, y_max) l5.SetLineColor(kBlack) l5.SetLineWidth(2) l5.Draw() atlas_template(pad4,**kwargs) from ROOT import TH1D, kAzure from TrigEgammaDevelopments.plots import AutoFixAxes pad5 = canvas.cd(5) if dovertical else canvas.cd(3) #pad5.SetLogy() h5 = TH1D(sgn_hist2D.ProjectionX()) h6 = TH1D(bkg_hist2D.ProjectionX()) if max(h5.GetMaximum(),h6.GetMaximum()) > 10*(min(h5.GetMaximum(),h6.GetMaximum())): pad5.SetLogy() h5.Rebin(10) h6.Rebin(10) h5.SetLineColor(kAzure+6) h5.SetFillColor(kAzure+6) h6.SetLineColor(kRed-7) h5.Draw() h6.Draw('sames') AutoFixAxes(pad5,False,False,1.5) atlas_template(pad5,**kwargs) pad6 = canvas.cd(6) #pad6.SetLogy() h7 = TH1D(bkg_hist2D.ProjectionX()) h8 = TH1D(sgn_hist2D.ProjectionX()) if max(h7.GetMaximum(),h8.GetMaximum()) > 10*(min(h7.GetMaximum(),h8.GetMaximum())): pad6.SetLogy() h7.Rebin(10) h8.Rebin(10) h7.SetLineColor(kRed-7) h7.SetFillColor(kRed-7) h8.SetLineColor(kAzure+6) h7.Draw() h8.Draw('sames') AutoFixAxes(pad6,False,False,1.5) atlas_template(pad6,**kwargs) canvas.SaveAs(output_name+'.pdf') return b,a,b0