def cutflow(cutlist, labellist, SRs):
    basecut = ""

    WPcut = [x.split(' && ')[-1] for x in cutlist]
    baseline = cutlist[0].split()
    baseline = filter(lambda x: x != "&&", baseline)
    baseline = filter(lambda x: x not in WPcut, baseline)
    print baseline
    Chain = {}
    hist = {}
    evDict = collections.OrderedDict()
    WPdict = collections.OrderedDict()
    n = 0.
    d = 0.
    for iwp in labellist:
        WPdict[iwp] = {'s': 0., 'b': 0., 'syield': 0., 'byield': 0.}
    ncuts = len(cutlist)
    #effs = [0]*(ncuts+1)
    effhist = TH1D('eff', ";Significance", ncuts, 0, ncuts)
    ## samplelist
    for i, s in enumerate(back + signals):
        Chain[s] = TChain("Events")
        evDict['%s' % s] = {}
        print s
        for rootfiles in samples[s]['files']:
            print rootfiles
            Chain[s].AddFile("%s%s" % (NTUPLEDIR, rootfiles))

        hist[s] = TH1F('%s' % s, "dum", 100, -0.5, 99.5)

        ## looping on cut
        cutsq = ""
        subdict = collections.OrderedDict()
        for j, cut in enumerate(baseline):
            dummy = hist
            if len(cutsq) == 0:
                cutsq += cut
            else:
                cutsq += " && " + cut
            #Chain[s].Project(s, "PV_npvs", "%s*XSWeight*(%s)"%(LUMI,cutsq))
            ##dummy[s].SetOption("%s" % Chain[s].GetTree().GetEntriesFast())
            #subdict['%s'%cut]=dummy[s].Integral()
            #print cut," : ",dummy[s].Integral()," : ",dummy[s].GetEntries()
            if j + 1 == len(baseline):
                wpcut = ""
                for k, wp in enumerate(WPcut):
                    wpcut = cutsq + " && " + wp
                    #print wpcut
                    Chain[s].Project(s, "PV_npvs",
                                     "%s*XSWeight*(%s)" % (LUMI, wpcut))
                    subdict['%s' % labellist[k]] = dummy[s].Integral()
                    print labellist[k], " : ", dummy[s].Integral(
                    ), " : ", dummy[s].GetEntries()
                    #signal/bkg
                    WPdict['%s' % labellist[k]][
                        's' if s in signals else 'b'] += dummy[s].GetEntries()
                    WPdict['%s' %
                           labellist[k]]['syield' if s in signals else
                                         'byield'] += dummy[s].Integral()
                    wpcut = ""
        evDict['%s' % s] = subdict

    for k, cs in enumerate(labellist):
        effhist.GetXaxis().SetBinLabel(k + 1, "%s" % labellist[k])

    print "-" * 80
    print SRs
    print "-" * 80
    for key in WPdict:
        print "-----> ", key
        print "syield = ", WPdict[key]['syield']
        print "byield = ", WPdict[key]['byield']
        print "s entries = ", WPdict[key]['s']
        print "d entires = ", WPdict[key]['b']
        print "sqrt(byield) = ", math.sqrt(WPdict[key]['byield'])
        print "float(syield/math.sqrt(byield)) = ", float(
            WPdict[key]['syield'] / math.sqrt(WPdict[key]['byield']))
        effs = float(WPdict[key]['syield'] / math.sqrt(WPdict[key]['byield']))
        effhist.Fill(key, effs)
    print "-" * 80

    effhist.SetLineColor(colors[2])
    effhist.SetLineWidth(3)
    leg = TLegend(0.7, 0.9 - 0.035 * len(signals), 0.9, 0.9)
    leg.SetBorderSize(0)
    leg.SetFillStyle(1001)
    leg.SetFillColor(0)
    leg.AddEntry('label', "l")

    c1 = TCanvas("c1", "Signals", 800, 600)
    c1.cd()
    c1.GetPad(0).SetTopMargin(0.06)
    c1.GetPad(0).SetRightMargin(0.05)
    c1.GetPad(0).SetTicks(1, 1)
    effhist.GetXaxis().SetTitle("Selection")
    effhist.GetYaxis().SetTitle("Significance (#frac{S}{#sqrt{B}})")
    effhist.Draw()
    leg.Draw()
    drawCMS("41.5", "Preliminary")
    drawRegion("%s" % SRs)

    #process: cut: value
    #printTable(evDict)

    c1.Print("./SignificanceSB_" + SRs + basecut + ".png")
    c1.Print("./SignificanceSB_" + SRs + basecut + ".pdf")
    #if not options.runBash: raw_input("Press Enter to continue...")
    pass
Beispiel #2
0
def do_plot(categories):
    #this sets how tall the canvas is
    N_cats = len(plot_categories.keys())
    #sets the number of divisions on the plot
    N_cuts = max(len(cuts) for cuts in plot_categories.itervalues())
    canv = TCanvas('theorycomp','',500,500+200*N_cats)
    main_pad_ylow = 1-(500.0/(500+200*N_cats))
    rat_pad_height = main_pad_ylow/N_cats
    canv.cd()

    max_cs = get_max_cs(categories)
    min_cs = get_min_cs(categories)
    
    scaffold = TH1F('scaf','',N_cuts,0,N_cuts)
    scaffold.GetYaxis().SetLimits(10*max_cs,min_cs/10.0)
    scaffold.GetYaxis().SetRangeUser(min_cs/10.0,10*max_cs)
    scaffold.SetNdivisions(100*N_cuts)
    scaffold.SetStats(False)
    scaffold.GetYaxis().SetTitle(y_axis_title)
    unshitify(scaffold)
    
    main_pad = TPad('main_plot','',0,main_pad_ylow,1,1,0,0,0)
    main_pad.SetLogy()
    
    main_pad.Draw()
    main_pad.cd()
    scaffold.Draw()

    cut_labels = TLatex()
    cut_labels.SetNDC()    
    plot_start = 0.15
    column_width = (0.945 - plot_start)/N_cuts    
    cut_labels.SetTextSize(0.04)
    cut_labels.DrawLatex(0.15,0.96,
                         "CMS %i, #sqrt{s} = %s"%(year,sqrts))
    cut_labels.DrawLatex(0.18,0.86,luminosity)

   

    labels_drawn = 0
    ratio_pads = []
    cat_meass = []
    cat_preds = []
    cat_meas_rats = []
    cat_pred_rats = []

    legend = TLegend(0.5,0.65,0.93,0.93)
    legend.SetFillColor(0)
    legend.SetLineColor(0)
    legend.SetBorderSize(1)
    
    for j, (cat, cuts) in enumerate(plot_categories.iteritems()):
        canv.cd()
        ratio_pads.append(TPad(cat,'',
                               0,rat_pad_height*j+0.075,
                               1,rat_pad_height*(j+1)+rat_pad_height/4,
                               0,0,0)) 
        ratio_pads[-1].Draw()
        ratio_pads[-1].cd()
        rat_scaf = scaffold.DrawCopy()
        rat_scaf.GetYaxis().SetLimits(-1,3)
        rat_scaf.GetYaxis().SetRangeUser(0,2)
        rat_scaf.GetYaxis().SetNdivisions(105)
        rat_scaf.GetYaxis().SetTitle("#frac{Data}{%s}"%(prediction_name))
        rat_scaf.GetYaxis().SetTitleOffset(0.6)
        rat_scaf.GetYaxis().SetTitleSize(0.10)
        
        main_pad.cd()
        print j,cat
        
        cat_meass.append([])
        cat_preds.append(TGraphErrors())
        cat_meas_rats.append([])
        cat_pred_rats.append(TGraphErrors())

        cat_preds[-1].SetName("%s (%s)"%(prediction_name,cat))

        added_channels = False
        
        for i,cut in enumerate(cuts):            
            cut_name = cut.keys()[0]            
            if len(cuts) == N_cuts and labels_drawn != len(cuts):
                canv.cd()
                cut_labels.DrawLatex(plot_start+column_width*(i+0.35),
                                     0.05,
                                     cut_name)
                labels_drawn+=1
            main_pad.cd()
            print '\t%i : %s'%(i,cut_name)

            realkeys = list(cut[cut_name].keys())
            realkeys.remove('PREDICTION')
            nchan = len(realkeys)            
            divsize = 1.0/(nchan)

            if not added_channels:
                cat_meass[-1] += [TGraphErrors() for l in range(nchan)]
                cat_meas_rats[-1] += [TGraphErrors() for l in range(nchan)]
                print cat_meass[-1]
                added_channels = True

            #graph entries for prediction
            pcs, perr = cut[cut_name]['PREDICTION']

            cat_preds[-1].SetPoint(i,i+0.5,pcs)
            cat_preds[-1].SetPointError(i,0.5,perr)

            cat_pred_rats[-1].SetPoint(i,i+0.5,1.0)
            cat_pred_rats[-1].SetPointError(i,0.5,perr/pcs)
            
            #graph entries for data measurement
            for k, key in enumerate(realkeys):
                gidx = i
                print cut[cut_name][key]
                cs,stat,syst = cut[cut_name][key]
                err = hypot(stat,syst)                

                cat_meass[-1][k].SetName("%s (%s)"%(key,cat))

                cat_meass[-1][k].SetPoint(gidx,
                                          i + (k+0.5)*divsize,
                                          cs)
                cat_meass[-1][k].SetPointError(gidx,
                                               0,
                                               err)
                
                cat_meas_rats[-1][k].SetPoint(gidx,
                                              i + (k+0.5)*divsize,
                                              cs/pcs)
                cat_meas_rats[-1][k].SetPointError(gidx,
                                                   0,
                                                   err/pcs)
        main_pad.cd()
        cat_preds[-1].SetFillColor(fill_colors[j]-3)
        cat_preds[-1].Draw('2')
        legend.AddEntry(cat_preds[-1],cat_preds[-1].GetName(),'f')
        for i,gr in enumerate(cat_meass[-1]):
            gr.SetMarkerStyle(20+4*j+i)
            gr.Draw('pe1')
            legend.AddEntry(gr,gr.GetName(),'pl')

        ratio_pads[-1].cd()        
        cat_pred_rats[-1].SetFillColor(fill_colors[j]-3)
        cat_pred_rats[-1].Draw('2')
        for i,gr in enumerate(cat_meas_rats[-1]):
            gr.SetMarkerStyle(20+4*j+i)
            gr.Draw('pe1')
    main_pad.cd()
    legend.Draw()

    canv.cd()
    cut_labels.DrawLatex(0.80,0.015,'E_{T}^{#gamma} (GeV)')
    
    canv.Print('vgamma_theory_comparison.pdf')
    canv.Print('vgamma_theory_comparison.eps')
    canv.Print('vgamma_theory_comparison.png')
Beispiel #3
0
def plot(var, cut, nm1=False):
    ### Preliminary Operations ###
    treeRead = True if not FILE else False  # Read from tree
    channel = cut
    isBlind = BLIND
    showSignal = False if 'SB' in cut or 'TR' in cut else True

    # Determine explicit cut
    if treeRead:
        for k in sorted(alias.keys(), key=len, reverse=True):
            if k in cut: cut = cut.replace(k, alias[k])

    # Determine Primary Dataset
    pd = []
    if "isSingleMuonPhotonTrigger" in cut:
        pd = [x for x in sample['data_obs']['files'] if "MuonEG" in x]
    elif "isJPsiTrigger" in cut:
        pd = [x for x in sample['data_obs']['files'] if "Charmonium" in x]
    else:
        print "Cannot determine Primary Dataset."
        exit()

    print "Plotting from", ("tree" if treeRead else
                            "file"), var, "in", channel, "channel with:"
    print "  dataset:", pd
    print "  cut    :", cut

    if isBlind and "SR" in channel and var in ["H_mass"]:
        cut += " && ( isMC ? 1 : !(H_mass > 86 && H_mass < 96) && !(H_mass > 120 && H_mass < 130) )"

    ### Create and fill MC histograms ###
    # Create dict
    file = {}
    tree = {}
    hist = {}
    cutstring = "(eventWeightLumi)" + ("*(" + cut +
                                       ")" if len(cut) > 0 else "")

    ### Create and fill MC histograms ###
    for i, s in enumerate(data + back + sign):
        hist[s] = TH1F(
            s, ";" + variable[var]['title'] + ";Events;" +
            ('logx' if variable[var]['logx'] else '') +
            ('logy' if variable[var]['logy'] else ''), variable[var]['nbins'],
            variable[var]['min'], variable[var]['max'])
        hist[s].Sumw2()
        tree[s] = TChain("Events")
        for j, ss in enumerate(sample[s]['files']):
            if s in data and not ss in pd: continue
            if YEAR == 2016 and not ('Run2016' in ss or 'Summer16' in ss):
                continue
            if YEAR == 2017 and not ('Run2017' in ss or 'Fall17' in ss):
                continue
            if YEAR == 2018 and not ('Run2018' in ss or 'Autumn18' in ss):
                continue
            for f in os.listdir(NTUPLEDIR + '/' + ss):
                tree[s].Add(NTUPLEDIR + '/' + ss + '/' + f)
        tree[s].Project(s, var, cutstring)
        if not tree[s].GetTree() == None:
            hist[s].SetOption("%s" % tree[s].GetTree().GetEntriesFast())

#    jobs = []
#    queue = multiprocessing.Queue()
#    for i, s in enumerate(data+back+sign):
#        for j, ss in enumerate(sample[s]['files']):
#            if s in data and not ss in pd: continue
#            if YEAR == 2016 and not ('Run2016' in ss or 'Summer16' in ss): continue
#            if YEAR == 2017 and not ('Run2017' in ss or 'Fall17' in ss): continue
#            if YEAR == 2018 and not ('Run2018' in ss or 'Autumn18' in ss): continue
#            if treeRead: # Project from tree
##                hist[s] = loopProject(s, ss, variable[var], cutstring, True)
#                p = multiprocessing.Process(target=parallelProject, args=(queue, s, ss, variable[var], cutstring, ))
#                jobs.append(p)
#                p.start()
#            else: # Histogram written to file
#                hist[s] = readhist(FILE, s, var, cut)
#
#    # Wait for all jobs to finish
#    for job in jobs:
#        h = queue.get()
#        if not h.GetOption() in hist: hist[h.GetOption()] = h
#        else: hist[h.GetOption()].Add(h)
#    for job in jobs:
#        job.join()

# Histogram style
    for i, s in enumerate(data + back + sign):
        hist[s].Scale(sample[s]['weight'] if hist[s].Integral() >= 0 else 0)
        hist[s].SetFillColor(sample[s]['fillcolor'])
        hist[s].SetFillStyle(sample[s]['fillstyle'] if not options.norm else 0)
        hist[s].SetLineColor(sample[s]['linecolor'])
        hist[s].SetLineStyle(sample[s]['linestyle'])
        hist[s].SetLineWidth(sample[s]['linewidth'])

    ### Create Bkg Sum histogram ###
    hist['BkgSum'] = hist['data_obs'].Clone(
        "BkgSum") if 'data_obs' in hist else hist[back[0]].Clone("BkgSum")
    hist['BkgSum'].Reset("MICES")
    hist['BkgSum'].SetFillStyle(3003)
    hist['BkgSum'].SetFillColor(1)
    for i, s in enumerate(back):
        hist['BkgSum'].Add(hist[s])

    if options.norm:
        for i, s in enumerate(back + ['BkgSum']):
            hist[s].Scale(hist[data[0]].Integral() / hist['BkgSum'].Integral())
        for i, s in enumerate(sign):
            hist[s].Scale(hist[data[0]].Integral() / hist[s].Integral())

    # Create data and Bkg sum histograms
#    if BLIND: # or 'SR' in channel:
#        hist['data_obs'] = hist['BkgSum'].Clone("data_obs")
#        hist['data_obs'].Reset("MICES")
# Set histogram style
    hist['data_obs'].SetMarkerStyle(20)
    hist['data_obs'].SetMarkerSize(1.25)

    #    for i, s in enumerate(data+back+sign+['BkgSum']): addOverflow(hist[s], False) # Add overflow
    for i, s in enumerate(sign):
        hist[s].SetLineWidth(3)
    for i, s in enumerate(sign):
        sample[s]['plot'] = True

    # Create stack
    bkg = THStack("Bkg",
                  ";" + hist['BkgSum'].GetXaxis().GetTitle() + ";Events")
    for i, s in enumerate(back):
        bkg.Add(hist[s])

    # Legend
    leg = TLegend(0.65, 0.6, 0.95, 0.9)
    leg.SetBorderSize(0)
    leg.SetFillStyle(0)  #1001
    leg.SetFillColor(0)
    if len(data) > 0:
        leg.AddEntry(hist[data[0]], sample[data[0]]['label'], "pe")
    for i, s in reversed(list(enumerate(['BkgSum'] + back))):
        leg.AddEntry(hist[s], sample[s]['label'], "f")
    if showSignal:
        for i, s in enumerate(sign):
            if sample[s]['plot']:
                leg.AddEntry(hist[s], sample[s]['label'], "fl")

    leg.SetY1(0.9 - leg.GetNRows() * 0.04)

    # --- Display ---
    c1 = TCanvas("c1",
                 hist.values()[0].GetXaxis().GetTitle(), 800,
                 800 if RATIO else 600)

    if RATIO:
        c1.Divide(1, 2)
        setTopPad(c1.GetPad(1), RATIO)
        setBotPad(c1.GetPad(2), RATIO)
    c1.cd(1)
    c1.GetPad(bool(RATIO)).SetTopMargin(0.06)
    c1.GetPad(bool(RATIO)).SetRightMargin(0.05)
    c1.GetPad(bool(RATIO)).SetTicks(1, 1)

    logX, logY = "logx" in hist['BkgSum'].GetZaxis().GetTitle(
    ), "logy" in hist['BkgSum'].GetZaxis().GetTitle()
    if logY: c1.GetPad(bool(RATIO)).SetLogy()
    if logX: c1.GetPad(bool(RATIO)).SetLogx()

    # Draw
    bkg.Draw("HIST")  # stack
    hist['BkgSum'].Draw("SAME, E2")  # sum of bkg
    if len(data) > 0: hist['data_obs'].Draw("SAME, PE")  # data
    #data_graph.Draw("SAME, PE")
    #    if showSignal:
    #        smagn = 1. #if treeRead else 1.e2 #if logY else 1.e2
    for i, s in enumerate(sign):
        if sample[s]['plot']: hist[s].Draw("SAME, HIST")


#                hist[s].Scale(smagn)
#                hist[s].Draw("SAME, HIST") # signals Normalized, hist[s].Integral()*sample[s]['weight']
#        #textS = drawText(0.80, 0.9-leg.GetNRows()*0.05 - 0.02, stype+" (x%d)" % smagn, True)
    bkg.GetYaxis().SetTitleOffset(bkg.GetYaxis().GetTitleOffset() * 1.075)
    bkg.SetMaximum((5. if logY else 1.25) * max(
        bkg.GetMaximum(),
        hist['data_obs'].GetBinContent(hist['data_obs'].GetMaximumBin()) +
        hist['data_obs'].GetBinError(hist['data_obs'].GetMaximumBin())))
    #if bkg.GetMaximum() < max(hist[sign[0]].GetMaximum(), hist[sign[-1]].GetMaximum()): bkg.SetMaximum(max(hist[sign[0]].GetMaximum(), hist[sign[-1]].GetMaximum())*1.25)
    bkg.SetMinimum(
        max(
            min(hist['BkgSum'].GetBinContent(hist['BkgSum'].GetMinimumBin(
            )), hist['data_obs'].GetMinimum()), 5.e-1) if logY else 0.)
    if logY:
        bkg.GetYaxis().SetNoExponent(bkg.GetMaximum() < 1.e4)
        bkg.GetYaxis().SetMoreLogLabels(True)

    #if logY: bkg.SetMinimum(1)
    leg.Draw()
    drawCMS(LUMI[YEAR], "Preliminary")
    if channel in aliasNames: drawRegion(aliasNames[channel], True)
    #drawAnalysis(channel)

    #if nm1 and not cutValue is None: drawCut(cutValue, bkg.GetMinimum(), bkg.GetMaximum()) #FIXME
    #if len(sign) > 0:
    #    if channel.startswith('X') and len(sign)>0: drawNorm(0.9-0.05*(leg.GetNRows()+1), "#sigma(X) = %.1f pb" % 1.)

    setHistStyle(bkg, 1.2 if RATIO else 1.1)
    setHistStyle(hist['BkgSum'], 1.2 if RATIO else 1.1)

    if RATIO:
        c1.cd(2)
        if logX: c1.GetPad(2).SetLogx()
        err = hist['BkgSum'].Clone("BkgErr;")
        err.SetTitle("")
        err.GetYaxis().SetTitle("Data / Bkg")
        for i in range(1, err.GetNbinsX() + 1):
            err.SetBinContent(i, 1)
            if hist['BkgSum'].GetBinContent(i) > 0:
                err.SetBinError(
                    i, hist['BkgSum'].GetBinError(i) /
                    hist['BkgSum'].GetBinContent(i))
        setBotStyle(err)
        errLine = err.Clone("errLine")
        errLine.SetLineWidth(1)
        errLine.SetFillStyle(0)
        res = hist['data_obs'].Clone("Residues")
        for i in range(0, res.GetNbinsX() + 1):
            if hist['BkgSum'].GetBinContent(i) > 0:
                res.SetBinContent(
                    i,
                    res.GetBinContent(i) / hist['BkgSum'].GetBinContent(i))
                res.SetBinError(
                    i,
                    res.GetBinError(i) / hist['BkgSum'].GetBinContent(i))
        setBotStyle(res)
        #err.GetXaxis().SetLabelOffset(err.GetXaxis().GetLabelOffset()*5)
        #err.GetXaxis().SetTitleOffset(err.GetXaxis().GetTitleOffset()*2)
        err.Draw("E2")
        errLine.Draw("SAME, HIST")
        if len(data) > 0:
            res.Draw("SAME, PE0")
            #res_graph.Draw("SAME, PE0")
            if len(err.GetXaxis().GetBinLabel(
                    1)) == 0:  # Bin labels: not a ordinary plot
                drawRatio(hist['data_obs'], hist['BkgSum'])
                drawStat(hist['data_obs'], hist['BkgSum'])

    if var in ["H_mass"]:
        c1.cd(bool(RATIO))
        boxZ = drawBox(XZMIN, hist['data_obs'].GetMinimum(), XZMAX,
                       hist['data_obs'].GetMaximum() / 1.30, "Z")
        boxH = drawBox(XHMIN, hist['data_obs'].GetMinimum(), XHMAX,
                       hist['data_obs'].GetMaximum() / 1.30, "H")

    c1.Update()

    if True:  #gROOT.IsBatch():
        varname = var.replace('.', '_').replace('()', '')
        if not os.path.exists("plots/" + channel):
            os.makedirs("plots/" + channel)
        c1.Print("plots/" + channel + "/" + varname + ".png")
        c1.Print("plots/" + channel + "/" + varname + ".pdf")

    # Print table
    printTable(hist, sign)

    if not gROOT.IsBatch(): raw_input("Press Enter to continue...")
    eeHist.Add(mmHist.Clone(""))
    eeHist.Scale(1. / eeHist.GetEntries())
    hCanvas = TCanvas("hCanvas", "Distribution", 800, 800)
    plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0.3, 1, 1)
    ratioPad = ROOT.TPad("ratioPad", "ratioPad", 0, 0., 1, 0.3)
    setTDRStyle()
    plotPad.UseCurrentStyle()
    ratioPad.UseCurrentStyle()
    plotPad.Draw()
    ratioPad.Draw()
    plotPad.cd()

    legend = TLegend(0.7, 0.55, 0.95, 0.95)
    legend.SetFillStyle(0)
    legend.SetBorderSize(0)

    yMin = 0
    yMax = max(eeHist.GetBinContent(eeHist.GetMaximumBin()),
               emHist.GetBinContent(mmHist.GetMaximumBin())) * 1.5
    hCanvas.DrawFrame(0, yMin, 100, yMax,
                      "; %s ; %s" % ("m(ll)", "N_{events} / 2 GeV [a.u.]"))
    ROOT.gStyle.SetOptStat(0)

    eeHist.SetLineColor(ROOT.kRed)
    #~ eeHist.SetLineColor(ROOT.kRed)
    fakeHist = ROOT.TH1F()
    fakeHist.SetLineColor(ROOT.kWhite)
    legend.SetHeader("t#bar{t} Simulation")
    legend.AddEntry(eeHist, "e^{#pm}e^{#mp} + #mu^{#pm}#mu^{#mp}", "l")
    legend.AddEntry(mmHist, "e^{#pm}#mu^{#mp}", "l")
def main():  #pylint: disable=too-many-locals,too-many-statements
    """
    Main function of the script
    """
    parser = argparse.ArgumentParser(description='Arguments to pass')
    parser.add_argument('cfgFileName',
                        metavar='text',
                        default='cfgFileName.yml',
                        help='config file name')
    parser.add_argument('outFileDir',
                        metavar='text',
                        default='./',
                        help='output file directory')
    args = parser.parse_args()

    with open(args.cfgFileName, 'r') as ymlCfgFile:
        inputCfg = yaml.load(ymlCfgFile, yaml.FullLoader)

    #Load data
    dfPromptP6 = LoadDfFromRootOrParquet(inputCfg['input']['prompt_files'][0])
    dfPromptP8 = LoadDfFromRootOrParquet(inputCfg['input']['prompt_files'][1])
    dfFDP6 = LoadDfFromRootOrParquet(inputCfg['input']['fd_files'][0])
    dfFDP8 = LoadDfFromRootOrParquet(inputCfg['input']['fd_files'][1])

    #Select pt bin
    ptMin = inputCfg['pt_bin'][0]
    ptMax = inputCfg['pt_bin'][1]
    dfPromptP6 = dfPromptP6.query(f'{ptMin} < pt_cand < {ptMax}')
    dfPromptP8 = dfPromptP8.query(f'{ptMin} < pt_cand < {ptMax}')
    dfFDP6 = dfFDP6.query(f'{ptMin} < pt_cand < {ptMax}')
    dfFDP8 = dfFDP8.query(f'{ptMin} < pt_cand < {ptMax}')

    SetGlobalStyle(padbottommargin=0.14,
                   padleftmargin=0.18,
                   padrightmargin=0.06,
                   titleoffsety=1.6)
    varTitle = inputCfg['scan_variable']['title']
    nBins = inputCfg['scan_variable']['histo_bins']
    binLims = inputCfg['scan_variable']['histo_lims']
    varName = inputCfg['scan_variable']['name']
    hPromptP6 = TH1F('hPromptP6', f';{varTitle};Counts', nBins, binLims[0],
                     binLims[1])
    hPromptP8 = TH1F('hPromptP8', f';{varTitle};Counts', nBins, binLims[0],
                     binLims[1])
    hFDP6 = TH1F('hFDP6', f';{varTitle};Counts', nBins, binLims[0], binLims[1])
    hFDP8 = TH1F('hFDP8', f';{varTitle};Counts', nBins, binLims[0], binLims[1])
    scaleFactor = inputCfg['scan_variable']['rescale_factor']
    dfPromptP6[varName] = dfPromptP6[varName] * scaleFactor
    dfPromptP8[varName] = dfPromptP8[varName] * scaleFactor
    dfFDP6[varName] = dfFDP6[varName] * scaleFactor
    dfFDP8[varName] = dfFDP8[varName] * scaleFactor
    for value in dfPromptP6[varName].to_numpy():
        hPromptP6.Fill(value)
    for value in dfPromptP8[varName].to_numpy():
        hPromptP8.Fill(value)
    for value in dfFDP6[varName].to_numpy():
        hFDP6.Fill(value)
    for value in dfFDP8[varName].to_numpy():
        hFDP8.Fill(value)
    SetObjectStyle(hPromptP6, color=kAzure + 4, marker=kFullCircle)
    SetObjectStyle(hPromptP8, color=kRed + 1, marker=kFullCircle)
    SetObjectStyle(hFDP6, color=kAzure + 4, marker=kFullCircle)
    SetObjectStyle(hFDP8, color=kRed + 1, marker=kFullCircle)
    hPromptP6.GetXaxis().SetNdivisions(505)
    hFDP6.GetXaxis().SetNdivisions(505)
    hPromptP8.GetXaxis().SetNdivisions(505)
    hFDP8.GetXaxis().SetNdivisions(505)

    scanRange = inputCfg['scan_variable']['scan_range']
    scanStep = inputCfg['scan_variable']['scan_step']
    nEffBins = round((scanRange[1] - scanRange[0]) / scanStep)
    hEffPromptP6 = TH1F('hEffPromptP6', f';{varTitle} >;Efficiency', nEffBins,
                        scanRange[0], scanRange[1])
    hEffPromptP8 = TH1F('hEffPromptP8', f';{varTitle} >;Efficiency', nEffBins,
                        scanRange[0], scanRange[1])
    hEffFDP6 = TH1F('hEffFDP6', f';{varTitle} >;Efficiency', nEffBins,
                    scanRange[0], scanRange[1])
    hEffFDP8 = TH1F('hEffFDP8', f';{varTitle} >;Efficiency', nEffBins,
                    scanRange[0], scanRange[1])
    SetObjectStyle(hEffPromptP6, color=kAzure + 4, marker=kFullCircle)
    SetObjectStyle(hEffPromptP8, color=kRed + 1, marker=kFullCircle)
    SetObjectStyle(hEffFDP6, color=kAzure + 4, marker=kFullCircle)
    SetObjectStyle(hEffFDP8, color=kRed + 1, marker=kFullCircle)

    effPromptP6, effPromptP8, effFDP6, effFDP8 = ([] for _ in range(4))
    effPromptUncP6, effPromptUncP8, effFDUncP6, effFDUncP8 = (
        [] for _ in range(4))
    labelsConf = inputCfg['legend']['conf_labels']
    legPrompt = TLegend(0.25, 0.2, 0.6, 0.4)
    legPrompt.SetBorderSize(0)
    legPrompt.SetFillStyle(0)
    legPrompt.SetHeader('Prompt')
    legPrompt.AddEntry(hEffPromptP6, labelsConf[0], 'p')
    legPrompt.AddEntry(hEffPromptP8, labelsConf[1], 'p')
    legFD = TLegend(0.25, 0.2, 0.65, 0.4)
    legFD.SetBorderSize(0)
    legFD.SetFillStyle(0)
    legFD.SetHeader('Non-prompt')
    legFD.AddEntry(hEffPromptP6, labelsConf[0], 'p')
    legFD.AddEntry(hEffPromptP8, labelsConf[1], 'p')

    for iBin, cut in enumerate(np.arange(scanRange[0], scanRange[1],
                                         scanStep)):
        dfPromptP6Sel = dfPromptP6.query(f'{varName} > {cut}')
        dfPromptP8Sel = dfPromptP8.query(f'{varName} > {cut}')
        dfFDP6Sel = dfFDP6.query(f'{varName} > {cut}')
        dfFDP8Sel = dfFDP8.query(f'{varName} > {cut}')

        effPromptP6.append(float(len(dfPromptP6Sel) / len(dfPromptP6)))
        effPromptP8.append(float(len(dfPromptP8Sel) / len(dfPromptP8)))
        effFDP6.append(float(len(dfFDP6Sel) / len(dfFDP6)))
        effFDP8.append(float(len(dfFDP8Sel) / len(dfFDP8)))

        effPromptUncP6.append(
            np.sqrt(effPromptP6[-1] * (1 - effPromptP6[-1]) / len(dfPromptP6)))
        effPromptUncP8.append(
            np.sqrt(effPromptP8[-1] * (1 - effPromptP8[-1]) / len(dfPromptP8)))
        effFDUncP6.append(
            np.sqrt(effFDP6[-1] * (1 - effFDP6[-1]) / len(dfFDP6)))
        effFDUncP8.append(
            np.sqrt(effFDP8[-1] * (1 - effFDP8[-1]) / len(dfFDP8)))

        hEffPromptP6.SetBinContent(iBin + 1, effPromptP6[-1])
        hEffPromptP8.SetBinContent(iBin + 1, effPromptP8[-1])
        hEffFDP6.SetBinContent(iBin + 1, effFDP6[-1])
        hEffFDP8.SetBinContent(iBin + 1, effFDP8[-1])

        hEffPromptP6.SetBinError(iBin + 1, effPromptUncP6[-1])
        hEffPromptP8.SetBinError(iBin + 1, effPromptUncP8[-1])
        hEffFDP6.SetBinError(iBin + 1, effFDUncP6[-1])
        hEffFDP8.SetBinError(iBin + 1, effFDUncP8[-1])

    hEffPromptP6.GetXaxis().SetNdivisions(505)
    hEffFDP6.GetXaxis().SetNdivisions(505)
    hEffPromptP8.GetXaxis().SetNdivisions(505)
    hEffFDP8.GetXaxis().SetNdivisions(505)

    hEffPromptRatio = hEffPromptP8.Clone('hEffPromptRatio')
    hEffPromptRatio.Divide(hEffPromptP6)
    hEffPromptRatio.GetYaxis().SetTitle(
        f'Prompt eff ratio {labelsConf[1]} / {labelsConf[0]}')
    hEffFDRatio = hEffFDP8.Clone('hEffFDRatio')
    hEffFDRatio.Divide(hEffFDP6)
    hEffFDRatio.GetYaxis().SetTitle(
        f'Non-prompt eff ratio {labelsConf[1]} / {labelsConf[0]}')

    hEffPromptRatio.GetXaxis().SetNdivisions(505)
    hEffFDRatio.GetXaxis().SetNdivisions(505)

    cDistributions = TCanvas('cDistributions', '', 1920, 1080)
    cDistributions.Divide(2, 1)
    cDistributions.cd(1).SetLogy()
    hPromptP8.Draw('e')
    hPromptP6.Draw('esame')
    legPrompt.Draw()
    cDistributions.cd(2).SetLogy()
    hFDP8.Draw('e')
    hFDP6.Draw('esame')
    legFD.Draw()

    cEfficiency = TCanvas('cEfficiency', '', 1920, 1080)
    cEfficiency.Divide(2, 1)
    cEfficiency.cd(1).SetLogy()
    hEffPromptP6.Draw('e')
    hEffPromptP8.Draw('esame')
    legPrompt.Draw()
    cEfficiency.cd(2).SetLogy()
    hEffFDP6.Draw('e')
    hEffFDP8.Draw('esame')
    legFD.Draw()

    cEfficiencyRatio = TCanvas('cEfficiencyRatio', '', 1920, 1080)
    cEfficiencyRatio.Divide(2, 1)
    cEfficiencyRatio.cd(1)
    hEffPromptRatio.Draw('e')
    cEfficiencyRatio.cd(2)
    hEffFDRatio.Draw('e')

    tag = f'{labelsConf[0]}Vs{labelsConf[1]}_pT{ptMin}_{ptMax}'
    cDistributions.SaveAs(f'{args.outFileDir}/{varName}_Distr_{tag}.pdf')
    cEfficiency.SaveAs(f'{args.outFileDir}/{varName}_CutEff_{tag}.pdf')
    cEfficiencyRatio.SaveAs(
        f'{args.outFileDir}/{varName}_CutEffRatio_{tag}.pdf')

    print('Press any key to exit!')
    input()
