def Compare(w, output, fn1, fn2, bins, var, other_vars= {}, line_pos=None): label_vars = [] for key, val in other_vars.iteritems(): w.var(key).setVal(val) label_vars.append('%s=%g' % (key, val)) h1 = w.function(fn1).createHistogram(fn1, w.var(var), ROOT.RooFit.Binning(*bins), ROOT.RooFit.Scaling(False) ) h2 = w.function(fn2).createHistogram(fn2, w.var(var), ROOT.RooFit.Binning(*bins), ROOT.RooFit.Scaling(False) ) canv = ROOT.TCanvas(output, output) pads = plot.TwoPadSplit(0.30, 0.01, 0.01) pads[0].cd() pads[0].SetGrid(1, 1) plot.Set(h1, LineColor=ROOT.kBlack, LineWidth=2) plot.Set(h1.GetYaxis(), Title='Efficiency') plot.Set(h2, LineColor=ROOT.kRed, LineWidth=2) for i in xrange(1, h1.GetNbinsX()+1): h1.SetBinError(i, 0.) for i in xrange(1, h2.GetNbinsX()+1): h2.SetBinError(i, 0.) h1.Draw('L') h2.Draw('LSAME') ratio = h1.Clone() ratio.Divide(h2) legend = ROOT.TLegend(0.18, 0.82, 0.6, 0.93, '', 'NBNDC') legend.AddEntry(h1, fn1, 'L') legend.AddEntry(h2, fn2, 'L') legend.Draw() print plot.GetPadYMax(pads[0]) plot.FixTopRange(pads[0], plot.GetPadYMax(pads[0]), 0.25) plot.DrawTitle(pads[0], ','.join(label_vars), 1) line = ROOT.TLine() plot.Set(line, LineColor=12, LineStyle=4, LineWidth=2) if line_pos is not None: plot.DrawVerticalLine(pads[0], line, line_pos) pads[1].cd() pads[1].SetGrid(1, 1) ratio.Draw('L') plot.SetupTwoPadSplitAsRatio( pads, plot.GetAxisHist( pads[0]), plot.GetAxisHist(pads[1]), 'Ratio', True, 0.91, 1.09) if line_pos is not None: plot.DrawVerticalLine(pads[1], line, line_pos) canv.Print('.pdf') canv.Print('.png')
y1.append(res[1]) y2.append(res[2]) gr0 = ROOT.TGraph(len(arr_x), arr_x, array('d', y0)) gr1 = ROOT.TGraph(len(arr_x), arr_x, array('d', y1)) gr2 = ROOT.TGraph(len(arr_x), arr_x, array('d', y2)) canv = ROOT.TCanvas('wg_M_cutoff_quantiles_%s' % year, 'wg_M_cutoff_quantiles_%s' % year) pads = plot.OnePad() plot.Set(gr0, LineWidth=2, LineColor=1, MarkerColor=1) plot.Set(gr1, LineWidth=2, LineColor=2, MarkerColor=2) plot.Set(gr2, LineWidth=2, LineColor=4, MarkerColor=4) gr0.Print() gr0.Draw('ALP') gr1.Draw('LPSAME') gr2.Draw('LPSAME') axis = plot.GetAxisHist(pads[0]) axis.SetMaximum(4000) axis.GetXaxis().SetTitle('p_{T}^{#gamma} cut-off [GeV]') axis.GetYaxis().SetTitle('M_{W#gamma} [GeV]') legend = plot.PositionedLegend(0.30, 0.20, 3, 0.015) legend.AddEntry(gr0, '68% quantile') legend.AddEntry(gr1, '95% quantile') legend.AddEntry(gr2, '99.7% quantile') legend.Draw() canv.Print('.png') canv.Print('.pdf') # Draw efficiencies for the stitched sample for year, var in itertools.product(years, ['l0_pt', 'p0_pt']): hist_dict = {} for opath, objname, obj in hists[year][var]['WG-NLO'].ListObjects(depth=0):
def main(filename, name, plot_dir, sig_model, bkg_model, title, particle, isMC, postfix, bin_replace): ROOT.PyConfig.IgnoreCommandLineOptions = True ROOT.gROOT.SetBatch(ROOT.kTRUE) ROOT.RooMsgService.instance().setGlobalKillBelow(ROOT.RooFit.WARNING) plot.ModTDRStyle(width=1200, l=0.35, r=0.15) # Apparently I don't need to do this... # ROOT.gSystem.Load('lib/libICHiggsTauTau.so') if plot_dir != '': os.system('mkdir -p %s' % plot_dir) ROOT.RooWorkspace.imp = getattr(ROOT.RooWorkspace, 'import') ROOT.TH1.AddDirectory(0) #filename = input.split(':')[0] #name = input.split(':')[1] infile = ROOT.TFile(filename) wsp = infile.Get('wsp_' + name) pdf_args = [] nparams = 1 if sig_model == 'DoubleVCorr': nparams = 15 pdf_args.extend([ "Voigtian::signal1Pass(m_ll, mean1[90,80,100], width[2.495], sigma1[2,1,3])", "Voigtian::signal2Pass(m_ll, mean2[90,80,100], width, sigma2[4,2,10])", "SUM::signalPass(vFrac[0.7,0,1]*signal1Pass, signal2Pass)", "Voigtian::signal1Fail(m_ll, mean1[90,80,100], width[2.495], sigma1[2,1,3])", "Voigtian::signal2Fail(m_ll, mean2[90,80,100], width, sigma2[4,2,10])", "SUM::signalFail(vFrac[0.7,0,1]*signal1Fail, signal2Fail)", ]) elif sig_model == 'DoubleVUncorr': nparams = 20 pdf_args.extend([ "Voigtian::signal1Pass(m_ll, mean1p[90,80,100], widthp[2.495], sigma1p[2,1,3])", "Voigtian::signal2Pass(m_ll, mean2p[90,80,100], widthp, sigma2p[4,2,10])", "SUM::signalPass(vFracp[0.7,0,1]*signal1Pass, signal2Pass)", "Voigtian::signal1Fail(m_ll, mean1f[90,80,100], widthf[2.495], sigma1f[2,1,3])", "Voigtian::signal2Fail(m_ll, mean2f[90,80,100], widthf, sigma2f[4,2,10])", "SUM::signalFail(vFracf[0.7,0,1]*signal1Fail, signal2Fail)" ]) else: raise RuntimeError('Chosen --sig-model %s not supported' % sig_model) if bkg_model == 'Exponential': pdf_args.extend([ "Exponential::backgroundPass(m_ll, lp[-0.1,-1,0.1])", "Exponential::backgroundFail(m_ll, lf[-0.1,-1,0.1])" ]) elif bkg_model == 'CMSShape': pdf_args.extend([ "RooCMSShape::backgroundPass(m_ll, alphaPass[70,60,90], betaPass[0.001,0,0.1], gammaPass[0.001,0,0.1], peak[90])", "RooCMSShape::backgroundFail(m_ll, alphaFail[70,60,90], betaFail[0.001,0,0.1], gammaFail[0.001,0,0.1], peak[90])", ]) elif bkg_model == 'Chebychev': pdf_args.extend([ "RooChebychev::backgroundPass(m_ll, {a0p[0.25,0,0.5], a1p[-0.25,-1,0.1],a2p[0.,-0.25,0.25]})", "RooChebychev::backgroundFail(m_ll, {a0f[0.25,0,0.5], a1f[-0.25,-1,0.1],a2f[0.,-0.25,0.25]})", ]) else: raise RuntimeError('Chosen --bkg-model %s not supported' % bkg_model) for arg in pdf_args: wsp.factory(arg) model_args = [ "expr::nSignalPass('efficiency*fSigAll*numTot',efficiency[0,1], fSigAll[0,1],numTot[1,0,1e10])", "expr::nSignalFail('(1-efficiency)*fSigAll*numTot',efficiency,fSigAll,numTot)", "expr::nBkgPass('effBkg*(1-fSigAll)*numTot',effBkg[0,1],fSigAll,numTot)", "expr::nBkgFail('(1-effBkg)*(1-fSigAll)*numTot',effBkg,fSigAll,numTot)", "SUM::passing(nSignalPass*signalPass,nBkgPass*backgroundPass)", "SUM::failing(nSignalFail*signalFail,nBkgFail*backgroundFail)", "cat[fail,pass]", "SIMUL::model(cat,fail=failing,pass=passing)" ] for arg in model_args: wsp.factory(arg) hist = infile.Get(name) bin_cfg = { 'name': hist.GetName(), 'binvar_x': hist.GetXaxis().GetTitle(), 'binvar_y': hist.GetYaxis().GetTitle() } bins = [] for i in xrange(1, hist.GetNbinsX() + 1): for j in xrange(1, hist.GetNbinsY() + 1): bins.append((i, j, hist.GetXaxis().GetBinLowEdge(i), hist.GetXaxis().GetBinUpEdge(i), hist.GetYaxis().GetBinLowEdge(j), hist.GetYaxis().GetBinUpEdge(j))) res = [] for b in bins: dat = '%s>=%g && %s<%g && %s>=%g && %s<%g' % ( bin_cfg['binvar_x'], b[2], bin_cfg['binvar_x'], b[3], bin_cfg['binvar_y'], b[4], bin_cfg['binvar_y'], b[5], ) label = '%s.%g_%g.%s.%g_%g' % (bin_cfg['binvar_x'], b[2], b[3], bin_cfg['binvar_y'], b[4], b[5]) label = label.replace('(', '_') label = label.replace(')', '_') # Set the initial yield and efficiency values yield_tot = wsp.data(dat).sumEntries() yield_pass = wsp.data(dat).sumEntries("cat==cat::pass") wsp.var("numTot").setVal(yield_tot) try: wsp.var("efficiency").setVal(yield_pass / yield_tot) wsp.var("efficiency").setAsymError(0, 0) except ZeroDivisionError: wsp.var("efficiency").setVal(0) # wsp.pdf("model").fitTo(wsp.data(dat), # ROOT.RooFit.Minimizer("Minuit2", "Scan"), # ROOT.RooFit.Offset(True), # ROOT.RooFit.Extended(True), # ROOT.RooFit.PrintLevel(-1)) # wsp.pdf("model").fitTo(wsp.data(dat), # ROOT.RooFit.Minimizer("Minuit2", "Migrad"), # ROOT.RooFit.Strategy(2), # ROOT.RooFit.Offset(True), # ROOT.RooFit.Extended(True), # ROOT.RooFit.SumW2Error(True), # ROOT.RooFit.PrintLevel(-1), # ROOT.RooFit.NumCPU(10)) fitres = wsp.pdf("model").fitTo( wsp.data(dat), ROOT.RooFit.Minimizer("Minuit2", "Migrad"), #ROOT.RooFit.Strategy(2), ROOT.RooFit.Offset(True), ROOT.RooFit.Extended(True), ROOT.RooFit.SumW2Error(True), ROOT.RooFit.PrintLevel(-1), #ROOT.RooFit.NumCPU(10), ROOT.RooFit.Save()) #ROOT.RooFit.Minos()) #fitres.Print() #fitres.correlationMatrix().Print() #print "The Error for this Bin is: {}".format(wsp.var('efficiency').getError()) res.append((dat, wsp.var('efficiency').getVal(), wsp.var('efficiency').getError())) hist.SetBinContent(b[0], b[1], wsp.var('efficiency').getVal()) hist.SetBinError(b[0], b[1], wsp.var('efficiency').getError()) canv = ROOT.TCanvas('%s' % (label), "%s" % (label)) pad_left = ROOT.TPad('left', '', 0., 0., 0.5, 1.) pad_left.Draw() pad_right = ROOT.TPad('right', '', 0.5, 0., 1., 1.) pad_right.Draw() pads = [pad_left, pad_right] latex = ROOT.TLatex() latex.SetNDC() ROOT.TGaxis.SetExponentOffset(-0.08, -0.02) splitData = wsp.data(dat).split(wsp.cat('cat')) xframe = wsp.var("m_ll").frame(ROOT.RooFit.Title("Passing")) width = (wsp.var("m_ll").getMax() - wsp.var("m_ll").getMin()) / splitData.At(1).numEntries() splitData.At(1).plotOn(xframe, ROOT.RooFit.DataError(ROOT.RooAbsData.Poisson), ROOT.RooFit.Name("DataPass")) wsp.pdf("passing").plotOn(xframe, ROOT.RooFit.Slice(wsp.cat('cat'), "pass"), ROOT.RooFit.LineColor(ROOT.kBlue), ROOT.RooFit.Name("AllPass")) wsp.pdf("passing").plotOn(xframe, ROOT.RooFit.Slice(wsp.cat('cat'), "pass"), ROOT.RooFit.Components('backgroundPass'), ROOT.RooFit.LineStyle(ROOT.kDashed), ROOT.RooFit.LineColor(ROOT.kBlue), ROOT.RooFit.Name("BkgPass")) pads[0].cd() xframe.Draw() axis = plot.GetAxisHist(pads[0]) #plot.Set(axis.GetXaxis().SetTitle('m_{tag-probe} (GeV)')) if particle == 'e': plot.Set(axis.GetXaxis().SetTitle('m_{ee} (GeV)')) else: plot.Set(axis.GetXaxis().SetTitle('m_{#mu#mu} (GeV)')) plot.Set(axis.GetYaxis().SetTitle('Events / %g GeV' % width)) #plot.DrawTitle(pads[0], 'Pass Region', 1) plot.DrawTitle(pads[0], title, 1) latex.SetTextSize(0.035) #latex.DrawLatex(0.5, 0.89, args.title) #latex.DrawLatex(0.5, 0.84, 'p_{T}: [%g, %g] GeV #eta: [%g, %g]' % (b[2], b[3], b[4], b[5])) font = latex.GetTextFont() latex.DrawLatex(0.2, 0.9, 'pass region') latex.SetTextFont(42) latex.DrawLatex( 0.63, 0.75, '#chi^{2} = %.2f' % (xframe.chiSquare("AllPass", "DataPass", nparams))) latex.DrawLatex( 0.63, 0.7, '#varepsilon = %.4f #pm %.4f' % (wsp.var('efficiency').getVal(), wsp.var('efficiency').getError())) ROOT.gStyle.SetLegendBorderSize(1) legend1 = ROOT.TLegend(0.6, 0.8, 0.925, 0.939) legend1.AddEntry(xframe.findObject("DataPass"), "data", "ep") legend1.AddEntry(xframe.findObject("AllPass"), "Z #rightarrow #mu#mu + BG", "l") legend1.AddEntry(xframe.findObject("BkgPass"), "BG", "l") legend1.Draw() xframe2 = wsp.var("m_ll").frame(ROOT.RooFit.Title("Failing")) splitData.At(0).plotOn(xframe2, ROOT.RooFit.DataError(ROOT.RooAbsData.Poisson), ROOT.RooFit.Name("DataFail")) wsp.pdf("failing").plotOn(xframe2, ROOT.RooFit.Slice(wsp.cat('cat'), "fail"), ROOT.RooFit.LineColor(ROOT.kRed), ROOT.RooFit.Name("AllFail")) wsp.pdf("failing").plotOn(xframe2, ROOT.RooFit.Slice(wsp.cat('cat'), "fail"), ROOT.RooFit.Components('backgroundFail'), ROOT.RooFit.LineStyle(ROOT.kDashed), ROOT.RooFit.LineColor(ROOT.kRed), ROOT.RooFit.Name("BkgFail")) pads[1].cd() xframe2.Draw() axis = plot.GetAxisHist(pads[1]) #plot.Set(axis.GetXaxis().SetTitle('m_{tag-probe} (GeV)')) if particle == 'e': plot.Set(axis.GetXaxis().SetTitle('m_{ee} (GeV)')) else: plot.Set(axis.GetXaxis().SetTitle('m_{#mu#mu} (GeV)')) plot.Set(axis.GetYaxis().SetTitle('Events / %g GeV' % width)) plot.DrawTitle( pads[1], 'p_{T}: [%g, %g] GeV #eta: [%g, %g]' % (b[2], b[3], b[4], b[5]), 1) if isMC: plot.DrawTitle(pads[1], 'MC Fall17', 3) else: #plot.DrawTitle(pads[1], '18.25 fb^{-1} (13 TeV)', 3) plot.DrawTitle(pads[1], '41.29 fb^{-1} (13 TeV)', 3) #plot.DrawTitle(pads[1], 'Fail Region', 1) latex.DrawLatex( 0.63, 0.75, '#chi^{2} = %.2f' % (xframe2.chiSquare("AllFail", "DataFail", nparams))) latex.SetTextFont(font) latex.DrawLatex(0.2, 0.9, 'fail region') legend2 = ROOT.TLegend(0.6, 0.8, 0.925, 0.939) legend2.AddEntry(xframe2.findObject("DataFail"), "data", "ep") legend2.AddEntry(xframe2.findObject("AllFail"), "Z #rightarrow #mu#mu + BG", "l") legend2.AddEntry(xframe2.findObject("BkgFail"), "BG", "l") legend2.Draw() canv.Print('%s/%s.png' % (plot_dir, canv.GetName())) canv.Print('%s/%s.pdf' % (plot_dir, canv.GetName())) if bin_replace is not None: replacements = bin_replace.split(':') for rep in replacements: bins = [float(x) for x in rep.split(',')] dest_bin_x = hist.GetXaxis().FindFixBin(bins[0]) dest_bin_y = hist.GetYaxis().FindFixBin(bins[1]) src_bin_x = hist.GetXaxis().FindFixBin(bins[2]) src_bin_y = hist.GetYaxis().FindFixBin(bins[3]) dest_val, dest_err = hist.GetBinContent( dest_bin_x, dest_bin_y), hist.GetBinError(dest_bin_x, dest_bin_y) src_val, src_err = hist.GetBinContent(src_bin_x, src_bin_y), hist.GetBinError( src_bin_x, src_bin_y) print 'Replacing content of bin %g,%g (%g +/- %g) with %g,%g (%g +/- %g)' % ( dest_bin_x, dest_bin_y, dest_val, dest_err, src_bin_x, src_bin_y, src_val, src_err) hist.SetBinContent(dest_bin_x, dest_bin_y, src_val) hist.SetBinError(dest_bin_x, dest_bin_y, src_err) outfile = ROOT.TFile( filename.replace('.root', '_Fits_%s%s.root' % (name, postfix)), 'RECREATE') hist.Write() for i in xrange(1, hist.GetNbinsY() + 1): slice = hist.ProjectionX('%s_projx_%i' % (hist.GetName(), i), i, i) slice.Write() gr = ROOT.TGraphAsymmErrors(slice) gr.SetName('gr_' + slice.GetName()) gr.Write() outfile.Close() wsp.Delete() # if __name__ == "__main__": # # execute only if run as a script # args = parse_arguments() # main(args)
pads[1].cd() pads[1].SetGrid(0, 1) h_axes[1].Draw() # r_data = plot.MakeRatioHist(h_data, h_tot, True, False) # r_nominal = plot.MakeRatioHist(h_nominal, h_nominal, True, False) r_NLO_inc = plot.MakeRatioHist(h_NLO_inc, h_LO_inc, True, True) # r_LO_130 = plot.MakeRatioHist(h_LO_130, h_LO_inc, True, True) # r_LO_inc_cut_130 = plot.MakeRatioHist(h_LO_130, h_LO_inc, True, True) # r_LO_500 = plot.MakeRatioHist(h_LO_inc_cut_130, h_LO_inc, True, True) r_NLO_inc.Draw('SAMEE') # r_LO_130.Draw('SAMEE') # r_LO_inc_cut_130.Draw('SAMEE') # r_LO_500.Draw('SAMEE') # r_data.Draw('SAME') plot.SetupTwoPadSplitAsRatio(pads, plot.GetAxisHist(pads[0]), plot.GetAxisHist(pads[1]), 'C_{3W} = X / Nominal', True, 0.8, 1.8) # Go back and tidy up the axes and frame pads[0].cd() pads[0].GetFrame().Draw() pads[0].RedrawAxis() # CMS logo # plot.DrawCMSLogo(pads[0], 'CMS', 'Internal', 11, 0.045, 0.05, 1.0, '', 1.0) # plot.DrawTitle(pads[0], '0.1 fb^{-1} (13 TeV)', 3) # latex = ROOT.TLatex() # plot.Set(latex, NDC=None, TextFont=42, TextSize=0.03) # # latex.DrawLatex(0.20, 0.75, args.title)
legend = ROOT.TLegend(0.50, 0.75, 0.93, 0.93, '', 'NBNDC') plot.Set(res[0], LineColor=ROOT.kBlack, LineWidth=3) plot.Set(res[1], LineColor=ROOT.kRed, LineWidth=3) legend.AddEntry(res[0], 'Unweighted', 'L') legend.AddEntry(res[1], 'Weighted', 'L') res[0].Draw('HISTESAME') res[1].Draw('HISTESAME') plot.FixTopRange(pads[0], plot.GetPadYMax(pads[0]), 0.40) delta_acc = Rate(res[1]) / Rate(res[0]) legend.SetHeader('Rel. Acc.: %.3f #pm %.3f' % (delta_acc.n, delta_acc.s)) legend.Draw() axis = plot.GetAxisHist(pads[0]) plot.Set(axis.GetXaxis(), Title=args.x_title) plot.Set(axis.GetYaxis(), Title='a.u.') rmin = float(args.ratio_range.split(',')[0]) rmax = float(args.ratio_range.split(',')[1]) pads[1].cd() pads[1].SetGrid(0, 1) ratio_hist = res[1].Clone() ratio_hist.Divide(res[0]) ratio_hist.Draw('HISTESAME') plot.SetupTwoPadSplitAsRatio( pads, plot.GetAxisHist( pads[0]), plot.GetAxisHist(pads[1]), 'Ratio', True, rmin, rmax)
def SummaryPlots(cfg): h_ref = cfg['h_ref'].Clone() main_label = cfg['main_label'] ref_axis = h_ref.GetYaxis() if cfg['proj'] == 'X' else h_ref.GetXaxis() for ix in xrange(1, ref_axis.GetNbins() + 1): bin_label = '%s #in [%g, %g]' % (cfg['y_label'], ref_axis.GetBinLowEdge(ix), ref_axis.GetBinUpEdge(ix)) canv = ROOT.TCanvas('%s_%s_%i' % (main_label, cfg['proj'], ix), '%s_%s_%i' % (main_label, cfg['proj'], ix)) pads = plot.TwoPadSplit(cfg.get('ratio_split', 0.4), 0.01, 0.01) pads[0].cd() text = ROOT.TPaveText(0.17, 0.84, 0.6, 0.93, 'NDC') legend = ROOT.TLegend(0.6, 0.75, 0.94, 0.93, '', 'NDC') data_hists = MakeProjections(cfg['data'], '%s_data' % main_label, ix, color=cfg.get('data_colour', 4), marker=21, along=cfg['proj']) mc_hists = MakeProjections(cfg['mc'], '%s_mc' % main_label, ix, color=cfg.get('mc_colour', 2), marker=20, along=cfg['proj']) ratio_hists = MakeProjections(cfg['ratio'], '%s_ratio' % main_label, ix, color=cfg.get('ratio_colour', 1), marker=21, along=cfg['proj']) if 'total' in data_hists: data_hists['total'].Draw('E2SAME') if 'syst' in data_hists: data_hists['syst'].Draw('E0X0SAME') if 'stat' in data_hists: data_hists['stat'].Draw('E1X0SAME') if 'stat' in mc_hists: mc_hists['stat'].Draw('E1X0PSAME') if 'syst' in data_hists: legend.AddEntry(data_hists['stat'], 'Data', 'P') legend.AddEntry(data_hists['stat'], ' Statistical', 'E') legend.AddEntry(data_hists['syst'], ' Systematic', 'E') legend.AddEntry(data_hists['total'], ' Total', 'F') legend.AddEntry(mc_hists['stat'], 'Simulation', 'P') legend.AddEntry(mc_hists['stat'], ' Statistical', 'E') else: legend.AddEntry(data_hists['stat'], 'Data', 'PE') legend.AddEntry(mc_hists['stat'], 'Simulation', 'PE') axis = plot.GetAxisHist(pads[0]) plot.Set(axis, Minimum=cfg['y_range'][0], Maximum=cfg['y_range'][1]) plot.FixTopRange(pads[0], plot.GetPadYMax(pads[0]), 0.40) axis.GetYaxis().SetTitle('Efficiency') pads[1].cd() if 'total' in ratio_hists: ratio_hists['total'].Draw('E2SAME') if 'syst' in ratio_hists: ratio_hists['syst'].Draw('E0X0SAME') if 'stat' in ratio_hists: ratio_hists['stat'].Draw('E1X0SAME') plot.SetupTwoPadSplitAsRatio(pads, plot.GetAxisHist(pads[0]), plot.GetAxisHist(pads[1]), 'Data/Sim', True, cfg['ratio_range'][0], cfg['ratio_range'][1]) r_axis = plot.GetAxisHist(pads[1]) if cfg['logx']: pads[1].SetLogx(True) r_axis.GetXaxis().SetMoreLogLabels(True) r_axis.GetXaxis().SetNoExponent(True) r_axis.GetXaxis().SetTitle(cfg['x_axis_title']) r_axis.GetXaxis().SetTitleOffset(ROOT.gStyle.GetTitleXOffset()) pads[1].SetGrid(1, 1) pads[1].RedrawAxis('g') pads[0].cd() legend.Draw() text.AddText(cfg['main_text']) text.AddText(bin_label) text.SetTextAlign(13) text.SetBorderSize(0) text.Draw() pads[0].SetGrid(1, 1) if cfg['logx']: pads[0].SetLogx(True) canv.Print('.png') canv.Print('.pdf')
float(i) * 0.1 + 0.05, graph_data.GetY()[i] / graph_mc.GetY()[i]) graph_ratio.SetPointError( i, 0.05, 0.05, graph_data.GetEYlow()[i] / graph_mc.GetY()[i], graph_data.GetEYhigh()[i] / graph_mc.GetY()[i]) plot.Set(graph_data, LineColor=ROOT.kRed, MarkerColor=ROOT.kRed) graph_data.Draw('SAMEP') graph_mc.Draw('SAMEP') plot.FixTopRange(pads[0], plot.GetPadYMax(pads[0]), 0.35) pads[1].cd() pads[1].SetGrid(0, 1) axisr.Draw() plot.SetupTwoPadSplitAsRatio(pads, plot.GetAxisHist(pads[0]), plot.GetAxisHist(pads[1]), 'Data/MC', True, 0.61, 1.39) graph_ratio.Draw('SAMEP') # CMS logo plot.DrawCMSLogo(pads[0], 'CMS', 'Internal', 11, 0.045, 0.05, 1.0, '', 1.0) plot.DrawTitle(pads[0], '12.9 fb^{-1} (13 TeV)', 3) latex = ROOT.TLatex() plot.Set(latex, NDC=None, TextFont=42, TextSize=0.03) latex.DrawLatex(0.20, 0.75, args.title) # graph_data.Print() legend = ROOT.TLegend(0.67, 0.78, 0.90, 0.91, '', 'NBNDC') legend.AddEntry(graph_data, 'Data', 'PL') legend.AddEntry(graph_mc, 'All MC', 'PL')
plot.FixTopRange(pads[0], plot.GetPadYMax(pads[0]), 0.30) legend.Draw() plot.FixBoxPadding(pads[0], legend, 0.05) # Do the ratio plot pads[1].cd() pads[1].SetGrid(0, 1) h_axes[1].Draw() r_data = plot.MakeRatioHist(h_data, h_tot, True, False) r_tot = plot.MakeRatioHist(h_tot, h_tot, True, False) r_tot.Draw('E2SAME') r_data.Draw('SAME') plot.SetupTwoPadSplitAsRatio(pads, plot.GetAxisHist(pads[0]), plot.GetAxisHist(pads[1]), 'Obs/Exp', True, 0.61, 1.39) # Go back and tidy up the axes and frame pads[0].cd() pads[0].GetFrame().Draw() pads[0].RedrawAxis() # CMS logo plot.DrawCMSLogo(pads[0], 'CMS', 'Preliminary', 11, 0.045, 0.05, 1.0, '', 1.0) plot.DrawTitle(pads[0], '2.3 fb^{-1} (13 TeV)', 3) # latex = ROOT.TLatex() # plot.Set(latex, NDC=None, TextFont=42, TextSize=0.08) # latex.DrawLatex(0.67, 0.57, CHANNELS[args.channel])
interval['valid_hi'], }) info[scan.label].update(scan_info) scanner.AddMinima(scan_info=info[scan.label], scan=scan) scanner.AddUnc(info[scan.label]) scanner.AddUncs(info, ['nominal'], ['Error']) scanner.AddUncs(info, ['nominal', 'fr_all'], ['Syst', 'Stat']) pprint.pprint(info) for i, scan in enumerate(scans): plotting.Set(scan.gr, **scan.graph_settings) plotting.Set(scan.fn, **scan.func_settings) if i == 0: scan.gr.Draw('AP') axishist = plotting.GetAxisHist(pads[0]) axishist.SetMaximum(args.y_max) axishist.GetYaxis().SetTitle("#minus2 ln #Lambda") axishist.GetXaxis().SetTitle("x") for crossing in crossings_vals: line = ROOT.TLine() line.SetLineColor(ROOT.kRed) plotting.DrawHorizontalLine(pads[0], line, crossing) scan.gr.Draw('PSAME') scan.fn.Draw('SAME') ## Draw a white box in the top of the pad box = ROOT.TBox(axishist.GetXaxis().GetXmin(), args.box_frac * args.y_max, axishist.GetXaxis().GetXmax(), args.y_max)
def ParametrizeBin(x_vals, y_vals, y_val_errs, sumw2, sA, sB, sA_2, sB_2, label, makePlots=False, dropBSM=False, dropInt=False, wsp=None, binStr=''): if y_vals[0] == 0.: print '>> Skipping bin %s due to zero content' % label return y_vals_rel = [y / y_vals[0] for y in y_vals] # y_vals_errs_rel = [y / y_vals[0] for y in y_val_errs] y_vals_errs_rel = [0] * len(y_val_errs) npoints = len(x_vals) gr = ROOT.TGraphErrors(npoints, array('d', x_vals), array('d', y_vals_rel), array('d', [0] * npoints), array('d', y_vals_errs_rel)) fn_full = None fn_lin = None fn_BSM = None sig_SM = y_vals_rel[0] y_0 = y_vals_rel[0] y_0p1 = y_vals_rel[1] y_0p2 = y_vals_rel[2] sig_BSM = (y_0p2 - 2. * y_0p1 + y_0) / 0.02 sig_int = (y_0p1 - y_0 - 0.01 * sig_BSM) / 0.1 A = sA / y_vals[0] B = sB / y_vals[0] neff = math.pow(y_vals[0], 2) / sumw2[0] print 'neff: %g' % neff stddev2_A = (sA_2 / y_vals[0]) - A * A stddev2_B = (sB_2 / y_vals[0]) - B * B if stddev2_A < 0.: print 'Error, stddev2_A = %g' % stddev2_A stddev_A = 0. else: stddev_A = math.sqrt(stddev2_A) if stddev2_B < 0.: print 'Error, stddev2_B = %g' % stddev2_B stddev_B = 0. else: stddev_B = math.sqrt(stddev2_B) stderr_A = stddev_A / math.sqrt(neff) stderr_B = stddev_B / math.sqrt(neff) print 'Nom: %.2g, %.2g, %.2g' % (sig_SM, sig_int, sig_BSM) print 'Alt: %.2g, %.2g +/- %.2g, %.2g +/- %2.g' % (sig_SM, A, stderr_A, B, stderr_B) if makePlots: fn_full = ROOT.TF1("fn_full", "([0] + x*[1] + x*x*[2])/[0]", 0, 1) fn_lin = ROOT.TF1("fn_lin", "([0] + x*[1])/[0]", 0, 1) fn_BSM = ROOT.TF1("fn_BSM", "([0] + x*x*[1])/[0]", 0, 1) fn_full.SetParameter(0, sig_SM) fn_full.SetParameter(1, sig_int) fn_full.SetParameter(2, sig_BSM) fn_lin.SetParameter(0, sig_SM) fn_lin.SetParameter(1, sig_int) fn_BSM.SetParameter(0, sig_SM) fn_BSM.SetParameter(1, sig_BSM) canv = ROOT.TCanvas('%s' % (label), '%s' % (label)) plot.Set(gr, MarkerColor=2, LineColor=2, LineWidth=2) pads = plot.OnePad() gr.Draw('AP') gr.Print() if fn_full is not None: plot.Set(fn_full, MarkerColor=2, LineColor=2, LineWidth=2) fn_full.Draw("SAME") plot.Set(fn_lin, MarkerColor=4, LineColor=4, LineWidth=2) fn_lin.Draw('SAME') plot.Set(fn_BSM, MarkerColor=1, LineColor=1, LineWidth=2) fn_BSM.Draw('SAME') axis = plot.GetAxisHist(pads[0]) axis.SetMinimum(min(axis.GetMinimum(), fn_lin.Eval(1))) axis.SetMaximum(max(axis.GetMaximum(), fn_BSM.Eval(1))) # axis.SetMaximum(2) plot.Set(axis.GetXaxis(), Title='C_{3W} (TeV^{-2})') plot.Set(axis.GetYaxis(), Title='#sigma(C_{3W})/#sigma_{SM}') legend = ROOT.TLegend(0.2, 0.86 - 0.04 * 3, 0.4, 0.91, '', 'NBNDC') legend.AddEntry(fn_full, 'Full', 'L') legend.AddEntry(fn_lin, 'Int. only', 'L') legend.AddEntry(fn_BSM, 'BSM^2 only', 'L') legend.Draw() # axis.GetXaxis().SetRangeUser(0, 1.0) # WriteToTFile(gr, fout, '', 'w_%s_gen_bin_%i_%i' % (pm_label, jb - 1, ib - 1)) plot.DrawTitle( pads[0], '#scale[0.7]{#sigma/#sigma_{SM} = 1 + (%.2f)#upointC_{3W} + (%.2f)#upointC_{3W}^{2}}' % (sig_int, sig_BSM), 1) plot.DrawTitle(pads[0], '#scale[0.7]{%s}' % binStr, 3) canv.Print(plotdir + '/%s.png' % label) canv.Print(plotdir + '/%s.pdf' % label) if dropInt: sig_int = 0. if dropBSM: sig_BSM = 0. if wsp is not None: wsp.factory( 'expr::%s("%.3g+@0*%.3g+@1*@0*@0*%.3g",c3w[0,0,10],withBSM[1])' % (label, sig_SM, sig_int, sig_BSM)) return (sig_SM, sig_int, sig_BSM, stderr_A, stderr_B)
def run_method(self): ROOT.gROOT.SetBatch(ROOT.kTRUE) outfile = ROOT.TFile('%s.root' % self.args.output, 'RECREATE') points = self.args.points file = ROOT.TFile(self.args.workspace.split(':')[0]) wsp = file.Get(self.args.workspace.split(':')[1]) mc = wsp.genobj('ModelConfig') pdf = mc.GetPdf() if self.args.data is None: data = wsp.data('data_obs') else: ws_d = self.args.data.split(':') print '>> Data: ' + str(ws_d) f_d = ROOT.TFile(ws_d[0]) if len(ws_d) == 2: data = f_d.Get(ws_d[1]) else: data = f_d.Get(ws_d[1]).data(ws_d[2]) ll = ROOT.RooLinkedList() nll = pdf.createNLL(data, ll) pars = pdf.getParameters(data) pars.Print() snap = pars.snapshot() # nll.setZeroPoint() nll.Print() if self.args.fitres is not None: fitfile = ROOT.TFile(self.args.fitres.split(':')[0]) rfr = fitfile.Get(self.args.fitres.split(':')[1]) snap = rfr.floatParsFinal() pars.assignValueOnly(snap) page = 0 doPars = [] for par in self.RooColIter(pars): if par.isConstant(): continue if self.args.match is not None: if not re.match(self.args.match, par.GetName()): continue if self.args.no_match is not None: if re.match(self.args.no_match, par.GetName()): continue par.Print() if not (par.hasMax() and par.hasMin()): print 'Parameter does not have an associated range, skipping' continue doPars.append(par) plot.ModTDRStyle(width=700, height=1000) for idx, par in enumerate(doPars): print '%s : (%i/%i)' % (par.GetName(), idx + 1, len(doPars)) nlld1 = nll.derivative(par, 1) nlld2 = nll.derivative(par, 2) xmin = par.getMin() xmax = par.getMax() gr = ROOT.TGraph(points) grd1 = ROOT.TGraph(points) grd2 = ROOT.TGraph(points) gr.SetName(par.GetName()) grd1.SetName(par.GetName() + "_d1") grd2.SetName(par.GetName() + "_d2") w = (xmax - xmin) / float(points) for i in xrange(points): x = xmin + (float(i) + 0.5) * w par.setVal(x) gr.SetPoint(i, x, nll.getVal()) grd1.SetPoint(i, x, nlld1.getVal()) grd2.SetPoint(i, x, nlld2.getVal()) plot.ReZeroTGraph(gr, True) # plot.RemoveGraphYAbove(gr, 2.) # gr.Print() outfile.cd() gr.Write() grd1.Write() grd2.Write() pars.assignValueOnly(snap) canv = ROOT.TCanvas(self.args.output, self.args.output) pads = plot.MultiRatioSplit([0.4, 0.3], [0.005, 0.005], [0.005, 0.005]) pads[0].cd() plot.Set(gr, MarkerSize=0.5) gr.Draw('APL') axis1 = plot.GetAxisHist(pads[0]) axis1.GetYaxis().SetTitle('NLL') pads[1].cd() plot.Set(grd1, MarkerSize=0.5) grd1.Draw('APL') axis2 = plot.GetAxisHist(pads[1]) axis2.GetYaxis().SetTitle('NLL\'') pads[2].cd() plot.Set(grd2, MarkerSize=0.5) grd2.Draw('APL') axis3 = plot.GetAxisHist(pads[2]) axis3.GetYaxis().SetTitle('NLL\'\'') plot.Set( axis3.GetXaxis(), Title=par.GetName(), TitleSize=axis3.GetXaxis().GetTitleSize() * 0.5, TitleOffset=axis3.GetXaxis().GetTitleOffset() * 2, ) extra = '' if page == 0: extra = '(' if page == len(doPars) - 1: extra = ')' print extra canv.Print('.pdf%s' % extra) page += 1 outfile.Write()
# # # # Do the ratio plot pads[1].cd() pads[1].SetGrid(0, 1) h_axes[1].Draw() # r_MC = plot.MakeRatioHist(h_MC, h_matrix, True, False) r_pdf_nnlo_fill = plot.MakeRatioHist(h_pdf_nnlo_fill, h_pdf_nnlo_fill, True, False) r_pdf_nlo_fill = plot.MakeRatioHist(h_pdf_nlo_fill, h_pdf_nnlo_fill, True, False) r_pdf_nlo = plot.MakeRatioHist(h_pdf_nlo, h_pdf_nnlo_fill, True, False) r_pdf_nnlo_fill.Draw('E2SAME') r_pdf_nlo_fill.Draw('E2SAME') # r_matrix_fill.Draw('E2SAME') r_pdf_nlo.Draw('HISTSAME') plot.SetupTwoPadSplitAsRatio(pads, plot.GetAxisHist(pads[0]), plot.GetAxisHist(pads[1]), 'ratio to NNLO', True, 0.92, 1.08) # # # Go back and tidy up the axes and frame pads[0].cd() pads[0].GetFrame().Draw() pads[0].RedrawAxis() canv.Print('.png') canv.Print('.pdf') fout = ROOT.TFile('output_pdf_uncertainty.root', 'RECREATE') NodeToTDir(fout, hists) fout.Close()
r_scale_0 = plot.MakeRatioHist(h_scale_0, h_nominal, True, False) r_scale_1 = plot.MakeRatioHist(h_scale_1, h_nominal, True, False) r_scale_2 = plot.MakeRatioHist(h_scale_2, h_nominal, True, False) r_scale_3 = plot.MakeRatioHist(h_scale_3, h_nominal, True, False) r_scale_4 = plot.MakeRatioHist(h_scale_4, h_nominal, True, False) r_scale_5 = plot.MakeRatioHist(h_scale_5, h_nominal, True, False) r_env.Draw('E2SAME') # r_matrix_fill.Draw('E2SAME') r_scale_0.Draw('HISTSAME') r_scale_1.Draw('HISTSAME') r_scale_2.Draw('HISTSAME') r_scale_3.Draw('HISTSAME') r_scale_4.Draw('HISTSAME') r_scale_5.Draw('HISTSAME') plot.SetupTwoPadSplitAsRatio( pads, plot.GetAxisHist( pads[0]), plot.GetAxisHist(pads[1]), 'Ratio', True, 0.81, 1.19) # # # Go back and tidy up the axes and frame pads[0].cd() pads[0].GetFrame().Draw() pads[0].RedrawAxis() canv.Print('.png') canv.Print('.pdf') fout = ROOT.TFile('output_scale_uncertainty.root', 'RECREATE') NodeToTDir(fout, hists) fout.Close()
def Compare(w, output, SFname, fn1, fn2, bins, var, other_vars= {}, line_pos=None, ylims=None): label_vars = [] for key, val in other_vars.iteritems(): w.var(key).setVal(val) name = key particle = "" if name=="e_eta": name="#eta(e)" particle = "(e)" if name=="m_eta": name="#eta(#mu)" particle = "(#mu)" label_vars.append('%s=%g' % (name, val)) h1 = w.function(fn1).createHistogram(fn1, w.var(var), ROOT.RooFit.Binning(*bins), ROOT.RooFit.Scaling(False) ) h2 = w.function(fn2).createHistogram(fn2, w.var(var), ROOT.RooFit.Binning(*bins), ROOT.RooFit.Scaling(False) ) herr = h1.Clone() canv = ROOT.TCanvas(output, output) pads = plot.TwoPadSplit(0.30, 0.01, 0.01) pads[0].cd() pads[0].SetGrid(1, 1) plot.Set(h1, LineColor=ROOT.kBlack, LineWidth=2) plot.Set(herr, FillColor=18, MarkerSize=0) plot.Set(herr.GetYaxis(), Title='Scale Factor') plot.Set(herr.GetXaxis(), Title='p_{T}%s' % (particle)) plot.Set(h2, LineColor=ROOT.kRed, LineWidth=2) for i in xrange(1, h1.GetNbinsX()+1): h1.SetBinError(i, 0.) herr.SetBinError(i, herr.GetBinContent(i)*0.02) for i in xrange(1, h2.GetNbinsX()+1): h2.SetBinError(i, 0.) herr.Draw('E3') h1.Draw('LSAME') h2.Draw('LSAME') ratio = h2.Clone() ratio.Divide(h1) ratioerr = herr.Clone() ratioerr.Divide(h1) #legend = ROOT.TLegend(0.18, 0.82, 0.6, 0.93, '', 'NBNDC') #legend.AddEntry(h1, 'KIT + 2% error band', 'L') #legend.AddEntry(h2, 'DESY', 'L') #legend.Draw() print plot.GetPadYMax(pads[0]) #plot.FixTopRange(pads[0], 1.5, 0) #plot.GetPadYMax(pads[0]), 0.25) #plot.FixBothRanges(pads[0], 0.0, 0, 1.5, 0) if ylims==None: upperlim=plot.GetPadYMax(pads[0]) if upperlim>1.2: upperlim=1.2 plot.FixTopRange(pads[0], upperlim, 0.25) else: plot.FixBothRanges(pads[0], ylims[0], 0, ylims[1], 0) plot.DrawTitle(pads[0], SFname, 1) plot.DrawTitle(pads[0], ','.join(label_vars), 3) canv.Update() box = ROOT.TBox() box.SetFillColor(1) box.SetFillStyle(3004) box.DrawBox(bins[1], pads[0].GetUymin(), line_pos, pads[0].GetUymax()) line = ROOT.TLine() plot.Set(line, LineColor=12, LineStyle=4, LineWidth=2) if line_pos is not None: #plot.DrawVerticalLine(pads[0], line, line_pos) line.DrawLine(line_pos, pads[0].GetUymin(), line_pos, pads[0].GetUymax()) legend = ROOT.TLegend(0.18, 0.82, 0.6, 0.93, '', 'NBNDC') legend.AddEntry(h1, 'KIT + 2% error band', 'L') legend.AddEntry(h2, 'DESY', 'L') legend.Draw() pads[1].cd() pads[1].SetGrid(1, 1) ratioerr.Draw('E3') ratio.Draw('LSAME') plot.SetupTwoPadSplitAsRatio( pads, plot.GetAxisHist( pads[0]), plot.GetAxisHist(pads[1]), 'KIT/DESY', True, 0.91, 1.09) canv.Update() box.DrawBox(bins[1], pads[1].GetUymin(), line_pos, pads[1].GetUymax()) if line_pos is not None: #plot.DrawVerticalLine(pads[1], line, line_pos) line.DrawLine(line_pos, pads[1].GetUymin(), line_pos, pads[1].GetUymax()) canv.Print('.pdf') canv.Print('.png')
text = ROOT.TPaveText(0.55, 0.37, 0.9, 0.50, 'NDC') legend = ROOT.TLegend(0.18, 0.37, 0.5, 0.50, '', 'NDC') else: text = ROOT.TPaveText(0.55, 0.67, 0.9, 0.80, 'NDC') legend = ROOT.TLegend(0.18, 0.67, 0.5, 0.80, '', 'NDC') for j, src in enumerate(args.input): splitsrc = src.split(':') slice = hists[j].ProjectionX('%s_projx_%i' % (hists[j].GetName(), j), i, i) if len(splitsrc) >= 3: settings = {x.split('=')[0]: eval(x.split('=')[1]) for x in splitsrc[2].split(',')} plot.Set(slice, **settings) slice.Draw('SAME') legend.AddEntry(slice) slices.append(slice) axis = plot.GetAxisHist(pads[0]) axis.GetYaxis().SetTitle('Efficiency') axis.GetXaxis().SetTitle(args.x_title) axis.SetMinimum(float(args.y_range.split(',')[0])) axis.SetMaximum(float(args.y_range.split(',')[1])) pads[0].SetGrid(1, 1) latex.SetTextSize(0.04) text.AddText(args.title) text.AddText(bin_label) text.SetTextAlign(13) text.SetBorderSize(0) text.Draw() legend.Draw() plot.DrawCMSLogo(pads[0], 'CMS', 'Internal', 0, 0.16, 0.035, 1.2, cmsTextSize=0.9)
legend.AddEntry(res_stitched[0], 'Stitched', 'L') res_inc[0].Draw('SAME') res_stitched[0].Draw('SAME') elif args.type == 1: cols = [28, 2, 4, 6, 8, 9, 30, 40, 46, 48, 1] for i, f in enumerate(files): plot.Set(res[i], LineColor=cols.pop(), LineWidth=3) if args.norm and res[i].Integral(0, res[i].GetNbinsX() + 1) > 0.: res[i].Scale(1 / res[i].Integral(0, res[i].GetNbinsX() + 1)) legend.AddEntry(res[i], f, 'L') res[i].Draw('SAME') plot.FixTopRange(pads[0], plot.GetPadYMax(pads[0]), 0.40) legend.Draw() axis = plot.GetAxisHist(pads[0]) plot.Set(axis.GetXaxis(), Title=args.x_title) plot.Set(axis.GetYaxis(), Title='Events') rmin = float(args.ratio_range.split(',')[0]) rmax = float(args.ratio_range.split(',')[1]) pads[1].cd() pads[1].SetGrid(0, 1) if args.type == 0: ratio_hist = res_stitched[0].Clone() ratio_hist.Divide(res_inc[0]) ratio_hist.Draw('SAME') plot.SetupTwoPadSplitAsRatio(pads, plot.GetAxisHist(pads[0]), plot.GetAxisHist(pads[1]), 'Stitched/Inc', True, rmin, rmax) elif args.type == 1:
def SummaryPlotsPhotonFakes(cfg): h_ref = cfg['h_ref'].Clone() main_label = cfg['main_label'] ref_axis = h_ref.GetYaxis() if cfg['proj'] == 'X' else h_ref.GetXaxis() for ix in xrange(1, ref_axis.GetNbins() + 1): bin_label = '%s #in [%g, %g]' % (cfg['y_label'], ref_axis.GetBinLowEdge(ix), ref_axis.GetBinUpEdge(ix)) canv = ROOT.TCanvas('%s_%s_%i' % (main_label, cfg['proj'], ix), '%s_%s_%i' % (main_label, cfg['proj'], ix)) pads = plot.OnePad() pads[0].cd() text = ROOT.TPaveText(0.17, 0.84, 0.6, 0.93, 'NDC') legend = ROOT.TLegend(0.6, 0.75, 0.94, 0.93, '', 'NDC') data_hists = MakeProjections(cfg['data'], '%s_data' % main_label, ix, color=cfg.get('data_colour', 4), marker=21, along=cfg['proj'], sublabels=cfg['data_labels']) # mc_hists = MakeProjections(cfg['mc'], '%s_mc' % main_label, ix, color=cfg.get('mc_colour', 2), marker=20, along=cfg['proj']) # ratio_hists = MakeProjections(cfg['ratio'], '%s_ratio' % main_label, ix, color=cfg.get('ratio_colour', 1), marker=21, along=cfg['proj']) if 'const_syst' in data_hists: data_hists['total_err'] = data_hists['total'].Clone() plot.Set(data_hists['total_err'], FillColorAlpha=(data_hists['total_err'].GetLineColor(), 0.3), MarkerColor=data_hists['total_err'].GetLineColor(), LineWidth=0, MarkerSize=0) plot.Set(data_hists['bkg_syst'], FillColorAlpha=(0, 0), LineColor=2, LineWidth=2, MarkerSize=0) plot.Set(data_hists['const_syst'], FillColorAlpha=(0, 0), LineColor=1, LineWidth=2, MarkerSize=0) plot.Set(data_hists['stat'], FillColorAlpha=(0, 0), LineColor=4, LineWidth=2, LineStyle=2) for h in ['stat', 'const_syst', 'bkg_syst']: data_hists[h + '_hi'] = data_hists[h].Clone() data_hists[h + '_lo'] = data_hists[h].Clone() for ib in xrange(1, data_hists['const_syst'].GetNbinsX() + 1): for h in ['stat', 'const_syst', 'bkg_syst']: data_hists[h + '_hi'].SetBinContent( ib, data_hists[h].GetBinContent(ib) + data_hists[h].GetBinError(ib)) data_hists[h + '_lo'].SetBinContent( ib, data_hists[h].GetBinContent(ib) - data_hists[h].GetBinError(ib)) data_hists[h + '_hi'].SetBinError(ib, 1E-6) data_hists[h + '_lo'].SetBinError(ib, 1E-6) data_hists['total'].SetBinError(ib, 1E-6) data_hists['total'].SetBinError(ib, 1E-6) data_hists['total'].Draw('ESAME') data_hists['total_err'].Draw('E2SAME') data_hists['const_syst_hi'].Draw('ESAME') data_hists['const_syst_lo'].Draw('ESAME') data_hists['bkg_syst_hi'].Draw('ESAME') data_hists['bkg_syst_lo'].Draw('ESAME') data_hists['stat_hi'].Draw('ESAME') data_hists['stat_lo'].Draw('ESAME') legend.AddEntry(data_hists['total'], 'Data', 'L') legend.AddEntry(data_hists['stat'], ' Statistical', 'L') legend.AddEntry(data_hists['const_syst'], ' Non-closure syst.', 'L') legend.AddEntry(data_hists['bkg_syst'], ' Prompt subtraction syst.', 'L') legend.AddEntry(data_hists['total_err'], ' Total', 'F') # legend.AddEntry(mc_hists['stat'], 'Simulation', 'P') # legend.AddEntry(mc_hists['stat'], ' Statistical', 'E') elif 'mc' in data_hists: plot.Set(data_hists['mc'], LineColor=13, LineWidth=2, MarkerSize=0) plot.Set(data_hists['mc_true'], LineColor=9, LineWidth=2, MarkerSize=0) data_hists['mc_err'] = data_hists['mc'].Clone() plot.Set(data_hists['mc_err'], FillColorAlpha=(data_hists['mc_err'].GetLineColor(), 0.3), LineWidth=0, MarkerSize=0) data_hists['mc_true_err'] = data_hists['mc_true'].Clone() plot.Set(data_hists['mc_true_err'], FillColorAlpha=(data_hists['mc_true_err'].GetLineColor(), 0.3), LineWidth=0, MarkerSize=0) for ib in xrange(1, data_hists['mc'].GetNbinsX() + 1): data_hists['mc'].SetBinError(ib, 1E-6) data_hists['mc_true'].SetBinError(ib, 1E-6) data_hists['mc'].Draw('ESAME') data_hists['mc_err'].Draw('E2SAME') data_hists['mc_true'].Draw('ESAME') data_hists['mc_true_err'].Draw('E2SAME') legend.AddEntry(data_hists['mc'], 'Simulation - fit', 'LF') legend.AddEntry(data_hists['mc_true'], 'Simulation - truth', 'LF') # legend.AddEntry(mc_hists['stat'], 'Simulation', 'PE') axis = plot.GetAxisHist(pads[0]) plot.Set(axis, Minimum=cfg['y_range'][0], Maximum=cfg['y_range'][1]) plot.FixTopRange(pads[0], plot.GetPadYMax(pads[0]), 0.40) axis.GetYaxis().SetTitle('#sigma_{i#etai#eta} extrapolation') axis.GetXaxis().SetTitle(cfg['x_axis_title']) pads[0].cd() legend.Draw() text.AddText(cfg['main_text']) text.AddText(bin_label) text.SetTextAlign(13) text.SetBorderSize(0) text.Draw() pads[0].SetGrid(1, 1) if cfg['logx']: pads[0].SetLogx(True) canv.Print('.png') canv.Print('.pdf')
slo = fin.Get(cat + '_Down') canv = ROOT.TCanvas(cat, cat) pads = plot.TwoPadSplit(0.30, 0.01, 0.01) legend = ROOT.TLegend(0.50, 0.75, 0.93, 0.93, '', 'NBNDC') plot.Set(nom, LineColor=ROOT.kBlack, LineWidth=3) plot.Set(shi, LineColor=ROOT.kRed, LineWidth=3) plot.Set(slo, LineColor=ROOT.kBlue, LineWidth=3) nom.Draw('HIST') shi.Draw('HISTSAME') slo.Draw('HISTSAME') axis = plot.GetAxisHist(pads[0]) axis.GetXaxis().SetRangeUser(0, 700) legend.AddEntry(nom, 'Weighted (Nominal)', 'L') legend.AddEntry(slo, 'Unweighted (Down)', 'L') legend.AddEntry(shi, 'Weighted^2 (Up)', 'L') plot.FixTopRange(pads[0], plot.GetPadYMax(pads[0]), 0.30) legend.Draw() plot.Set(axis.GetXaxis(), Title='m_{T,#tau#tau}') plot.Set(axis.GetYaxis(), Title='Events') pads[1].cd() rhi = shi.Clone()
def MakePlot(name, outdir, hists, cfg, layouts): copyhists = {} for hname, h in hists.iteritems(): if len(cfg['rebinvar']): copyhists[hname] = VariableRebin(h, cfg['rebinvar']) else: copyhists[hname] = h.Clone() if cfg['divwidth']: copyhists[hname].Scale(1., 'width') hists = copyhists # Canvas and pads canv = ROOT.TCanvas(name, name) if cfg['ratio'] or cfg['fraction']: pads = plot.TwoPadSplit(0.27, 0.01, 0.01) else: pads = plot.OnePad() # Get the data and create axis hist h_data = hists[cfg['data_name']] # h_data = Getter(file, '%s/data_obs' % target, True) if isinstance(h_data, ROOT.TH2): print 'TH2: aborting!' return h_axes = [h_data.Clone() for x in pads] for h in h_axes: if len(cfg['x_range']): h.GetXaxis().SetRangeUser(*cfg['x_range']) h.Reset() build_h_tot = True h_tot = None if 'TotalProcs' in hists: h_tot = hists['TotalProcs'] build_h_tot = False x_title = cfg['x_title'][0] units = cfg['x_title'][1] if x_title == '' and h_data.GetXaxis().GetTitle() != '': x_title = h_data.GetXaxis().GetTitle() if ':' in x_title: units = x_title.split(':')[1] x_title = x_title.split(':')[0] if cfg['logy']: pads[0].SetLogy() h_axes[0].SetMinimum(0.001) if cfg['ratio'] or cfg['fraction']: plot.StandardAxes(h_axes[1].GetXaxis(), h_axes[0].GetYaxis(), x_title, units) else: plot.StandardAxes(h_axes[0].GetXaxis(), h_axes[0].GetYaxis(), x_title, units) h_axes[0].Draw() # A dict to keep track of the hists h_store = {} layout = layouts[cfg['layout']] stack = ROOT.THStack() legend = ROOT.TLegend(*(cfg['legend_pos'] + ['', 'NBNDC'])) for info in layout: hist = hists[info['entries'][0]] col = info['color'] if isinstance(col, list): col = ROOT.TColor.GetColor(*col) plot.Set(hist, FillColor=col, Title=info['legend']) if len(info['entries']) > 1: for other in info['entries'][1:]: hist.Add(hists[other]) h_store[info['name']] = hist if build_h_tot: if h_tot is None: h_tot = hist.Clone() else: h_tot.Add(hist) stack.Add(hist) h_tot.SetFillColor(plot.CreateTransparentColor(12, 0.3)) h_tot.SetMarkerSize(0) legend.AddEntry(h_data, 'Observed', 'PL') for ele in reversed(layout): legend.AddEntry(h_store[ele['name']], '', 'F') bkg_uncert_label = 'Stat. Uncertainty' if not build_h_tot: bkg_uncert_label = 'Uncertainty' legend.AddEntry(h_tot, bkg_uncert_label, 'F') stack.Draw('HISTSAME') h_tot.Draw("E2SAME") if not cfg['hide_data']: h_data.Draw('E0SAME') plot.FixTopRange(pads[0], plot.GetPadYMax(pads[0]), 0.35) legend.Draw() if cfg['legend_padding'] > 0.: print h_axes[0].GetMinimum(), h_axes[0].GetMaximum() if not h_axes[0].GetMaximum() == 0.: plot.FixBoxPadding(pads[0], legend, cfg['legend_padding']) # Do the ratio plot if cfg['ratio'] or cfg['fraction']: pads[1].cd() pads[1].SetGrid(0, 1) h_axes[1].Draw() if cfg['ratio']: r_data = plot.MakeRatioHist(h_data, h_tot, True, False) r_tot = plot.MakeRatioHist(h_tot, h_tot, True, False) r_tot.Draw('E2SAME') if not cfg['hide_data']: r_data.Draw('SAME') plot.SetupTwoPadSplitAsRatio(pads, plot.GetAxisHist(pads[0]), plot.GetAxisHist(pads[1]), 'Obs/Exp', True, 0.61, 1.69) if cfg['fraction']: r_frac = plot.MakeRatioHist(h_tot, h_data, True, True) r_frac.Draw('SAME') plot.SetupTwoPadSplitAsRatio(pads, plot.GetAxisHist(pads[0]), plot.GetAxisHist(pads[1]), 'Exp/Obs', True, 0.0, 0.5) # Go back and tidy up the axes and frame pads[0].cd() pads[0].GetFrame().Draw() pads[0].RedrawAxis() # CMS logo plot.DrawCMSLogo(pads[0], cfg['main_logo'], cfg['sub_logo'], 11, 0.045, 0.05, 1.0, '', 1.0) plot.DrawTitle(pads[0], cfg['top_title_left'], 1) if cfg['auto_top_title_right']: title_right = h_data.GetTitle() if title_right.startswith('lumi:'): plot.DrawTitle(pads[0], title_right.replace('lumi:', ''), 3) else: plot.DrawTitle(pads[0], cfg['top_title_right'], 3) latex = ROOT.TLatex() plot.Set(latex, NDC=None, TextFont=42, TextSize=0.03) latex.DrawLatex(0.20, 0.75, args.title) # plot.DrawTitle(pads[0], args.title, 1) # ... and we're done canv.Print(outdir + '/' + cfg['prefix'] + name + cfg['postfix'] + '.png') canv.Print(outdir + '/' + cfg['prefix'] + name + cfg['postfix'] + '.pdf')
'test', outdir='.', hists=h_dicts[i], cfg=thiscfg, layout=layouts[layout_name], ) out_objects.append(res) # h_dicts_c3w_p1[i]['TotalProcs'].Scale(1.0, 'width') # plot.Set(h_dicts_c3w_p1[i]['TotalProcs'], LineColor=4, LineWidth=3) # h_dicts_c3w_p1[i]['TotalProcs'].Draw('HISTSAME') pads[i].cd() pads[i].SetLogy(True) h = plot.GetAxisHist(pads[i]) hr = plot.GetAxisHist(ratio_pads[i]) if args.selection == 'eft_region': h.SetMinimum(1E-4) h.SetMaximum(1E+2) if args.selection == 'fid_region': h.SetMinimum(1E-2) h.SetMaximum(1E+5) # h.Draw() h.GetXaxis().SetNdivisions(510) hr.GetXaxis().SetNdivisions(510) hr.GetXaxis().ChangeLabel(-1, -1., -1., -1, -1, -1, ' ') h.GetYaxis().SetTickLength(h.GetYaxis().GetTickLength() * 0.5) hr.GetYaxis().SetTickLength(hr.GetYaxis().GetTickLength() * 0.5) if i == 0:
some_presc_l1 = ROOT.TBox() some_presc_l1.SetFillColorAlpha(ROOT.kYellow, 0.3) boxes = [] pads[0].cd() plot.Set(pads[0], Grid=(0, 1), Tickx=1, Ticky=1) plot.Set(yield_hist, LineWidth=2, MarkerSize=2, LineColor=ROOT.kRed, MarkerColor=ROOT.kRed) plot.Set(yield_hist.GetXaxis(), Title='', LabelSize=0) plot.Set(yield_hist.GetYaxis(), Title='Yield / pb^{-1}') yield_hist.Draw('P0') plot.FixBothRanges(pads[0], plot.GetAxisHist(pads[0]).GetMinimum(), 0.05, plot.GetAxisHist(pads[0]).GetMaximum(), 0.05) for i, run in enumerate(runs): if not prescale_ok[str(run)]: boxes.append( bad_trigger.DrawBox(float(i), plot.GetAxisHist(pads[0]).GetMinimum(), float(i + 1), plot.GetAxisHist(pads[0]).GetMaximum())) elif not prescale_l1_ok[str(run)]: boxes.append( some_presc_l1.DrawBox(float(i), plot.GetAxisHist(pads[0]).GetMinimum(), float(i + 1), plot.GetAxisHist(pads[0]).GetMaximum()))
plot.Set(h, LineColor=cols.pop(), LineWidth=3) h.Scale(1 / h.Integral(0, h.GetNbinsX() + 1)) h.Draw('SAMEHIST') legend.AddEntry( h, scale_legends[points[i]] + ': %s / %.3f' % (unc_ratio_list[i], (unc_ratio_list[i] / unc_ratio_list[0]).nominal_value), 'L') plot.FixTopRange(pads[0], plot.GetPadYMax(pads[0]), 0.50) legend.Draw() latex = ROOT.TLatex() latex.SetNDC() latex.SetTextSize(0.04) latex.DrawLatex(0.2, 0.85, args.text) axis = plot.GetAxisHist(pads[0]) plot.Set(axis.GetXaxis(), Title='m_{T} (GeV)') plot.Set(axis.GetYaxis(), Title='a.u.') pads[1].cd() pads[1].SetGrid(0, 1) ratio_hists = [x.Clone() for x in mt_hists] # ratio_hists[0].Draw('') for i, h in enumerate(ratio_hists): h.Divide(mt_hists[0]) h.Draw('SAMEHIST') plot.SetupTwoPadSplitAsRatio(pads, plot.GetAxisHist(pads[0]), plot.GetAxisHist(pads[1]), 'Ratio', True, 0.91, 1.09)
plot.FixTopRange(pads[0], plot.GetPadYMax(pads[0]), 0.35) legend.Draw() # plot.FixBoxPadding(pads[0], legend, 0.05) # Do the ratio plot pads[1].cd() pads[1].SetGrid(0, 1) h_axes[1].Draw() r_data = plot.MakeRatioHist(h_data, h_tot, True, False) r_tot = plot.MakeRatioHist(h_tot, h_tot, True, False) r_tot.Draw('E2SAME') r_data.Draw('SAME') plot.SetupTwoPadSplitAsRatio( pads, plot.GetAxisHist( pads[0]), plot.GetAxisHist(pads[1]), 'Obs/Exp', True, 0.61, 1.39) # Go back and tidy up the axes and frame pads[0].cd() pads[0].GetFrame().Draw() pads[0].RedrawAxis() # CMS logo plot.DrawCMSLogo(pads[0], 'CMS', 'Internal', 11, 0.045, 0.05, 1.0, '', 1.0) plot.DrawTitle(pads[0], '12.9 fb^{-1} (13 TeV)', 3) latex = ROOT.TLatex() plot.Set(latex, NDC=None, TextFont=42, TextSize=0.03) latex.DrawLatex(0.20, 0.75, args.title) # plot.DrawTitle(pads[0], args.title, 1)
if args.logy: axis[0].SetMinimum(0.1) # we'll fix this later pads[0].SetLogy(True) # Apparently switching to logy puts the band back over the top of the axis if has_band: pads[0].RedrawAxis() pads[0].RedrawAxis('g') pads[0].GetFrame().Draw() # axis[0].GetYaxis().SetMoreLogLabels() # axis[0].SetNdivisions(50005, "X") y_min, y_max = (plot.GetPadYMin(pads[0]), plot.GetPadYMax(pads[0])) plot.FixBothRanges(pads[0], y_min if args.logy else 0, 0.05 if args.logy else 0, y_max, 0.25) if args.y_axis_min is not None or args.y_axis_max is not None: hobj = plot.GetAxisHist(pads[0]) if args.y_axis_min is not None: hobj.SetMinimum(float(args.y_axis_min)) if args.y_axis_max is not None: hobj.SetMaximum(float(args.y_axis_max)) ratio_graph_sets = [] ratio_graphs = [] if args.ratio_to is not None: pads[1].cd() plot.SetupTwoPadSplitAsRatio(pads, axis[0], axis[1], '', True, 0.1, 2.4) axis[1].SetNdivisions(506, 'Y') splitsrc = args.ratio_to.split(':') ref = plot.LimitTGraphFromJSONFile(splitsrc[0], splitsrc[1]) for gr_set in graph_sets: ratio_set = {} for key in gr_set:
canv = ROOT.TCanvas(args.output, args.output) pads = plot.OnePad() if args.pub: main_scan['graph'].SetMarkerSize(0) pads[0].SetTickx(True) pads[0].SetTicky(True) if args.hide_envelope: main_scan['graph'].SetMarkerSize(0) main_scan['graph'].SetMarkerColor(0) main_scan['graph'].Draw('AP') # main_scan['graph'].Fit('pol4') # polfunc = main_scan['graph'].GetFunction('pol4') # print 'Function min at %f' % polfunc.GetMinimumX(0.05, 0.25) axishist = plot.GetAxisHist(pads[0]) # axishist.SetMinimum(1E-5) # pads[0].SetLogy(True) axishist.SetMaximum(args.y_max) # axishist.GetYaxis().SetTitle("- 2 #Delta ln #Lambda(%s)" % fixed_name) axishist.GetYaxis().SetTitle("#minus2 ln #Lambda (#sigma)") axishist.GetXaxis().SetTitle("#sigma [nb]") if args.x_title is not None: axishist.GetXaxis().SetTitle("#sigma [nb]") # main_scan['graph'].Draw('SAME') new_min = axishist.GetXaxis().GetXmin() new_max = axishist.GetXaxis().GetXmax() mins = [] maxs = []
bad_trigger = ROOT.TBox() bad_trigger.SetFillColorAlpha(ROOT.kRed, 0.3) some_presc_l1 = ROOT.TBox() some_presc_l1.SetFillColorAlpha(ROOT.kYellow, 0.3) boxes = [] pads[0].cd() plot.Set(pads[0], Grid=(0, 1), Tickx=1, Ticky=1) plot.Set(yield_hist, LineWidth=2, MarkerSize=2, LineColor=ROOT.kRed, MarkerColor=ROOT.kRed) plot.Set(yield_hist.GetXaxis(), Title='', LabelSize=0) plot.Set(yield_hist.GetYaxis(), Title='Yield / pb^{-1}') yield_hist.Draw('P0') plot.FixBothRanges(pads[0], plot.GetAxisHist(pads[0]).GetMinimum(), 0.05, plot.GetAxisHist(pads[0]).GetMaximum(), 0.05) for i, run in enumerate(runs): if not prescale_ok[str(run)]: boxes.append(bad_trigger.DrawBox(float(i), plot.GetAxisHist(pads[0]).GetMinimum(), float(i+1), plot.GetAxisHist(pads[0]).GetMaximum())) elif not prescale_l1_ok[str(run)]: boxes.append(some_presc_l1.DrawBox(float(i), plot.GetAxisHist(pads[0]).GetMinimum(), float(i+1), plot.GetAxisHist(pads[0]).GetMaximum())) pads[1].cd() plot.Set(pads[1], Grid=(0, 1), Tickx=1, Ticky=1) plot.Set(npu_hist, LineWidth=2, MarkerSize=2, LineColor=ROOT.kGreen-2, MarkerColor=ROOT.kGreen-2) plot.Set(npu_hist.GetXaxis(), Title='', LabelSize=0) plot.Set(npu_hist.GetYaxis(), Title='Avg. PU') npu_hist.GetYaxis().CenterTitle(True) npu_hist.Draw('P') plot.FixBothRanges(pads[1], plot.GetAxisHist(pads[1]).GetMinimum(), 0.05, plot.GetAxisHist(pads[1]).GetMaximum(), 0.05)
def MakeMultiHistPlot(name, outdir, hists, cfg, layout, ratios=None): js_workaround = False copyhists = {} for hname, h in hists.iteritems(): if len(cfg['rebinvar']): copyhists[hname] = VariableRebin(h, cfg['rebinvar']) else: copyhists[hname] = h.Clone() if cfg['norm_to'] > 0.: copyhists[hname].Scale(cfg['norm_to'] / copyhists[hname].Integral()) if cfg['divwidth']: copyhists[hname].Scale(1., 'width') hists = copyhists # Canvas and pads if cfg['pads'] is not None: pads = cfg['pads'] elif cfg['ratio'] or cfg['fraction']: canv = ROOT.TCanvas(name, name) if cfg['purity']: pads = plot.MultiRatioSplit([0.27, 0.13], [0.005, 0.005], [0.005, 0.005]) else: # if js_workaround: # upper = ROOT.TPad('upper', 'upper', 0., cfg['ratio_pad_frac'], 1., 1.) # upper.SetBottomMargin(0.01) # # upper.SetFillStyle(4000) # upper.Draw() # lower = ROOT.TPad('lower', 'lower', 0., 0., 1., cfg['ratio_pad_frac']) # lower.SetTopMargin(0.01) # # lower.SetFillStyle(4000) # lower.Draw() # upper.cd() # pads = [upper, lower] # else: # pads = plot.TwoPadSplit(cfg['ratio_pad_frac'], 0.01, 0.01) pads = plot.TwoPadSplit(cfg['ratio_pad_frac'], 0.01, 0.01) else: canv = ROOT.TCanvas(name, name) pads = plot.OnePad() # Allow the user to skip specifying a list of entries for a given plot element. # If it's not been specified then we will add it manually for info in layout: if 'entries' not in info: info['entries'] = [info['name']] for opt in cfg['global_hist_opts']: if opt not in info: info[opt] = cfg['global_hist_opts'][opt] h_data = None if cfg['type'] == 'datamc': # Get the data and create axis hist h_data = hists[cfg['data_name']] else: h_data = hists[layout[0]['entries'][0]] if isinstance(h_data, ROOT.TH2): print 'TH2: aborting!' return h_axes = [h_data.Clone() for x in pads] for h in h_axes: h.SetTitle("") if len(cfg['x_range']): h.GetXaxis().SetRangeUser(*cfg['x_range']) h.Reset() build_h_tot = True h_tot = None if 'TotalProcs' in hists: h_tot = hists['TotalProcs'] build_h_tot = False if cfg['type'] != 'datamc': build_h_tot = False if isinstance(cfg['x_title'], list) or isinstance(cfg['x_title'], tuple): x_title = cfg['x_title'][0] units = cfg['x_title'][1] else: x_title = cfg['x_title'] units = '' if x_title == '' and h_data.GetXaxis().GetTitle() != '': x_title = h_data.GetXaxis().GetTitle() if ':' in x_title: units = x_title.split(':')[1] x_title = x_title.split(':')[0] if cfg['logy']: pads[0].SetLogy() h_axes[0].SetMinimum(cfg['logy_min']) rpad_idx = len(pads) - 1 if cfg['ratio'] or cfg['fraction']: plot.StandardAxes(h_axes[rpad_idx].GetXaxis(), h_axes[0].GetYaxis(), x_title, units) else: plot.StandardAxes(h_axes[0].GetXaxis(), h_axes[0].GetYaxis(), x_title, units) h_axes[0].Draw() # A dict to keep track of the hists h_store = {} p_store = {} legend = ROOT.TLegend(*(cfg['legend_pos'] + ['', 'NBNDC'])) stack = ROOT.THStack() purity_stack = ROOT.THStack() curr_auto_colour = 0 for info in layout: hist = hists[info['entries'][0]] if 'color' in info: col = info['color'] else: col = AUTO_COLOURS[curr_auto_colour] if curr_auto_colour == (len(AUTO_COLOURS) - 1): curr_auto_colour = 0 else: curr_auto_colour += 1 # col = info['color'] if isinstance(col, list): col = ROOT.TColor.GetColor(*col) # print info['line_width'] if cfg['type'] == 'multihist': plot.Set(hist, FillColor=col, MarkerColor=col, LineColor=col, Title=info['legend'], MarkerSize=info['marker_size'], LineWidth=info['line_width']) else: plot.Set(hist, FillColor=col, MarkerColor=col, Title=info['legend'], MarkerSize=info['marker_size'], LineWidth=info['line_width']) if len(info['entries']) > 1: for other in info['entries'][1:]: hist.Add(hists[other]) h_store[info['name']] = hist p_store[info['name']] = hist.Clone() if build_h_tot: if h_tot is None: h_tot = hist.Clone() else: h_tot.Add(hist) if cfg['type'] == 'datamc': stack.Add(hist) else: hist.Draw('SAME%s' % info['draw_opts']) # h_tot_purity = h_tot.Clone() for info in layout: p_store[info['name']].Divide(h_tot) purity_stack.Add(p_store[info['name']]) if cfg['type'] == 'datamc': h_tot.SetFillColor(plot.CreateTransparentColor(12, 0.3)) h_tot.SetMarkerSize(0) legend.AddEntry(h_data, 'Observed', 'PL') # Build overlays for info in cfg['overlays']: hist = None input_list = [] if isinstance(info['entries'], str): input_list = list(all_input_hists) else: input_list = list(info['entries']) updated_list = [] for xh in input_list: if xh + info['hist_postfix'] in hists: updated_list.append(xh + info['hist_postfix']) else: updated_list.append(xh) print updated_list hist = HistSum(hists, updated_list) col = info['color'] if isinstance(col, list): col = ROOT.TColor.GetColor(*col) plot.Set(hist, LineColor=col, LineWidth=1, MarkerSize=0, Title=info['legend']) for ib in xrange(1, hist.GetNbinsX() + 1): hist.SetBinError(ib, 1E-7) h_store[info['name']] = hist if cfg['type'] == 'datamc': for ele in reversed(layout): legend.AddEntry(h_store[ele['name']], ele['legend'], ele['legend_opts']) else: for ele in layout: leg_extra = '' if cfg['legend_show_yields']: leg_extra = ' (%.1f)' % h_store[ele['name']].Integral( 'width' if cfg['divwidth'] else '') legend.AddEntry(h_store[ele['name']], ele['legend'] + leg_extra, ele['legend_opts']) if cfg['type'] == 'datamc': bkg_uncert_label = 'Stat. Uncertainty' if not build_h_tot: bkg_uncert_label = 'Uncertainty' legend.AddEntry(h_tot, bkg_uncert_label, 'F') stack.Draw('HISTSAME') h_tot.Draw("E2SAME") for info in cfg['overlays']: h_store[info['name']].Draw('HISTSAME') if not cfg['hide_data']: h_data.Draw('E0SAME') for info in cfg['overlays']: legend.AddEntry(h_store[info['name']], info['legend'], 'L') plot.FixTopRange(pads[0], plot.GetPadYMax(pads[0]), 0.35) legend.Draw() # if cfg['legend_padding'] > 0.: # plot.FixBoxPadding(pads[0], legend, cfg['legend_padding']) # Do the ratio plot r_store = {} r_data = None r_tot = None if cfg['ratio'] or cfg['fraction']: pads[rpad_idx].cd() pads[rpad_idx].SetGrid(0, 1) h_axes[rpad_idx].Draw() if cfg['type'] == 'datamc' and cfg['ratio']: r_data = plot.MakeRatioHist(h_data, h_tot, True, False) r_tot = plot.MakeRatioHist(h_tot, h_tot, True, False) r_tot.Draw('E2SAME') for info in cfg['overlays']: r_store[info['name']] = plot.MakeRatioHist( h_store[info['name']], h_tot, False, False) r_store[info['name']].Draw('SAME') if not cfg['hide_data']: r_data.Draw('SAME') if cfg['type'] == 'datamc' and cfg['fraction']: r_frac = plot.MakeRatioHist(h_tot, h_data, True, True) r_frac.Draw('SAME') plot.SetupTwoPadSplitAsRatio(pads, plot.GetAxisHist(pads[0]), plot.GetAxisHist(pads[rpad_idx]), 'Exp/Obs', True, 0.0, 0.5) if ratios is not None: for info in ratios: if 'type' in info and info['type'] == 'binomial': rhist = h_store[info['num']].Clone() rhist.Divide(h_store[info['num']], h_store[info['den']], 1., 1., "B") elif 'type' in info and info['type'] == 'noerror': rhist = plot.MakeRatioHist(h_store[info['num']], h_store[info['den']], True, False) else: rhist = plot.MakeRatioHist(h_store[info['num']], h_store[info['den']], True, True) r_store['%s_%s' % (info['num'], info['den'])] = rhist rhist.Draw('SAMEE0') plot.SetupTwoPadSplitAsRatio(pads, plot.GetAxisHist(pads[0]), plot.GetAxisHist(pads[rpad_idx]), cfg['ratio_y_title'], True, *(cfg['ratio_y_range'])) if js_workaround: # This makes the ticks way too large plot.GetAxisHist(pads[rpad_idx]).GetYaxis().SetTickLength( ROOT.gStyle.GetTickLength()) if cfg['purity']: pads[1].cd() h_axes[1].Draw() plot.SetupTwoPadSplitAsRatio(pads, plot.GetAxisHist(pads[0]), plot.GetAxisHist(pads[1]), 'f', True, 0, 1) plot.Set(h_axes[1].GetXaxis(), TitleSize=0, LabelSize=0) plot.Set(h_axes[1].GetYaxis(), Ndivisions=(502, False)) purity_stack.Draw('HISTSAME') # purity_stack.Print() h_axes[1].SetMinimum(0) h_axes[1].SetMaximum(1) pads[1].RedrawAxis() # Go back and tidy up the axes and frame pads[0].cd() if not js_workaround: pads[0].GetFrame().Draw() pads[0].RedrawAxis() # CMS logo plot.DrawCMSLogo(pads[0], cfg['main_logo'], cfg['sub_logo'], 11, 0.045, 0.05, 1.0, '', 1.0) plot.DrawTitle(pads[0], cfg['top_title_left'], 1) if cfg['auto_top_title_right']: title_right = h_data.GetTitle() if title_right.startswith('lumi:'): plot.DrawTitle(pads[0], title_right.replace('lumi:', ''), 3) latex = ROOT.TLatex() plot.Set(latex, NDC=None, TextFont=42, TextSize=0.03) # latex.DrawLatex(0.20, 0.75, args.title) # plot.DrawTitle(pads[0], args.title, 1) # ... and we're done if cfg['pads'] is None: canv.Print(outdir + '/' + cfg['prefix'] + name + cfg['postfix'] + '.png') canv.Print(outdir + '/' + cfg['prefix'] + name + cfg['postfix'] + '.pdf') # canv.Print(outdir + '/' + cfg['prefix'] + name + cfg['postfix'] + '.root') # canv.Print(outdir + '/' + cfg['prefix'] + name + cfg['postfix'] + '.svg') # canv.Print(outdir + '/' + cfg['prefix'] + name + cfg['postfix'] + '.json') outobjs = {} outobjs['axes'] = h_axes outobjs['hists'] = hists outobjs['stack'] = stack outobjs['purity_stack'] = purity_stack outobjs['h_tot'] = h_tot outobjs['legend'] = legend outobjs['r_store'] = r_store outobjs['p_store'] = p_store outobjs['r_data'] = r_data outobjs['r_tot'] = r_tot return outobjs
def main(files, label, output, draw_options, title, y_range, ratio_y_range, binned_in, x_title, ratio_to, plot_dir, label_pos): ROOT.PyConfig.IgnoreCommandLineOptions = True ROOT.gROOT.SetBatch(ROOT.kTRUE) ROOT.TH1.AddDirectory(0) plot.ModTDRStyle() # parser = argparse.ArgumentParser() # parser.add_argument( # 'input', nargs='+', help="""Input files""") # parser.add_argument( # '--output', '-o', default='efficiency', help="""Name of the output # plot without file extension""") # parser.add_argument('--title', default='Muon ID Efficiency') # parser.add_argument('--y-range', default='0,1') # parser.add_argument('--ratio-y-range', default='0.5,1.5') # parser.add_argument('--binned-in', default='#eta') # parser.add_argument('--x-title', default='p_{T} (GeV)') # parser.add_argument('--ratio-to', default=None, type=int) # parser.add_argument('--plot-dir', '-p', default='./') # parser.add_argument('--label-pos', default=1) # args = parser.parse_args() if plot_dir != '': os.system('mkdir -p %s' % plot_dir) hists = [] # file = ROOT.TFile('%s.root' % target) # Process each input argument for src in files: #splitsrc = src.split(':') file = ROOT.TFile(src) if src.find("gen") >= 0: hists.append(file.Get(label + "_tot").Clone()) else: hists.append(file.Get(label).Clone()) file.Close() print hists hist = hists[0] latex = ROOT.TLatex() latex.SetNDC() for i in xrange(1, hist.GetNbinsY() + 1): bin_label = '%s: [%g,%g]' % (binned_in, hist.GetYaxis().GetBinLowEdge(i), hist.GetYaxis().GetBinUpEdge(i)) canv = ROOT.TCanvas('%s_%i' % (output, i), output) if ratio_to is not None: pads = plot.TwoPadSplit(0.50, 0.01, 0.01) else: pads = plot.OnePad() slices = [] if label_pos == 1: text = ROOT.TPaveText(0.55, 0.37, 0.9, 0.50, 'NDC') legend = ROOT.TLegend(0.18, 0.37, 0.5, 0.50, '', 'NDC') elif label_pos == 2: text = ROOT.TPaveText(0.55, 0.67, 0.9, 0.80, 'NDC') legend = ROOT.TLegend(0.18, 0.67, 0.5, 0.80, '', 'NDC') else: text = ROOT.TPaveText(0.55, 0.54, 0.9, 0.67, 'NDC') legend = ROOT.TLegend(0.55, 0.67, 0.9, 0.80, '', 'NDC') text = ROOT.TPaveText(0.55, 0.54, 0.9, 0.67, 'NDC') legend = ROOT.TLegend(0.6, 0.54, 0.95, 0.74, '', 'NDC') #~ if 'ID' in splitsrc[1]: #~ legend = ROOT.TLegend(0.18, 0.67, 0.5, 0.85, '', 'NDC') for j, src in enumerate(files): #splitsrc = src.split(':') htgr = hists[j].ProjectionX( '%s_projx_%i' % (hists[j].GetName(), j), i, i) #if len(splitsrc) >= 3: # settings = {x.split('=')[0]: eval(x.split('=')[1]) for x in splitsrc[2].split(',')} if draw_options[j] != None: settings = draw_options[j] plot.Set(htgr, **settings) htgr.Draw('HIST LP SAME') #htgr.Draw('SAME') legend.AddEntry(htgr) slices.append(htgr) latex.SetTextSize(0.06) #~ text.AddText(args.title) #~ text.AddText(bin_label) #~ text.SetTextAlign(13) #~ text.SetBorderSize(0) #~ text.Draw() legend.Draw() axis = plot.GetAxisHist(pads[0]) axis.GetYaxis().SetTitle('Efficiency') axis.GetXaxis().SetTitle(x_title) #~ axis.GetXaxis().SetRange(10,1000) axis.SetMinimum(float(y_range[0])) axis.SetMaximum(float(y_range[1])) pads[0].SetGrid(0, 1) pads[0].SetLogx(True) pads[0].RedrawAxis('g') #~ plot.DrawCMSLogo(pads[0], args.title, bin_label, 0, 0.16, 0.035, 1.2, cmsTextSize=0.5) plot.DrawTitle(pads[0], title + ' - ' + bin_label, 1) #plot.DrawTitle(pads[0], '18.99 fb^{-1} (13 TeV)', 3) plot.DrawTitle(pads[0], '41.29 fb^{-1} (13 TeV)', 3) if ratio_to is not None: pads[1].cd() pads[1].SetLogx(True) ratios = [] for slice in slices: ratios.append(slice.Clone()) ratios[-1].Divide(slices[ratio_to]) ratios[0].Draw('AXIS') plot.SetupTwoPadSplitAsRatio(pads, plot.GetAxisHist(pads[0]), plot.GetAxisHist(pads[1]), 'Ratio to data', True, float(ratio_y_range[0]), float(ratio_y_range[1])) for j, ratio in enumerate(ratios): if j == ratio_to: continue ratio.Draw('HIST LP SAME') #('SAME E0') pads[1].SetGrid(0, 1) pads[1].RedrawAxis('g') outname = '%s.%s.%g_%g' % (output, hist.GetYaxis().GetTitle(), hist.GetYaxis().GetBinLowEdge(i), hist.GetYaxis().GetBinUpEdge(i)) outname = outname.replace('(', '_') outname = outname.replace(')', '_') outname = outname.replace('.', '_') canv.Print('%s/%s.png' % (plot_dir, outname)) canv.Print('%s/%s.pdf' % (plot_dir, outname))