Example #1
0
    h.Reset()

h_axes[1].GetXaxis().SetTitle('Higgs p_{T} (GeV)')

h_axes[0].GetYaxis().SetTitle('d#sigma/dp_{T}')
h_axes[0].Draw()
if True:
    pads[0].SetLogy()
    h_axes[0].SetMinimum(1E-4)

# A dict to keep track of the hists
legend = ROOT.TLegend(0.60, 0.86 - 0.04 * 5, 0.90, 0.91, '', 'NBNDC')

legend.AddEntry(h_nominal, 'SM', 'L')

plot.Set(h_nominal, LineColor=1, LineWidth=2)

h_nominal.Draw('HISTSAMEE')

for tgt in targets:
    print "tgt=",tgt
    plot.Set(hists[tgt[0]], LineColor=tgt[3], LineWidth=2)
    hists[tgt[0]].Draw('HISTSAME')
    ci = tgt[2]
    if len(tgt) >= 6:
        ci = ci * tgt[5]
    legend.AddEntry(hists[tgt[0]], '%s = %.3g' % (tgt[4], ci), 'L')


plot.FixTopRange(pads[0], plot.GetPadYMax(pads[0]), 0.43)
legend.Draw()
Example #2
0
h_axes[1].GetXaxis().SetTitle(args.x_title)

h_axes[0].GetYaxis().SetTitle('a.u.')
h_axes[0].Draw()
if True:
    pads[0].SetLogy()
    h_axes[0].SetMinimum(args.y_min)

# A dict to keep track of the hists
legend = ROOT.TLegend(0.60, 0.88 - 0.05 * len(args.draw), 0.90, 0.91, '',
                      'NBNDC')

legend.AddEntry(h_nominal, 'Nominal', 'L')

plot.Set(h_nominal, LineColor=1, LineWidth=3)

h_nominal.Draw('HISTSAMEE')

for tgt in args.draw:
    val_part = tgt.split(':')[0]
    opt_part = tgt.split(':')[1:]
    vals = {}
    labels = []
    for X in val_part.split(','):
        label = X.split('=')[0]
        val = float(X.split('=')[1])
        vals[label] = float(val)
        labels.append('%s=%g' % (Translate(label, translate_tex), val))
    h = MakeHist('hist1', jhist, vals, args.no_square, args.no_cross)
    h_err = h.Clone()
Example #3
0
# parser.add_argument('--x-title', default='m_{ll}', help='x-axis variable, without GeV')
# parser.add_argument('--logy', action='store_true')
# parser.add_argument('--y-min', type=float, default=1)

args = parser.parse_args()

Type = args.typet

# Canvas and pads
canv = ROOT.TCanvas(args.output, args.output)
pads = plot.OnePad()
pads[0].SetTicks(1, -1)

axis = ROOT.TH2F('axis', '', 1, -.5, 3, 10, 0, 10)

plot.Set(axis.GetYaxis(), LabelSize=0)
plot.Set(axis.GetXaxis(), Title='Best fit #mu = #sigma/#sigma_{SM}')
axis.Draw()

y_pos = 8.5
x_text = 1.85

latex = ROOT.TLatex()
latexNum = ROOT.TLatex()
plot.Set(latex, TextAlign=12, TextSize=0.035)
plot.Set(latexNum, TextAlign=12, TextSize=0.025)