def plotDataMC(args, plot_mu, plot_el):

    hCanvas = TCanvas("hCanvas", "Distribution", 800, 800)
    if args.ratio:
        plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0.5, 1, 1)
        ratioPad = ROOT.TPad("ratioPad", "ratioPad", 0, 0., 1, 0.5)
        setTDRStyle()
        plotPad.UseCurrentStyle()
        ratioPad.UseCurrentStyle()
        plotPad.Draw()
        ratioPad.Draw()
        plotPad.cd()
    else:
        plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0, 1, 1)
        setTDRStyle()
        plotPad.UseCurrentStyle()
        plotPad.Draw()
        plotPad.cd()

    # Data load processes
    colors = createMyColors()
    if args.use2016:
        data_mu = Process(Data2016, normalized=True)
        data_el = Process(Data2016, normalized=True)
    elif args.use2018:
        data_mu = Process(Data2018, normalized=True)
        data_el = Process(Data2018, normalized=True)
    elif args.useall:
        data_all = [
            Process(Data2016, normalized=True),
            Process(Data, normalized=True),
            Process(Data2018, normalized=True)
        ]
    else:
        data_mu = Process(Data, normalized=True)
        data_el = Process(Data, normalized=True)

    eventCounts_mu = totalNumberOfGeneratedEvents(path,
                                                  plot_mu["default"].muon)
    eventCounts_el = totalNumberOfGeneratedEvents(path,
                                                  plot_el["default"].muon)
    negWeights_mu = negWeightFractions(path, plot_mu["default"].muon)
    negWeights_el = negWeightFractions(path, plot_el["default"].muon)

    # Background load processes
    backgrounds = copy(args.backgrounds)
    if plot_mu["default"].useJets:
        if "Wjets" in backgrounds:
            backgrounds.remove("Wjets")
        backgrounds.insert(0, "Jets")
    processes_mu = []
    processes_el = []
    processes_mu2016 = []
    processes_mu2017 = []
    processes_mu2018 = []
    processes_el2016 = []
    processes_el2017 = []
    processes_el2018 = []
    for background in backgrounds:
        if args.use2016:
            if background == "Jets":
                processes_mu.append(
                    Process(getattr(Backgrounds2016, background),
                            eventCounts_mu,
                            negWeights_mu,
                            normalized=True))
                processes_el.append(
                    Process(getattr(Backgrounds2016, background),
                            eventCounts_el,
                            negWeights_el,
                            normalized=True))
            else:
                processes_mu.append(
                    Process(getattr(Backgrounds2016, background),
                            eventCounts_mu, negWeights_mu))
                processes_el.append(
                    Process(getattr(Backgrounds2016, background),
                            eventCounts_el, negWeights_el))
        elif args.use2018:
            if background == "Jets":
                processes_mu.append(
                    Process(getattr(Backgrounds2018, background),
                            eventCounts_mu,
                            negWeights_mu,
                            normalized=True))
                processes_el.append(
                    Process(getattr(Backgrounds2018, background),
                            eventCounts_el,
                            negWeights_el,
                            normalized=True))
            else:
                processes_mu.append(
                    Process(getattr(Backgrounds2018, background),
                            eventCounts_mu, negWeights_mu))
                processes_el.append(
                    Process(getattr(Backgrounds2018, background),
                            eventCounts_el, negWeights_el))
        elif args.useall:
            if background == "Jets":
                processes_mu2016.append(
                    Process(getattr(Backgrounds2016, background),
                            eventCounts_mu,
                            negWeights_mu,
                            normalized=True))
                processes_el2016.append(
                    Process(getattr(Backgrounds2016, background),
                            eventCounts_el,
                            negWeights_el,
                            normalized=True))
                processes_mu2017.append(
                    Process(getattr(Backgrounds, background),
                            eventCounts_mu,
                            negWeights_mu,
                            normalized=True))
                processes_el2017.append(
                    Process(getattr(Backgrounds, background),
                            eventCounts_el,
                            negWeights_el,
                            normalized=True))
                processes_mu2018.append(
                    Process(getattr(Backgrounds2018, background),
                            eventCounts_mu,
                            negWeights_mu,
                            normalized=True))
                processes_el2018.append(
                    Process(getattr(Backgrounds2018, background),
                            eventCounts_el,
                            negWeights_el,
                            normalized=True))
                processes_mu = [
                    processes_mu2016, processes_mu2017, processes_mu2018
                ]
                processes_el = [
                    processes_mu2016, processes_mu2017, processes_mu2018
                ]
            else:
                processes_mu2016.append(
                    Process(getattr(Backgrounds2016, background),
                            eventCounts_mu, negWeights_mu))
                processes_el2016.append(
                    Process(getattr(Backgrounds2016, background),
                            eventCounts_el, negWeights_el))
                processes_mu2017.append(
                    Process(getattr(Backgrounds, background), eventCounts_mu,
                            negWeights_mu))
                processes_el2017.append(
                    Process(getattr(Backgrounds, background), eventCounts_el,
                            negWeights_el))
                processes_mu2018.append(
                    Process(getattr(Backgrounds2018, background),
                            eventCounts_mu, negWeights_mu))
                processes_el2018.append(
                    Process(getattr(Backgrounds2018, background),
                            eventCounts_el, negWeights_el))
                processes_mu = [
                    processes_mu2016, processes_mu2017, processes_mu2018
                ]
                processes_el = [
                    processes_mu2016, processes_mu2017, processes_mu2018
                ]
        else:
            if background == "Jets":
                processes_mu.append(
                    Process(getattr(Backgrounds, background),
                            eventCounts_mu,
                            negWeights_mu,
                            normalized=True))
                processes_el.append(
                    Process(getattr(Backgrounds, background),
                            eventCounts_el,
                            negWeights_el,
                            normalized=True))
            else:
                processes_mu.append(
                    Process(getattr(Backgrounds, background), eventCounts_mu,
                            negWeights_mu))
                processes_el.append(
                    Process(getattr(Backgrounds, background), eventCounts_el,
                            negWeights_el))

    legend = TLegend(0.55, 0.75, 0.925, 0.925)
    legend.SetFillStyle(0)
    legend.SetBorderSize(0)
    legend.SetTextFont(42)

    latex = ROOT.TLatex()
    latex.SetTextFont(42)
    latex.SetTextAlign(31)
    latex.SetTextSize(0.04)
    latex.SetNDC(True)
    latexCMS = ROOT.TLatex()
    latexCMS.SetTextFont(61)
    latexCMS.SetTextSize(0.06)
    latexCMS.SetNDC(True)
    latexCMSExtra = ROOT.TLatex()
    latexCMSExtra.SetTextFont(52)
    latexCMSExtra.SetTextSize(0.045)
    latexCMSExtra.SetNDC(True)
    legendHists = []

    # Modify legend information
    legendHistData_mu = ROOT.TH1F()
    legendHistData_el = ROOT.TH1F()
    dy_mu = ROOT.TH1F()
    dy_el = ROOT.TH1F()
    if args.data:
        legendHistData_mu.SetMarkerColor(ROOT.kViolet)
        legendHistData_el.SetMarkerColor(ROOT.kOrange)
        dy_mu.SetLineColor(ROOT.kBlue - 3)
        dy_el.SetLineColor(ROOT.kRed - 3)
        legend.AddEntry(legendHistData_mu, "Data #rightarrow #mu^{+}#mu^{-}",
                        "pe")
        legend.AddEntry(legendHistData_el, "Data #rightarrow e^{+}e^{-}", "pe")
        legend.AddEntry(dy_mu, "MC Inclusive #rightarrow #mu^{+}#mu^{-}", "l")
        legend.AddEntry(dy_el, "MC Inclusive #rightarrow e^{+}e^{-}", "l")

    if args.useall:
        for i in range(3):
            for process in reversed(processes_mu[i]):
                if not plot_mu[
                        "default"].muon and "#mu^{+}#mu^{-}" in process.label:
                    process.label = process.label.replace(
                        "#mu^{+}#mu^{-}", "e^{+}e^{-}")
                process.theColor = ROOT.kBlue
                process.theLineColor = ROOT.kBlue
                temphist = ROOT.TH1F()
                temphist.SetFillColor(process.theColor)

            for process in reversed(processes_el[i]):
                if not plot_el[
                        "default"].muon and "#mu^{+}#mu^{-}" in process.label:
                    process.label = process.label.replace(
                        "#mu^{+}#mu^{-}", "e^{+}e^{-}")
                process.theColor = ROOT.kRed
                process.theLineColor = ROOT.kRed
                temphist = ROOT.TH1F()
                temphist.SetFillColor(process.theColor)
    else:
        for process in reversed(processes_mu):
            if not plot_mu[
                    "default"].muon and "#mu^{+}#mu^{-}" in process.label:
                process.label = process.label.replace("#mu^{+}#mu^{-}",
                                                      "e^{+}e^{-}")
            process.theColor = ROOT.kBlue
            process.theLineColor = ROOT.kBlue
            temphist = ROOT.TH1F()
            temphist.SetFillColor(process.theColor)

        for process in reversed(processes_el):
            if not plot_el[
                    "default"].muon and "#mu^{+}#mu^{-}" in process.label:
                process.label = process.label.replace("#mu^{+}#mu^{-}",
                                                      "e^{+}e^{-}")
            process.theColor = ROOT.kRed
            process.theLineColor = ROOT.kRed
            temphist = ROOT.TH1F()
            temphist.SetFillColor(process.theColor)

    # Modify plot pad information
    nEvents = -1

    ROOT.gStyle.SetOptStat(0)

    intlumi = ROOT.TLatex()
    intlumi.SetTextAlign(12)
    intlumi.SetTextSize(0.045)
    intlumi.SetNDC(True)
    intlumi2 = ROOT.TLatex()
    intlumi2.SetTextAlign(12)
    intlumi2.SetTextSize(0.07)
    intlumi2.SetNDC(True)
    scalelabel = ROOT.TLatex()
    scalelabel.SetTextAlign(12)
    scalelabel.SetTextSize(0.03)
    scalelabel.SetNDC(True)
    metDiffLabel = ROOT.TLatex()
    metDiffLabel.SetTextAlign(12)
    metDiffLabel.SetTextSize(0.03)
    metDiffLabel.SetNDC(True)
    chi2Label = ROOT.TLatex()
    chi2Label.SetTextAlign(12)
    chi2Label.SetTextSize(0.03)
    chi2Label.SetNDC(True)
    hCanvas.SetLogy()

    # Luminosity information
    plotPad.cd()
    plotPad.SetLogy(0)
    logScale = plot_mu["default"].log

    if logScale == True:
        plotPad.SetLogy()

    if args.use2016:
        lumi_el = 35.9 * 1000
        lumi_mu = 36.3 * 1000
    elif args.use2018:
        lumi_el = 59.97 * 1000
        lumi_mu = 61.608 * 1000
    elif args.useall:
        lumi_el = [35.9 * 1000, 41.529 * 1000, 59.97 * 1000]
        lumi_mu = [36.3 * 1000, 42.135 * 1000, 61.608 * 1000]
    else:
        lumi_el = 41.529 * 1000
        lumi_mu = 42.135 * 1000
    if args.use2016:
        zScaleFac_mu = zScale2016["muons"]
        zScaleFac_el = zScale2016["electrons"]
    elif args.use2018:
        zScaleFac_mu = zScale2018["muons"]
        zScaleFac_el = zScale2018["electrons"]
    elif args.useall:
        zScaleFac_mu = [
            zScale2016["muons"], zScale["muons"], zScale2018["muons"]
        ]
        zScaleFac_el = [
            zScale2016["electrons"], zScale["electrons"],
            zScale2018["electrons"]
        ]
    else:
        zScaleFac_mu = zScale["muons"]
        zScaleFac_el = zScale["electrons"]

    # Data and background loading
    if args.useall:
        datamu = []
        datael = []
        for i in range(3):
            datamu.append(data_all[i].loadHistogram(plot_mu["default"],
                                                    lumi_mu[i],
                                                    zScaleFac_mu[i]))
            datael.append(data_all[i].loadHistogram(plot_el["default"],
                                                    lumi_el[i],
                                                    zScaleFac_el[i]))
        stackmu = Stacks(processes_mu, lumi_mu, plot_mu["default"],
                         zScaleFac_mu)
        mu_scaleup = Stacks(processes_mu, lumi_mu, plot_mu["scale_up"],
                            zScaleFac_mu)
        mu_scaledown = Stacks(processes_mu, lumi_mu, plot_mu["scale_down"],
                              zScaleFac_mu)
        mu_ID = Stacks(processes_mu, lumi_mu, plot_mu["ID"], zScaleFac_mu)
        mu_reso = Stacks(processes_mu, lumi_mu, plot_mu["reso"], zScaleFac_mu)
        stackel = Stacks(processes_el, lumi_el, plot_el["default"],
                         zScaleFac_el)
        el_scaleup = Stacks(processes_el, lumi_el, plot_el["scale_up"],
                            zScaleFac_el)
        el_scaledown = Stacks(processes_el, lumi_el, plot_el["scale_down"],
                              zScaleFac_el)
        el_PUup = Stacks(processes_el, lumi_el, plot_el["PU_up"], zScaleFac_el)
        el_PUdown = Stacks(processes_el, lumi_el, plot_el["PU_down"],
                           zScaleFac_el)
    else:
        datamu = data_mu.loadHistogram(plot_mu["default"], lumi_mu,
                                       zScaleFac_mu)
        datael = data_el.loadHistogram(plot_el["default"], lumi_el,
                                       zScaleFac_el)
        stackmu = TheStack(processes_mu, lumi_mu, plot_mu["default"],
                           zScaleFac_mu)
        mu_scaleup = TheStack(processes_mu, lumi_mu, plot_mu["scale_up"],
                              zScaleFac_mu)
        mu_scaledown = TheStack(processes_mu, lumi_mu, plot_mu["scale_down"],
                                zScaleFac_mu)
        mu_ID = TheStack(processes_mu, lumi_mu, plot_mu["ID"], zScaleFac_mu)
        mu_reso = TheStack(processes_mu, lumi_mu, plot_mu["reso"],
                           zScaleFac_mu)

        stackel = TheStack(processes_el, lumi_el, plot_el["default"],
                           zScaleFac_el)
        el_scaleup = TheStack(processes_el, lumi_el, plot_el["scale_up"],
                              zScaleFac_el)
        el_scaledown = TheStack(processes_el, lumi_el, plot_el["scale_down"],
                                zScaleFac_el)
        el_PUup = TheStack(processes_el, lumi_el, plot_el["PU_up"],
                           zScaleFac_el)
        el_PUdown = TheStack(processes_el, lumi_el, plot_el["PU_down"],
                             zScaleFac_el)

    if args.znorm:
        muheight = stackmu.theHistogram.FindBin(90)
        print("Z height of mu: %d +- %d" %
              (stackmu.theHistogram.GetBinCenter(muheight),
               stackmu.theHistogram.GetBinWidth(muheight)))
        print("Z height of mu mc&data: %d, %d" %
              (stackmu.theHistogram.GetBinContent(muheight),
               datamu.GetBinContent(muheight)))
        elheight = stackel.theHistogram.FindBin(90)
        print("Z height of el: %d +- %d" %
              (stackel.theHistogram.GetBinCenter(elheight),
               stackel.theHistogram.GetBinWidth(elheight)))
        print("Z height of el mc&data: %d, %d" %
              (stackel.theHistogram.GetBinContent(elheight),
               datael.GetBinContent(elheight)))
        znum = stackmu.theHistogram.GetBinContent(muheight)
        for h in stackmu.theStack.GetHists():
            print("Z height of each hist in mu")
            print(h.GetBinContent(muheight))
            h.Scale(1. / znum)
        for h in stackel.theStack.GetHists():
            print("Z height of each hist in ee")
            print(h.GetBinContent(elheight))
            h.Scale(1. / znum)
        stackmu.theHistogram.Scale(1. / znum)
        stackel.theHistogram.Scale(1. / znum)

        datamu.Scale(1. / znum)
        datael.Scale(1. / znum)

    if args.ae:
        if args.useall:
            i = 0
            for year in range(2016, 2019):
                for h in stackmu[i].theStack.GetHists():
                    inverseAE(h, plot_mu["default"], year)
                for h in stackel[i].theStack.GetHists():
                    inverseAE(h, plot_el["default"], year)
                inverseAE(stackmu[i].theHistogram, plot_mu["default"], year)
                inverseAE(stackel[i].theHistogram, plot_el["default"], year)
                inverseAE(mu_scaleup[i].theHistogram, plot_mu["scale_up"],
                          year)
                inverseAE(mu_scaledown[i].theHistogram, plot_mu["scale_down"],
                          year)
                inverseAE(mu_ID[i].theHistogram, plot_mu["ID"], year)
                inverseAE(mu_reso[i].theHistogram, plot_mu["reso"], year)
                inverseAE(el_scaleup[i].theHistogram, plot_el["scale_up"],
                          year)
                inverseAE(el_scaledown[i].theHistogram, plot_el["scale_down"],
                          year)
                inverseAE(el_PUup[i].theHistogram, plot_el["PU_up"], year)
                inverseAE(el_PUdown[i].theHistogram, plot_el["PU_down"], year)
                inverseAE(datamu[i], plot_mu["default"], year)
                inverseAE(datael[i], plot_el["default"], year)
        else:
            if args.use2016: year = 2016
            elif args.use2018: year = 2018
            else: year = 2017
            for h in stackmu.theStack.GetHists():
                inverseAE(h, plot_mu["default"], year)
            for h in stackel.theStack.GetHists():
                inverseAE(h, plot_el["default"], year)
            inverseAE(stackmu.theHistogram, plot_mu["default"], year)
            inverseAE(stackel.theHistogram, plot_el["default"], year)
            inverseAE(mu_scaleup.theHistogram, plot_mu["scale_up"], year)
            inverseAE(mu_scaledown.theHistogram, plot_mu["scale_down"], year)
            inverseAE(mu_ID.theHistogram, plot_mu["ID"], year)
            inverseAE(mu_reso.theHistogram, plot_mu["reso"], year)
            inverseAE(el_scaleup.theHistogram, plot_el["scale_up"], year)
            inverseAE(el_scaledown.theHistogram, plot_el["scale_down"], year)
            inverseAE(el_PUup.theHistogram, plot_el["PU_up"], year)
            inverseAE(el_PUdown.theHistogram, plot_el["PU_down"], year)
            inverseAE(datamu, plot_mu["default"], year)
            inverseAE(datael, plot_el["default"], year)

    if args.useall:
        i = 0
        Errs_mu = []
        Errs_el = []
        for year in range(2016, 2019):
            lis_mu = [[
                mu_scaleup[i].theHistogram, mu_scaledown[i].theHistogram
            ], mu_ID[i].theHistogram, mu_reso[i].theHistogram]
            lis_el = [[
                el_scaleup[i].theHistogram, el_scaledown[i].theHistogram
            ], [el_PUup[i].theHistogram, el_PUdown[i].theHistogram]]
            Errs_mu.append(getErrors(stackmu[i].theHistogram, lis_mu))
            Errs_el.append(getErrors(stackel[i].theHistogram, lis_el))
            i += 1
        errmu = Errs_mu[0] + Errs_mu[1] + Errs_mu[2]
        errel = Errs_el[0] + Errs_el[1] + Errs_el[2]
        stackmu = Addstack(stackmu)
        stackel = Addstack(stackel)
        mu_scaleup = Addstack(mu_scaleup)
        mu_scaledown = Addstack(mu_scaledown)
        mu_ID = Addstack(mu_ID)
        mu_reso = Addstack(mu_reso)
        el_scaleup = Addstack(el_scaleup)
        el_scaledown = Addstack(el_scaledown)
        el_PUup = Addstack(el_PUup)
        el_PUdown = Addstack(el_PUdown)
        datamu = Addhist(datamu)
        datael = Addhist(datael)
    else:
        lis_mu = [[mu_scaleup.theHistogram, mu_scaledown.theHistogram],
                  mu_ID.theHistogram, mu_reso.theHistogram]
        lis_el = [[el_scaleup.theHistogram, el_scaledown.theHistogram],
                  [el_PUup.theHistogram, el_PUdown.theHistogram]]
        errmu = getErrors(stackmu.theHistogram, lis_mu)

        errel = getErrors(stackel.theHistogram, lis_el)
    if args.data:
        yMax = datamu.GetBinContent(datamu.GetMaximumBin())
        if "Mass" in plot_mu["default"].fileName:
            yMin = 0.00001
        else:
            yMin = 0.01
        xMax = datamu.GetXaxis().GetXmax()
        xMin = datael.GetXaxis().GetXmin()
    else:
        yMax = stackmu.theHistogram.GetBinContent(datahist.GetMaximumBin())
        yMin = 0.01
        xMax = stackmu.theHistogram.GetXaxis().GetXmax()
        xMin = stackmu.theHistogram.GetXaxis().GetXmin()
    if plot_mu["default"].yMax == None:
        if logScale:
            yMax = yMax * 10000
        else:
            yMax = yMax * 1.5
    else:
        yMax = plot_mu["default"].yMax

    if "Mass" in plot_mu["default"].fileName:
        yMax = 20000000

    if not plot_mu["default"].yMin == None:
        yMin = plot_mu.yMin
    if not plot_mu["default"].xMin == None:
        xMin = plot_mu["default"].xMin
    if not plot_mu["default"].xMax == None:
        xMax = plot_mu["default"].xMax

    xMin = 200
    xMax = 2000
    yMin = 1e-3
    yMax = 1e4

    if args.ae:
        yMin = 0.00001 / 40
        yMax = 200000000.0 / 40
        xMin = 200
        xMax = 2000
        yMin *= 10000
        yMax /= 10
    if args.ae:
        # ~ vh = plotPad.DrawFrame(xMin,yMin,xMax,yMax,"; %s ; %s" %("m(l^{+}l^{-}) [GeV]","3 years data"))
        vh = plotPad.DrawFrame(
            xMin, yMin, xMax, yMax, "; %s ; %s" %
            ("m(l^{+}l^{-}) [GeV]", "Events / GeV * 1/(acc. x eff)"))
    else:
        # ~ vh = plotPad.DrawFrame(xMin,yMin,xMax,yMax,"; %s ; %s" %("m(l^{+}l^{-}) [GeV]","Lumi #times d#sigma(pp#rightarrow ll)"))
        vh = plotPad.DrawFrame(
            xMin, yMin, xMax, yMax,
            "; %s ; %s" % ("m(l^{+}l^{-}) [GeV]", "Events / GeV"))
    vh.GetXaxis().SetMoreLogLabels()

    drawStack_mu = stackmu
    drawStack_el = stackel

    # Draw background from stack
    drawStack_mu.theHistogram.SetLineColor(ROOT.kBlue - 3)
    drawStack_el.theHistogram.SetLineColor(ROOT.kRed - 3)
    drawStack_mu.theHistogram.Draw("same hist")
    drawStack_el.theHistogram.Draw("same hist")

    # Draw data
    datamu.SetMinimum(0.0001)
    if args.data:
        datamu.SetMarkerColor(ROOT.kViolet)
        datael.SetMarkerColor(ROOT.kOrange)
        datamu.Draw("samep")
        datael.Draw("samep")

    # Draw legend
    if "Eta" in plot_mu["default"].fileName or "CosTheta" in plot_mu[
            "default"].fileName:
        legendEta.Draw()
    else:
        legend.Draw()

    plotPad.SetLogx(plot_mu["default"].logX)
    if args.useall:
        latex.DrawLatex(0.95, 0.96, "three years data")
    else:
        latex.DrawLatex(
            0.95, 0.96,
            "%.1f fb^{-1} (13 TeV, #mu#mu), %.1f fb^{-1} (13 TeV, ee)" %
            (lumi_mu * 0.001, lumi_el * 0.001))
    yLabelPos = 0.85
    cmsExtra = "Private Work"
    if not args.data:
        cmsExtra = "#splitline{Private Work}{Simulation}"
        yLabelPos = 0.82
    latexCMS.DrawLatex(0.19, 0.89, "CMS")
    latexCMSExtra.DrawLatex(0.19, yLabelPos, "%s" % (cmsExtra))

    if args.ratio:
        ratioPad.cd()
        ratioPad.SetLogx(plot_mu["default"].logX)

        hhmu = drawStack_mu.theHistogram
        hhel = drawStack_el.theHistogram
        h_mu_scaleup = mu_scaleup.theHistogram
        h_mu_scaledown = mu_scaledown.theHistogram
        h_mu_ID = mu_ID.theHistogram
        h_mu_reso = mu_reso.theHistogram
        h_el_scaleup = el_scaleup.theHistogram
        h_el_scaledown = el_scaledown.theHistogram
        h_el_PUup = el_PUup.theHistogram
        h_el_PUdown = el_PUdown.theHistogram
        ratioGraphs = ROOT.TGraphAsymmErrors(hhmu.GetSize() - 2)
        chann = True if "BB" in plot_mu["default"].fileName else False
        #print(errel)
        #print(errmu)
        for i in range(1, hhmu.GetSize() - 1):
            xval = hhmu.GetBinCenter(i)
            xerr = hhmu.GetBinWidth(i) / 2
            if hhel.GetBinContent(i) == 0: continue
            if hhmu.GetBinContent(i) == 0: continue
            #print(math.sqrt(errmu[i-1])/hhmu.GetBinContent(i))
            yval = hhmu.GetBinContent(i) * 1.0 / hhel.GetBinContent(i)
            yerr = yval * math.sqrt(
                (errel[i - 1]**0.5 / hhel.GetBinContent(i))**2 +
                (errmu[i - 1]**0.5 / hhmu.GetBinContent(i))**2 +
                (hhmu.GetBinError(i) / hhmu.GetBinContent(i))**2 +
                (hhel.GetBinError(i) / hhel.GetBinContent(i))**2)
            ratioGraphs.SetPoint(i, xval, yval)
            ratioGraphs.SetPointError(i, xerr, xerr, yerr, yerr)
            print("M = %f, r+-e = %f +- %f" % (xval, yval, yerr / yval))
        ratioData = ROOT.TGraphAsymmErrors(datamu.GetSize() - 2)
        for i in range(1, datamu.GetSize() - 1):
            xval = datamu.GetBinCenter(i)
            xerr = datamu.GetBinWidth(i) / 2
            if datael.GetBinContent(i) == 0: continue
            if datamu.GetBinContent(i) == 0: continue
            #print(datael.GetBinContent(i))
            #print(datael.GetBinError(i))
            yval = datamu.GetBinContent(i) * 1.0 / datael.GetBinContent(i)
            yerr = yval * math.sqrt(
                (datamu.GetBinError(i) / datamu.GetBinContent(i))**2 +
                (datael.GetBinError(i) / datael.GetBinContent(i))**2)
            ratioData.SetPoint(i, xval, yval)
            ratioData.SetPointError(i, xerr, xerr, yerr, yerr)
            print("M = %f, r+-e = %f +- %f" % (xval, yval, yerr / yval))
        nBinsX = 20
        nBinsY = 10
        if args.ae:
            hAxis = ROOT.TH2F("hAxis", "", nBinsX, xMin, xMax, nBinsY, 0.5,
                              2.5)
        else:
            hAxis = ROOT.TH2F("hAxis", "", nBinsX, xMin, xMax, nBinsY, 0.5, 5)
        hAxis.Draw("AXIS")

        hAxis.GetYaxis().SetNdivisions(408)
        hAxis.SetTitleOffset(0.4, "Y")
        hAxis.SetTitleSize(0.09, "Y")
        hAxis.SetTitleSize(0.06, "X")
        hAxis.SetYTitle("R_{#mu#mu/ee}")
        hAxis.SetXTitle("m(l^{+}l^{-}) [GeV]")
        hAxis.GetXaxis().SetLabelSize(0.048)
        hAxis.GetYaxis().SetLabelSize(0.048)
        #hAxis.GetXaxis().SetTicks("+")
        #hAxis.SetTitleSize(0.15, "Y")
        hAxis.GetXaxis().SetMoreLogLabels()
        oneLine = ROOT.TLine(xMin, 1.0, xMax, 1.0)
        oneLine.SetLineStyle(2)
        oneLine.Draw()

        ratioGraphs.SetFillColor(ROOT.kBlue - 3)
        ratioGraphs.SetMarkerColor(ROOT.kBlue - 3)
        ratioGraphs.GetXaxis().SetLabelSize(0.0)
        ratioGraphs.SetFillStyle(3002)
        ratioGraphs.Draw("SAME p")
        ratioData.SetMarkerColor(ROOT.kViolet)
        ratioData.Draw("same p")

        rlegend = TLegend(0.2, 0.65, 0.5, 0.925)
        rlegend.SetFillStyle(0)
        rlegend.SetBorderSize(1)
        rlegend.SetTextFont(42)
        rlegend.AddEntry(ratioGraphs, "e/mu in MC inclusive", "pe")
        rlegend.AddEntry(ratioData, "e/mu in data", "pe")
        rlegend.Draw("same")

        ratioPad.Update()

    ROOT.gPad.RedrawAxis()
    plotPad.RedrawAxis()
    if args.ratio:
        ratioPad.RedrawAxis()
    if not os.path.exists("lepFlavor"):
        os.makedirs("lepFlavor")

    if args.use2016: year = "2016"
    elif args.useall: year = "2016_to_2018"
    elif args.use2018: year = "2018"
    else: year = "2017"

    if args.ae: year += "_inverseAE"
    if args.znorm: year += "_znorm"

    hCanvas.Print("lepFlavor/%s_%s_datamc.pdf" %
                  (plot_mu["default"].fileName, year))
Beispiel #7
0
def dijet(category):

    channel = 'bb'
    stype = channel
    isSB = True  # relict from using Alberto's more complex script
    isData = not ISMC
    nTupleDir = NTUPLEDIR

    samples = data if isData else back
    pd = []
    for sample_name in samples:
        if YEAR == 'run2':
            pd += sample[sample_name]['files']
        else:
            pd += [x for x in sample[sample_name]['files'] if YEAR in x]
    print "datasets:", pd
    if not os.path.exists(PLOTDIR): os.makedirs(PLOTDIR)
    if BIAS: print "Running in BIAS mode"

    order = 0
    RSS = {}

    X_mass = RooRealVar("jj_mass_widejet", "m_{jj}", X_min, X_max, "GeV")
    weight = RooRealVar("MANtag_weight", "", -1.e9, 1.e9)

    variables = RooArgSet(X_mass)
    variables.add(RooArgSet(weight))

    if VARBINS:
        binsXmass = RooBinning(len(abins) - 1, abins)
        X_mass.setBinning(RooBinning(len(abins_narrow) - 1, abins_narrow))
        plot_binning = RooBinning(
            int((X_mass.getMax() - X_mass.getMin()) / 100), X_mass.getMin(),
            X_mass.getMax())
    else:
        X_mass.setBins(int((X_mass.getMax() - X_mass.getMin()) / 10))
        binsXmass = RooBinning(int((X_mass.getMax() - X_mass.getMin()) / 100),
                               X_mass.getMin(), X_mass.getMax())
        plot_binning = binsXmass

    baseCut = ""

    print stype, "|", baseCut

    print " - Reading from Tree"
    treeBkg = TChain("tree")
    for ss in pd:
        if os.path.exists(nTupleDir + ss + "_" + BTAGGING + ".root"):
            treeBkg.Add(nTupleDir + ss + "_" + BTAGGING + ".root")
        else:
            print "found no file for sample:", ss
    setData = RooDataSet("setData", "Data (QCD+TTbar MC)", variables,
                         RooFit.Cut(baseCut), RooFit.WeightVar(weight),
                         RooFit.Import(treeBkg))

    nevents = setData.sumEntries()
    dataMin, dataMax = array('d', [0.]), array('d', [0.])
    setData.getRange(X_mass, dataMin, dataMax)
    xmin, xmax = dataMin[0], dataMax[0]

    lastBin = X_mass.getMax()
    if VARBINS:
        for b in narrow_bins:
            if b > xmax:
                lastBin = b
                break

    print "Imported", (
        "data" if isData else "MC"
    ), "RooDataSet with", nevents, "events between [%.1f, %.1f]" % (xmin, xmax)
    #xmax = xmax+binsXmass.averageBinWidth() # start form next bin

    # 1 parameter
    print "fitting 1 parameter model"
    p1_1 = RooRealVar("CMS" + YEAR + "_" + category + "_p1_1", "p1", 7.0, 0.,
                      2000.)
    modelBkg1 = RooGenericPdf("Bkg1", "Bkg. fit (2 par.)",
                              "1./pow(@0/13000, @1)", RooArgList(X_mass, p1_1))
    normzBkg1 = RooRealVar(
        modelBkg1.GetName() + "_norm", "Number of background events", nevents,
        0., 5. * nevents)  #range dependent of actual number of events!
    modelExt1 = RooExtendPdf(modelBkg1.GetName() + "_ext",
                             modelBkg1.GetTitle(), modelBkg1, normzBkg1)
    fitRes1 = modelExt1.fitTo(setData, RooFit.Extended(True), RooFit.Save(1),
                              RooFit.SumW2Error(not isData),
                              RooFit.Strategy(2), RooFit.Minimizer("Minuit2"),
                              RooFit.PrintLevel(1 if VERBOSE else -1))
    fitRes1.Print()
    RSS[1] = drawFit("Bkg1", category, X_mass, modelBkg1, setData, binsXmass,
                     [fitRes1], normzBkg1.getVal())

    # 2 parameters
    print "fitting 2 parameter model"
    p2_1 = RooRealVar("CMS" + YEAR + "_" + category + "_p2_1", "p1", 0., -100.,
                      1000.)
    p2_2 = RooRealVar("CMS" + YEAR + "_" + category + "_p2_2", "p2",
                      p1_1.getVal(), -100., 600.)
    modelBkg2 = RooGenericPdf("Bkg2", "Bkg. fit (3 par.)",
                              "pow(1-@0/13000, @1) / pow(@0/13000, @2)",
                              RooArgList(X_mass, p2_1, p2_2))
    normzBkg2 = RooRealVar(modelBkg2.GetName() + "_norm",
                           "Number of background events", nevents, 0.,
                           5. * nevents)
    modelExt2 = RooExtendPdf(modelBkg2.GetName() + "_ext",
                             modelBkg2.GetTitle(), modelBkg2, normzBkg2)
    fitRes2 = modelExt2.fitTo(setData, RooFit.Extended(True), RooFit.Save(1),
                              RooFit.SumW2Error(not isData),
                              RooFit.Strategy(2), RooFit.Minimizer("Minuit2"),
                              RooFit.PrintLevel(1 if VERBOSE else -1))
    fitRes2.Print()
    RSS[2] = drawFit("Bkg2", category, X_mass, modelBkg2, setData, binsXmass,
                     [fitRes2], normzBkg2.getVal())

    # 3 parameters
    print "fitting 3 parameter model"
    p3_1 = RooRealVar("CMS" + YEAR + "_" + category + "_p3_1", "p1",
                      p2_1.getVal(), -2000., 2000.)
    p3_2 = RooRealVar("CMS" + YEAR + "_" + category + "_p3_2", "p2",
                      p2_2.getVal(), -400., 2000.)
    p3_3 = RooRealVar("CMS" + YEAR + "_" + category + "_p3_3", "p3", -2.5,
                      -500., 500.)
    modelBkg3 = RooGenericPdf(
        "Bkg3", "Bkg. fit (4 par.)",
        "pow(1-@0/13000, @1) / pow(@0/13000, @2+@3*log(@0/13000))",
        RooArgList(X_mass, p3_1, p3_2, p3_3))
    normzBkg3 = RooRealVar(modelBkg3.GetName() + "_norm",
                           "Number of background events", nevents, 0.,
                           5. * nevents)
    modelExt3 = RooExtendPdf(modelBkg3.GetName() + "_ext",
                             modelBkg3.GetTitle(), modelBkg3, normzBkg3)
    fitRes3 = modelExt3.fitTo(setData, RooFit.Extended(True), RooFit.Save(1),
                              RooFit.SumW2Error(not isData),
                              RooFit.Strategy(2), RooFit.Minimizer("Minuit2"),
                              RooFit.PrintLevel(1 if VERBOSE else -1))
    fitRes3.Print()
    RSS[3] = drawFit("Bkg3", category, X_mass, modelBkg3, setData, binsXmass,
                     [fitRes3], normzBkg3.getVal())

    # 4 parameters
    print "fitting 4 parameter model"
    p4_1 = RooRealVar("CMS" + YEAR + "_" + category + "_p4_1", "p1",
                      p3_1.getVal(), -2000., 2000.)
    p4_2 = RooRealVar("CMS" + YEAR + "_" + category + "_p4_2", "p2",
                      p3_2.getVal(), -2000., 2000.)
    p4_3 = RooRealVar("CMS" + YEAR + "_" + category + "_p4_3", "p3",
                      p3_3.getVal(), -50., 50.)
    p4_4 = RooRealVar("CMS" + YEAR + "_" + category + "_p4_4", "p4", 0.1, -50.,
                      50.)
    modelBkg4 = RooGenericPdf(
        "Bkg4", "Bkg. fit (5 par.)",
        "pow(1 - @0/13000, @1) / pow(@0/13000, @2+@3*log(@0/13000)+@4*pow(log(@0/13000), 2))",
        RooArgList(X_mass, p4_1, p4_2, p4_3, p4_4))
    normzBkg4 = RooRealVar(modelBkg4.GetName() + "_norm",
                           "Number of background events", nevents, 0.,
                           5. * nevents)
    modelExt4 = RooExtendPdf(modelBkg4.GetName() + "_ext",
                             modelBkg4.GetTitle(), modelBkg4, normzBkg4)
    fitRes4 = modelExt4.fitTo(setData, RooFit.Extended(True), RooFit.Save(1),
                              RooFit.SumW2Error(not isData),
                              RooFit.Strategy(2), RooFit.Minimizer("Minuit2"),
                              RooFit.PrintLevel(1 if VERBOSE else -1))
    fitRes4.Print()
    RSS[4] = drawFit("Bkg4", category, X_mass, modelBkg4, setData, binsXmass,
                     [fitRes4], normzBkg4.getVal())

    # Normalization parameters are should be set constant, but shape ones should not
    #    if BIAS:
    #        p1_1.setConstant(True)
    #        p2_1.setConstant(True)
    #        p2_2.setConstant(True)
    #        p3_1.setConstant(True)
    #        p3_2.setConstant(True)
    #        p3_3.setConstant(True)
    #        p4_1.setConstant(True)
    #        p4_2.setConstant(True)
    #        p4_3.setConstant(True)
    #        p4_4.setConstant(True)
    normzBkg1.setConstant(True)
    normzBkg2.setConstant(True)
    normzBkg3.setConstant(True)
    normzBkg4.setConstant(True)

    #*******************************************************#
    #                                                       #
    #                         Fisher                        #
    #                                                       #
    #*******************************************************#

    # Fisher test
    with open(PLOTDIR + "/Fisher_" + category + ".tex", 'w') as fout:
        fout.write(r"\begin{tabular}{c|c|c|c|c}")
        fout.write("\n")
        fout.write(r"function & $\chi^2$ & RSS & ndof & F-test \\")
        fout.write("\n")
        fout.write("\hline")
        fout.write("\n")
        CL_high = False
        for o1 in range(1, 5):
            o2 = min(o1 + 1, 5)
            fout.write("%d par & %.2f & %.2f & %d & " %
                       (o1 + 1, RSS[o1]["chi2"], RSS[o1]["rss"],
                        RSS[o1]["nbins"] - RSS[o1]["npar"]))
            if o2 > len(RSS):
                fout.write(r"\\")
                fout.write("\n")
                continue  #order==0 and
            CL = fisherTest(RSS[o1]['rss'], RSS[o2]['rss'], o1 + 1., o2 + 1.,
                            RSS[o1]["nbins"])
            fout.write("CL=%.3f " % (CL))
            if CL > 0.10:  # The function with less parameters is enough
                if not CL_high:
                    order = o1
                    #fout.write( "%d par are sufficient " % (o1+1))
                    CL_high = True
            else:
                #fout.write( "%d par are needed " % (o2+1))
                if not CL_high:
                    order = o2
            fout.write(r"\\")
            fout.write("\n")
        fout.write("\hline")
        fout.write("\n")
        fout.write(r"\end{tabular}")
    print "saved F-test table as", PLOTDIR + "/Fisher_" + category + ".tex"

    #print "-"*25
    #print "function & $\\chi^2$ & RSS & ndof & F-test & result \\\\"
    #print "\\multicolumn{6}{c}{", "Zprime_to_bb", "} \\\\"
    #print "\\hline"
    #CL_high = False
    #for o1 in range(1, 5):
    #    o2 = min(o1 + 1, 5)
    #    print "%d par & %.2f & %.2f & %d & " % (o1+1, RSS[o1]["chi2"], RSS[o1]["rss"], RSS[o1]["nbins"]-RSS[o1]["npar"]),
    #    if o2 > len(RSS):
    #        print "\\\\"
    #        continue #order==0 and
    #    CL = fisherTest(RSS[o1]['rss'], RSS[o2]['rss'], o1+1., o2+1., RSS[o1]["nbins"])
    #    print "%d par vs %d par CL=%f & " % (o1+1, o2+1, CL),
    #    if CL > 0.10: # The function with less parameters is enough
    #        if not CL_high:
    #            order = o1
    #            print "%d par are sufficient" % (o1+1),
    #            CL_high=True
    #    else:
    #        print "%d par are needed" % (o2+1),
    #        if not CL_high:
    #            order = o2
    #    print "\\\\"
    #print "\\hline"
    #print "-"*25
    #print "@ Order is", order, "("+category+")"

    #order = min(3, order)
    #order = 2
    if order == 1:
        modelBkg = modelBkg1  #.Clone("Bkg")
        modelAlt = modelBkg2  #.Clone("BkgAlt")
        normzBkg = normzBkg1  #.Clone("Bkg_norm")
        fitRes = fitRes1
    elif order == 2:
        modelBkg = modelBkg2  #.Clone("Bkg")
        modelAlt = modelBkg3  #.Clone("BkgAlt")
        normzBkg = normzBkg2  #.Clone("Bkg_norm")
        fitRes = fitRes2
    elif order == 3:
        modelBkg = modelBkg3  #.Clone("Bkg")
        modelAlt = modelBkg4  #.Clone("BkgAlt")
        normzBkg = normzBkg3  #.Clone("Bkg_norm")
        fitRes = fitRes3
    elif order == 4:
        modelBkg = modelBkg4  #.Clone("Bkg")
        modelAlt = modelBkg3  #.Clone("BkgAlt")
        normzBkg = normzBkg4  #.Clone("Bkg_norm")
        fitRes = fitRes4
    else:
        print "Functions with", order + 1, "or more parameters are needed to fit the background"
        exit()

    modelBkg.SetName("Bkg_" + YEAR + "_" + category)
    modelAlt.SetName("Alt_" + YEAR + "_" + category)
    normzBkg.SetName("Bkg_" + YEAR + "_" + category + "_norm")

    print "-" * 25

    # Generate pseudo data
    setToys = RooDataSet()
    setToys.SetName("data_toys")
    setToys.SetTitle("Data (toys)")
    if not isData:
        print " - Generating", nevents, "events for toy data"
        setToys = modelBkg.generate(RooArgSet(X_mass), nevents)
        #setToys = modelAlt.generate(RooArgSet(X_mass), nevents)
        print "toy data generated"

    if VERBOSE: raw_input("Press Enter to continue...")

    #*******************************************************#
    #                                                       #
    #                         Plot                          #
    #                                                       #
    #*******************************************************#

    print "starting to plot"
    c = TCanvas("c_" + category, category, 800, 800)
    c.Divide(1, 2)
    setTopPad(c.GetPad(1), RATIO)
    setBotPad(c.GetPad(2), RATIO)
    c.cd(1)
    frame = X_mass.frame()
    setPadStyle(frame, 1.25, True)
    if VARBINS: frame.GetXaxis().SetRangeUser(X_mass.getMin(), lastBin)
    signal = getSignal(
        category, stype,
        2000)  #replacing Alberto's getSignal by own dummy function

    graphData = setData.plotOn(frame, RooFit.Binning(plot_binning),
                               RooFit.Scaling(False), RooFit.Invisible())
    modelBkg.plotOn(frame, RooFit.VisualizeError(fitRes, 1, False),
                    RooFit.LineColor(602), RooFit.FillColor(590),
                    RooFit.FillStyle(1001), RooFit.DrawOption("FL"),
                    RooFit.Name("1sigma"))
    modelBkg.plotOn(frame, RooFit.LineColor(602), RooFit.FillColor(590),
                    RooFit.FillStyle(1001), RooFit.DrawOption("L"),
                    RooFit.Name(modelBkg.GetName()))
    modelAlt.plotOn(frame, RooFit.LineStyle(7), RooFit.LineColor(613),
                    RooFit.FillColor(609), RooFit.FillStyle(1001),
                    RooFit.DrawOption("L"), RooFit.Name(modelAlt.GetName()))
    if not isSB and signal[0] is not None:  # FIXME remove /(2./3.)
        signal[0].plotOn(
            frame,
            RooFit.Normalization(signal[1] * signal[2], RooAbsReal.NumEvent),
            RooFit.LineStyle(3), RooFit.LineWidth(6), RooFit.LineColor(629),
            RooFit.DrawOption("L"), RooFit.Name("Signal"))
    graphData = setData.plotOn(
        frame, RooFit.Binning(plot_binning), RooFit.Scaling(False),
        RooFit.XErrorSize(0 if not VARBINS else 1),
        RooFit.DataError(RooAbsData.Poisson if isData else RooAbsData.SumW2),
        RooFit.DrawOption("PE0"), RooFit.Name(setData.GetName()))
    fixData(graphData.getHist(), True, True, not isData)
    pulls = frame.pullHist(setData.GetName(), modelBkg.GetName(), True)
    chi = frame.chiSquare(setData.GetName(), modelBkg.GetName(), True)
    #setToys.plotOn(frame, RooFit.DataError(RooAbsData.Poisson), RooFit.DrawOption("PE0"), RooFit.MarkerColor(2))
    frame.GetYaxis().SetTitle("Events / ( 100 GeV )")
    frame.GetYaxis().SetTitleOffset(1.05)
    frame.Draw()
    #print "frame drawn"
    # Get Chi2
    #    chi2[1] = frame.chiSquare(modelBkg1.GetName(), setData.GetName())
    #    chi2[2] = frame.chiSquare(modelBkg2.GetName(), setData.GetName())
    #    chi2[3] = frame.chiSquare(modelBkg3.GetName(), setData.GetName())
    #    chi2[4] = frame.chiSquare(modelBkg4.GetName(), setData.GetName())

    frame.SetMaximum(frame.GetMaximum() * 10)
    frame.SetMinimum(max(frame.GetMinimum(), 1.e-1))
    c.GetPad(1).SetLogy()

    drawAnalysis(category)
    drawRegion(category, True)
    #drawCMS(LUMI, "Simulation Preliminary")
    drawCMS(LUMI, "Work in Progress", suppressCMS=True)

    leg = TLegend(0.575, 0.6, 0.95, 0.9)
    leg.SetBorderSize(0)
    leg.SetFillStyle(0)  #1001
    leg.SetFillColor(0)
    leg.AddEntry(setData.GetName(),
                 setData.GetTitle() + " (%d events)" % nevents, "PEL")
    leg.AddEntry(modelBkg.GetName(), modelBkg.GetTitle(),
                 "FL")  #.SetTextColor(629)
    leg.AddEntry(modelAlt.GetName(), modelAlt.GetTitle(), "L")
    if not isSB and signal[0] is not None:
        leg.AddEntry("Signal", signal[0].GetTitle(), "L")
    leg.SetY1(0.9 - leg.GetNRows() * 0.05)
    leg.Draw()

    latex = TLatex()
    latex.SetNDC()
    latex.SetTextSize(0.04)
    latex.SetTextFont(42)
    if not isSB:
        latex.DrawLatex(leg.GetX1() * 1.16,
                        leg.GetY1() - 0.04, "HVT model B (g_{V}=3)")
    #    latex.DrawLatex(0.67, leg.GetY1()-0.045, "#sigma_{X} = 1.0 pb")

    c.cd(2)
    frame_res = X_mass.frame()
    setPadStyle(frame_res, 1.25)
    frame_res.addPlotable(pulls, "P")
    setBotStyle(frame_res, RATIO, False)
    if VARBINS: frame_res.GetXaxis().SetRangeUser(X_mass.getMin(), lastBin)
    frame_res.GetYaxis().SetRangeUser(-5, 5)
    frame_res.GetYaxis().SetTitle("pulls(#sigma)")
    frame_res.GetYaxis().SetTitleOffset(0.3)
    frame_res.Draw()
    fixData(pulls, False, True, False)

    drawChi2(RSS[order]["chi2"], RSS[order]["nbins"] - (order + 1), True)
    line = drawLine(X_mass.getMin(), 0, lastBin, 0)

    if VARBINS:
        c.SaveAs(PLOTDIR + "/BkgSR_" + category + ".pdf")
        c.SaveAs(PLOTDIR + "/BkgSR_" + category + ".png")
    else:
        c.SaveAs(PLOTDIR + "/BkgSR_" + category + ".pdf")
        c.SaveAs(PLOTDIR + "/BkgSR_" + category + ".png")

    #*******************************************************#
    #                                                       #
    #                   Generate workspace                  #
    #                                                       #
    #*******************************************************#

    if BIAS:
        gSystem.Load("libHiggsAnalysisCombinedLimit.so")
        from ROOT import RooMultiPdf
        cat = RooCategory("pdf_index", "Index of Pdf which is active")
        pdfs = RooArgList(modelBkg, modelAlt)
        roomultipdf = RooMultiPdf("roomultipdf", "All Pdfs", cat, pdfs)
        normulti = RooRealVar("roomultipdf_norm",
                              "Number of background events", nevents, 0., 1.e6)

    normzBkg.setConstant(
        False
    )  ## newly put here to ensure it's freely floating in the combine fit

    # create workspace
    w = RooWorkspace("Zprime_" + YEAR, "workspace")
    # Dataset
    if isData: getattr(w, "import")(setData, RooFit.Rename("data_obs"))
    else: getattr(w, "import")(setToys, RooFit.Rename("data_obs"))
    #getattr(w, "import")(setData, RooFit.Rename("data_obs"))
    if BIAS:
        getattr(w, "import")(cat, RooFit.Rename(cat.GetName()))
        getattr(w, "import")(normulti, RooFit.Rename(normulti.GetName()))
        getattr(w, "import")(roomultipdf, RooFit.Rename(roomultipdf.GetName()))
    getattr(w, "import")(modelBkg, RooFit.Rename(modelBkg.GetName()))
    getattr(w, "import")(modelAlt, RooFit.Rename(modelAlt.GetName()))
    getattr(w, "import")(normzBkg, RooFit.Rename(normzBkg.GetName()))
    w.writeToFile(WORKDIR + "%s_%s.root" % (DATA_TYPE + "_" + YEAR, category),
                  True)
    print "Workspace", WORKDIR + "%s_%s.root" % (
        DATA_TYPE + "_" + YEAR, category), "saved successfully"
    if VERBOSE: raw_input("Press Enter to continue...")
def makeLimitPlot(output, exp, chan, printStats=False, obs2="", ratioLabel=""):
    #fileForHEPData = TFile("plots/"+output+"_forHEPData.root","RECREATE")
    fileObs = open(obs, 'r')

    observedx = []
    observedy = []

    expectedy = []
    expected1SigLow = []
    expected1SigHigh = []
    expected2SigLow = []
    expected2SigHigh = []

    for entry in fileObs:
        observedx.append(float(entry.split()[0]))
        observedy.append(float(entry.split()[6]))
        expectedy.append(float(entry.split()[3]))
        expected2SigLow.append(float(entry.split()[1]))
        expected1SigLow.append(float(entry.split()[2]))
        expected2SigHigh.append(float(entry.split()[5]))
        expected1SigHigh.append(float(entry.split()[4]))

    expX = numpy.array(observedx)
    expY = numpy.array(expectedy)

    values = []
    values2 = []

    print values
    xPointsForValues = []
    for i in range(0, len(observedx)):
        values.append(expected1SigLow[i])
        values2.append(expected2SigLow[i])

        xPointsForValues.append(observedx[i])
    for i in range(0, len(observedx)):
        values.append(expected1SigHigh[len(observedx) - i - 1])
        values2.append(expected2SigHigh[len(observedx) - i - 1])

        xPointsForValues.append(observedx[len(observedx) - i - 1])
    exp2Sig = numpy.array(values2)
    exp1Sig = numpy.array(values)
    xPointsForValues = numpy.array(xPointsForValues)

    GraphErr2Sig = TGraphAsymmErrors(len(xPointsForValues), xPointsForValues,
                                     exp2Sig)
    GraphErr2Sig.SetFillColor(ROOT.kOrange)
    GraphErr1Sig = TGraphAsymmErrors(len(xPointsForValues), xPointsForValues,
                                     exp1Sig)
    GraphErr1Sig.SetFillColor(ROOT.kGreen + 1)
    #cCL=TCanvas("cCL", "cCL",0,0,567,384)
    cCL = TCanvas("cCL", "cCL", 0, 0, 600, 450)
    gStyle.SetOptStat(0)
    gStyle.SetPadRightMargin(0.063)
    gStyle.SetPadLeftMargin(0.14)
    gStyle.SetPadBottomMargin(0.12)

    if not obs2 == "":
        plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0.3, 1, 1)
        ratioPad = ROOT.TPad("ratioPad", "ratioPad", 0, 0., 1, 0.3)
        plotPad.Draw()
        ratioPad.Draw()
        plotPad.cd()
    else:
        plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0, 1, 1)
        plotPad.Draw()
        plotPad.cd()

    expX = numpy.array(observedx)
    expY = numpy.array(expectedy)
    GraphExp = TGraph(len(expX), expX, expY)
    GraphExp.SetLineWidth(3)
    GraphExp.SetLineStyle(2)
    GraphExp.SetLineColor(ROOT.kBlue)

    obsX = numpy.array(observedx)
    obsY = numpy.array(observedy)
    if printStats: print "obsX: ", obsX
    if printStats: print "obsY: ", obsY

    if SMOOTH:
        smooth_obs = TGraphSmooth("normal")
        GraphObs_nonSmooth = TGraph(len(obsX), obsX, obsY)
        GraphObs = smooth_obs.SmoothSuper(GraphObs_nonSmooth, "linear", 0,
                                          0.005)
    else:
        GraphObs = TGraph(len(obsX), obsX, obsY)

    GraphObs.SetLineWidth(3)
    if not obs2 == "":

        ratio = []
        ratiox = []
        for index, val in enumerate(observedy):
            mass = observedx[index]
            foundIndex = -1
            for index2, mass2 in enumerate(observedx2):
                if mass == mass2:
                    foundIndex = index2

            if foundIndex > 0:
                ratio.append(observedy2[foundIndex] / val)
                ratiox.append(mass)
        ratioA = numpy.array(ratio)
        ratioX = numpy.array(ratiox)
        obsX2 = numpy.array(observedx2)
        obsY2 = numpy.array(observedy2)
        ratioGraph = TGraph(len(ratioX), ratioX, ratioA)
        if printStats: print "obsX2: ", obsX2
        if printStats: print "obsY2: ", obsY2

        if SMOOTH:
            smooth_obs2 = TGraphSmooth("normal")
            GraphObs2_nonSmooth = TGraph(len(obsX2), obsX2, obsY2)
            GraphObs2 = smooth_obs2.SmoothSuper(GraphObs2_nonSmooth, "linear",
                                                0, 0.005)
        else:
            GraphObs2 = TGraph(len(obsX2), obsX2, obsY2)

        GraphObs2.SetLineWidth(3)

    if SPIN2:
        signals = ["RS_kMpl01", "RS_kMpl005", "RS_kMpl001"]
    elif GUT:
        signals = ["ssm", "psi", "kai", "eta", "I", "S", "N"]
    else:
        signals = ["ssm", "psi"]

    xSecCurves = []
    for signal in signals:
        xSecCurves.append(getXSecCurve(signal, kFacs[signal]))
        #xSecCurves.append(getXSecCurve(signal,kFacs[signal],massDependent=True))