Channel_Category_Name = {
    'signal': {
        'ggH': 'ggH',
        'qqH': 'qqH',
h_axes[0].Draw()

# A dict to keep track of the hists
h_store = {}

layout = LAYOUTS[args.channel]

stack = ROOT.THStack()
legend = ROOT.TLegend(0.67, 0.86 - 0.04 * len(layout), 0.90, 0.91, '', 'NBNDC')

for ele in layout:
    info = ele[1]
    hist = file.Get('%s/%s' % (folder, info['entries'][0]))
    print "hist name is %s and its yield is %f" % (hist.GetName(),
                                                   hist.Integral())
    plot.Set(hist, FillColor=info['color'], Title=info['legend'])
    if len(info['entries']) > 1:
        for other in info['entries'][1:]:
            hist.Add(file.Get('%s/%s' % (folder, other)))
    h_store[ele[0]] = hist
    stack.Add(hist)

legend.AddEntry(h_data, 'Observed', 'PL')
for ele in reversed(layout):
    legend.AddEntry(h_store[ele[0]], '', 'F')
legend.AddEntry(h_tot, 'Uncertainty', 'F')

stack.Draw('HISTSAME')
h_tot.Draw("E2SAME")
h_data.Draw('SAME')
Example #5
0

## Boilerplate
ROOT.PyConfig.IgnoreCommandLineOptions = True
ROOT.gROOT.SetBatch(ROOT.kTRUE)
plot.ModTDRStyle()
ROOT.gStyle.SetNdivisions(510, 'XYZ')  # probably looks better

canv = ROOT.TCanvas(args.output, args.output)

pads = plot.OnePad()

# Set the style options of the pads
for padx in pads:
    # Use tick marks on oppsite axis edges
    plot.Set(padx, Tickx=1, Ticky=1)
    if args.pad_style is not None:
        settings = {
            x.split('=')[0]: eval(x.split('=')[1])
            for x in args.pad_style.split(',')
        }
        print 'Applying style options to the TPad(s):'
        print settings
        plot.Set(padx, **settings)

graphs = []
graph_sets = []

legend = plot.PositionedLegend(0.45, 0.10, 3, 0.015)
plot.Set(legend, NColumns=2)
def main(filename, name, plot_dir, sig_model, bkg_model, title, particle,
         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)
        #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)
def plot_lepton(files, label, era, 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()
        pads[0].SetLogx(True)
        axis = plot.GetAxisHist(pads[0])
        axis.GetYaxis().SetTitle('Efficiency')
        axis.GetXaxis().SetTitle(x_title)
        axis.GetXaxis().SetRangeUser(1, 1000)
        axis.SetMinimum(float(y_range[0]))
        axis.SetMaximum(float(y_range[1]))
        #~ pads[0].SetGrid(0, 1)
        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)
        if era == "2016":
            plot.DrawTitle(pads[0], '35.9 fb^{-1} (2016, 13 TeV)', 3)
        elif era == "2017":
            plot.DrawTitle(pads[0], '41.5 fb^{-1} (2017, 13 TeV)', 3)
        elif era == "2018":
            plot.DrawTitle(pads[0], '59.7 fb^{-1} (2018, 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))
def plot_hadronic(input_file, triggers, working_points, file_types, era,
                  per_dm, 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()
    plot_dir = "plots"
    hists = {}
    graphs = {}
    if plot_dir != '':
        os.system('mkdir -p %s' % plot_dir)
    if per_dm:
        decayModes = ["inclusive", 0, 1, 10]
    else:
        decayModes = ["inclusive"]
    file = ROOT.TFile(input_file)
    for trg in triggers:
        hists[trg] = {}
        graphs[trg] = {}
        for decayMode in decayModes:
            dm_label = "" if decayMode == "inclusive" else "dm{}_".format(
                decayMode)
            hists[trg][decayMode] = {}
            graphs[trg][decayMode] = {}
            for wp in working_points:
                hists[trg][decayMode][wp] = []
                graphs[trg][decayMode][wp] = []

                for ft in file_types:
                    hists[trg][decayMode][wp].append(
                        file.Get(
                            "hist_{}TriggerEfficiency_{}TauMVA_{}{}".format(
                                trg, wp, dm_label, ft)).Clone())
                    graphs[trg][decayMode][wp].append(
                        file.Get(
                            "hist_{}TriggerEfficiency_{}TauMVA_{}{}".format(
                                trg, wp, dm_label, ft)).Clone())

    file.Close()

    latex = ROOT.TLatex()
    latex.SetNDC()
    for trg in triggers:
        for decayMode in decayModes:
            dm_label = "" if decayMode == "inclusive" else "dm{}_".format(
                decayMode)
            for wp in working_points:
                bin_label = "{}".format(wp)
                canv = ROOT.TCanvas('%s_%s' % (output, wp), 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, hist in enumerate(graphs[trg][decayMode][wp]):
                    #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(hist, **settings)
                    hist.Draw('LP SAME')  #htgr.Draw('SAME')
                    legend.AddEntry(hist)
                for j, hist in enumerate(hists[trg][decayMode][wp]):
                    if draw_options[j] != None:
                        settings = draw_options[j]
                        plot.Set(hist, **settings)
                    slices.append(hist)
                latex.SetTextSize(0.06)
                #~ text.AddText(args.title)
                #~ text.AddText(bin_label)
                #~ text.SetTextAlign(13)
                #~ text.SetBorderSize(0)
                #~ text.Draw()
                legend.Draw()
                pads[0].SetLogx(True)
                axis = plot.GetAxisHist(pads[0])
                axis.GetYaxis().SetTitle('Efficiency')
                axis.GetXaxis().SetTitle(x_title)
                # axis.GetXaxis().SetRangeUser(1,1000)
                axis.SetMinimum(float(y_range[0]))
                axis.SetMaximum(float(y_range[1]))
                #~ pads[0].SetGrid(0, 1)
                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], trg + ' ' + title +
                    dm_label.replace('_', '').replace('dm', ' - dm') + ' - ' +
                    bin_label, 1)

                #plot.DrawTitle(pads[0], '18.99 fb^{-1} (13 TeV)', 3)
                if era == "2016":
                    plot.DrawTitle(pads[0], '35.9 fb^{-1} (2016, 13 TeV)', 3)
                elif era == "2017":
                    plot.DrawTitle(pads[0], '41.5 fb^{-1} (2017, 13 TeV)', 3)
                elif era == "2018":
                    plot.DrawTitle(pads[0], '59.7 fb^{-1} (2018, 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('LP SAME')  #('SAME E0')
                    pads[1].SetGrid(0, 1)
                    pads[1].RedrawAxis('g')

                outname = '{}_{}_{}_{}{}'.format(trg, era, output, dm_label,
                                                 wp)
                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))
Example #9
0
h_axes[1].GetXaxis().SetTitle(args.x_title)

h_axes[0].GetYaxis().SetTitle('a.u.')
h_axes[0].Draw()
if args.logy:
    pads[0].SetLogy()
    h_axes[0].SetMinimum(args.y_min)

# A dict to keep track of the hists
legend = ROOT.TLegend(0.60, 0.88 - 0.05 * len(args.draw), 0.90, 0.91, '',
                      'NBNDC')

legend.AddEntry(h_nominal, 'Nominal', 'L')

plot.Set(h_nominal, LineColor=1, LineWidth=3)

h_nominal.Draw('HISTSAMEE')

for tgt in args.draw:
    val_part = tgt.split(':')[0]
    opt_part = tgt.split(':')[1:]
    vals = {}
    labels = []
    for X in val_part.split(','):
        label = X.split('=')[0]
        val = float(X.split('=')[1])
        vals[label] = float(val)
        labels.append('%s=%g' % (Translate(label, translate_tex), val))
    h = MakeHist('hist1', jhist, vals, args.no_square, args.no_cross)
    h_err = h.Clone()