#Draw the graphs:
    plotPad.SetLogy()
    DummyGraph = TH1F("DummyGraph", "", 100, 200, 5500)
    DummyGraph.GetXaxis().SetTitle("M [GeV]")
    if SPIN2:
        DummyGraph.GetYaxis().SetTitle(
            "[#sigma#upoint#font[12]{B}] G_{KK} / [#sigma#upoint#font[12]{B}] Z"
        )
    else:
        DummyGraph.GetYaxis().SetTitle(
            "[#sigma#upoint#font[12]{B}] Z' / [#sigma#upoint#font[12]{B}] Z")

#	if SPIN2:
#	    	if chan=="mumu":
#       	 		DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowG_{KK}+X#rightarrow#mu^{+}#mu^{-}+X) / #sigma(pp#rightarrowZ+X#rightarrow#mu^{+}#mu^{-}+X)")
#    		elif chan=="elel":
#        		DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowG_{KK}+X#rightarrowee+X) / #sigma(pp#rightarrowZ+X#rightarrowee+X)")
#    		elif chan=="elmu":
#        		DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowG_{KK}+X#rightarrow#font[12]{ll}+X) / #sigma(pp#rightarrowZ+X#rightarrow#font[12]{ll}+X)")
#	else:
#    		if chan=="mumu":
#        		DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowZ'+X#rightarrow#mu^{+}#mu^{-}+X) / #sigma(pp#rightarrowZ+X#rightarrow#mu^{+}#mu^{-}+X)")
#    		elif chan=="elel":
#        		DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowZ'+X#rightarrowee+X) / #sigma(pp#rightarrowZ+X#rightarrowee+X)")
#    		elif chan=="elmu":
#        		DummyGraph.GetYaxis().SetTitle("#sigma(pp#rightarrowZ'+X#rightarrow#font[12]{ll}+X) / #sigma(pp#rightarrowZ+X#rightarrow#font[12]{ll}+X)")

    gStyle.SetOptStat(0)
    DummyGraph.GetXaxis().SetRangeUser(200, 5500)

    DummyGraph.SetMinimum(5e-9)
    DummyGraph.SetMaximum(1e-4)
    DummyGraph.GetXaxis().SetLabelSize(0.055)
    DummyGraph.GetXaxis().SetTitleSize(0.055)
    DummyGraph.GetXaxis().SetTitleOffset(1.05)
    DummyGraph.GetYaxis().SetLabelSize(0.055)
    DummyGraph.GetYaxis().SetTitleSize(0.055)
    DummyGraph.GetYaxis().SetTitleOffset(1.3)
    DummyGraph.Draw()
    if (FULL):
        GraphErr2Sig.Draw("F")
        GraphErr1Sig.Draw("F")
        GraphExp.Draw("lpsame")
    else:
        if obs2 == "":
            GraphExp.Draw("lp")
    if not EXPONLY:
        GraphObs.Draw("plsame")
    if not obs2 == "":
        GraphObs2.SetLineColor(ROOT.kRed)
        GraphObs2.SetLineStyle(ROOT.kDashed)
        GraphObs2.Draw("plsame")
    for curve in xSecCurves:
        curve.Draw("lsame")

    plCMS = TPaveLabel(.16, .81, .27, .88, "CMS", "NBNDC")
    #plCMS.SetTextSize(0.8)
    plCMS.SetTextAlign(12)
    plCMS.SetTextFont(62)
    plCMS.SetFillColor(0)
    plCMS.SetFillStyle(0)
    plCMS.SetBorderSize(0)

    plCMS.Draw()

    plPrelim = TPaveLabel(.16, .76, .27, .82, "Preliminary", "NBNDC")
    plPrelim.SetTextSize(0.6)
    plPrelim.SetTextAlign(12)
    plPrelim.SetTextFont(52)
    plPrelim.SetFillColor(0)
    plPrelim.SetFillStyle(0)
    plPrelim.SetBorderSize(0)
    if "2017" in output or "Combination" in output or 'Run2' in output:
        plPrelim.Draw()

    cCL.SetTickx(1)
    cCL.SetTicky(1)
    cCL.RedrawAxis()
    cCL.Update()

    #leg=TLegend(0.65,0.65,0.87,0.87,"","brNDC")
    #leg=TLegend(0.540517,0.623051,0.834885,0.878644,"","brNDC")   Default
    leg = TLegend(0.5, 0.58, 0.834885, 0.878644, "", "brNDC")
    if SPIN2:
        leg = TLegend(0.5, 0.58, 0.834885, 0.878644, "", "brNDC")
#    	leg=TLegend(0.55,0.55,0.87,0.87,"","brNDC")
    leg.SetTextSize(0.0425)
    if not obs2 == "":
        if ratioLabel == "":
            ratioLabel = "Variant/Default"
        ratioLabels = ratioLabel.split("/")
        print ratioLabels
        leg.AddEntry(GraphObs, "%s Obs. 95%% CL limit" % ratioLabels[1], "l")
        leg.AddEntry(GraphObs2, "%s Obs. 95%% CL limit" % ratioLabels[0], "l")

    else:
        if not EXPONLY:
            leg.AddEntry(GraphObs, "Obs. 95% CL limit", "l")
        leg.AddEntry(GraphExp, "Exp. 95% CL limit, median", "l")
        if (FULL):
            leg.AddEntry(GraphErr1Sig, "Exp. (68%)", "f")
            leg.AddEntry(GraphErr2Sig, "Exp. (95%)", "f")

    leg1 = TLegend(0.7, 0.4, 0.9, 0.55, "", "brNDC")
    leg1.SetTextSize(0.05)
    if GUT:
        leg1 = TLegend(0.6, 0.35, 0.75, 0.623051, "", "brNDC")
    if SPIN2:
        leg1 = TLegend(0.7, 0.35, 0.9, 0.58, "G_{KK} (LO x 1.6)", "brNDC")
        leg1.SetTextSize(0.045)
    for index, signal in enumerate(signals):
        xSecCurves[index].SetName(labels[signal])
        xSecCurves[index].Write(labels[signal])
        leg1.AddEntry(xSecCurves[index], labels[signal], "l")
    leg1.SetBorderSize(0)

    leg.SetLineWidth(0)
    leg.SetLineStyle(0)
    leg.SetFillStyle(0)
    leg.SetLineColor(0)
    leg.Draw("hist")

    leg1.SetLineWidth(0)
    leg1.SetLineStyle(0)
    leg1.SetFillStyle(0)
    leg1.SetLineColor(0)
    leg1.Draw("hist")
    if "Moriond" in output:
        if (chan == "mumu"):
            plLumi = TPaveLabel(.65, .885, .9, .99,
                                "36.3 fb^{-1} (13 TeV, #mu^{+}#mu^{-})",
                                "NBNDC")
        elif (chan == "elel"):
            plLumi = TPaveLabel(.65, .885, .9, .99,
                                "35.9 fb^{-1} (13 TeV, ee)", "NBNDC")
        elif (chan == "elmu"):
            plLumi = TPaveLabel(
                .27, .885, .9, .99,
                "35.9 fb^{-1} (13 TeV, ee) + 36.3 fb^{-1} (13 TeV, #mu^{+}#mu^{-})",
                "NBNDC")

    elif "2017" in output or "Combination" in output:
        if (chan == "mumu"):
            plLumi = TPaveLabel(.65, .885, .9, .99,
                                "42.4 fb^{-1} (13 TeV, #mu^{+}#mu^{-})",
                                "NBNDC")
        elif (chan == "elel"):
            plLumi = TPaveLabel(.65, .885, .9, .99,
                                "41.4 fb^{-1} (13 TeV, ee)", "NBNDC")
        elif (chan == "elmu"):
            plLumi = TPaveLabel(
                .27, .885, .9, .99,
                "77.3 fb^{-1} (13 TeV, ee) + 78.7 fb^{-1} (13 TeV, #mu^{+}#mu^{-})",
                "NBNDC")
    else:
        if (chan == "mumu"):
            plLumi = TPaveLabel(.65, .905, .9, .99,
                                " 139.7 fb^{-1} (13 TeV, #mu#mu)", "NBNDC")
        elif (chan == "elel"):
            plLumi = TPaveLabel(.65, .905, .9, .99,
                                "136.8 fb^{-1} (13 TeV, ee)", "NBNDC")
        elif (chan == "elmu"):
            plLumi = TPaveLabel(
                .4, .905, .9, .99,
                "136.8 fb^{-1} (13 TeV, ee) + 139.7 fb^{-1} (13 TeV, #mu#mu)",
                "NBNDC")

    plLumi.SetTextSize(0.5)
    plLumi.SetTextFont(42)
    plLumi.SetFillColor(0)
    plLumi.SetBorderSize(0)
    plLumi.Draw()

    plotPad.SetTicks(1, 1)
    plotPad.RedrawAxis()

    if not obs2 == "":

        ratioPad.cd()

        line = ROOT.TLine(200, 1, 5500, 1)
        line.SetLineStyle(ROOT.kDashed)

        ROOT.gStyle.SetTitleSize(0.12, "Y")
        ROOT.gStyle.SetTitleYOffset(0.35)
        ROOT.gStyle.SetNdivisions(000, "Y")
        ROOT.gStyle.SetNdivisions(408, "Y")
        ratioPad.DrawFrame(200, 0.8, 5500, 1.2, "; ; %s" % ratioLabel)

        line.Draw("same")

        ratioGraph.Draw("sameP")

#GraphErr2SigForHEPData.SetName("graph2Sig")
#GraphErr2SigForHEPData.Write("graph2Sig")

#GraphErr1SigForHEPData.SetName("graph1Sig")
#GraphErr1SigForHEPData.Write("graph1Sig")

#GraphExp.SetName("graphExp")
#GraphExp.Write("graphExp")

#GraphObs.SetName("graphObs")
#GraphObs.Write("graphObs")

#fileForHEPData.Write()
#fileForHEPData.Close()
    cCL.Update()
    printPlots(cCL, output)
Beispiel #9
0
def createPlots_(plot):
    """Cumulative material budget from simulation.
    
       Internal function that will produce a cumulative profile of the
       material budget inferred from the simulation starting from the
       single detectors that compose the tracker. It will iterate over
       all existing detectors contained in the DETECTORS
       dictionary. The function will automatically skip non-existent
       detectors.

    """

    IBs = ["InnerServices", "Phase2PixelBarrel", "TIB", "TIDF", "TIDB"]
    theDirname = "Figures"

    if plot not in plots.keys():
        print("Error: chosen plot name not known %s" % plot)
        return

    hist_X0_IB = None
    # We need to keep the file content alive for the lifetime of the
    # full function....
    subDetectorFiles = []

    hist_X0_elements = OrderedDict()
    prof_X0_elements = OrderedDict()
    for subDetector, color in six.iteritems(DETECTORS):
        subDetectorFilename = "matbdg_%s.root" % subDetector
        if not checkFile_(subDetectorFilename):
            print("Error opening file: %s" % subDetectorFilename)
            continue

        subDetectorFiles.append(TFile(subDetectorFilename))
        subDetectorFile = subDetectorFiles[-1]
        print("Opening file: %s" % subDetectorFilename)
        prof_X0_XXX = subDetectorFile.Get("%d" % plots[plot].plotNumber)

        # Merge together the "inner barrel detectors".
        if subDetector in IBs:
            hist_X0_IB = assignOrAddIfExists_(hist_X0_IB, prof_X0_XXX)

        hist_X0_detectors[subDetector] = prof_X0_XXX.ProjectionX()

        # category profiles
        for label, [num, color, leg] in six.iteritems(hist_label_to_num):
            prof_X0_elements[label] = subDetectorFile.Get(
                "%d" % (num + plots[plot].plotNumber))
            hist_X0_elements[label] = assignOrAddIfExists_(
                hist_X0_elements.setdefault(label, None),
                prof_X0_elements[label])

    cumulative_matbdg = TH1D("CumulativeSimulMatBdg", "CumulativeSimulMatBdg",
                             hist_X0_IB.GetNbinsX(),
                             hist_X0_IB.GetXaxis().GetXmin(),
                             hist_X0_IB.GetXaxis().GetXmax())
    cumulative_matbdg.SetDirectory(0)

    # colors
    for det, color in six.iteritems(DETECTORS):
        setColorIfExists_(hist_X0_detectors, det, color)

    for label, [num, color, leg] in six.iteritems(hist_label_to_num):
        hist_X0_elements[label].SetFillColor(color)

    # First Plot: BeamPipe + Pixel + TIB/TID + TOB + TEC + Outside
    # stack
    stackTitle_SubDetectors = "Tracker Material Budget;%s;%s" % (
        plots[plot].abscissa, plots[plot].ordinate)
    stack_X0_SubDetectors = THStack("stack_X0", stackTitle_SubDetectors)
    for det, histo in six.iteritems(hist_X0_detectors):
        stack_X0_SubDetectors.Add(histo)
        cumulative_matbdg.Add(histo, 1)

    # canvas
    can_SubDetectors = TCanvas("can_SubDetectors", "can_SubDetectors", 800,
                               800)
    can_SubDetectors.Range(0, 0, 25, 25)
    can_SubDetectors.SetFillColor(kWhite)

    # Draw
    stack_X0_SubDetectors.SetMinimum(plots[plot].ymin)
    stack_X0_SubDetectors.SetMaximum(plots[plot].ymax)
    stack_X0_SubDetectors.Draw("HIST")
    stack_X0_SubDetectors.GetXaxis().SetLimits(plots[plot].xmin,
                                               plots[plot].xmax)

    # Legenda
    theLegend_SubDetectors = TLegend(0.180, 0.8, 0.98, 0.92)
    theLegend_SubDetectors.SetNColumns(3)
    theLegend_SubDetectors.SetFillColor(0)
    theLegend_SubDetectors.SetFillStyle(0)
    theLegend_SubDetectors.SetBorderSize(0)

    for det, histo in six.iteritems(hist_X0_detectors):
        theLegend_SubDetectors.AddEntry(histo, det, "f")

    theLegend_SubDetectors.Draw()

    # text
    text_SubDetectors = TPaveText(0.180, 0.727, 0.402, 0.787, "NDC")
    text_SubDetectors.SetFillColor(0)
    text_SubDetectors.SetBorderSize(0)
    text_SubDetectors.AddText("CMS Simulation")
    text_SubDetectors.SetTextAlign(11)
    text_SubDetectors.Draw()

    # Store
    can_SubDetectors.Update()
    if not checkFile_(theDirname):
        os.mkdir(theDirname)
    can_SubDetectors.SaveAs("%s/Tracker_SubDetectors_%s.pdf" %
                            (theDirname, plot))
    can_SubDetectors.SaveAs("%s/Tracker_SubDetectors_%s.root" %
                            (theDirname, plot))

    # Second Plot: BeamPipe + SEN + ELE + CAB + COL + SUP + OTH/AIR +
    # Outside stack
    stackTitle_Materials = "Tracker Material Budget;%s;%s" % (
        plots[plot].abscissa, plots[plot].ordinate)
    stack_X0_Materials = THStack("stack_X0", stackTitle_Materials)
    stack_X0_Materials.Add(hist_X0_detectors["BeamPipe"])
    for label, [num, color, leg] in six.iteritems(hist_label_to_num):
        stack_X0_Materials.Add(hist_X0_elements[label])

    # canvas
    can_Materials = TCanvas("can_Materials", "can_Materials", 800, 800)
    can_Materials.Range(0, 0, 25, 25)
    can_Materials.SetFillColor(kWhite)

    # Draw
    stack_X0_Materials.SetMinimum(plots[plot].ymin)
    stack_X0_Materials.SetMaximum(plots[plot].ymax)
    stack_X0_Materials.Draw("HIST")
    stack_X0_Materials.GetXaxis().SetLimits(plots[plot].xmin, plots[plot].xmax)

    # Legenda
    theLegend_Materials = TLegend(0.180, 0.8, 0.95, 0.92)
    theLegend_Materials.SetNColumns(3)
    theLegend_Materials.SetFillColor(0)
    theLegend_Materials.SetBorderSize(0)

    theLegend_Materials.AddEntry(hist_X0_detectors["BeamPipe"], "Beam Pipe",
                                 "f")
    for label, [num, color, leg] in six.iteritems(hist_label_to_num):
        theLegend_Materials.AddEntry(hist_X0_elements[label], leg, "f")
    theLegend_Materials.Draw()

    # text
    text_Materials = TPaveText(0.180, 0.727, 0.402, 0.787, "NDC")
    text_Materials.SetFillColor(0)
    text_Materials.SetBorderSize(0)
    text_Materials.AddText("CMS Simulation")
    text_Materials.SetTextAlign(11)
    text_Materials.Draw()

    # Store
    can_Materials.Update()
    can_Materials.SaveAs("%s/Tracker_Materials_%s.pdf" % (theDirname, plot))
    can_Materials.SaveAs("%s/Tracker_Materials_%s.root" % (theDirname, plot))

    return cumulative_matbdg
def plotInputComparison(files,runs,processes,path):

    #clear memory 
    gROOT.Reset()
#make canvas to save plots to
    c1 = TCanvas('c1')
    c1.SetLogy()
    i=0
    Tfiles=[]
    while i<len(files):
        print "Adding file: %s to list of files to run with Run Number: %s and Process Name: %s" % (files[i],runs[i],processes[i])
        Tfiles.append(TFile(files[i]))
        i+=1

    j=0
    Thists=[]
    while j<len(Tfiles):
        dirname="DQMData/Run %s/HLT/Run summary/TimerService/Running 1 processes/process %s/Paths/%s_module_counter" % (runs[j],processes[j],path)
        print dirname
        hist=Tfiles[j].Get(dirname)

        Thists.append(hist)
        j+=1

    k=0
    leg = TLegend(0.4,0.6,0.9,0.9,"")
    leg.SetFillStyle(0)
    leg.SetBorderSize(0)

    while k< len(Thists):
        if k==0:
            Thists[k].Scale( 1.0 / Thists[k].Integral() )
            Thists[k].GetYaxis().SetRangeUser(0.000008,0.2)
            print "lower bound of bin 100: %i" % Thists[k].GetBinCenter(100)
            print "percentage of events running particle flow: %i " % Thists[k].Integral(100,500)
            Thists[k].SetLineWidth(2)
            Thists[k].SetLineColor(k+1)
            if args.ext:
                Thists[k].GetXaxis().SetRangeUser(0,2000)
            else:
                Thists[k].GetXaxis().SetRangeUser(0,400)
            Thists[k].Draw()

        else:
            Thists[k].Scale( 1.0 / Thists[k].Integral() )
            Thists[k].SetLineWidth(2)
            Thists[k].SetLineColor(k+1)
            Thists[k].Draw("same")
        #write name in full
        name = files[k]
        if args.ext:
            Thists[k].GetXaxis().SetRangeUser(0,2000)
        else:
            Thists[k].GetXaxis().SetRangeUser(0,400)
  
        leg.AddEntry(Thists[k],name,"l")
        k+=1
        
    leg.Draw("same")

    filename='ModuleCounter_%s.pdf' %path
    c1.Print(filename)
Beispiel #11
0
def drawHistsWithRatio(hists, name, **kwargs):
    """Draw histograms with ratios."""

    title = kwargs.get('title', "")
    xtitle = kwargs.get('xtitle', "")
    ytitle = kwargs.get('ytitle', "")
    rtitle = kwargs.get('rtitle', "Ratio")
    xmin = kwargs.get('xmin', hists[0].GetXaxis().GetXmin())
    xmax = kwargs.get('xmax', hists[0].GetXaxis().GetXmax())
    ymin = kwargs.get('ymin', None)
    ymax = kwargs.get('ymax', None)
    rmin = kwargs.get('rmin', 0.45)
    rmax = kwargs.get('rmax', 1.55)
    logx = kwargs.get('logx', False)
    logy = kwargs.get('logy', False)
    denom = kwargs.get('denom', 1) - 1  # denominator for ratio
    textsize = kwargs.get('textsize', 0.045)
    texts = kwargs.get('text', [])
    #textheight = kwargs.get('textheight',   1.09                 )
    #ctext      = kwargs.get('ctext',        [ ]                  ) # corner text
    #cposition  = kwargs.get('cposition',    'topleft'            ).lower() # cornertext
    #ctextsize  = kwargs.get('ctextsize',    1.4*legendtextsize   )
    colors = kwargs.get('colors', linecolors)
    if not isinstance(texts, list) or isinstance(texts, tuple):
        texts = [texts]
    if ymax == None:
        ymax = 1.12 * max(h.GetMaximum() for h in hists)

    # MAIN plot
    canvas = TCanvas('canvas', 'canvas', 100, 100, 800, 800)
    canvas.SetFillColor(0)
    canvas.SetBorderMode(0)
    canvas.SetFrameBorderMode(0)
    canvas.Divide(2)
    canvas.SetMargin(0.0, 0.0, 0.0, 0.0)
    canvas.cd(1)
    gPad.SetPad('pad1', 'pad1', 0, 0.33, 1, 1)
    gPad.SetMargin(0.12, 0.04, 0.02, 0.08)
    gPad.SetFillColor(0)
    gPad.SetBorderMode(0)
    gPad.SetTickx(0)
    gPad.SetTicky(0)
    gPad.SetGrid()
    gPad.Draw()
    canvas.cd(2)
    gPad.SetPad('pad2', 'pad2', 0, 0, 1, 0.33)
    gPad.SetMargin(0.12, 0.04, 0.30, 0.03)
    gPad.SetFillColor(0)
    gPad.SetFillStyle(4000)
    gPad.SetFrameFillStyle(0)
    gPad.SetBorderMode(0)
    gPad.Draw()

    # MAIN plot
    canvas.cd(1)
    for i, hist in enumerate(hists):
        color = colors[i % len(colors)]
        hist.SetLineColor(color)
        hist.SetLineWidth(2)
        hist.Draw('HIST SAME')
    frame = hists[0]
    frame.GetYaxis().SetTitleSize(0.060)
    frame.GetXaxis().SetTitleSize(0)
    frame.GetXaxis().SetLabelSize(0)
    frame.GetYaxis().SetLabelSize(0.052)
    frame.GetXaxis().SetLabelOffset(0.010)
    frame.GetXaxis().SetTitleOffset(0.98)
    frame.GetYaxis().SetTitleOffset(1.05)
    frame.GetXaxis().SetNdivisions(508)
    frame.GetYaxis().SetTitle(ytitle)
    frame.GetXaxis().SetTitle(xtitle)
    if logx:
        gPad.Update()
        gPad.SetLogx()
    if logy:
        gPad.Update()
        gPad.SetLogy()
    if ymin: frame.SetMinimum(ymin)
    if ymax: frame.SetMaximum(ymax)

    width = 0.25
    height = 1.1 * textsize * len([l for l in texts + hists if l])
    x1, y1 = 0.65, 0.88
    x2, y2 = x1 + width, y1 - height
    legend = TLegend(x1, y1, x2, y2)
    legend.SetTextSize(textsize)
    legend.SetBorderSize(0)
    legend.SetFillStyle(0)
    legend.SetFillColor(0)
    legend.SetMargin(0.05 / width)
    if title:
        legend.SetTextFont(62)
        legend.SetHeader(title)
    legend.SetTextFont(42)
    for hist in hists:
        legend.AddEntry(hist, hist.GetTitle(), 'l')
    for text in texts:
        legend.AddEntry(0, text, '')
    legend.Draw()

    gPad.SetTicks(1, 1)
    gPad.Modified()
    frame.Draw('AXIS SAME')
    CMS_style.CMS_lumi(gPad, 13, 0)

    # RATIO plot
    canvas.cd(2)
    ratios = []
    for i, hist in enumerate(hists):
        if i == denom: continue
        ratio = hist.Clone(hist.GetName() + "_ratio")
        ratio.Divide(hists[denom])
        ratio.Draw('HIST SAME')
        ratios.append(ratio)
    frame_ratio = ratios[0]
    frame_ratio.GetYaxis().SetRangeUser(rmin, rmax)
    frame_ratio.GetYaxis().CenterTitle()
    frame_ratio.GetYaxis().SetTitleSize(0.13)
    frame_ratio.GetXaxis().SetTitleSize(0.13)
    frame_ratio.GetXaxis().SetLabelSize(0.12)
    frame_ratio.GetYaxis().SetLabelSize(0.11)
    frame_ratio.GetXaxis().SetLabelOffset(0.012)
    frame_ratio.GetXaxis().SetTitleOffset(1.02)
    frame_ratio.GetYaxis().SetTitleOffset(0.48)
    frame_ratio.GetXaxis().SetNdivisions(508)
    frame_ratio.GetYaxis().CenterTitle(True)
    frame_ratio.GetYaxis().SetTitle(rtitle)
    frame_ratio.GetXaxis().SetTitle(xtitle)
    frame_ratio.GetYaxis().SetNdivisions(505)
    if logx:
        gPad.Update()
        gPad.SetLogx()
    line = TLine(xmin, 1., xmax, 1.)
    line.SetLineColor(hists[denom].GetLineColor())
    line.SetLineWidth(hists[denom].GetLineWidth())
    line.SetLineStyle(1)
    line.Draw('SAME')
    gPad.SetTicks(1, 1)
    gPad.Update()
    gPad.SetGrid()
    gPad.Modified()
    frame_ratio.Draw('SAME AXIS')

    canvas.SaveAs(name + ".png")
    canvas.SaveAs(name + ".pdf")
    canvas.Close()
Beispiel #12
0
def printmultigraph(grs, sortk, plotoptions, outn, title, year, doext,
                    ploterror, ymax):
    import CMS_lumi, tdrstyle
    import array
    #set the tdr style
    tdrstyle.setTDRStyle()

    #change the CMS_lumi variables (see CMS_lumi.py)
    CMS_lumi.writeExtraText = 1
    CMS_lumi.extraText = "Preliminary"
    if year == 2018:
        CMS_lumi.extraText2 = "2018 pp data"
    if year == 2017:
        CMS_lumi.extraText2 = "2017 pp data"
    if year == 2016:
        CMS_lumi.extraText2 = "2016 pp data"
    CMS_lumi.lumi_sqrtS = "13 TeV"  # used with iPeriod = 0, e.g. for simulation-only plots (default is an empty string)
    CMS_lumi.writeTitle = 1
    CMS_lumi.textTitle = title

    iPos = 11
    if (iPos == 0): CMS_lumi.relPosX = 0.12

    H_ref = 600
    W_ref = 800
    W = W_ref
    H = H_ref

    iPeriod = 0
    # references for T, B, L, R
    T = 0.08 * H_ref
    B = 0.12 * H_ref
    L = 0.12 * W_ref
    R = 0.04 * W_ref

    c = TCanvas("c", "c", 50, 50, W, H)
    #gStyle.SetOptStat(0)
    c.SetFillColor(0)
    c.SetBorderMode(0)
    c.SetFrameFillStyle(0)
    c.SetFrameBorderMode(0)
    c.SetLeftMargin(L / W)
    c.SetRightMargin(R / W)
    c.SetTopMargin(T / H)
    c.SetBottomMargin(B / H)
    c.SetTickx(0)
    c.SetTicky(0)
    #canvassettings(c)

    mg = TMultiGraph()
    mg.SetTitle(title)
    #gStyle.SetTitleAlign(33)
    #gStyle.SetTitleX(0.99)
    leg = TLegend(
        0.345, 0.68, 0.645, 0.88
    )  #TLegend(1. - c.GetRightMargin() - 0.8, 1. - c.GetTopMargin() - 0.40,1. - c.GetRightMargin()- 0.60, 1. - c.GetTopMargin() -0.02)
    leg.SetFillStyle(0)
    leg.SetBorderSize(0)
    leg.SetMargin(0.1)
    #ymax = 0;
    ratesFromFit = {}
    evVal = 15000
    if doext:
        evVal = 50000

    #f=TFile.Open(outn+".root","RECREATE")


#  for name,value in plotoptions.iteritems():
    for name in sortk:
        if name != 'main': continue
        value = plotoptions[name]
        #print grs
        gr = grs[name]
        #print gr
        gr.SetName(title)
        #extrate = fitGraph(gr,evVal)
        #ratesFromFit[name] = extrate
        if doext:
            #print name, extrate[0], extrate[1]
            NN = gr.GetN()
            gr.Set(NN + 1)
            gr.SetPoint(NN + 1, 50000.0, extrate["rate"][0])
            yErr = extrate["rate"][1]
            if not ploterror:
                yErr = 0.0
            gr.SetPointError(NN + 1, 0.0, yErr)
        gr.SetMarkerColor(value['color'])
        gr.SetMarkerStyle(value['markst'])
        gr.SetLineColor(value['color'])
        gr.SetMarkerSize(1.15)  #1.05
        gr.SetMinimum(0.1)
        #gr.Write()
        mg.Add(gr)
        text = title  #name #+plotoptions[name]['leg']
        leg.AddEntry(gr, text, "p")
        continue

    mg.SetName(outn)
    mg.SetMinimum(0.1)
    mg.SetMaximum(ymax)  #1.6*ymax
    mg.Draw("AP")
    mg.GetXaxis().SetRangeUser(2000, 20000)
    c.Update()
    graphAxis(mg)

    CMS_lumi.CMS_lumi(c, iPeriod, iPos)
    c.cd()
    c.Update()
    frame = c.GetFrame()
    frame.Draw()

    leg.Draw()
    c.SaveAs(outn + ".png")
    #c.SaveAs(outn+".C")
    del c

    return ratesFromFit
Beispiel #13
0
def DrawOverlap(histList,
                titleVec,
                legendtext,
                pngname,
                logstatus=[0, 0],
                xRange=[-99999, 99999, 1],
                cat='2b'):

    gStyle.SetOptTitle(0)
    gStyle.SetOptStat(0)
    gStyle.SetTitleOffset(1.1, "Y")
    #gStyle.SetTitleOffset(1.9,"X");
    gStyle.SetLineWidth(3)
    gStyle.SetFrameLineWidth(3)
    gStyle.SetTickLength(0.0, "x")

    i = 0

    # histList_=[]
    # histList=[]
    # histList1=[]
    # maximum=[]

    ## Legend
    leg = TLegend(0.2, 0.80, 0.89, 0.89)  #,NULL,"brNDC");
    leg.SetBorderSize(0)
    leg.SetNColumns(3)
    # leg.SetLineColor(1)
    leg.SetLineStyle(1)
    leg.SetLineWidth(1)
    # leg.SetFillColor(0)
    leg.SetFillStyle(0)
    leg.SetTextFont(42)
    leg.SetTextSize(0.05)

    c = TCanvas("c1", "c1", 0, 0, 500, 500)
    c.SetBottomMargin(0.15)
    c.SetLeftMargin(0.15)
    c.SetLogy(logstatus[1])
    c.SetLogx(logstatus[0])
    # print ("you have provided "+str(len(fileVec))+" files and "+str(len(histVec))+" histograms to make a overlapping plot" )
    # print "opening rootfiles"
    c.cd()

    print "provided hists", histList
    for ih in range(len(histList)):
        tt = type(histList[ih])
        if logstatus[1] is 1:
            histList[ih].SetMaximum(1.5)  #1.4 for log
            histList[ih].SetMinimum(0.1)  #1.4 for log
        if logstatus[1] is 0:
            maxi = histList[ih].GetMaximum()
            histList[ih].SetMaximum(maxi * 2)  #1.4 for log
            histList[ih].SetMinimum(0)  #1.4 for log
#        print "graph_status =" ,(tt is TGraphAsymmErrors)
#        print "hist status =", (tt is TH1D) or (tt is TH1F)
        if ih == 0:
            if tt is TGraphAsymmErrors:
                histList[ih].Draw("APL")
            if (tt is TH1D) or (tt is TH1F) or (tt is TH1) or (tt is TH1I):
                histList[ih].Draw("PE2 ")
        if ih > 0:
            #histList[ih].SetLineWidth(2)
            if tt is TGraphAsymmErrors:
                histList[ih].Draw("PL same")
            if (tt is TH1D) or (tt is TH1F) or (tt is TH1) or (tt is TH1I):
                histList[ih].Draw("PE0  same")

        if tt is TGraphAsymmErrors:
            histList[ih].SetMaximum(100)
            histList[ih].SetMarkerColor(colors[ih])
            histList[ih].SetLineColor(colors[ih])
            histList[ih].SetLineWidth(0)
            histList[ih].SetMarkerStyle(markerStyle[ih])
            histList[ih].SetMarkerSize(1)
            leg.AddEntry(histList[ih], legendtext[ih], "PL")
        if (tt is TH1D) or (tt is TH1F) or (tt is TH1) or (tt is TH1I):
            print "setting style for hist"
            print "color code", colors[ih]
            # histList[ih].SetLineStyle(linestyle[ih])
            histList[ih].SetLineColor(colors[ih])
            histList[ih].SetMarkerColor(colors[ih])
            histList[ih].SetFillColor(colors[ih])
            histList[ih].SetMarkerStyle(20)
            histList[ih].SetMarkerSize(1.0)
            histList[ih].SetLineWidth(1)
            #invert legend between first and second
            if ih == 0:
                leg.AddEntry(histList[ih + 1], legendtext[ih + 1],
                             "PEL")  #"f")
            if ih == 1:
                leg.AddEntry(histList[ih - 1], legendtext[ih - 1],
                             'f')  #"PEL")
        histList[ih].GetYaxis().SetTitle(titleVec[1])
        histList[ih].GetYaxis().SetTitleSize(0.052)
        histList[ih].GetYaxis().SetTitleOffset(1.4)
        histList[ih].GetYaxis().SetTitleFont(42)
        histList[ih].GetYaxis().SetLabelFont(42)
        histList[ih].GetYaxis().SetLabelSize(.052)
        histList[ih].GetXaxis().SetRangeUser(xRange[0], xRange[1])
        #     histList[ih].GetXaxis().SetLabelSize(0.0000);

        histList[ih].GetXaxis().SetTitle(titleVec[0])
        histList[ih].GetXaxis().SetLabelSize(0.052)
        histList[ih].GetXaxis().SetTitleSize(0.052)
        #histList[ih].GetXaxis().SetTitleOffset(1.14)
        histList[ih].GetXaxis().SetTitleFont(42)

        histList[ih].GetXaxis().SetLabelFont(42)
        histList[ih].GetYaxis().SetLabelFont(42)
        histList[ih].GetXaxis().SetNdivisions(507)
        #histList[ih].GetXaxis().SetMoreLogLabels();
        #histList[ih].GetXaxis().SetNoExponent();
        #histList[ih].GetTGaxis().SetMaxDigits(3);
        # histList[ih].GetXaxis().SetTickSize(0.00)

        i = i + 1
    pt = TPaveText(0.01, 0.92, 0.95, 0.96, "brNDC")
    pt.SetBorderSize(0)
    pt.SetTextAlign(12)
    pt.SetFillStyle(0)
    pt.SetTextFont(42)
    pt.SetTextSize(0.046)
    #text = pt.AddText(0.12,0.35,"CMS Internal                     36 fb^{-1} (2016) ")
    text = pt.AddText(0.12, 0.35,
                      "CMS Internal                     41.5 fb^{-1} (2017) ")
    #text = pt.AddText(0.12,0.35,"CMS Internal                     59.6 fb^{-1} (2018) ")
    #text = pt.AddText(0.6,0.5,"41.5 fb^{-1} (2017) ")
    cattxt = TLatex(0.20, 0.75, cat + '  ' + "category")
    cattxt.SetTextSize(0.06)

    cattxt.SetTextAlign(12)
    cattxt.SetNDC(1)
    cattxt.SetTextFont(42)

    pt.Draw()
    cattxt.Draw()

    leg.Draw()
    outputdirname = 'TFplots/'
    histname = outputdirname + pngname
    c.SaveAs(histname + '.png')
    c.SaveAs(histname + '.pdf')
def significanceSB(cutlist, labellist):
    basecut = ""

    ncuts = len(cutlist)
    effs = [0] * (ncuts + 1)
    hist = TH1D('eff', ";Significance", ncuts, 0, ncuts)

    for k, cs in enumerate(labellist):
        hist.GetXaxis().SetBinLabel(k + 1, "%s" % labellist[k])

    for j, c in enumerate(cutlist):
        chainbkg = {}
        chainsig = {}
        n = 0.
        d = 0.
        ##signal
        for s, v in enumerate(signals):
            chainsig[v] = TChain("Events")
            for rootfiles in samples[v]['files']:
                chainsig[v].AddFile("%s%s" % (NTUPLEDIR, rootfiles))

            #signalmatch = [x for x in Run2_17_nanov2_la if x.name()==v][0]
            #if float(signalmatch.matcheff())==1.:
            #    XSWeight= float( (signalmatch.xsec())*1000. / (signalmatch.nevent()) )
            #    Norm= XSWeight*LUMI
            #elif float(signalmatch.matcheff())!=1.:
            #XSWeight=signalmatch.matcheff()
            #Norm = float(XSWeight*LUMI)
            #print "k = ", k," : signalmatch.matcheff() = ", float(signalmatch.matcheff())," ; Norm = %f"%Norm
            #elif float(matches.matcheff())==1.:
            #    print "1.) ERROR 404"
            #    sys.exit()
            print v, " : n = ", chainsig[v].GetEntries("%s*XSWeight*(%s)" %
                                                       (LUMI, cutlist[j]))
            n += chainsig[v].GetEntries("%s*XSWeight*(%s)" %
                                        (LUMI, cutlist[j]))
            print "tot = ", n

        ##backgrounds
        for b, k in enumerate(back):
            chainbkg[k] = TChain("Events")
            for rootfiles in samples[k]['files']:
                chainbkg[k].AddFile("%s%s" % (NTUPLEDIR, rootfiles))

            #matches = [x for x in Run2_17_nanov2_la if x.name()==k][0]
            #if float(matches.matcheff())!=1.:
            #XSWeight=matches.matcheff()
            #Norm = float(XSWeight*LUMI)
            #print "k = ", k," : matches.matcheff() = ", float(matches.matcheff())," ; Norm = ",Norm
            #elif float(matches.matcheff())==1.:
            #    print "k = ", k
            #    print "matches.matcheff() = ", float(matches.matcheff())
            #    print "2.) ERROR 404"
            #    sys.exit()
            print k, " : d = ", chainbkg[k].GetEntries("%s*XSWeight*(%s)" %
                                                       (LUMI, cutlist[j]))
            d += chainbkg[k].GetEntries("%s*XSWeight*(%s)" %
                                        (LUMI, cutlist[j]))
            print "tot = ", d

        print "s = ", float(n)
        print "d = ", float(d)
        print "sqrt(d) = ", math.sqrt(d)
        effs[j] = float(n / math.sqrt(d))
        print "effs[j] = ", effs[j]
        hist.Fill(j, effs[j])
    #hist[s].SetMarkerStyle(20)
    #hist[s].SetMarkerColor(colors[i])
    hist.SetLineColor(colors[2])
    hist.SetLineWidth(3)
    #hist[s].GetXaxis().SetTitleOffset(hist[s].GetXaxis().GetTitleOffset()*1.2)
    #hist[s].GetYaxis().SetTitleOffset(hist[s].GetYaxis().GetTitleOffset()*1.2)

    leg = TLegend(0.7, 0.9 - 0.035 * len(signals), 0.9, 0.9)
    leg.SetBorderSize(0)
    leg.SetFillStyle(1001)
    leg.SetFillColor(0)
    leg.AddEntry('label', "l")

    c1 = TCanvas("c1", "Signals", 800, 600)
    c1.cd()
    c1.GetPad(0).SetTopMargin(0.06)
    c1.GetPad(0).SetRightMargin(0.05)
    c1.GetPad(0).SetTicks(1, 1)

    #hist[signals[0]].SetMaximum(1.3)
    #hist[signals[0]].SetMinimum(0.)

    hist.GetXaxis().SetTitle("Selection")
    hist.GetYaxis().SetTitle("Significance (#frac{S}{#sqrt{B}})")
    #hist.GetYaxis().SetRangeUser(0., 1.)
    hist.Draw()
    leg.Draw()
    drawCMS("41.5", "Preliminary")
    drawRegion(basecut)

    c1.Print("./SignificanceSB_" + basecut + ".png")
    c1.Print("./SignificanceSB_" + basecut + ".pdf")
    #if not options.runBash: raw_input("Press Enter to continue...")
    pass
Beispiel #15
0
def plotDataMC(args, plot):

    hCanvas = TCanvas("hCanvas", "Distribution", 800, 800)
    if args.ratio:
        plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0.3, 1, 1)
        ratioPad = ROOT.TPad("ratioPad", "ratioPad", 0, 0., 1, 0.3)
        setTDRStyle()
        plotPad.UseCurrentStyle()
        ratioPad.UseCurrentStyle()
        plotPad.Draw()
        ratioPad.Draw()
        plotPad.cd()
    else:
        plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0, 1, 1)
        setTDRStyle()
        plotPad.UseCurrentStyle()
        plotPad.Draw()
        plotPad.cd()

    # Data load processes
    colors = createMyColors()
    if args.use2016:
        data = Process(Data2016, normalized=True)
    elif args.use2018:
        data = Process(Data2018, normalized=True)
    elif args.useRun2:
        data2016 = Process(Data2016, normalized=True)
        data2017 = Process(Data, normalized=True)
        data2018 = Process(Data2018, normalized=True)
    else:
        data = Process(Data, normalized=True)

    eventCounts = totalNumberOfGeneratedEvents(path, plot.muon)
    negWeights = negWeightFractions(path, plot.muon)
    #print negWeights

    # Background load processes
    backgrounds = copy(args.backgrounds)
    if plot.useJets:
        if "Wjets" in backgrounds:
            backgrounds.remove("Wjets")
        if not "Jets" in backgrounds:
            backgrounds.insert(0, "Jets")
    if args.use2016 and not plot.muon and "Other" in backgrounds:
        backgrounds.remove("Other")
        backgrounds.insert(1, "OtherEle")
    processes = []
    processes2016 = []
    processes2017 = []
    processes2018 = []
    for background in backgrounds:
        if args.use2016:
            if background == "Jets":
                processes.append(
                    Process(getattr(Backgrounds2016, background),
                            eventCounts,
                            negWeights,
                            normalized=True))
            else:
                processes.append(
                    Process(getattr(Backgrounds2016, background), eventCounts,
                            negWeights))
        elif args.use2018:
            if background == "Jets":
                processes.append(
                    Process(getattr(Backgrounds2018, background),
                            eventCounts,
                            negWeights,
                            normalized=True))
            else:
                processes.append(
                    Process(getattr(Backgrounds2018, background), eventCounts,
                            negWeights))
        elif args.useRun2:

            if background == "Jets":
                processes.append(
                    Process(getattr(Backgrounds2016, background),
                            eventCounts,
                            negWeights,
                            normalized=True))
                processes2016.append(
                    Process(getattr(Backgrounds2016, background),
                            eventCounts,
                            negWeights,
                            normalized=True))
                processes2017.append(
                    Process(getattr(Backgrounds, background),
                            eventCounts,
                            negWeights,
                            normalized=True))
                processes2018.append(
                    Process(getattr(Backgrounds2018, background),
                            eventCounts,
                            negWeights,
                            normalized=True))
            elif background == "Other" and not plot.muon:
                processes.append(
                    Process(getattr(Backgrounds2016, "OtherEle"), eventCounts,
                            negWeights))
                processes2016.append(
                    Process(getattr(Backgrounds2016, "OtherEle"), eventCounts,
                            negWeights))
                processes2017.append(
                    Process(getattr(Backgrounds, background), eventCounts,
                            negWeights))
                processes2018.append(
                    Process(getattr(Backgrounds2018, background), eventCounts,
                            negWeights))
            else:
                processes.append(
                    Process(getattr(Backgrounds2016, background), eventCounts,
                            negWeights))
                processes2016.append(
                    Process(getattr(Backgrounds2016, background), eventCounts,
                            negWeights))
                processes2017.append(
                    Process(getattr(Backgrounds, background), eventCounts,
                            negWeights))
                processes2018.append(
                    Process(getattr(Backgrounds2018, background), eventCounts,
                            negWeights))
        else:
            if background == "Jets":
                processes.append(
                    Process(getattr(Backgrounds, background),
                            eventCounts,
                            negWeights,
                            normalized=True))
            else:
                processes.append(
                    Process(getattr(Backgrounds, background), eventCounts,
                            negWeights))

    # Signal load processes
    signals = []
    signals2016 = []
    signals2017 = []
    signals2018 = []
    for signal in args.signals:
        if args.use2016:
            if args.ADD:
                signals.append(
                    Process(getattr(Signals2016ADD, signal), eventCounts,
                            negWeights))
            else:
                signals.append(
                    Process(getattr(Signals2016, signal), eventCounts,
                            negWeights))
        elif args.use2018:
            if args.ADD:
                signals.append(
                    Process(getattr(Signals2018ADD, signal), eventCounts,
                            negWeights))
            else:
                signals.append(
                    Process(getattr(Signals2018, signal), eventCounts,
                            negWeights))
        elif args.useRun2:
            if args.ADD:
                signals.append(
                    Process(getattr(Signals2016ADD, signal), eventCounts,
                            negWeights))
                signals2016.append(
                    Process(getattr(Signals2016ADD, signal), eventCounts,
                            negWeights))
                signals2017.append(
                    Process(getattr(SignalsADD, signal), eventCounts,
                            negWeights))
                signals2018.append(
                    Process(getattr(Signals2018ADD, signal), eventCounts,
                            negWeights))
            else:
                signals.append(
                    Process(getattr(Signals2016, signal), eventCounts,
                            negWeights))
                signals2016.append(
                    Process(getattr(Signals2016, signal), eventCounts,
                            negWeights))
                signals2017.append(
                    Process(getattr(Signals, signal), eventCounts, negWeights))
                signals2018.append(
                    Process(getattr(Signals2018, signal), eventCounts,
                            negWeights))
        else:
            if args.ADD:
                signals.append(
                    Process(getattr(SignalsADD, signal), eventCounts,
                            negWeights))
            else:
                signals.append(
                    Process(getattr(Signals, signal), eventCounts, negWeights))

    legend = TLegend(0.55, 0.6, 0.925, 0.925)
    legend.SetFillStyle(0)
    legend.SetBorderSize(0)
    legend.SetTextFont(42)

    legendEta = TLegend(0.45, 0.75, 0.925, 0.925)
    legendEta.SetFillStyle(0)
    legendEta.SetBorderSize(0)
    legendEta.SetTextFont(42)
    legendEta.SetNColumns(2)

    latex = ROOT.TLatex()
    latex.SetTextFont(42)
    latex.SetTextAlign(31)
    latex.SetTextSize(0.04)
    latex.SetNDC(True)
    latexCMS = ROOT.TLatex()
    latexCMS.SetTextFont(61)
    latexCMS.SetTextSize(0.06)
    latexCMS.SetNDC(True)
    latexCMSExtra = ROOT.TLatex()
    latexCMSExtra.SetTextFont(52)
    latexCMSExtra.SetTextSize(0.045)
    latexCMSExtra.SetNDC(True)
    legendHists = []

    # Modify legend information
    legendHistData = ROOT.TH1F()
    if args.data:
        legend.AddEntry(legendHistData, "Data", "pe")
        legendEta.AddEntry(legendHistData, "Data", "pe")

    for process in reversed(processes):
        if not plot.muon and "#mu^{+}#mu^{-}" in process.label:
            process.label = process.label.replace("#mu^{+}#mu^{-}",
                                                  "e^{+^{*}}e^{-}")
        temphist = ROOT.TH1F()
        temphist.SetFillColor(process.theColor)
        legendHists.append(temphist.Clone)
        legend.AddEntry(temphist, process.label, "f")
        legendEta.AddEntry(temphist, process.label, "f")

    if args.signals != 0:
        processesWithSignal = []
        for process in processes:
            processesWithSignal.append(process)
        for Signal in signals:
            processesWithSignal.append(Signal)
            temphist = ROOT.TH1F()
            temphist.SetFillColor(Signal.theColor)
            temphist.SetLineColor(Signal.theLineColor)
            legendHists.append(temphist.Clone)
            legend.AddEntry(temphist, Signal.label, "l")
            legendEta.AddEntry(temphist, Signal.label, "l")

    # Modify plot pad information
    nEvents = -1

    ROOT.gStyle.SetOptStat(0)

    intlumi = ROOT.TLatex()
    intlumi.SetTextAlign(12)
    intlumi.SetTextSize(0.045)
    intlumi.SetNDC(True)
    intlumi2 = ROOT.TLatex()
    intlumi2.SetTextAlign(12)
    intlumi2.SetTextSize(0.07)
    intlumi2.SetNDC(True)
    scalelabel = ROOT.TLatex()
    scalelabel.SetTextAlign(12)
    scalelabel.SetTextSize(0.03)
    scalelabel.SetNDC(True)
    metDiffLabel = ROOT.TLatex()
    metDiffLabel.SetTextAlign(12)
    metDiffLabel.SetTextSize(0.03)
    metDiffLabel.SetNDC(True)
    chi2Label = ROOT.TLatex()
    chi2Label.SetTextAlign(12)
    chi2Label.SetTextSize(0.03)
    chi2Label.SetNDC(True)
    hCanvas.SetLogy()

    # Luminosity information
    plotPad.cd()
    plotPad.SetLogy(0)
    logScale = plot.log

    if logScale == True:
        plotPad.SetLogy()
    if args.use2016:
        lumi = 35.9 * 1000
        if plot.muon:
            lumi = 36294.6
    elif args.use2018:
        lumi = 59401
        if plot.muon:
            lumi = 61298.775231718995
    elif args.useRun2:
        lumi2016 = 35.9 * 1000
        lumi2017 = 41.529 * 1000
        lumi2018 = 59401
        if plot.muon:
            lumi2016 = 36294.6
            lumi2018 = 61298.775231718995
            lumi2017 = 42079.880396
    else:
        lumi = 41.529 * 1000
        if plot.muon:
            lumi = 42079.880396
    if args.use2016:
        zScaleFac = zScale2016["muons"]
        if not plot.muon:
            if "bbbe" in plot.histName:
                zScaleFac = zScale2016["electrons"][0]
            elif "bb" in plot.histName:
                zScaleFac = zScale2016["electrons"][1]
            elif "be" in plot.histName:
                zScaleFac = zScale2016["electrons"][2]
            else:
                zScaleFac = zScale2016["electrons"][0]
    elif args.use2018:
        zScaleFac = zScale2018["muons"]
        if not plot.muon:
            if "bbbe" in plot.histName:
                zScaleFac = zScale2018["electrons"][0]
            elif "bb" in plot.histName:
                zScaleFac = zScale2018["electrons"][1]
            elif "be" in plot.histName:
                zScaleFac = zScale2018["electrons"][2]
            else:
                zScaleFac = zScale2018["electrons"][0]

    elif args.useRun2:
        zScaleFac2016 = zScale2016["muons"]
        zScaleFac2017 = zScale["muons"]
        zScaleFac2018 = zScale2018["muons"]
        if not plot.muon:
            if "bbbe" in plot.histName:
                zScaleFac2016 = zScale2016["electrons"][0]
                zScaleFac2017 = zScale["electrons"][0]
                zScaleFac2018 = zScale2018["electrons"][0]
            elif "bb" in plot.histName:
                zScaleFac2016 = zScale2016["electrons"][1]
                zScaleFac2017 = zScale["electrons"][1]
                zScaleFac2018 = zScale2018["electrons"][1]
            elif "be" in plot.histName:
                zScaleFac2016 = zScale2016["electrons"][2]
                zScaleFac2017 = zScale["electrons"][2]
                zScaleFac2018 = zScale2018["electrons"][2]
            else:
                zScaleFac2016 = zScale2016["electrons"][0]
                zScaleFac2017 = zScale["electrons"][0]
                zScaleFac2018 = zScale2018["electrons"][0]

    else:
        zScaleFac = zScale["muons"]
        if not plot.muon:
            if "bbbe" in plot.histName:
                zScaleFac = zScale["electrons"][0]
            elif "bb" in plot.histName:
                zScaleFac = zScale["electrons"][1]
            elif "be" in plot.histName:
                zScaleFac = zScale["electrons"][2]
            else:
                zScaleFac = zScale["electrons"][0]

    # Data and background loading
    if plot.plot2D:
        if args.useRun2:

            datahist = data2016.loadHistogramProjected(plot, lumi2016,
                                                       zScaleFac2016)
            datahist.Add(
                data2017.loadHistogramProjected(plot, lumi2017, zScaleFac2017))
            datahist.Add(
                data2016.loadHistogramProjected(plot, lumi2018, zScaleFac2018))

            stack = TheStack2DRun2(
                [processes2016, processes2017, processes2018],
                [lumi2016, lumi2017, lumi2018], plot,
                [zScaleFac2016, zScaleFac2017, zScaleFac2018])

        else:
            datahist = data.loadHistogramProjected(plot, lumi, zScaleFac)

            stack = TheStack2D(processes, lumi, plot, zScaleFac)
    else:

        if args.useRun2:
            datahist = data2016.loadHistogram(plot, lumi2016, zScaleFac2016)
            datahist.Add(data2017.loadHistogram(plot, lumi2017, zScaleFac2017))
            datahist.Add(data2018.loadHistogram(plot, lumi2018, zScaleFac2018))
            stack = TheStackRun2([processes2016, processes2017, processes2018],
                                 [lumi2016, lumi2017, lumi2018], plot,
                                 [zScaleFac2016, zScaleFac2017, zScaleFac2018])
        else:
            datahist = data.loadHistogram(plot, lumi, zScaleFac)
            stack = TheStack(processes, lumi, plot, zScaleFac)
    if args.data:
        yMax = datahist.GetBinContent(datahist.GetMaximumBin())
        if "Mass" in plot.fileName:
            yMin = 0.00001
        else:
            yMin = 0.01
        xMax = datahist.GetXaxis().GetXmax()
        xMin = datahist.GetXaxis().GetXmin()
    else:
        yMax = stack.theHistogram.GetBinContent(datahist.GetMaximumBin())
        yMin = 0.01
        xMax = stack.theHistogram.GetXaxis().GetXmax()
        xMin = stack.theHistogram.GetXaxis().GetXmin()
    if plot.yMax == None:
        if logScale:
            yMax = yMax * 10000
        else:
            yMax = yMax * 1.5
    else:
        yMax = plot.yMax

    if "Mass" in plot.fileName:
        yMax = 20000000

    if not plot.yMin == None:
        yMin = plot.yMin
    if not plot.xMin == None:
        xMin = plot.xMin
    if not plot.xMax == None:
        xMax = plot.xMax
    #if args.ADD and args.use2016:
    #	xMin = 1700
    #	xMax = 4000
    #	yMax = 1.0
    if "CosThetaStarBBM1800" in plot.fileName:
        yMax = 3
    plotPad.DrawFrame(xMin, yMin, xMax, yMax,
                      "; %s ; %s" % (plot.xaxis, plot.yaxis))

    drawStack = stack
    #~ print datahist.Integral(datahist.FindBin(60),datahist.FindBin(120))/drawStack.theHistogram.Integral(drawStack.theHistogram.FindBin(60),drawStack.theHistogram.FindBin(120))
    #~ low = 900
    #~ high = 1300
    #~ print datahist.Integral(datahist.FindBin(low),datahist.FindBin(high))
    #~ print drawStack.theHistogram.Integral(datahist.FindBin(low),datahist.FindBin(high))

    # Draw signal information
    if len(args.signals) != 0:
        if args.useRun2:
            signalhists = []
            for index, Signal in enumerate(signals2016):
                if plot.plot2D:  # plot collins-soper angle
                    signalhist = Signal.loadHistogramProjected(
                        plot, lumi2016, zScaleFac2016)
                    signalhist.Add(signals2017[index].loadHistogramProjected(
                        plot, lumi2017, zScaleFac2017))
                    signalhist.Add(signals2018[index].loadHistogramProjected(
                        plot, lumi2018, zScaleFac2018))
                    signalhist.SetLineWidth(2)
                    signalBackgrounds = deepcopy(backgrounds)
                    signalBackgrounds.remove("DrellYan")
                    signalProcesses2016 = []
                    signalProcesses2017 = []
                    signalProcesses2018 = []
                    for background in signalBackgrounds:
                        if background == "Jets":
                            signalProcesses2016.append(
                                Process(getattr(Backgrounds2016, background),
                                        eventCounts,
                                        negWeights,
                                        normalized=True))
                            signalProcesses2017.append(
                                Process(getattr(Backgrounds, background),
                                        eventCounts,
                                        negWeights,
                                        normalized=True))
                            signalProcesses2018.append(
                                Process(getattr(Backgrounds2018, background),
                                        eventCounts,
                                        negWeights,
                                        normalized=True))
                        else:
                            signalProcesses2016.append(
                                Process(getattr(Backgrounds2016, background),
                                        eventCounts, negWeights))
                            signalProcesses2017.append(
                                Process(getattr(Backgrounds, background),
                                        eventCounts, negWeights))
                            signalProcesses2018.append(
                                Process(getattr(Backgrounds2018, background),
                                        eventCounts, negWeights))
                    signalStack = TheStack2DRun2(
                        [
                            signalProcesses2016, signalProcesses2017,
                            signalProcesses2018
                        ], [lumi2016, lumi2017, lumi2018], plot,
                        [zScaleFac2016, zScaleFac2017, zScaleFac2018])
                    signalhist.Add(signalStack.theHistogram)
                    signalhist.SetMinimum(0.1)
                    signalhist.Draw("samehist")
                    signalhists.append(signalhist)
                else:
                    signalhist = Signal.loadHistogram(plot, lumi2016,
                                                      zScaleFac2016)
                    signalhist.Add(signals2017[index].loadHistogram(
                        plot, lumi2017, zScaleFac2017))
                    signalhist.Add(signals2018[index].loadHistogram(
                        plot, lumi2018, zScaleFac2018))
                    signalhist.SetLineWidth(2)
                    signalBackgrounds = deepcopy(backgrounds)
                    signalBackgrounds.remove(
                        "DrellYan")  # signalBackgrounds = ["Jets", "Other"]
                    signalProcesses2016 = []
                    signalProcesses2017 = []
                    signalProcesses2018 = []
                    for background in signalBackgrounds:
                        if background == "Jets":
                            signalProcesses2016.append(
                                Process(getattr(Backgrounds2016, background),
                                        eventCounts,
                                        negWeights,
                                        normalized=True))
                            signalProcesses2017.append(
                                Process(getattr(Backgrounds, background),
                                        eventCounts,
                                        negWeights,
                                        normalized=True))
                            if plot.muon:
                                signalProcesses2018.append(
                                    Process(getattr(Backgrounds2018,
                                                    background),
                                            eventCounts,
                                            negWeights,
                                            normalized=True))
                            else:
                                signalProcesses2018.append(
                                    Process(getattr(Backgrounds, background),
                                            eventCounts,
                                            negWeights,
                                            normalized=True))
                        else:
                            signalProcesses2016.append(
                                Process(getattr(Backgrounds2016, background),
                                        eventCounts, negWeights))
                            signalProcesses2017.append(
                                Process(getattr(Backgrounds, background),
                                        eventCounts, negWeights))
                            signalProcesses2018.append(
                                Process(getattr(Backgrounds2018, background),
                                        eventCounts, negWeights))
                    signalStack = TheStackRun2(
                        [
                            signalProcesses2016, signalProcesses2017,
                            signalProcesses2018
                        ], [lumi2016, lumi2017, lumi2018], plot,
                        [zScaleFac2016, zScaleFac2017, zScaleFac2018])
                    signalhist.Add(signalStack.theHistogram)
                    signalhist.SetMinimum(0.0001)
                    signalhist.Draw("samehist")
                    signalhists.append(signalhist)
        else:
            signalhists = []
            for Signal in signals:
                if plot.plot2D:  # plot collins-soper angle
                    signalhist = Signal.loadHistogramProjected(
                        plot, lumi, zScaleFac)
                    signalhist.SetLineWidth(2)
                    signalBackgrounds = deepcopy(backgrounds)
                    signalBackgrounds.remove("DrellYan")
                    signalProcesses = []
                    for background in signalBackgrounds:
                        if background == "Jets":
                            signalProcesses.append(
                                Process(getattr(Backgrounds, background),
                                        eventCounts,
                                        negWeights,
                                        normalized=True))
                        else:
                            signalProcesses.append(
                                Process(getattr(Backgrounds, background),
                                        eventCounts, negWeights))
                    signalStack = TheStack2D(signalProcesses, lumi, plot,
                                             zScaleFac)
                    signalhist.Add(signalStack.theHistogram)
                    signalhist.SetMinimum(0.1)
                    signalhist.Draw("samehist")
                    signalhists.append(signalhist)
                else:
                    signalhist = Signal.loadHistogram(plot, lumi, zScaleFac)
                    signalhist.SetLineWidth(2)
                    signalBackgrounds = deepcopy(backgrounds)
                    signalBackgrounds.remove(
                        "DrellYan")  # signalBackgrounds = ["Jets", "Other"]
                    signalProcesses = []
                    for background in signalBackgrounds:
                        if background == "Jets":
                            signalProcesses.append(
                                Process(getattr(Backgrounds, background),
                                        eventCounts,
                                        negWeights,
                                        normalized=True))
                        else:
                            signalProcesses.append(
                                Process(getattr(Backgrounds, background),
                                        eventCounts, negWeights))
                    signalStack = TheStack(signalProcesses, lumi, plot,
                                           zScaleFac)
                    signalhist.Add(signalStack.theHistogram)
                    signalhist.SetMinimum(0.0001)
                    signalhist.Draw("samehist")
                    signalhists.append(signalhist)

    # Draw background from stack
    drawStack.theStack.Draw("samehist")

    # Draw data
    datahist.SetMinimum(0.0001)
    if args.data:
        datahist.Draw("samep")

    # Draw legend
    if "Eta" in plot.fileName or "CosTheta" in plot.fileName:
        legendEta.Draw()
    else:
        legend.Draw()

    plotPad.SetLogx(plot.logX)
    if args.useRun2:
        if plot.muon:
            latex.DrawLatex(0.95, 0.96, "139.7 fb^{-1} (13 TeV)")
        else:
            latex.DrawLatex(0.95, 0.96, "136.8 fb^{-1} (13 TeV)")
    else:
        latex.DrawLatex(0.95, 0.96,
                        "%.1f fb^{-1} (13 TeV)" % (float(lumi) / 1000, ))
    yLabelPos = 0.85
    cmsExtra = "Preliminary"
    if not args.data:
        cmsExtra = "#splitline{Preliminary}{Simulation}"
        yLabelPos = 0.82
    latexCMS.DrawLatex(0.19, 0.89, "CMS")
    latexCMSExtra.DrawLatex(0.19, yLabelPos, "%s" % (cmsExtra))
    #~ print datahist.Integral()
    if args.ratio:
        try:
            ratioPad.cd()
            ratioPad.SetLogx(plot.logX)
        except AttributeError:
            print("Plot fails. Look up in errs/failedPlots.txt")
            outFile = open("errs/failedPlots.txt", "a")
            outFile.write('%s\n' % plot.filename %
                          ("_" + run.label + "_" + dilepton))
            outFile.close()
            plot.cuts = baseCut
            return 1
        ratioGraphs = ratios.RatioGraph(datahist,
                                        drawStack.theHistogram,
                                        xMin=xMin,
                                        xMax=xMax,
                                        title="(Data - Bkg) / Bkg",
                                        yMin=-1.0,
                                        yMax=1.0,
                                        ndivisions=10,
                                        color=ROOT.kBlack,
                                        adaptiveBinning=10000000000000,
                                        labelSize=0.125,
                                        pull=True)
        ratioGraphs.draw(ROOT.gPad, True, False, True, chi2Pos=0.8)

    ROOT.gPad.RedrawAxis()
    plotPad.RedrawAxis()
    if args.ratio:

        ratioPad.RedrawAxis()
    if not os.path.exists("plots"):
        os.makedirs("plots")
    if args.use2016:
        hCanvas.Print("plots/" + plot.fileName + "_2016.pdf")
    elif args.use2018:
        hCanvas.Print("plots/" + plot.fileName + "_2018.pdf")
    elif args.useRun2:
        hCanvas.Print("plots/" + plot.fileName + "_Run2.pdf")
    else:
        hCanvas.Print("plots/" + plot.fileName + "_2017.pdf")
def compareDatasets(trigger,
                    leg,
                    datasets,
                    lineColors,
                    legendLabels,
                    axisTitle,
                    canvas,
                    dataLumi,
                    metHLTFilters,
                    outputSuffix=None):

    inputFiles = [
        TFile.Open("triggerEfficiency_" + x + ".root") for x in datasets
    ]
    efficiencies = [x.Get(trigger + "_" + leg) for x in inputFiles]

    for iEff in range(len(efficiencies)):
        SetStyle(efficiencies[iEff])
        efficiencies[iEff].SetLineColor(lineColors[iEff])
        efficiencies[iEff].SetMarkerColor(lineColors[iEff])

    oneLine = TLine(xlo, 1.0, xhi, 1.0)
    oneLine.SetLineWidth(3)
    oneLine.SetLineStyle(2)

    backgroundHist = TH1D("backgroundHist", "backgroundHist", 1, xlo, xhi)
    backgroundHist.GetYaxis().SetTitle("Trigger Efficiency")
    backgroundHist.GetYaxis().SetRangeUser(ylo, yhi)
    backgroundHist.GetXaxis().SetTitle(axisTitle)
    SetStyle(backgroundHist)

    canvas.cd()
    backgroundHist.Draw()
    for eff in efficiencies:
        eff.Draw("CP same")
    #oneLine.Draw("same")

    pt_cmsPrelim = TPaveText(0.132832, 0.859453, 0.486216, 0.906716, "brNDC")
    pt_cmsPrelim.SetBorderSize(0)
    pt_cmsPrelim.SetFillStyle(0)
    pt_cmsPrelim.SetTextFont(62)
    pt_cmsPrelim.SetTextSize(0.0374065)
    if dataLumi > 0:
        pt_cmsPrelim.AddText("CMS Preliminary")
    else:
        pt_cmsPrelim.AddText("CMS Simulation")
    pt_cmsPrelim.Draw("same")

    if dataLumi > 0:
        pt_lumi = TPaveText(0.744361, 0.92928, 0.860902, 0.977667, "brNDC")
        pt_lumi.SetBorderSize(0)
        pt_lumi.SetFillStyle(0)
        pt_lumi.SetTextFont(42)
        pt_lumi.SetTextSize(0.0374065)
        pt_lumi.AddText("{:.2f}".format(dataLumi / 1000.0) +
                        " fb^{-1}, 13 TeV")
        pt_lumi.Draw("same")

    pt_leg = TPaveText(0.160401, 0.768657, 0.342105, 0.863184, "brNDC")
    pt_leg.SetBorderSize(0)
    pt_leg.SetFillStyle(0)
    pt_leg.SetTextFont(42)
    pt_leg.SetTextSize(0.025)
    pt_leg.SetTextAlign(12)
    if leg == "METLeg":
        legLabel = ""
        for filt in metHLTFilters[:-1]:
            legLabel = legLabel + filt + ", "
        legLabel = legLabel + metHLTFilters[-1]
        pt_leg.AddText(legLabel)
    if leg == "TrackLeg":
        pt_leg.AddText(trigger + "*")
        legLabel = ""
        for filt in metHLTFilters[:-1]:
            legLabel = legLabel + filt + ", "
        legLabel = legLabel + metHLTFilters[-1] + " applied"
        pt_leg.AddText(legLabel)
    if leg == "METPath":
        if trigger == "GrandOr":
            pt_leg.AddText("OR of Signal Paths")
        else:
            if len(trigger) > 25 and len(trigger.split("_")) > 2:
                firstLine = trigger.split("_")[0] + "_" + trigger.split(
                    "_")[1] + "_"
                pt_leg.AddText(firstLine)
                secondLine = ""
                for line in trigger.split("_")[2:-1]:
                    secondLine += line + "_"
                secondLine += trigger.split("_")[-1] + "*"
                pt_leg.AddText(secondLine)
            else:
                pt_leg.AddText(trigger + "*")
    pt_leg.Draw("same")

    legendLabel = trigger

    legend = TLegend(0.65, 0.75, 0.93, 0.88)
    legend.SetBorderSize(0)
    legend.SetFillColor(0)
    legend.SetFillStyle(0)
    legend.SetTextFont(42)
    if leg == 'METLeg':
        legend.SetHeader('MET Leg')
    elif leg == 'TrackLeg':
        legend.SetHeader('Track Leg')
    for iEff in range(len(efficiencies)):
        legend.AddEntry(efficiencies[iEff], legendLabels[iEff], 'P')
    legend.Draw("same")

    if outputSuffix is not None:
        canvas.SaveAs('compareDatasets_' + trigger + '_' + leg + '_' +
                      outputSuffix + '.pdf')
    else:
        canvas.SaveAs('compareDatasets_' + trigger + '_' + leg + '_.pdf')

    for inputFile in inputFiles:
        inputFile.Close()

    return
Beispiel #17
0
def OverlayHistograms(fitName, plotType, histograms, outputfileName):

    if debug:
        print "Fitting", fit, "function"
        print "PlotType:", plotType

    #create and draw legend and canvas
    c = TCanvas("canvas", "canvas", 1600, 800)
    legend = TLegend(0.12, 0.47, 0.40, 0.87)
    legend.AddEntry(None, "#bf{mean[GeV] / sigma[GeV] / ratio}", "")
    legend.SetBorderSize(0)
    legend.SetFillStyle(0)
    legend.SetTextFont(42)
    legend.SetTextSize(0.03)

    gStyle.SetOptTitle(0)
    gStyle.SetOptStat(0)

    #make a template histo so that y axis has correct height
    #find max height
    for hist in histograms:
        heights = []
        height = hist.GetMaximum()
        heights.append(height)

    maxheight = max(heights) + 100
    template = histograms[0].Clone()
    template.SetMaximum(maxheight)
    template.Reset()
    template.Draw()
    template.SetXTitle("mbb [GeV]")
    template.SetYTitle("Number of events")

    col = 2
    #loop over histos to overlay
    for hist in histograms:

        #get fitting params
        height = hist.GetMaximum()
        mean = hist.GetMean()
        rms = hist.GetRMS()

        #set line color
        hist.SetLineColor(col)

        #define fit range variables
        xmin = mean - 3 * rms
        xmax = mean + 3 * rms

        #make the required fit
        if fitName == "Gauss":
            fitfunc = TF1('Gauss', Gauss(), xmin, xmax, 3)
            fitfunc.SetParameters(height, mean, rms)

        elif fitName == "Bukin":
            fitfunc = TF1('Bukin', Bukin(), xmin, xmax, 6)
            fitfunc.SetParameters(height, mean, rms, -0.4, 0.01, 0.005)

        #fit and plot according to requirements
        if plotType == "hist":
            hist.Fit(fitfunc, "0")
            legend.AddEntry(hist, hist.GetName(), "l")
            hist.Draw("same")

        elif plotType == "overlay":
            hist.Fit(fitfunc, "0")
            func = hist.GetFunction(fitName)
            legend.AddEntry(hist, hist.GetName(), "l")
            hist.Draw("same")
            func.SetLineColor(col)
            func.Draw("SAME")

        elif plotType == "fit":
            hist.Fit(fitfunc, "0")
            func = hist.GetFunction(fitName)
            legend.AddEntry(hist, hist.GetName(), "l")
            func.Draw("SAME")
            func.SetLineColor(col)

        #show fit results in the legend
        func = hist.GetFunction(fitName)
        fitresults = (func.GetParameter(0), func.GetParameter(1),
                      func.GetParameter(2), func.GetParameter(3),
                      func.GetParameter(4), func.GetParameter(5))
        legend_text = "#bf{%-.3f/%-.3f/%-.3f}" % (
            fitresults[1], fitresults[2], ratio(fitresults[2], fitresults[1]))
        legend.AddEntry(None, legend_text, "")

        col += 1
        #end for loop

    legend.Draw("same")

    #plot text
    t = TLatex()
    t.SetNDC()
    t.SetTextSize(14)
    t.SetTextFont(43)
    t.SetTextAlign(13)
    t.DrawLatex(0.8, 0.85, "#it{#bf{SUPAROOT} lab2 }")
    t.Draw("same")

    c.Print(outputfileName)
    return
def compare(trigger, leg, data, mc, axisTitle, canvas, dataLumi,
            metHLTFilters):
    dataFile = TFile.Open("triggerEfficiency_" + data + ".root", "read")
    mcFile = TFile.Open("triggerEfficiency_" + mc + ".root", "read")

    dataEff = dataFile.Get(trigger + "_" + leg)
    mcEff = mcFile.Get(trigger + "_" + leg)

    SetStyle(dataEff)
    SetStyle(mcEff)
    mcEff.SetLineColor(600)
    mcEff.SetMarkerColor(600)

    oneLine = TLine(xlo, 1.0, xhi, 1.0)
    oneLine.SetLineWidth(3)
    oneLine.SetLineStyle(2)

    backgroundHist = TH1D("backgroundHist", "backgroundHist", 1, xlo, xhi)
    backgroundHist.GetYaxis().SetTitle("Trigger Efficiency")
    backgroundHist.GetYaxis().SetRangeUser(ylo, yhi)
    backgroundHist.GetXaxis().SetTitle(axisTitle)
    SetStyle(backgroundHist)

    canvas.cd()
    backgroundHist.Draw()
    dataEff.Draw("CP same")
    mcEff.Draw("CP same")
    #oneLine.Draw("same")

    pt_cmsPrelim = TPaveText(0.132832, 0.859453, 0.486216, 0.906716, "brNDC")
    pt_cmsPrelim.SetBorderSize(0)
    pt_cmsPrelim.SetFillStyle(0)
    pt_cmsPrelim.SetTextFont(62)
    pt_cmsPrelim.SetTextSize(0.0374065)
    pt_cmsPrelim.AddText("CMS Preliminary")
    pt_cmsPrelim.Draw("same")

    pt_lumi = TPaveText(0.744361, 0.92928, 0.860902, 0.977667, "brNDC")
    pt_lumi.SetBorderSize(0)
    pt_lumi.SetFillStyle(0)
    pt_lumi.SetTextFont(42)
    pt_lumi.SetTextSize(0.0374065)
    pt_lumi.AddText("{:.2f}".format(dataLumi / 1000.0) + " fb^{-1}, 13 TeV")
    pt_lumi.Draw("same")

    pt_leg = TPaveText(0.160401, 0.768657, 0.342105, 0.863184, "brNDC")
    pt_leg.SetBorderSize(0)
    pt_leg.SetFillStyle(0)
    pt_leg.SetTextFont(42)
    pt_leg.SetTextSize(0.025)
    pt_leg.SetTextAlign(12)
    if leg == "METLeg":
        legLabel = ""
        for filt in metHLTFilters[:-1]:
            legLabel = legLabel + filt + ", "
        legLabel = legLabel + metHLTFilters[-1]
        pt_leg.AddText(legLabel)
    if leg == "TrackLeg":
        pt_leg.AddText(trigger + "*")
        legLabel = ""
        for filt in metHLTFilters[:-1]:
            legLabel = legLabel + filt + ", "
        legLabel = legLabel + metHLTFilters[-1] + " applied"
        pt_leg.AddText(legLabel)
    if leg == "METPath":
        if trigger == "GrandOr":
            pt_leg.AddText("OR of Signal Paths")
        else:
            if len(trigger) > 25 and len(trigger.split("_")) > 2:
                firstLine = trigger.split("_")[0] + "_" + trigger.split(
                    "_")[1] + "_"
                pt_leg.AddText(firstLine)
                secondLine = ""
                for line in trigger.split("_")[2:-1]:
                    secondLine += line + "_"
                secondLine += trigger.split("_")[-1] + "*"
                pt_leg.AddText(secondLine)
            else:
                pt_leg.AddText(trigger + "*")
    pt_leg.Draw("same")

    dataLabel = '2015 data'
    if '2016BC' in data:
        dataLabel = '2016 B+C data'
    if '2016DEFGH' in data:
        dataLabel = '2016 D-H data'
    if '2017' in data:
        dataLabel = '2017 data'
    if '2018' in data:
        dataLabel = '2018 data'

    legendLabel = trigger

    legend = TLegend(0.65, 0.75, 0.93, 0.88)
    legend.SetBorderSize(0)
    legend.SetFillColor(0)
    legend.SetFillStyle(0)
    legend.SetTextFont(42)
    if leg == 'METLeg':
        legend.SetHeader('MET Leg')
    elif leg == 'TrackLeg':
        legend.SetHeader('Track Leg')
    legend.AddEntry(dataEff, dataLabel, 'P')
    legend.AddEntry(mcEff, 'W #rightarrow l#nu MC', 'P')
    legend.Draw("same")

    outputDirectory = 'plots_compare'
    if 'BC' in data:
        outputDirectory = 'plots_compareBC'
    if 'DEFGH' in data:
        outputDirectory = 'plots_compareDEFGH'

    if not os.path.exists(outputDirectory):
        os.mkdir(outputDirectory)

    canvas.SaveAs(outputDirectory + '/' + trigger + '_' + leg + '.pdf')

    mcFile.Close()
    dataFile.Close()

    return
def make_comparison_plot(outdir, var, groupname1, groupname2, category, weight = "PU_weight*MC_weight*bTagSF_weight*leptonSF_weight*triggerSF_weight*FR_weight", dataset = "ttH"):
  var_name = var[0]
  n_bins = var[3]
  range_low = var[4]
  range_high = var[5]
  
  histos = []
  plot_name = "p"   #segfault when using different names for each
  #"%s_%s_%s_%s_%s_vs_%s" % (outdir, var_name, dataset, category, groupname1, groupname2)
  name1 = "plot_%s_%s" % (groupname1, plot_name)
  plot1 = single_plot("%s/%s" % (groups[groupname1]["inputPath"], groups[groupname1]["inputFiles"][dataset]),
    name1,
    "%s_%s" % (groups[groupname1]["treePrefix"], category),
    var_name,
    weight,
    n_bins, range_low, range_high)
    
  name2 = "plot_%s_%s" % (groupname2, plot_name)
  plot2 = single_plot("%s/%s" % (groups[groupname2]["inputPath"], groups[groupname2]["inputFiles"][dataset]),
    name2,
    "%s_%s" % (groups[groupname2]["treePrefix"], category),
    var_name,
    weight,
    n_bins, range_low, range_high)
  histos.append(plot1)
  histos.append(plot2)

  leg_entry = []
  leg_entry.append("%s:\t N=%d, mean=%.2f, RMS=%.2f" % (groupname1, plot1.GetEntries(), plot1.GetMean(), plot1.GetRMS()))
  leg_entry.append("%s:\t N=%d, mean=%.2f, RMS=%.2f" % (groupname2, plot2.GetEntries(), plot2.GetMean(), plot2.GetRMS()))
  leg=TLegend(0.45,0.74,0.85,0.89)
  
  leg.SetHeader(get_header(category));
  leg.SetBorderSize(0)
  leg.SetTextSize(0.04)
  leg.SetFillColor(0)

  for i in range(len(histos)):
    normalize_histogram(histos[i])
    leg.AddEntry(histos[i], leg_entry[i])

  histos[0].SetLineColor(ROOT.kOrange-2)
  histos[0].SetFillColor(ROOT.kOrange-2)
  histos[0].SetStats(0)
  histos[0].SetTitle("")

  histos[1].SetLineColor(1)
  histos[1].SetLineWidth(2)

  c=TCanvas("c_%s" % plot_name,"c_%s" % plot_name, 800, 600)

  pad1 = TPad("pad1", "pad1", 0, 0.3, 1, 1.0)
  pad1.SetLeftMargin(0.15)
  pad1.SetBottomMargin(0) # Upper and lower plot are joined
  pad1.Draw()             # Draw the upper pad: pad1
  pad1.cd()               # pad1 becomes the current pad
  
  max_val = 0.1
  min_val = 0
  for i in range(len(histos)):
    max_val = max(histos[i].GetMaximum(), max_val)
    min_val = min(histos[i].GetMinimum(), min_val)
  
  for i in range(len(histos)):
    histos[i].SetMaximum(1.4*max_val)
    histos[i].SetMinimum(1.4*min_val)
    histos[i].GetXaxis().SetTitle(var_name)
    histos[i].GetYaxis().SetTitle("a.u.")
    histos[i].GetYaxis().SetTitleOffset(1.7)
    #histos[i].GetYaxis().SetTickLength(0)
    #histos[i].GetYaxis().SetLabelOffset(999)

  texl = TLatex(histos[0].GetBinLowEdge(1), 1.01*1.4*max_val, "CMS Preliminary, Simulation ttH #sqrt{s}=13 TeV")
  texl.SetTextSize(0.04)
  texl.Draw("same")

  histos[0].Draw("hist")
  histos[1].Draw("same")
  leg.Draw("same")
  texl.Draw("same")
  
  histos[0].GetYaxis().SetLabelSize(0.)
  axis = TGaxis(range_low, min_val, range_low, max_val, min_val, max_val, 510, "")
  axis.SetLabelFont(43) #Absolute font size in pixel (precision 3)
  axis.SetLabelSize(15)
  axis.Draw()
  
  # lower plot will be in pad
  c.cd()    # Go back to the main canvas before defining pad2
  pad2 = TPad("pad2", "pad2", 0, 0.05, 1, 0.3)
  pad2.SetLeftMargin(0.15)
  pad2.SetTopMargin(0)
  pad2.SetBottomMargin(0.35)
  pad2.Draw()
  pad2.cd()
  
  h_ratio = make_ratio_histogram("h_ratio", histos[1], histos[0])
  
  """
  h_ratio = h[1].Clone("h_ratio")
  """
  
  h_ratio.SetTitle("")
  h_ratio.Draw()       #Draw the ratio plot
  
  # Y axis histo_emul plot settings
  histos[0].GetYaxis().SetTitleSize(20)
  histos[0].GetYaxis().SetTitleFont(43)
  histos[0].GetYaxis().SetTitleOffset(1.5)
  
  # Ratio plot (h_ratio) settings
  #h_ratio.SetTitle("") # Remove the ratio title
  
  h_ratio.GetYaxis().SetLabelSize(0.)
  axis2 = TGaxis( range_low, 0.01, range_low, 1.99, 0.01, 1.99, 505,"")
  axis2.SetLabelFont(43) # Absolute font size in pixel (precision 3)
  axis2.SetLabelSize(15)
  axis2.Draw()
  
  # Y axis ratio plot settings
  h_ratio.GetYaxis().SetTitle("%s/%s" % (groupname2, groupname1))
  h_ratio.GetYaxis().SetNdivisions(505)
  h_ratio.GetYaxis().SetTitleSize(20)
  h_ratio.GetYaxis().SetTitleFont(43)
  h_ratio.GetYaxis().SetTitleOffset(1.5)
  #h_ratio.GetYaxis().SetLabelFont(43) # Absolute font size in pixel (precision 3)
  #h_ratio.GetYaxis().SetLabelSize(15)

  
  # X axis ratio plot settings
  h_ratio.GetXaxis().SetTitleSize(20)
  h_ratio.GetXaxis().SetTitleFont(43)
  h_ratio.GetXaxis().SetTitleOffset(4.)
  h_ratio.GetXaxis().SetLabelFont(43) # Absolute font size in pixel (precision 3)
  h_ratio.GetXaxis().SetLabelSize(15)

  
  line = TLine(range_low, 1., range_high,1.)
  line.Draw("same")

  plot_file_name="%s" % (var_name)
  dirname = ("%s_vs_%s/%s/%s" % (groupname1, groupname2, category, outdir)).replace(" ", "_")
  for file_format in ["png", "pdf"]:
      mkdir_p("plots_test/%s/%s" % (dirname, file_format))
      c.SaveAs("plots_test/%s/%s/%s.%s" % (dirname, file_format, plot_file_name, file_format))
Beispiel #20
0
            a_dvdd.append( 1.e-6*vc1._i_dvdd[i] );
            a_vdd.append( 1.e-6*vc1._i_vdd[i] );
            a_prech.append( 1.e-6*vc1._i_prech[i] );

        gr_dvdd = TGraph( len(a_t), a_t, a_dvdd );
        gr_vdd = TGraph( len(a_t), a_t, a_vdd );
        gr_prech = TGraph( len(a_t), a_t, a_prech );

        gr_dvdd.SetLineColor(1);
        gr_vdd.SetLineColor(2);
        gr_prech.SetLineColor(4);

        leg = TLegend(0.65,0.25,0.85,0.45);
        leg.SetFillStyle(1001);
        leg.SetFillColor(0);    
        leg.SetBorderSize(1);  
        leg.AddEntry(gr_dvdd,"I (dvdd)","l");
        leg.AddEntry(gr_vdd,"I (vdd)","l");
        leg.AddEntry(gr_prech,"I (prech)","l");

        c_i = TCanvas( "c_i", "c_i", 1200, 800 );
        hrl = c_i.DrawFrame(0,1.0e-4,float(len(a_t)),1.0);
        hrl.GetYaxis().SetTitle("current (A)");
        hrl.GetXaxis().SetTitle("time (N bursts)");
        c_i.SetGrid(); 
        gr_dvdd.Draw("l");
        gr_vdd.Draw("l");
        gr_prech.Draw("l");
        leg.Draw();
        gPad.SetLogy();
        c_i.SaveAs(options.odir+"/power_NStress"+str(options.NStress)+"_freq"+str(options.freq)+".pdf");
Beispiel #21
0
         binwidths.append(30.0)
 #print binwidths
 normCMS = normalizeGraph(unnormCMS, binwidths)
 normCMS.SetMarkerStyle(kFullCircle)
 normCMS.SetMarkerSize(1.4)
 normCMS.SetMarkerColor(kBlue + 2)
 normCMS.SetLineColor(kBlue + 2)
 normCMS.Draw('apz')
 normCMS.SetMaximum(0.3)
 leg = TLegend(0.4, 1. - gPad.GetTopMargin() - 0.03 - 0.18,
               1. - gPad.GetRightMargin() - 0.02,
               1. - gPad.GetTopMargin() - 0.03, '', 'NDC')
 leg.SetMargin(0.15)
 #leg.Dump()
 leg.SetFillStyle(0)
 leg.SetBorderSize(0)
 leg.AddEntry(normCMS, 'CMS, |y|<2, #sqrt{s}=7 TeV', 'pe')
 if (D0):
     D0.Draw('pz')
     leg.AddEntry(D0, 'D#oslash, |y|<1.8, #sqrt{s}=1.96 TeV', 'pe')
 else:
     leg.SetY1(1. - gPad.GetTopMargin() - 0.03 - 0.12)
 if (CDF):
     CDF.Draw('pz')
     leg.AddEntry(CDF, 'CDF, |y|<0.4, #sqrt{s}=1.8 TeV', 'pe')
 #leg.Dump()
 leg.Draw('same')
 l.DrawLatex(1.0 - gPad.GetRightMargin() - 0.04,
             leg.GetY1() - 0.06, '#varUpsilon(%iS)' % resonance)
 gPad.SetLogy()
 gPad.Update()
Beispiel #22
0
def main():
    gStyle.SetOptStat(0)
    BIAS_DIR = global_paths.BIASDIR + args.btagging + "/"
    if args.year == 'run2c':
        BIAS_DIR += "combined_run2_r{}{}/"
        ## individual plots stored in run2c_masspoints

    ## extract pulls
    pulls = {}
    for signal_strength in ['0', '2sigma', '5sigma']:
        print
        print
        print "--------------------------------------------------"
        print "r = " + signal_strength
        print "--------------------------------------------------"
        pulls[signal_strength] = TGraphErrors()
        for m in range(1600, 8001, 100):
            if (signal_strength == '2sigma'
                    and m < 2600) or (signal_strength == '5sigma'
                                      and m < 4100):  ##FIXME FIXME
                datacard_correction = True
            else:
                datacard_correction = False
            print
            print "m = " + str(m)
            if datacard_correction:
                print "correcting signal strength in the datacard"
            print
            pull0 = int(SIGNAL_STRENGTH[signal_strength][m])

            tree = TChain("tree_fit_sb")
            for seed in [
                    '123456', '234567', '345678', '456789', '567891', '678912',
                    '789123', '891234', '912345', '123459'
            ]:
                tree.Add(
                    BIAS_DIR.format(signal_strength,
                                    "_lowm" if datacard_correction else "") +
                    "fitDiagnostics_M{mass}_{seed}.root".format(
                        mass=m, seed=seed))  ##FIXME FIXME

            hist = TH1D("s_pulls",
                        ";%s/#sigma_{r};Number of toys" % ("#Deltar"), 25, -5,
                        +5)  #
            for i in range(tree.GetEntries()):
                if hist.GetEntries() >= 1000: continue
                tree.GetEntry(i)
                #print "r = {} (+{}, -{})".format(tree.r, tree.rHiErr, tree.rLoErr)
                ##if tree.rLoErr < 0.: continue
                if abs(tree.r + 1.) < 0.001: continue
                if abs(tree.r - 1.) < 0.001: continue
                if abs(tree.r - 0.) < 0.001: continue
                if tree.rHiErr == 0. or tree.rLoErr == 0.: continue
                if abs(tree.r + abs(tree.rHiErr) -
                       round(tree.r + abs(tree.rHiErr))) < 0.0001:
                    continue
                if abs(tree.r - abs(tree.rLoErr) -
                       round(tree.r - abs(tree.rLoErr))) < 0.0001:
                    continue
                #print "r = {} (+{}, -{})".format(tree.r, tree.rHiErr, tree.rLoErr)
                pull = (tree.r - pull0) / abs(
                    tree.rHiErr) if tree.r - pull0 > 0. else (
                        tree.r - pull0) / abs(tree.rLoErr)  ## my own approach
                hist.Fill(pull)

            ## individual plots for checking the fit quality
            c1 = TCanvas("c1", "Pulls", 600, 600)
            c1.cd()
            hist.GetXaxis().SetTitleSize(0.045)
            hist.GetYaxis().SetTitleSize(0.045)
            hist.GetYaxis().SetTitleOffset(1.1)
            hist.GetXaxis().SetTitleOffset(1.05)
            hist.GetXaxis().SetLimits(-6, 6.)
            hist.GetYaxis().SetLimits(0, 200.)
            hist.SetMinimum(0.)
            hist.SetMaximum(190.)
            c1.SetTopMargin(0.05)

            ##print "@ m= {}: \t mean = {}".format(m, hist.GetMean())
            #pulls[signal_strength].SetPoint(pulls[signal_strength].GetN(), m, hist.GetMean()) ## get actual mean of histogram
            fit_func = TF1("gaussfit", "gaus", -3., 3.)
            hist.Fit(fit_func, "E")

            hist.Draw()

            drawCMS(-1, "Simulation Preliminary", year='run2')
            drawMass("m_{Z'} = " + str(m) + " GeV")
            c1.Print("plots/bias/run2c_masspoints/r" + signal_strength +
                     "/bias_fit_" + str(m) + "_" + args.year + ".pdf")
            c1.Print("plots/bias/run2c_masspoints/r" + signal_strength +
                     "/bias_fit_" + str(m) + "_" + args.year + ".png")

            n = pulls[signal_strength].GetN()
            pulls[signal_strength].SetPoint(
                n, m, fit_func.GetParameter(1))  ## get fitted gaussian mean
            pulls[signal_strength].SetPointError(
                n, 0., fit_func.GetParError(1))  ## set gaussian width as error

            fit_func.Delete()
            hist.Delete()
            c1.Delete()
        #except:
        #    print "something went wrong in m =", m

    ## draw pulls
    outfile = TFile("plots/bias/bias_study_new_" + args.year + ".root",
                    "RECREATE")

    c = TCanvas("canvas", "canvas", 800, 600)
    leg = TLegend(0.65, 0.7, 0.95, 0.9)
    leg.SetBorderSize(0)
    leg.SetFillStyle(0)  #1001
    leg.SetFillColor(0)
    for i, signal_strength in enumerate(['0', '2sigma', '5sigma']):
        pulls[signal_strength].SetMarkerStyle(2)
        pulls[signal_strength].SetMarkerColor(COLORS[signal_strength])
        pulls[signal_strength].SetLineColor(COLORS[signal_strength])
        pulls[signal_strength].SetLineWidth(2)
        pulls[signal_strength].SetMinimum(-0.7)
        pulls[signal_strength].SetMaximum(0.7)
        pulls[signal_strength].Draw("APL" if i == 0 else "PL")
        leg.AddEntry(pulls[signal_strength], LEGEND[signal_strength])
    zeroline = TGraph()
    zeroline.SetPoint(zeroline.GetN(), 1000, 0)
    zeroline.SetPoint(zeroline.GetN(), 8600, 0)
    zeroline.SetMarkerStyle(7)
    zeroline.SetMarkerSize(0)
    zeroline.SetLineStyle(15)
    zeroline.SetLineColor(1)
    zeroline.Draw("PL")
    c.SetGrid()
    pulls['0'].SetTitle(";m_{Z'} (GeV);mean #Deltar/#sigma_{r}")
    pulls['0'].GetXaxis().SetTitleSize(0.045)
    pulls['0'].GetYaxis().SetTitleSize(0.045)
    pulls['0'].GetYaxis().SetTitleOffset(1.1)
    pulls['0'].GetXaxis().SetTitleOffset(1.05)
    pulls['0'].GetXaxis().SetLimits(1350., 8150.)
    c.SetTopMargin(0.05)
    leg.Draw()
    drawCMS(-1, "Simulation Preliminary", year='run2')
    c.Print("plots/bias/bias_study_new_" + args.year + ".png")
    c.Print("plots/bias/bias_study_new_" + args.year + ".pdf")
    c.Write()
    outfile.Close()
def plotBlockComparison(treeBlockA,
                        treeBlockB,
                        variable,
                        additionalCut,
                        nBins,
                        firstBin,
                        lastBin,
                        labelX,
                        labelY,
                        suffix,
                        log=False,
                        signal=False):

    hCanvas = TCanvas("hCanvas", "Distribution", 800, 800)
    plotPad = ROOT.TPad("plotPad", "plotPad", 0, 0.3, 1, 1)
    ratioPad = ROOT.TPad("ratioPad", "ratioPad", 0, 0., 1, 0.3)
    setTDRStyle()
    plotPad.UseCurrentStyle()
    ratioPad.UseCurrentStyle()
    plotPad.Draw()
    ratioPad.Draw()
    plotPad.cd()

    legend = TLegend(0.7, 0.55, 0.95, 0.95)
    legend.SetFillStyle(0)
    legend.SetBorderSize(1)

    minMll = 20

    ROOT.gStyle.SetOptStat(0)
    Cutlabel = ROOT.TLatex()
    Cutlabel.SetTextAlign(12)
    Cutlabel.SetTextSize(0.03)
    Labelin = ROOT.TLatex()
    Labelin.SetTextAlign(12)
    Labelin.SetTextSize(0.07)
    Labelin.SetTextColor(ROOT.kRed + 2)
    Labelout = ROOT.TLatex()
    Labelout.SetTextAlign(12)
    Labelout.SetTextSize(0.07)
    Labelout.SetTextColor(ROOT.kBlack)

    EMuhistBlockA = createHistoFromTree(treeBlockA, variable, additionalCut,
                                        nBins, firstBin, lastBin, -1)

    EMuhistBlockB = createHistoFromTree(treeBlockB, variable, additionalCut,
                                        nBins, firstBin, lastBin, -1)

    EMuhistBlockB.Scale(9.2 / 10.4)
    print EMuhistBlockA.Integral()
    print EMuhistBlockB.Integral()
    EMuhistBlockA.SetMarkerStyle(21)
    EMuhistBlockB.SetMarkerStyle(22)
    EMuhistBlockA.SetMarkerColor(ROOT.kGreen + 3)
    EMuhistBlockB.SetMarkerColor(ROOT.kBlack)
    EMuhistBlockA.SetLineColor(ROOT.kGreen + 3)
    EMuhistBlockB.SetLineColor(ROOT.kBlack)

    if log:
        yMin = 0.1
        yMax = max(EMuhistBlockA.GetBinContent(EMuhistBlockA.GetMaximumBin()),
                   EMuhistBlockB.GetBinContent(
                       EMuhistBlockB.GetMaximumBin())) * 10
        plotPad.SetLogy()
    else:
        yMin = 0
        yMax = max(EMuhistBlockA.GetBinContent(EMuhistBlockA.GetMaximumBin()),
                   EMuhistBlockB.GetBinContent(
                       EMuhistBlockB.GetMaximumBin())) * 1.5
    hCanvas.DrawFrame(firstBin, yMin, lastBin, yMax,
                      "; %s ; %s" % (labelX, labelY))

    EMuhistBlockA.Draw("samep")
    EMuhistBlockB.Draw("samep")

    legend.AddEntry(EMuhistBlockA, "First 9.2 fb^{-1}", "p")
    legend.AddEntry(EMuhistBlockB, "Second 10.4 fb^{-1} scaled", "p")
    #~
    latex = ROOT.TLatex()
    latex.SetTextSize(0.043)
    latex.SetTextFont(42)
    latex.SetNDC(True)
    latex.DrawLatex(
        0.13, 0.95,
        "CMS Preliminary,    #sqrt{s} = 8 TeV,     #scale[0.6]{#int}Ldt = 9.2-10.4 fb^{-1}"
    )
    #~

    legend.Draw("same")

    ratioPad.cd()

    ratioGraphs = ratios.RatioGraph(EMuhistBlockA,
                                    EMuhistBlockB,
                                    firstBin,
                                    lastBin,
                                    title="Bl. A / Bl. B",
                                    yMin=0.0,
                                    yMax=2,
                                    ndivisions=10,
                                    color=ROOT.kGreen + 3,
                                    adaptiveBinning=0.25)

    ratioGraphs.draw(ROOT.gPad, True, False, True, chi2Pos=0.8)
    if signal:
        name = "OFUnblinding_SignalRegion_%s_%s.pdf"
    else:
        name = "OFUnblinding_Inclusive_%s_%s.pdf"
    if variable == "p4.M()":

        hCanvas.Print(name % (suffix, "Mll"))
    else:
        hCanvas.Print(name % (suffix, variable))
        hCanvas.Clear()
Beispiel #24
0
def makeProComp(var, label, log):
    new_file = TFile("tmp/histOut_data2017D_new_HLT_multiRP.root")
    old_file = TFile("tmp/histOut_data2017D_old_HLT_multiRP.root")

    str_45 = 'xip' if var == 'xi' else 'thetaY_45'
    str_56 = 'xim' if var == 'xi' else 'thetaY_56'

    h_new_45 = new_file.Get('plots/h_pro_%s' % str_45)
    h_new_56 = new_file.Get('plots/h_pro_%s' % str_56)
    h_old_45 = old_file.Get('plots/h_pro_%s' % str_45)
    h_old_56 = old_file.Get('plots/h_pro_%s' % str_56)

    c1 = Canvas('c1')
    c1.SetLeftMargin(0.15)
    c1.cd()
    c1.SetTicks(1, 1)
    if log: c1.SetLogy()
    h_new_45.SetTitle('')
    h_new_45.GetYaxis().SetTitleOffset(2.1)
    h_new_45.GetYaxis().SetTitle('Events')
    h_new_45.GetXaxis().SetTitleOffset(1.2)
    h_new_45.GetXaxis().SetTitle(label)
    h_new_45.SetLineColor(r.kRed)
    h_new_45.GetXaxis().SetNdivisions(507)
    h_old_45.SetLineColor(r.kBlue)
    h_new_45.Draw('HIST')
    h_old_45.Draw('HIST same')
    text45 = TPaveText(0.72, 0.81, 0.9, 0.9, 'NB NDC')
    text45.AddText('sector 45')
    text45.SetTextSize(0.032)
    text45.SetTextFont(42)
    text45.SetFillStyle(0)
    text45.Draw()
    legend = TLegend(0.6, 0.6, 0.75, 0.7)
    legend.SetBorderSize(0)
    legend.SetFillColor(0)
    legend.SetFillStyle(0)
    legend.SetTextFont(42)
    legend.SetTextSize(0.028)
    legend.AddEntry(h_old_45, 'Legacy data', 'l')
    legend.AddEntry(h_new_45, 'Reminiaod data', 'l')
    legend.Draw()
    pLabel = prelimLabel('top', False)
    pLabel.Draw()
    c1.SaveAs('plots/reMiniAOD_validation_%s_45.%s' % (var, extension))

    c2 = Canvas('c2')
    c2.SetLeftMargin(0.15)
    c2.cd()
    c2.SetTicks(1, 1)
    if log: c2.SetLogy()
    h_new_56.SetTitle('')
    h_new_56.GetYaxis().SetTitleOffset(2.1)
    h_new_56.GetYaxis().SetTitle('Events')
    h_new_56.GetXaxis().SetTitleOffset(1.2)
    h_new_56.GetXaxis().SetTitle(label)
    h_new_56.SetLineColor(r.kRed)
    h_new_56.GetXaxis().SetNdivisions(507)
    h_old_56.SetLineColor(r.kBlue)
    h_new_56.Draw('HIST')
    h_old_56.Draw('HIST same')
    text56 = TPaveText(0.72, 0.81, 0.9, 0.9, 'NB NDC')
    text56.AddText('sector 56')
    text56.SetTextSize(0.032)
    text56.SetTextFont(42)
    text56.SetFillStyle(0)
    text56.Draw()
    pLabel.Draw()
    legend.Draw()
    c2.SaveAs('plots/reMiniAOD_validation_%s_56.%s' % (var, extension))
Beispiel #25
0
def main():
    # usage description
    usage = "Example: ./scripts/plotLimits.py -M Asymptotic -l logs -f qq --massrange 1200 7000 100"

    # input parameters
    parser = ArgumentParser(
        description='Script that plots limits for specified mass points',
        epilog=usage)

    parser.add_argument("-M",
                        "--method",
                        dest="method",
                        required=True,
                        choices=[
                            'ProfileLikelihood', 'HybridNew', 'Asymptotic',
                            'MarkovChainMC', 'theta'
                        ],
                        help="Method to calculate upper limits",
                        metavar="METHOD")

    results_group = parser.add_mutually_exclusive_group(required=True)
    results_group.add_argument("-l",
                               "--logs_path",
                               dest="logs_path",
                               help="Path to log files",
                               metavar="LOGS_PATH")
    results_group.add_argument("-r",
                               "--results_file",
                               dest="results_file",
                               help="Path to a file containing results",
                               metavar="RESULTS_FILE")

    parser.add_argument("-f",
                        "--final_state",
                        dest="final_state",
                        required=True,
                        help="Final state (e.g. qq, qg, gg)",
                        metavar="FINAL_STATE")

    parser.add_argument(
        "--postfix",
        dest="postfix",
        default='',
        help="Postfix for the output plot name (default: %(default)s)")

    parser.add_argument(
        "--fileFormat",
        dest="fileFormat",
        default='pdf',
        help="Format of the output plot (default: %(default)s)")

    parser.add_argument("--extraText",
                        dest="extraText",
                        default='Simulation Preliminary',
                        help="Extra text on the plot (default: %(default)s)")

    parser.add_argument(
        "--lumi_sqrtS",
        dest="lumi_sqrtS",
        default='1 fb^{-1} (13 TeV)',
        help=
        "Integrated luminosity and center-of-mass energy (default: %(default)s)"
    )

    parser.add_argument("--printResults",
                        dest="printResults",
                        default=False,
                        action="store_true",
                        help="Print results to the screen")

    mass_group = parser.add_mutually_exclusive_group(required=True)
    mass_group.add_argument(
        "--mass",
        type=int,
        nargs='*',
        default=1000,
        help=
        "Mass can be specified as a single value or a whitespace separated list (default: %(default)i)"
    )
    mass_group.add_argument(
        "--massrange",
        type=int,
        nargs=3,
        help="Define a range of masses to be produced. Format: min max step",
        metavar=('MIN', 'MAX', 'STEP'))
    mass_group.add_argument("--masslist",
                            help="List containing mass information")

    args = parser.parse_args()

    # mass points for which resonance shapes will be produced
    input_masses = []

    if args.massrange != None:
        MIN, MAX, STEP = args.massrange
        input_masses = range(MIN, MAX + STEP, STEP)
    elif args.masslist != None:
        # A mass list was provided
        print "Will create mass list according to", args.masslist
        masslist = __import__(args.masslist.replace(".py", ""))
        input_masses = masslist.masses
    else:
        input_masses = args.mass
    # sort masses
    input_masses.sort()

    # arrays holding results
    masses = array('d')
    xs_obs_limits = array('d')
    xs_exp_limits = array('d')
    masses_exp = array('d')
    xs_exp_limits_1sigma = array('d')
    xs_exp_limits_1sigma_up = array('d')
    xs_exp_limits_2sigma = array('d')
    xs_exp_limits_2sigma_up = array('d')

    if args.logs_path != None:

        logs_path = os.path.join(os.getcwd(), args.logs_path)

        for mass in input_masses:

            print ">> Reading results for %s resonance with m = %i GeV..." % (
                args.final_state, int(mass))

            masses.append(mass)
            if args.method == 'Asymptotic': masses_exp.append(mass)

            logName = 'limits_%s_%s_m%i.log' % (args.method, args.final_state,
                                                int(mass))

            if args.method == 'theta': logName = logName.replace('limits_', '')

            log_file = open(os.path.join(logs_path, logName), 'r')

            foundMethod = False

            # read the log file
            for line in log_file:
                if args.method == 'Asymptotic':
                    if re.search("^Observed Limit: r", line):
                        xs_obs_limits.append(float(line.split()[-1]))
                    if re.search("^Expected 50.0%: r", line):
                        xs_exp_limits.append(float(line.split()[-1]))
                    if re.search("^Expected 16.0%: r", line):
                        xs_exp_limits_1sigma.append(float(line.split()[-1]))
                    if re.search("^Expected 84.0%: r", line):
                        xs_exp_limits_1sigma_up.append(float(line.split()[-1]))
                    if re.search("^Expected  2.5%: r", line):
                        xs_exp_limits_2sigma.append(float(line.split()[-1]))
                    if re.search("^Expected 97.5%: r", line):
                        xs_exp_limits_2sigma_up.append(float(line.split()[-1]))
                elif args.method == 'theta':
                    if re.search('^# x; y; yerror', line):
                        foundMethod = True
                    if line.split()[0] == '0' and foundMethod:
                        xs_obs_limits.append(float(line.split()[1]))
                else:
                    if re.search(' -- ' + args.method, line):
                        foundMethod = True
                    if re.search("^Limit: r", line) and foundMethod:
                        xs_obs_limits.append(float(line.split()[3]))

            if len(masses) != len(xs_obs_limits):
                print "** ERROR: ** Could not find observed limit for m =", int(
                    mass), "GeV. Aborting."
                sys.exit(1)

            if args.method == 'Asymptotic':
                if len(masses) != len(xs_exp_limits):
                    print "** ERROR: ** Could not find expected limit for m =", int(
                        mass), "GeV. Aborting."
                    sys.exit(1)

                if len(masses) != len(xs_exp_limits_1sigma):
                    print "** ERROR: ** Could not find expected 1 sigma down limit for m =", int(
                        mass), "GeV. Aborting."
                    sys.exit(1)

                if len(masses) != len(xs_exp_limits_1sigma_up):
                    print "** ERROR: ** Could not find expected 1 sigma up limit for m =", int(
                        mass), "GeV. Aborting."
                    sys.exit(1)

                if len(masses) != len(xs_exp_limits_2sigma):
                    print "** ERROR: ** Could not find expected 2 sigma down limit for m =", int(
                        mass), "GeV. Aborting."
                    sys.exit(1)

                if len(masses) != len(xs_exp_limits_2sigma_up):
                    print "** ERROR: ** Could not find expected 2 sigma up limit for m =", int(
                        mass), "GeV. Aborting."
                    sys.exit(1)
        if args.method == 'Asymptotic':
            # complete the expected limit arrays
            for i in range(0, len(masses)):
                masses_exp.append(masses[len(masses) - i - 1])
                xs_exp_limits_1sigma.append(
                    xs_exp_limits_1sigma_up[len(masses) - i - 1])
                xs_exp_limits_2sigma.append(
                    xs_exp_limits_2sigma_up[len(masses) - i - 1])
    else:
        print ">> Importing results..."

        sys.path.insert(0, os.path.dirname(args.results_file))

        results = __import__(
            os.path.basename(args.results_file).replace(".py", ""))

        all_masses = np.array(results.masses)
        all_masses_exp = np.array(results.masses_exp)
        indices = []
        indices_exp = []

        # search for indices of input_masses
        for mass in input_masses:
            where = np.where(all_masses == mass)[0]
            if len(where) == 0:
                print "** WARNING: ** Cannot find results for m =", int(
                    mass
                ), "GeV in the provided results file. Skipping this mass point."
            indices.extend(where)
            if len(all_masses_exp) > 0:
                where = np.where(all_masses_exp == mass)[0]
                if len(where) == 0:
                    print "** WARNING: ** Cannot find results for m =", int(
                        mass
                    ), "GeV in the provided results file. Skipping this mass point."
                indices_exp.extend(where)

        # sort indices
        indices.sort()
        indices_exp.sort()

        for i in indices:
            masses.append(results.masses[i])
            xs_obs_limits.append(results.xs_obs_limits[i])
            if len(all_masses_exp) > 0:
                xs_exp_limits.append(results.xs_exp_limits[i])
        for i in indices_exp:
            masses_exp.append(results.masses_exp[i])
            xs_exp_limits_1sigma.append(results.xs_exp_limits_1sigma[i])
            xs_exp_limits_2sigma.append(results.xs_exp_limits_2sigma[i])

    if args.printResults:
        print "masses =", masses.tolist()
        print "xs_obs_limits =", xs_obs_limits.tolist()
        print "xs_exp_limits =", xs_exp_limits.tolist()
        print ""
        print "masses_exp =", masses_exp.tolist()
        print "xs_exp_limits_1sigma =", xs_exp_limits_1sigma.tolist()
        print "xs_exp_limits_2sigma =", xs_exp_limits_2sigma.tolist()

    # import ROOT stuff
    from ROOT import kTRUE, kFALSE, gROOT, gStyle, gPad, TGraph, TCanvas, TLegend
    from ROOT import kGreen, kYellow, kWhite

    gROOT.SetBatch(kTRUE)
    gStyle.SetOptStat(0)
    gStyle.SetOptTitle(0)
    gStyle.SetTitleFont(42, "XYZ")
    gStyle.SetTitleSize(0.06, "XYZ")
    gStyle.SetLabelFont(42, "XYZ")
    gStyle.SetLabelSize(0.05, "XYZ")
    gStyle.SetCanvasBorderMode(0)
    gStyle.SetFrameBorderMode(0)
    gStyle.SetCanvasColor(kWhite)
    gStyle.SetPadTickX(1)
    gStyle.SetPadTickY(1)
    gStyle.SetPadLeftMargin(0.15)
    gStyle.SetPadRightMargin(0.05)
    gStyle.SetPadTopMargin(0.05)
    gStyle.SetPadBottomMargin(0.15)
    gROOT.ForceStyle()

    # theory curves: gg
    massesS8 = array('d', [
        1000.0, 1100.0, 1200.0, 1300.0, 1400.0, 1500.0, 1600.0, 1700.0, 1800.0,
        1900.0, 2000.0, 2100.0, 2200.0, 2300.0, 2400.0, 2500.0, 2600.0, 2700.0,
        2800.0, 2900.0, 3000.0, 3100.0, 3200.0, 3300.0, 3400.0, 3500.0, 3600.0,
        3700.0, 3800.0, 3900.0, 4000.0, 4100.0, 4200.0, 4300.0, 4400.0, 4500.0,
        4600.0, 4700.0, 4800.0, 4900.0, 5000.0, 5100.0, 5200.0, 5300.0, 5400.0,
        5500.0, 5600.0, 5700.0, 5800.0, 5900.0, 6000.0
    ])
    xsS8 = array('d', [
        5.46E+02, 3.12E+02, 1.85E+02, 1.12E+02, 7.19E+01, 4.59E+01, 3.02E+01,
        2.01E+01, 1.37E+01, 9.46E+00, 6.55E+00, 4.64E+00, 3.27E+00, 2.36E+00,
        1.70E+00, 1.24E+00, 9.11E-01, 6.69E-01, 4.97E-01, 3.71E-01, 2.78E-01,
        2.07E-01, 1.55E-01, 1.19E-01, 9.26E-02, 7.08E-02, 5.43E-02, 4.15E-02,
        3.22E-02, 2.50E-02, 1.92E-02, 1.51E-02, 1.19E-02, 9.25E-03, 7.35E-03,
        5.86E-03, 4.53E-03, 3.66E-03, 2.91E-03, 2.33E-03, 1.86E-03, 1.45E-03,
        1.12E-03, 8.75E-04, 6.90E-04, 5.55E-04, 4.47E-04, 3.63E-04, 2.92E-04,
        2.37E-04, 1.97E-04
    ])

    graph_xsS8 = TGraph(len(massesS8), massesS8, xsS8)
    graph_xsS8.SetLineWidth(3)
    graph_xsS8.SetLineStyle(8)
    graph_xsS8.SetLineColor(6)

    # theory curves: qg
    massesString = array('d', [
        1000.0, 1100.0, 1200.0, 1300.0, 1400.0, 1500.0, 1600.0, 1700.0, 1800.0,
        1900.0, 2000.0, 2100.0, 2200.0, 2300.0, 2400.0, 2500.0, 2600.0, 2700.0,
        2800.0, 2900.0, 3000.0, 3100.0, 3200.0, 3300.0, 3400.0, 3500.0, 3600.0,
        3700.0, 3800.0, 3900.0, 4000.0, 4100.0, 4200.0, 4300.0, 4400.0, 4500.0,
        4600.0, 4700.0, 4800.0, 4900.0, 5000.0, 5100.0, 5200.0, 5300.0, 5400.0,
        5500.0, 5600.0, 5700.0, 5800.0, 5900.0, 6000.0, 6100.0, 6200.0, 6300.0,
        6400.0, 6500.0, 6600.0, 6700.0, 6800.0, 6900.0, 7000.0, 7100.0, 7200.0,
        7300.0, 7400.0, 7500.0, 7600.0, 7700.0, 7800.0, 7900.0, 8000.0, 8100.0,
        8200.0, 8300.0, 8400.0, 8500.0, 8600.0, 8700.0, 8800.0, 8900.0, 9000.0,
        9100., 9200., 9300., 9400., 9500., 9600., 9700., 9800., 9900., 10000.
    ])
    xsString = array('d', [
        8316.184311558545, 5312.93137758767, 3435.0309937336524,
        2304.4139502741305, 1569.8115447896687, 1090.9516635659693,
        770.901859690924, 551.9206062572061, 399.69535383507633,
        293.77957451762086, 218.15126842827823, 162.87634729465125,
        123.17685479653694, 93.63530805932386, 71.53697229809124,
        55.37491301647483, 42.75271508357369, 33.36378355470234,
        26.06619302090876, 20.311817606835643, 16.1180931789545,
        12.768644973921226, 10.142660425967444, 8.057990848043234,
        6.400465846290908, 5.115134438331436, 4.132099789492928,
        3.3193854239538734, 2.6581204529344302, 2.157554604919995,
        1.7505176068913348, 1.4049155245498584, 1.140055677916783,
        0.9253251132104159, 0.7522038169131606, 0.6119747371392215,
        0.49612321727328523, 0.40492020959456737, 0.33091999402250655,
        0.27017917021492555, 0.2201693919322846, 0.17830700070267996,
        0.14564253802358157, 0.11940534430331146, 0.09694948234356839,
        0.0793065371847468, 0.06446186373361917, 0.05282660618352478,
        0.0428516302310620888, 0.0348997638039910363, 0.0283334766442618227,
        0.0231416918363592127, 0.0187417921340763783, 0.0153501307395115115,
        0.0124396534127133717, 0.0100542205744949455, 0.0081744954858627415,
        0.0066338099362915941, 0.0053365711503318145, 0.00430912459914657443,
        0.00346381039244064343, 0.00278602671711227174, 0.00225154342228859257,
        0.0018082930150063248, 0.00143929440338502119, 0.0011581373956044489,
        0.00091869589873893118, 0.00073410823691329855, 0.00058669382997948734,
        0.0004661568745858897, 0.000368716655469570365,
        0.000293168485206959169, 0.000230224535021638668,
        0.000182317101888465142, 0.000143263359883433282,
        0.000112630538527214965, 0.000088189175598406759,
        0.000068708474367442343, 0.000053931726669273556,
        0.0000416417855733682702, 0.0000326529676755488658,
        0.0000254365480426201587, 0.0000198410151166864761,
        0.0000154034425617473576, 0.0000119095554601641413,
        9.2537574320108232e-6, 7.2155417437856749e-6, 5.6130924422251982e-6,
        4.36634755605624901e-6, 3.39717456406994868e-6, 2.6766018046173896e-6
    ])

    massesQstar = array('d', [
        1000.0, 1100.0, 1200.0, 1300.0, 1400.0, 1500.0, 1600.0, 1700.0, 1800.0,
        1900.0, 2000.0, 2100.0, 2200.0, 2300.0, 2400.0, 2500.0, 2600.0, 2700.0,
        2800.0, 2900.0, 3000.0, 3100.0, 3200.0, 3300.0, 3400.0, 3500.0, 3600.0,
        3700.0, 3800.0, 3900.0, 4000.0, 4100.0, 4200.0, 4300.0, 4400.0, 4500.0,
        4600.0, 4700.0, 4800.0, 4900.0, 5000.0, 5100.0, 5200.0, 5300.0, 5400.0,
        5500.0, 5600.0, 5700.0, 5800.0, 5900.0, 6000.0, 6100.0, 6200.0, 6300.0,
        6400.0, 6500.0, 6600.0, 6700.0, 6800.0, 6900.0, 7000.0, 7100.0, 7200.0,
        7300.0, 7400.0, 7500.0, 7600.0, 7700.0, 7800.0, 7900.0, 8000.0, 8100.0,
        8200.0, 8300.0, 8400.0, 8500.0, 8600.0, 8700.0, 8800.0, 8900.0, 9000.0
    ])
    xsQstar = array('d', [
        0.4101E+03, 0.2620E+03, 0.1721E+03, 0.1157E+03, 0.7934E+02, 0.5540E+02,
        0.3928E+02, 0.2823E+02, 0.2054E+02, 0.1510E+02, 0.1121E+02, 0.8390E+01,
        0.6328E+01, 0.4807E+01, 0.3674E+01, 0.2824E+01, 0.2182E+01, 0.1694E+01,
        0.1320E+01, 0.1033E+01, 0.8116E+00, 0.6395E+00, 0.5054E+00, 0.4006E+00,
        0.3182E+00, 0.2534E+00, 0.2022E+00, 0.1616E+00, 0.1294E+00, 0.1038E+00,
        0.8333E-01, 0.6700E-01, 0.5392E-01, 0.4344E-01, 0.3503E-01, 0.2827E-01,
        0.2283E-01, 0.1844E-01, 0.1490E-01, 0.1205E-01, 0.9743E-02, 0.7880E-02,
        0.6373E-02, 0.5155E-02, 0.4169E-02, 0.3371E-02, 0.2725E-02, 0.2202E-02,
        0.1779E-02, 0.1437E-02, 0.1159E-02, 0.9353E-03, 0.7541E-03, 0.6076E-03,
        0.4891E-03, 0.3935E-03, 0.3164E-03, 0.2541E-03, 0.2039E-03, 0.1635E-03,
        0.1310E-03, 0.1049E-03, 0.8385E-04, 0.6699E-04, 0.5347E-04, 0.4264E-04,
        0.3397E-04, 0.2704E-04, 0.2151E-04, 0.1709E-04, 0.1357E-04, 0.1077E-04,
        0.8544E-05, 0.6773E-05, 0.5367E-05, 0.4251E-05, 0.3367E-05, 0.2666E-05,
        0.2112E-05, 0.1673E-05, 0.1326E-05
    ])

    graph_xsString = TGraph(len(massesString), massesString, xsString)
    graph_xsString.SetLineWidth(3)
    graph_xsString.SetLineStyle(8)
    graph_xsString.SetLineColor(9)

    graph_xsQstar = TGraph(len(massesQstar), massesQstar, xsQstar)
    graph_xsQstar.SetLineWidth(3)
    graph_xsQstar.SetLineStyle(2)
    graph_xsQstar.SetLineColor(1)

    # theory curves: qq
    massesTh = array('d', [
        1000.0, 1100.0, 1200.0, 1300.0, 1400.0, 1500.0, 1600.0, 1700.0, 1800.0,
        1900.0, 2000.0, 2100.0, 2200.0, 2300.0, 2400.0, 2500.0, 2600.0, 2700.0,
        2800.0, 2900.0, 3000.0, 3100.0, 3200.0, 3300.0, 3400.0, 3500.0, 3600.0,
        3700.0, 3800.0, 3900.0, 4000.0, 4100.0, 4200.0, 4300.0, 4400.0, 4500.0,
        4600.0, 4700.0, 4800.0, 4900.0, 5000.0, 5100.0, 5200.0, 5300.0, 5400.0,
        5500.0, 5600.0, 5700.0, 5800.0, 5900.0, 6000.0, 6100.0, 6200.0, 6300.0,
        6400.0, 6500.0, 6600.0, 6700.0, 6800.0, 6900.0, 7000.0, 7100.0, 7200.0,
        7300.0, 7400.0, 7500.0, 7600.0, 7700.0, 7800.0, 7900.0, 8000.0, 8100.0,
        8200.0, 8300.0, 8400.0, 8500.0, 8600.0, 8700.0, 8800.0, 8900.0, 9000.0
    ])

    xsAxi = array('d', [
        0.1849E+03, 0.1236E+03, 0.8473E+02, 0.5937E+02, 0.4235E+02, 0.3069E+02,
        0.2257E+02, 0.1680E+02, 0.1263E+02, 0.9577E+01, 0.7317E+01, 0.5641E+01,
        0.4374E+01, 0.3411E+01, 0.2672E+01, 0.2103E+01, 0.1658E+01, 0.1312E+01,
        0.1041E+01, 0.8284E+00, 0.6610E+00, 0.5294E+00, 0.4250E+00, 0.3417E+00,
        0.2752E+00, 0.2220E+00, 0.1792E+00, 0.1449E+00, 0.1172E+00, 0.9487E-01,
        0.7686E-01, 0.6219E-01, 0.5033E-01, 0.4074E-01, 0.3298E-01, 0.2671E-01,
        0.2165E-01, 0.1755E-01, 0.1422E-01, 0.1152E-01, 0.9322E-02, 0.7539E-02,
        0.6092E-02, 0.4917E-02, 0.3965E-02, 0.3193E-02, 0.2568E-02, 0.2062E-02,
        0.1653E-02, 0.1323E-02, 0.1057E-02, 0.8442E-03, 0.6728E-03, 0.5349E-03,
        0.4242E-03, 0.3357E-03, 0.2644E-03, 0.2077E-03, 0.1627E-03, 0.1271E-03,
        0.9891E-04, 0.7686E-04, 0.5951E-04, 0.4592E-04, 0.3530E-04, 0.2704E-04,
        0.2059E-04, 0.1562E-04, 0.1180E-04, 0.8882E-05, 0.6657E-05, 0.4968E-05,
        0.3693E-05, 0.2734E-05, 0.2016E-05, 0.1481E-05, 0.1084E-05, 0.7903E-06,
        0.5744E-06, 0.4160E-06, 0.3007E-06
    ])
    xsDiquark = array('d', [
        0.5824E+02, 0.4250E+02, 0.3172E+02, 0.2411E+02, 0.1862E+02, 0.1457E+02,
        0.1153E+02, 0.9211E+01, 0.7419E+01, 0.6019E+01, 0.4912E+01, 0.4031E+01,
        0.3323E+01, 0.2750E+01, 0.2284E+01, 0.1903E+01, 0.1590E+01, 0.1331E+01,
        0.1117E+01, 0.9386E+00, 0.7900E+00, 0.6658E+00, 0.5618E+00, 0.4745E+00,
        0.4010E+00, 0.3391E+00, 0.2869E+00, 0.2428E+00, 0.2055E+00, 0.1740E+00,
        0.1473E+00, 0.1246E+00, 0.1055E+00, 0.8922E-01, 0.7544E-01, 0.6376E-01,
        0.5385E-01, 0.4546E-01, 0.3834E-01, 0.3231E-01, 0.2720E-01, 0.2288E-01,
        0.1922E-01, 0.1613E-01, 0.1352E-01, 0.1132E-01, 0.9463E-02, 0.7900E-02,
        0.6584E-02, 0.5479E-02, 0.4551E-02, 0.3774E-02, 0.3124E-02, 0.2581E-02,
        0.2128E-02, 0.1750E-02, 0.1437E-02, 0.1177E-02, 0.9612E-03, 0.7833E-03,
        0.6366E-03, 0.5160E-03, 0.4170E-03, 0.3360E-03, 0.2700E-03, 0.2162E-03,
        0.1725E-03, 0.1372E-03, 0.1087E-03, 0.8577E-04, 0.6742E-04, 0.5278E-04,
        0.4114E-04, 0.3192E-04, 0.2465E-04, 0.1894E-04, 0.1448E-04, 0.1101E-04,
        0.8322E-05, 0.6253E-05, 0.4670E-05
    ])
    xsWprime = array('d', [
        0.8811E+01, 0.6024E+01, 0.4216E+01, 0.3010E+01, 0.2185E+01, 0.1610E+01,
        0.1200E+01, 0.9043E+00, 0.6875E+00, 0.5271E+00, 0.4067E+00, 0.3158E+00,
        0.2464E+00, 0.1932E+00, 0.1521E+00, 0.1201E+00, 0.9512E-01, 0.7554E-01,
        0.6012E-01, 0.4792E-01, 0.3827E-01, 0.3059E-01, 0.2448E-01, 0.1960E-01,
        0.1571E-01, 0.1259E-01, 0.1009E-01, 0.8090E-02, 0.6483E-02, 0.5193E-02,
        0.4158E-02, 0.3327E-02, 0.2660E-02, 0.2125E-02, 0.1695E-02, 0.1351E-02,
        0.1075E-02, 0.8546E-03, 0.6781E-03, 0.5372E-03, 0.4248E-03, 0.3353E-03,
        0.2642E-03, 0.2077E-03, 0.1629E-03, 0.1275E-03, 0.9957E-04, 0.7757E-04,
        0.6027E-04, 0.4670E-04, 0.3610E-04, 0.2783E-04, 0.2140E-04, 0.1641E-04,
        0.1254E-04, 0.9561E-05, 0.7269E-05, 0.5510E-05, 0.4167E-05, 0.3143E-05,
        0.2364E-05, 0.1774E-05, 0.1329E-05, 0.9931E-06, 0.7411E-06, 0.5523E-06,
        0.4108E-06, 0.3055E-06, 0.2271E-06, 0.1687E-06, 0.1254E-06, 0.9327E-07,
        0.6945E-07, 0.5177E-07, 0.3863E-07, 0.2888E-07, 0.2162E-07, 0.1622E-07,
        0.1218E-07, 0.9156E-08, 0.6893E-08
    ])
    xsZprime = array('d', [
        0.5027E+01, 0.3398E+01, 0.2353E+01, 0.1663E+01, 0.1196E+01, 0.8729E+00,
        0.6450E+00, 0.4822E+00, 0.3638E+00, 0.2769E+00, 0.2123E+00, 0.1639E+00,
        0.1272E+00, 0.9933E-01, 0.7789E-01, 0.6134E-01, 0.4848E-01, 0.3845E-01,
        0.3059E-01, 0.2440E-01, 0.1952E-01, 0.1564E-01, 0.1256E-01, 0.1010E-01,
        0.8142E-02, 0.6570E-02, 0.5307E-02, 0.4292E-02, 0.3473E-02, 0.2813E-02,
        0.2280E-02, 0.1848E-02, 0.1499E-02, 0.1216E-02, 0.9864E-03, 0.8002E-03,
        0.6490E-03, 0.5262E-03, 0.4264E-03, 0.3453E-03, 0.2795E-03, 0.2260E-03,
        0.1826E-03, 0.1474E-03, 0.1188E-03, 0.9566E-04, 0.7690E-04, 0.6173E-04,
        0.4947E-04, 0.3957E-04, 0.3159E-04, 0.2516E-04, 0.2001E-04, 0.1587E-04,
        0.1255E-04, 0.9906E-05, 0.7795E-05, 0.6116E-05, 0.4785E-05, 0.3731E-05,
        0.2900E-05, 0.2247E-05, 0.1734E-05, 0.1334E-05, 0.1022E-05, 0.7804E-06,
        0.5932E-06, 0.4492E-06, 0.3388E-06, 0.2544E-06, 0.1903E-06, 0.1417E-06,
        0.1051E-06, 0.7764E-07, 0.5711E-07, 0.4186E-07, 0.3055E-07, 0.2223E-07,
        0.1612E-07, 0.1164E-07, 0.8394E-08
    ])

    graph_xsAxi = TGraph(len(massesTh), massesTh, xsAxi)
    graph_xsAxi.SetLineWidth(3)
    graph_xsAxi.SetLineStyle(3)
    graph_xsAxi.SetLineColor(63)

    graph_xsDiquark = TGraph(len(massesTh), massesTh, xsDiquark)
    graph_xsDiquark.SetLineWidth(3)
    graph_xsDiquark.SetLineStyle(9)
    graph_xsDiquark.SetLineColor(8)

    graph_xsWprime = TGraph(len(massesTh), massesTh, xsWprime)
    graph_xsWprime.SetLineWidth(3)
    graph_xsWprime.SetLineStyle(7)
    graph_xsWprime.SetLineColor(46)

    graph_xsZprime = TGraph(len(massesTh), massesTh, xsZprime)
    graph_xsZprime.SetLineWidth(3)
    graph_xsZprime.SetLineStyle(5)
    graph_xsZprime.SetLineColor(38)

    # limits
    graph_exp_2sigma = (TGraph(len(masses_exp), masses_exp,
                               xs_exp_limits_2sigma)
                        if len(xs_exp_limits_2sigma) > 0 else TGraph(0))
    graph_exp_2sigma.SetFillColor(kYellow)

    graph_exp_1sigma = (TGraph(len(masses_exp), masses_exp,
                               xs_exp_limits_1sigma)
                        if len(xs_exp_limits_2sigma) > 0 else TGraph(0))
    graph_exp_1sigma.SetFillColor(kGreen + 1)

    graph_exp = (TGraph(len(masses), masses, xs_exp_limits)
                 if len(xs_exp_limits_2sigma) > 0 else TGraph(0))
    #graph_exp.SetMarkerStyle(24)
    graph_exp.SetLineWidth(3)
    graph_exp.SetLineStyle(2)
    graph_exp.SetLineColor(4)

    graph_obs = TGraph(len(masses), masses, xs_obs_limits)
    graph_obs.SetMarkerStyle(20)
    graph_obs.SetLineWidth(3)
    #graph_obs.SetLineStyle(1)
    graph_obs.SetLineColor(1)

    c = TCanvas("c", "", 800, 800)
    c.cd()

    legend = TLegend(.60, .55, .90, .70)
    legend.SetBorderSize(0)
    legend.SetFillColor(0)
    legend.SetFillStyle(0)
    legend.SetTextFont(42)
    legend.SetTextSize(0.03)
    legend.SetHeader('95% CL upper limits')

    if len(xs_exp_limits_2sigma) > 0:
        graph_exp_2sigma.GetXaxis().SetTitle("%s resonance mass [GeV]" %
                                             (args.final_state))
        graph_exp_2sigma.GetYaxis().SetTitle(
            "#sigma #times #it{B} #times #it{A} [pb]")
        graph_exp_2sigma.GetYaxis().SetTitleOffset(1.1)
        graph_exp_2sigma.GetYaxis().SetRangeUser(1e-02, 1e+03)
        #graph_exp_2sigma.GetXaxis().SetNdivisions(1005)

        graph_exp_2sigma.Draw("AF")
        graph_exp_1sigma.Draw("F")
        graph_exp.Draw("L")
        graph_obs.Draw("LP")

        legend.AddEntry(graph_obs, "Observed", "lp")
        legend.AddEntry(graph_exp, "Expected", "lp")
        legend.AddEntry(graph_exp_1sigma, "#pm 1#sigma", "F")
        legend.AddEntry(graph_exp_2sigma, "#pm 2#sigma", "F")
    else:
        graph_obs.GetXaxis().SetTitle("%s resonance mass [GeV]" %
                                      (args.final_state))
        graph_obs.GetYaxis().SetTitle(
            "#sigma #times #it{B} #times #it{A} [pb]")
        graph_obs.GetYaxis().SetTitleOffset(1.1)
        graph_obs.GetYaxis().SetRangeUser(1e-02, 1e+03)
        #graph_obs.GetXaxis().SetNdivisions(1005)

        graph_obs.Draw("ALP")

        legend.AddEntry(graph_obs, "Observed", "lp")

    if args.final_state == 'gg':
        graph_xsS8.Draw("L")
    elif args.final_state == 'qg':
        graph_xsQstar.Draw("L")
        graph_xsString.Draw("L")
    elif args.final_state == 'qq':
        graph_xsAxi.Draw("L")
        graph_xsDiquark.Draw("L")
        graph_xsWprime.Draw("L")
        graph_xsZprime.Draw("L")

    legend.Draw()

    if args.final_state == 'gg':
        legendTh = TLegend(.60, .80, .90, .84)
        legendTh.SetBorderSize(0)
        legendTh.SetFillColor(0)
        legendTh.SetFillStyle(0)
        legendTh.SetTextFont(42)
        legendTh.SetTextSize(0.03)
        legendTh.AddEntry(graph_xsS8, "S8", "l")
        legendTh.Draw()
    elif args.final_state == 'qg':
        legendTh = TLegend(.60, .80, .90, .88)
        legendTh.SetBorderSize(0)
        legendTh.SetFillColor(0)
        legendTh.SetFillStyle(0)
        legendTh.SetTextFont(42)
        legendTh.SetTextSize(0.03)
        legendTh.AddEntry(graph_xsString, "String", "l")
        legendTh.AddEntry(graph_xsQstar, "Excited quark", "l")
        legendTh.Draw()
    elif args.final_state == 'qq':
        legendTh = TLegend(.60, .72, .90, .88)
        legendTh.SetBorderSize(0)
        legendTh.SetFillColor(0)
        legendTh.SetFillStyle(0)
        legendTh.SetTextFont(42)
        legendTh.SetTextSize(0.03)
        legendTh.AddEntry(graph_xsAxi, "Axigluon/coloron", "l")
        legendTh.AddEntry(graph_xsDiquark, "Scalar diquark", "l")
        legendTh.AddEntry(graph_xsWprime, "W' SSM", "l")
        legendTh.AddEntry(graph_xsZprime, "Z' SSM", "l")
        legendTh.Draw()

    # draw the lumi text on the canvas
    CMS_lumi.extraText = args.extraText
    CMS_lumi.lumi_sqrtS = args.lumi_sqrtS  # used with iPeriod = 0 (free form)
    iPos = 11
    iPeriod = 0

    CMS_lumi.CMS_lumi(c, iPeriod, iPos)

    gPad.RedrawAxis()

    c.SetLogy()
    fileName = 'xs_limit_%s_%s.%s' % (args.method, args.final_state + (
        ('_' + args.postfix) if args.postfix != '' else ''),
                                      args.fileFormat.lower())
    c.SaveAs(fileName)
    print "Plot saved to '%s'" % (fileName)
Beispiel #26
0
def drawPlots(plots, plotopts, rootopts, output, optzero, optmean, opth, optw):
    from ROOT import TPostScript, TCanvas, TLegend
    from ROOT import gROOT, gStyle, gPad

    gROOT.Reset()
    gROOT.SetStyle("Plain")
    gStyle.SetOptStat(0)
    gStyle.SetPalette(1)

    leg = TLegend(0.54, 0.71, 0.9, 0.9)

    leg.SetLineColor(1)
    leg.SetLineStyle(1)
    leg.SetLineWidth(1)
    leg.SetFillColor(10)
    leg.SetFillStyle(0)
    leg.SetBorderSize(0)

    if output != "DISPLAY":
        ps = TPostScript(output, 111)
        ps.NewPage()
    canv = TCanvas('c1', "Validation Plot Viewer", 600, 800)
    canv.Divide(opth, optw)
    maxperlist = opth * optw

    #current pad
    num = 0
    #for stupid drawing system
    legends = []

    #drawing hists
    for plotopt in plotopts:
        print "Drawing", plotopt.display_name
        num += 1
        if (num > maxperlist
                and output != "DISPLAY"):  #end of a current PS page
            ps.NewPage()
            print "new page"
            num = 1
        canv.cd(num)
        gPad.SetLogy(plotopt.logy)
        leg.Clear()

        entries = {}
        valuemax = -999999.9
        valuemin = 999999.9
        entryZ = 0

        for rootopt in rootopts:  #get the max entries
            entries[rootopt] = plots[plotopt][rootopt].GetEntries()
            if (plots[plotopt][rootopt].GetEntries() > entryZ):
                entryZ = plots[plotopt][rootopt].GetEntries()

        for rootopt in rootopts:  #get the max entries
            plot = plots[plotopt][rootopt]
            if (plotopt.profile):
                print rootopt.legendname, "is a profile: no need to scale"
            else:
                if not (entries[rootopt] == 0):
                    print "scaling", rootopt.legendname, "to", entryZ / entries[
                        rootopt]
                    plot.Scale(entryZ / entries[rootopt])
                else:
                    print rootopt.legendname, "is an empty hist, no scale"

        for rootopt in rootopts:  #get the highest peak
            if (plots[plotopt][rootopt].GetMaximum() > valuemax):
                valuemax = plots[plotopt][rootopt].GetMaximum()
                entryZ = plots[plotopt][rootopt].GetEntries()

        sameDrawOpt = ""
        #now we plot all fillers, as otherwise they will render invisible everything behind them
        for rootopt in rootopts:
            if (rootopt.markerstyle > 0):  #not filler
                continue
            plot = plots[plotopt][rootopt]
            print "Drawing filler from", rootopt.legendname
            if optzero:
                if (plotopt.logy == 1):
                    plot.SetMinimum(1.0)
                else:
                    plot.SetMinimum(0.0)
            plot.SetMaximum(valuemax * 1.1)
            plot.GetXaxis().SetTitle(
                plotopt.axis_captions[plotopt.vars_to_draw[0].lstrip("+")])
            if len(plotopt.vars_to_draw) > 1:
                plot.GetYaxis().SetTitle(
                    plotopt.axis_captions[plotopt.vars_to_draw[1].lstrip("+")])
            if (plotopt.i2d):
                plot.Draw("CONT4Z " + sameDrawOpt)
            else:
                plot.Draw(rootopt.drawopt + sameDrawOpt)
            sameDrawOpt = " SAME"
        #plot the rest & fill the legend in the normal order
        for rootopt in rootopts:
            plot = plots[plotopt][rootopt]
            prname = rootopt.legendname
            if optmean and (not plotopt.profile):
                prname += " (mean: " + ("%.4f" % plot.GetMean()) + ")"
            leg.AddEntry(plot, prname, "L")
            if (rootopt.markerstyle == 0):  #filler
                continue  #fillers are already drawn
            print "Drawing plot from", rootopt.legendname
            if optzero:
                if (plotopt.logy == 1):
                    plot.SetMinimum(1.0)
                else:
                    plot.SetMinimum(0.0)
            plot.SetMaximum(valuemax * 1.1)
            plot.GetXaxis().SetTitle(
                plotopt.axis_captions[plotopt.vars_to_draw[0].lstrip("+")])
            if len(plotopt.vars_to_draw) > 1:
                plot.GetYaxis().SetTitle(
                    plotopt.axis_captions[plotopt.vars_to_draw[1].lstrip("+")])
            if (plotopt.i2d):
                plot.Draw("CONT4Z " + sameDrawOpt)
            else:
                plot.Draw(rootopt.drawopt + sameDrawOpt)
            sameDrawOpt = " SAME"
        if not plotopt.i2d:
            legends.append(leg.Clone())
            legends[len(legends) - 1].Draw()
        canv.Update()
    if output != "DISPLAY":
        canv.Close()
        ps.Close()
    return canv, legends
hist_700_1000 = fin.Get("charginoValidator/" + histName)
hist_700_1000.SetDirectory(0)
hist_700_1000.SetName("hist_700_1000")
fin.Close()

setStyle(hist_100_100, kRed)
setStyle(hist_300_100, kOrange)
setStyle(hist_500_100, kGreen)
setStyle(hist_700_100, kBlue)

setStyle(hist_700_10, kBlue + 2)
setStyle(hist_700_1000, kBlue - 7)

leg1 = TLegend(0.402256, 0.702842, 0.632832, 0.894057)
leg1.SetTextSize(0.0387597)
leg1.SetBorderSize(0)
leg1.AddEntry(hist_100_100, "100 GeV #tilde{#chi}^{#pm} (c#tau = 100 cm)", "p")
leg1.AddEntry(hist_300_100, "300 GeV #tilde{#chi}^{#pm} (c#tau = 100 cm)", "p")
leg1.AddEntry(hist_500_100, "500 GeV #tilde{#chi}^{#pm} (c#tau = 100 cm)", "p")
leg1.AddEntry(hist_700_100, "700 GeV #tilde{#chi}^{#pm} (c#tau = 100 cm)", "p")

c1 = TCanvas("c1", "c1", 800, 800)
c1.SetLeftMargin(0.121554)
c1.SetRightMargin(0.0401003)
c1.SetBottomMargin(0.0956072)
c1.SetTopMargin(0.0607235)
c1.cd()
hist_100_100.Draw()
hist_300_100.Draw("same")
hist_500_100.Draw("same")
hist_700_100.Draw("same")
Beispiel #28
0
    gCrossSectionSystLumi.SetPoint(0, 1., 1.)
    gCrossSectionSystLumi.SetPointError(0, 0.4, lumiUnc)
    SetObjectStyle(gCrossSectionSystLumi,
                   color=GetROOTColor('kBlue'),
                   fillstyle=0)

gROOT.SetBatch(args.batch)
SetGlobalStyle(padleftmargin=0.18, padbottommargin=0.14)

cCrossSec = TCanvas(f'c{histoName}', '', 700, 800)
cCrossSec.SetLogy()
hCrossSection.Draw()
gCrossSectionSyst['Tot'].Draw('2')

legFrac = TLegend(0.2, 0.84, 0.4, 0.94)
legFrac.SetBorderSize(0)
legFrac.SetFillStyle(0)
legFrac.SetTextSize(0.045)
legFrac.AddEntry(hPromptFrac, 'Prompt', 'p')
legFrac.AddEntry(hFDFrac, 'Non-prompt', 'p')

legEff = legFrac.Clone('legEff')
legEff.SetY1(0.2)
legEff.SetY2(0.4)
cCrossSec.Update()

cFrac = TCanvas('cFrac', '', 800, 800)
cFrac.DrawFrame(hPromptFrac.GetBinLowEdge(1), 0., ptMax, 1.2,
                ';#it{p}_{T} (GeV/#it{c}); fraction')
hPromptFrac.Draw('same')
hFDFrac.Draw('same')
def main():
    filename = read_file_name(
        "OUTPUT_TWITTER_TXT_generator/NY_OUTPUT_week1n2n3n4.txt")  ##FIXME
    can = TCanvas("can", "can")
    can.SetGrid()
    mg = TMultiGraph()
    nn = 7

    GR = []
    NAME = []
    px, py = array('d'), array('d')
    f = open(filename[2], 'r')
    indicator = 0

    for line in f:
        if (indicator == 0):
            indicator = indicator + 1
            continue

        Name, Total, Pos, Neg, TNum = line.split()
        name = Find_Loca(Name)
        name = Name.replace(Name[name:], "")
        #        print(name)

        px.append((indicator - 1) % 7)
        py.append(float(Pos) / float(Total))
        if ((indicator) % 7 == 0):
            NAME.append(name)
            gr = TGraph(nn, px, py)
            GR.append(gr)
            px, py = array('d'), array('d')
        indicator = indicator + 1


#    print(GR); print(len(GR))
    for i in range(len(GR)):
        GR[i].SetLineWidth(2)
        if "water" in NAME[i]:
            GR[i].SetLineWidth(5)
            GR[i].SetLineColor(1)
            GR[i].SetMarkerColor(1)
        if "wine" in NAME[i]:
            GR[i].SetMarkerColor(2)
            GR[i].SetLineColor(2)
        if "beer" in NAME[i]:
            GR[i].SetMarkerColor(5)
            GR[i].SetLineColor(5)
        if "tea" in NAME[i]:
            GR[i].SetMarkerColor(4)
            GR[i].SetLineColor(4)
        if "coffee" in NAME[i]:
            GR[i].SetMarkerColor(3)
            GR[i].SetLineColor(3)
        if "juice" in NAME[i]:
            GR[i].SetMarkerColor(7)
            GR[i].SetLineColor(7)
        if "COLA" in NAME[i]:
            GR[i].SetMarkerColor(6)
            GR[i].SetLineColor(6)
        GR[i].GetXaxis().SetTitle("days")
        GR[i].SetMarkerStyle(20)
        #        GR[i].Fit("pol4","q")
        mg.Add(GR[i])

    mg.Draw("ALP")

    leg = TLegend(0.75, 0.28, 0.95, 0.51)
    leg.SetBorderSize(0)
    leg.SetFillColor(10)
    for i in range(len(GR)):
        leg_entry = leg.AddEntry(GR[i], NAME[i], "l")
    leg.Draw()
    mg.SetTitle("Positive words propotion at NY(week 1&2&3&4)")  ##FIXME
    mg.GetHistogram().GetXaxis().SetTitle("days")
    mg.GetHistogram().GetXaxis().SetTitleOffset(1)
    mg.GetHistogram().GetXaxis().SetLabelSize(0.03)
    mg.GetHistogram().GetYaxis().SetTitle("Counts")
    mg.GetHistogram().GetYaxis().SetTitleOffset(1.3)
    mg.GetHistogram().GetYaxis().SetLabelSize(0.03)
    mg.GetHistogram().GetXaxis().SetBinLabel(5, "Mon")
    mg.GetHistogram().GetXaxis().SetBinLabel(20, "Tue")
    mg.GetHistogram().GetXaxis().SetBinLabel(35, "Wed")
    mg.GetHistogram().GetXaxis().SetBinLabel(51, "Thu")
    mg.GetHistogram().GetXaxis().SetBinLabel(66, "Fri")
    mg.GetHistogram().GetXaxis().SetBinLabel(81, "Sat")
    mg.GetHistogram().GetXaxis().SetBinLabel(96, "Sun")
    #    mg.GetHistogram().GetXaxis().SetBinLabel(84,"Mon")
    #    mg.GetHistogram().GetXaxis().SetBinLabel(96,"Tue")
    #    for i in range(len(GR)):
    #        mg.GetHistogram().GetXaxis().SetBinLabel(i,DAYS)
    #    mg.GetHistogram().GetXaxis().SetLabel("tt")

    can.Modified()
    can.Update()
    # can.GetFrame().SetBorderSize( 12 )
    can.Print("POS_NY_week1n2n3n4.pdf")  ##FIXME
Beispiel #30
0
def plotSysts():
    for feature, values in features.items():
        # set up legend
        legend = TLegend(0.5, 0.65, 0.9, 0.88)
        legend.SetHeader("2lss {} process".format(dataset))
        #legend.SetNColumns(3)
        legend.SetBorderSize(0)

        #c, pad1, pad2 = createCanvasPads()

        # loop over samples
        hist_vars = []
        hist_ratio_vars = []
        i = 0
        for ktkv in ktkvName:
            filename = "{}/output_inclusive_{}_{}.root".format(
                inputDirectories, dataset, ktkv)
            inputfile = TFile(filename, "read")
            if inputfile.IsZombie():
                print("inputfile is Zombie")
                sys.exit()
            # loop over features
            if i == 0:
                # get nominal histograms
                hist_nom_name = feature + "_" + dataset
                if not inputfile.GetListOfKeys().Contains(hist_nom_name):
                    print("%s doesn't have histogram %s" %
                          (filename, hist_nom_name))
                    continue
                hist_nom = inputfile.Get(hist_nom_name)
                hist_nom.SetDirectory(0)
                hist_nom.SetFillColor(0)
                hist_nom.SetLineColor(Color[ktkv])
                hist_nom.SetMarkerColor(Color[ktkv])
                hist_nom.SetMarkerStyle(Style[ktkv])
                hist_nom.SetMarkerSize(2)
                hist_nom.SetLineWidth(2)
                h_ratio = createRatio(hist_nom, hist_nom, values["xlabel"],
                                      normalization)
                h_ratio.SetDirectory(0)
                h_ratio.SetMarkerColor(Color[ktkv])
                legend.AddEntry(hist_nom, legName[ktkv], "lp")
            else:
                hist_name = feature + "_" + dataset
                if not inputfile.GetListOfKeys().Contains(hist_name):
                    print("%s doesn't have histogram %s" %
                          (filename, hist_name))
                    continue
                hist_var = inputfile.Get(hist_name)
                hist_var.SetDirectory(0)
                hist_var.SetFillColor(0)
                hist_var.SetLineColor(Color[ktkv])
                hist_var.SetMarkerColor(Color[ktkv])
                hist_var.SetMarkerStyle(Style[ktkv])
                hist_var.SetMarkerSize(2)
                hist_var.SetLineWidth(2)
                hist_vars.append(hist_var)
                h_ratio_var = createRatio(hist_var, hist_nom, values["xlabel"],
                                          normalization)
                h_ratio_var.SetMarkerColor(Color[ktkv])
                h_ratio_var.SetDirectory(0)
                hist_ratio_vars.append(h_ratio_var)
                legend.AddEntry(hist_var, legName[ktkv], "lp")

            i = i + 1
            inputfile.Close()

        # draw everything

        c = TCanvas("c", "canvas", 800, 800)
        c.cd()
        #c.SetGridx()
        #c.SetGridy()
        c.SetLeftMargin(1.65)
        c.SetBottomMargin(1.65)

        #pad1.cd()
        #pad1.SetGridx()
        #pad1.SetGridy()

        # set bounds
        Y_name = "Events"
        maximum = 0

        for hist in hist_vars:
            if normalization:
                hist.Scale(1. / hist.Integral())
            if hist.GetMaximum() > maximum: maximum = hist.GetMaximum()
        upperbound = 1.8 * maximum
        lowerbound = -maximum / 40.

        Y_name = "Events"
        if normalization:
            hist_nom.Scale(1. / hist_nom.Integral())
            Y_name = " Unit "
        if not showStats:
            hist_nom.SetStats(0)

        hist_nom.SetMaximum(upperbound)
        hist_nom.SetMinimum(lowerbound)
        hist_nom.SetTitle("{}".format(year))
        # Adjust y-axis settings
        y = hist_nom.GetYaxis()
        y.SetTitleSize(40)
        y.SetTitleFont(43)
        y.SetTitleOffset(0.8)
        y.SetLabelFont(43)
        y.SetLabelSize(20)
        y.SetTitle(Y_name)

        # Adjust x-axis settings
        x = hist_nom.GetXaxis()
        x.SetTitleSize(40)
        x.SetTitleFont(43)
        x.SetTitleOffset(0.8)
        x.SetLabelFont(43)
        x.SetLabelSize(20)
        x.SetTitle(values["xlabel"])

        hist_nom.Draw("EP")

        for hist in hist_vars:
            hist.Draw("EPsame")

        legend.Draw("same")

        #pad2.cd()
        #pad2.SetGridx()
        #pad2.SetGridy()
        #bins = h_ratio.GetNbinsX()
        #LowEdge = h_ratio.GetBinLowEdge(1)
        #HighEdge = h_ratio.GetBinLowEdge(bins+1)
        #line = TLine(LowEdge,1,HighEdge,1)
        #line.SetLineColor(kBlack)
        #h_ratio.SetFillColor(kGray+3)
        #h_ratio.SetFillStyle(3001)
        #h_ratio.Draw("E2")
        #h_ratio.SetMinimum(0.5)
        #h_ratio.SetMaximum(1.5)
        #for i in range(len(hist_ratio_vars)):
        #    hist_ratio_vars[i].Draw("EPsame")

        #line.Draw("same")

        c.SaveAs("%s%s_%s_isNorm%s_%s.png" %
                 (outputdir, feature, plotname, normalization, year))