Ejemplo n.º 1
0
                 FillColor=plot.CreateTransparentColor(ROOT.kAzure + 6, 0.5))
        if args.hist is not None:
            plot.Set(gr, LineWidth=2)
        gr.Draw(fillstyle)
        gr.Draw('LSAME')

# We just want the top pad to look like a box, so set all the text and tick
# sizes to zero
pads[0].cd()
h_top = h_axis.Clone()
plot.Set(h_top.GetXaxis(), LabelSize=0, TitleSize=0, TickLength=0)
plot.Set(h_top.GetYaxis(), LabelSize=0, TitleSize=0, TickLength=0)
h_top.Draw()

# Draw the legend in the top TPad
legend = plot.PositionedLegend(0.4, 0.11, 3, 0.015)
plot.Set(legend,
         NColumns=2,
         Header='#bf{%.0f%% CL Excluded:}' % (args.CL * 100.))
if 'obs' in contours:
    legend.AddEntry(contours['obs'][0], "Observed", "F")
if 'exp-1' in contours and 'exp+1' in contours:
    legend.AddEntry(contours['exp-1'][0], "#pm 1#sigma Expected", "F")
if 'exp0' in contours:
    if 'obs' in contours:
        legend.AddEntry(contours['exp0'][0], "Expected", "L")
    else:
        legend.AddEntry(contours['exp0'][0], "Expected", "F")
if 'exp-2' in contours and 'exp+2' in contours:
    legend.AddEntry(contours['exp-2'][0], "#pm 2#sigma Expected", "F")
legend.Draw()
Ejemplo n.º 2
0
for padx in pads:
    # Use tick marks on oppsite axis edges
    plot.Set(padx, Tickx=1, Ticky=1, Logx=args.logx)
    if args.pad_style is not None:
        settings = {
            x.split('=')[0]: eval(x.split('=')[1])
            for x in args.pad_style.split(',')
        }
        print 'Applying style options to the TPad(s):'
        print settings
        plot.Set(padx, **settings)

graphs = []
graph_sets = []

legend = plot.PositionedLegend(0.45, 0.10, 3, 0.015)
plot.Set(legend, NColumns=2)

axis = None

defcols = [
    ROOT.kGreen + 3, ROOT.kRed, ROOT.kBlue, ROOT.kBlack, ROOT.kYellow + 2,
    ROOT.kOrange + 10, ROOT.kCyan + 3, ROOT.kMagenta + 2, ROOT.kViolet - 5,
    ROOT.kGray
]

deflines = [1, 2, 3]

if args.auto_style is not None:
    icol = {x: 0 for x in args.auto_style.split(',')}
    icol['default'] = 0
Ejemplo n.º 3
0
    gr2 = ROOT.TGraph(len(arr_x), arr_x, array('d', y2))
    canv = ROOT.TCanvas('wg_M_cutoff_quantiles_%s' % year,
                        'wg_M_cutoff_quantiles_%s' % year)
    pads = plot.OnePad()
    plot.Set(gr0, LineWidth=2, LineColor=1, MarkerColor=1)
    plot.Set(gr1, LineWidth=2, LineColor=2, MarkerColor=2)
    plot.Set(gr2, LineWidth=2, LineColor=4, MarkerColor=4)
    gr0.Print()
    gr0.Draw('ALP')
    gr1.Draw('LPSAME')
    gr2.Draw('LPSAME')
    axis = plot.GetAxisHist(pads[0])
    axis.SetMaximum(4000)
    axis.GetXaxis().SetTitle('p_{T}^{#gamma} cut-off [GeV]')
    axis.GetYaxis().SetTitle('M_{W#gamma} [GeV]')
    legend = plot.PositionedLegend(0.30, 0.20, 3, 0.015)
    legend.AddEntry(gr0, '68% quantile')
    legend.AddEntry(gr1, '95% quantile')
    legend.AddEntry(gr2, '99.7% quantile')
    legend.Draw()
    canv.Print('.png')
    canv.Print('.pdf')

# Draw efficiencies for the stitched sample
for year, var in itertools.product(years, ['l0_pt', 'p0_pt']):
    hist_dict = {}
    for opath, objname, obj in hists[year][var]['WG-NLO'].ListObjects(depth=0):
        hist_dict[objname] = obj

    # Draw N/N-1 efficiencies
    MakeMultiHistPlot('efficiencies_m_%s_%s' % (year, var),
Ejemplo n.º 4
0
axish[0].GetXaxis().SetTitleSize(0)
axish[0].GetXaxis().SetLabelSize(0)
axish[1].GetYaxis().SetRangeUser(0.8, 1.2)
axish[1].GetXaxis().SetTitle("m_{ee} [GeV]")
axish[0].GetYaxis().SetTitle("Events")
axish[1].GetYaxis().SetTitle("Obs/Exp")
ratio_mchist = plot.MakeRatioHist(LOMC_Z_mass_unc, LOMC_Z_mass_unc, True,
                                  False)
ratio_datahist = plot.MakeRatioHist(data_Z_mass, LOMC_Z_mass, True, False)

pads[0].cd()
axish[0].Draw()
LOMC_Z_mass.Draw("HISTSAME")
LOMC_Z_mass_unc.Draw("e2same")
data_Z_mass.Draw("PSAME")
legend = plot.PositionedLegend(0.2, 0.1, 3, 0.015)
legend.AddEntry(LOMC_Z_mass, "Z#rightarrow ee", "F")
legend.AddEntry(data_Z_mass, "Data", "P")
legend.Draw("SAME")
axish[0].Draw("axissame")
pads[1].cd()
axish[1].Draw("axis")
ratio_mchist.SetMarkerSize(0)
ratio_mchist.Draw("e2same")
ratio_datahist.Draw("e0same")
pads[1].RedrawAxis("G")
plot.DrawTitle(pads[0], "41.5 fb^{-1} (13 TeV-2017)", 3)

canvas.SaveAs("mee_inclusive_nlo_weight_2017.pdf")
#canvas.SaveAs("mmumu_inclusive_weight.pdf")
Ejemplo n.º 5
0
old2 = ROOT.TFile('hig-16-043_2sigma.root', 'r')
cont_2sigma2 = old2.Get('Graph')

print cont_1sigma2
print cont_2sigma2

if debug is not None:
    debug.WriteTObject(hists, 'hist')
    for i, cont in enumerate(cont_1sigma):
        debug.WriteTObject(cont, 'cont_1sigma_%i' % i)
    for i, cont in enumerate(cont_2sigma):
        debug.WriteTObject(cont, 'cont_2sigma_%i' % i)

if args.sm_exp or args.bg_exp:
    #legend = plot.PositionedLegend(0.47, 0.20, 3, 0.015)
    legend = plot.PositionedLegend(0.47, 0.26, 4, 0.03)
else:
    legend = plot.PositionedLegend(0.3, 0.2, 3, 0.015)

pads[0].cd()
axis.Draw()
for i, p in enumerate(cont_2sigma):
    p.SetLineStyle(1)
    p.SetLineWidth(2)
    p.SetLineColor(ROOT.kBlack)
    p.SetFillColor(ROOT.kBlue - 10)
    p.SetFillStyle(1001)
    p.Draw("F SAME")
    p.Draw("L SAME")
    if i == 0: continue
    legend.AddEntry(cont_1sigma[0], "68% CL", "F")
Ejemplo n.º 6
0
def main(args):

    fitvars = 'm_sv_vs_pt_tt'
    fitvars = 'm_sv'

    if len(args.file_dir.split("_")) >= 4: era = args.file_dir.split("_")[3]
    else: era = 'all'
    if era == "2016":
        lumi = "36.3 fb^{-1} (13 TeV)"
    elif era == "2017":
        lumi = "41.5 fb^{-1} (13 TeV)"
    elif era == "2018":
        lumi = "59.7 fb^{-1} (13 TeV)"
    elif era == "all":
        lumi = "138 fb^{-1} (13 TeV)"

    plot.ModTDRStyle(width=1800, height=700, r=0.4, l=0.16, t=0.12, b=0.15)
    ROOT.TGaxis.SetExponentOffset(-0.06, 0.01, "y")
    # Channel & Category label

    if args.channel == '':
        args.channel = args.file_dir.split("_")[1]
    if args.channel == "tt":
        channel_label = "#tau_{h}#tau_{h}"
    if args.channel == "lt":
        channel_label = "#mu_{}#tau_{h}+e_{}#tau_{h}"
    if args.channel == "mt":
        channel_label = "#mu_{}#tau_{h}"
    if args.channel == "et":
        channel_label = "e_{}#tau_{h}"
    if args.channel == "em":
        channel_label = "e_{}#mu_{}"

    bin_number = args.file_dir.split("_")[2]
    #if args.ratio_range=="":
    #  args.ratio_range = "0.7,1.3"
    if bin_number in ["2", "35", "36", "37"]:
        if args.channel == 'tt': bin_label = "b tag"
        if args.channel in ['mt', 'et', 'lt']:
            bin_label = "b tag"
            if bin_number == "35": bin_label = "b tag, Tight-m_{T}"
            if bin_number == "36": bin_label = "b tag, Loose-m_{T}"
        if args.channel in ['em']:
            bin_label = "b tag"
            if bin_number == "2": bin_label = "t#bar{t} CR"
            if bin_number == "35": bin_label = "b tag, High D_{#zeta}"
            if bin_number == "36": bin_label = "b tag, Medium D_{#zeta}"
            if bin_number == "37": bin_label = "b tag, Low D_{#zeta}"
        plot.ModTDRStyle(r=0.04, l=0.18)
        if args.ratio_range == "":
            args.ratio_range = "0.85,1.15"
        bin_label = "b tag"  # no sub labels when combing all sub-categories
    if bin_number in ["32", "33", "34"]:
        if args.ratio_range == "":
            args.ratio_range = "0.4,1.6"
        if args.channel == 'tt': bin_label = "No b tag"
        if args.channel in ['mt', 'et', 'lt']:
            bin_label = "No b tag"
            if bin_number == "32": bin_label = "No b tag, Tight-m_{T}"
            if bin_number == "33": bin_label = "No b tag, Loose-m_{T}"
        if args.channel in ['em']:
            bin_label = "No b tag"
            if bin_number == "32": bin_label = "No b tag, High D_{#zeta}"
            if bin_number == "33": bin_label = "No b tag, Medium D_{#zeta}"
            if bin_number == "34": bin_label = "No b tag, Low D_{#zeta}"
        bin_label = "b tag"  # no sub labels when combing all sub-categories

    if bin_number in [
            "132", "232", "332", "432", "133", "233", "333", "433", "33", "34"
    ]:
        if args.ratio_range == "":
            args.ratio_range = "0.7,1.3"
        if args.channel == 'tt': bin_label = "No b tag"
        if args.channel in ['mt', 'et', 'lt']:
            bin_label = "No b tag"
            if bin_number[1:] == "32": bin_label = "No b tag, Tight-m_{T}"
            if bin_number[1:] == "33": bin_label = "No b tag, Loose-m_{T}"
        if args.channel in ['em']:
            bin_label = "No b tag"
            if bin_number[1:] == "32": bin_label = "No b tag, High D_{#zeta}"
            if bin_number[1:] == "33": bin_label = "No b tag, Medium D_{#zeta}"
            if bin_number[1:] == "34": bin_label = "No b tag, Low D_{#zeta}"

        bin_label = "No b tag"  # no sub labels when combing all sub-categories
        if bin_number[0] == '1': bin_label += ', p_{T}^{#tau#tau}<50 GeV'
        if bin_number[0] == '2': bin_label += ', 50< p_{T}^{#tau#tau}<100 GeV'
        if bin_number[0] == '3': bin_label += ', 100< p_{T}^{#tau#tau}<200 GeV'
        if bin_number[0] == '4': bin_label += ', p_{T}^{#tau#tau}> 200 GeV'
        plot.ModTDRStyle(r=0.04, l=0.18)

    ## Add bin labels
    bin_labels = {}
    with open("scripts/bin_labels.json") as jsonfile:
        full_bin_labels = json.load(jsonfile)
        if bin_number in ["32", "33", "34"]:
            bin_labels = full_bin_labels[fitvars]['nobtag']
        else:
            bin_labels = full_bin_labels[fitvars]['btag']

    is2D = False

    print fitvars, bin_number
    if fitvars == 'm_sv' or bin_number in [
            "2", "35", "36", "37", "132", "232", "332", "432", "133", "233",
            "333", "433"
    ]:
        x_title = "m_{#tau#tau} (GeV)"
        #x_bins = re.split("\[|\]",bin_labels)[1].split(",")
        #Nxbins = len(x_bins) - 1
    else:
        is2D = True
        x_title = "Bin number"
        x_bins = re.split("\[|\]", bin_labels)[3].split(",")
        Nxbins = len(x_bins) - 1

    if is2D:
        y_bin_var = re.split(",|\[|\]", bin_labels)[0]
        y_bin_labels = re.split("\[|\]", bin_labels)[1].split(",")
    else:
        y_bin_var = ""
        y_bin_labels = ""

    is2D = False  # we now split 2D histograms into 1D

    file_dir = args.file_dir
    mode = args.mode
    manual_blind = args.manual_blind
    x_blind_min = args.x_blind_min
    x_blind_max = args.x_blind_max
    cms_label = args.cms_label
    empty_bin_error = args.empty_bin_error
    extra_pad = float(args.extra_pad)
    custom_x_range = args.custom_x_range
    custom_y_range = args.custom_y_range
    x_axis_min = float(args.x_axis_min)
    x_axis_max = float(args.x_axis_max)
    y_axis_min = float(args.y_axis_min)
    y_axis_max = float(args.y_axis_max)
    log_y = args.log_y
    log_x = args.log_x
    if (args.outname != ''):
        outname = args.outname + '_'
    else:
        outname = ''

    if args.file_dir == "htt_tt_232": extra_pad = 0.45
    if args.file_dir == "htt_tt_35": extra_pad = 0.57
    if args.file_dir == "htt_tt_132": extra_pad = 0.65
    if args.file_dir == "htt_tt_232": extra_pad = 0.62
    if args.file_dir == "htt_em_35": extra_pad = 0.7
    if args.file_dir == "htt_lt_35": extra_pad = 0.45
    if args.file_dir == "htt_lt_232": extra_pad = 0.45
    if args.file_dir == "htt_em_232": extra_pad = 0.45
    if '_35' in args.file_dir or '_132' in args.file_dir or '_232' in args.file_dir or args.bOnly:
        cms_label = 'Supplementary'

    if args.file:
        print "Providing shape file: ", args.file, ", with specified subdir name: ", file_dir
        shape_file = args.file
        shape_file_name = args.file

    histo_file = ROOT.TFile(shape_file)

    #Store plotting information for different backgrounds
    background_schemes = {
        'mt': [
            backgroundComp("Others",
                           ["ZL", "VVL", "qqH125", "bbH125", "ggH125"],
                           ROOT.TColor.GetColor("#B0C4DE")),
            #backgroundComp("H(125 GeV)#rightarrow#tau#tau",["qqH125","bbH125","ggH125"],ROOT.TColor.GetColor(51,51,230)),
            #backgroundComp("Diboson",["VVL"],ROOT.TColor.GetColor("#6F2D35")),
            backgroundComp("t#bar{t}", ["TTL"],
                           ROOT.TColor.GetColor("#9999cc")),
            #backgroundComp("Z#rightarrowll",["ZL"],ROOT.TColor.GetColor("#4496c8")),
            backgroundComp("Jet#rightarrow#tau_{h}", ["jetFakes"],
                           ROOT.TColor.GetColor(192, 232, 100)),
            backgroundComp("#tau#tau Bkg.", ["EMB"],
                           ROOT.TColor.GetColor("#ffcc66")),
        ],
        'et': [
            backgroundComp("Others",
                           ["ZL", "VVL", "qqH125", "bbH125", "ggH125"],
                           ROOT.TColor.GetColor("#B0C4DE")),
            #backgroundComp("H(125 GeV)#rightarrow#tau#tau",["qqH125","bbH125","ggH125"],ROOT.TColor.GetColor(51,51,230)),
            #backgroundComp("Diboson",["VVL"],ROOT.TColor.GetColor("#6F2D35")),
            backgroundComp("t#bar{t}", ["TTL"],
                           ROOT.TColor.GetColor("#9999cc")),
            #backgroundComp("Z#rightarrowll",["ZL"],ROOT.TColor.GetColor("#4496c8")),
            backgroundComp("Jet#rightarrow#tau_{h}", ["jetFakes"],
                           ROOT.TColor.GetColor(192, 232, 100)),
            backgroundComp("#tau#tau Bkg.", ["EMB"],
                           ROOT.TColor.GetColor("#ffcc66")),
        ],
        'lt': [
            backgroundComp("Others",
                           ["ZL", "VVL", "qqH125", "bbH125", "ggH125"],
                           ROOT.TColor.GetColor("#B0C4DE")),
            #backgroundComp("H(125 GeV)#rightarrow#tau#tau",["qqH125","bbH125","ggH125"],ROOT.TColor.GetColor(51,51,230)),
            #backgroundComp("Diboson",["VVL"],ROOT.TColor.GetColor("#6F2D35")),
            backgroundComp("t#bar{t}", ["TTL"],
                           ROOT.TColor.GetColor("#9999cc")),
            #backgroundComp("Z#rightarrowll",["ZL"],ROOT.TColor.GetColor("#4496c8")),
            backgroundComp("Jet#rightarrow#tau_{h}", ["jetFakes"],
                           ROOT.TColor.GetColor(192, 232, 100)),
            backgroundComp("#tau#tau Bkg.", ["EMB"],
                           ROOT.TColor.GetColor("#ffcc66")),
        ],
        'tt': [
            backgroundComp("Others",
                           ["ZL", "VVL", "qqH125", "bbH125", "ggH125"],
                           ROOT.TColor.GetColor("#B0C4DE")),
            #backgroundComp("H(125 GeV)#rightarrow#tau#tau",["qqH125","bbH125","ggH125"],ROOT.TColor.GetColor(51,51,230)),
            #backgroundComp("Diboson",["VVL"],ROOT.TColor.GetColor("#6F2D35")),
            backgroundComp("t#bar{t}", ["TTL"],
                           ROOT.TColor.GetColor("#9999cc")),
            #backgroundComp("Z#rightarrowll",["ZL"],ROOT.TColor.GetColor("#4496c8")),
            backgroundComp("Jet#rightarrow#tau_{h}", ["jetFakes", "wFakes"],
                           ROOT.TColor.GetColor(192, 232, 100)),
            backgroundComp("#tau#tau Bkg.", ["EMB"],
                           ROOT.TColor.GetColor("#ffcc66")),
        ],
        'em': [
            backgroundComp("Others", [
                "ZL", "qqH125", "bbH125", "ggH125", 'WHWW125', 'ZHWW125',
                'ggHWW125', 'qqHWW125', "W", "VVL"
            ], ROOT.TColor.GetColor("#B0C4DE")),
            #backgroundComp("H(125 GeV)",["qqH125","bbH125","ggH125",'WHWW125','ZHWW125','ggHWW125','qqHWW125'],ROOT.TColor.GetColor(51,51,230)),
            backgroundComp("QCD", ["QCD"], ROOT.TColor.GetColor("#ffccff")),
            #backgroundComp("Electroweak",["W","VVL"],ROOT.TColor.GetColor(222, 90, 106)),
            backgroundComp("t#bar{t}", ["TTL"],
                           ROOT.TColor.GetColor("#9999cc")),
            #backgroundComp("Z#rightarrowll",["ZL"],ROOT.TColor.GetColor("#4496c8")),
            backgroundComp("#tau#tau Bkg.", ["EMB"],
                           ROOT.TColor.GetColor("#ffcc66")),
        ],
    }

    #Extract relevent histograms from shape file
    sighists = []

    #signal_names = 'TotalSig'
    signal_names = ['ggh_t', 'ggh_i', 'ggh_b']
    if args.no_signal: signal_names = []

    file_dir_list = []
    file_dir_list = [file_dir]

    if not args.no_signal:
        [sighist,
         binname] = getHistogram(histo_file, signal_names, file_dir_list, mode,
                                 args.no_signal, log_x)
        sighists.append(sighist)
    bkghist = getHistogram(histo_file, 'TotalBkg', file_dir, mode,
                           logx=log_x)[0]
    sbhist = bkghist.Clone()
    # can use this one for showing ggX as well as qqX
    sbhist_alt = bkghist.Clone()

    if not args.use_asimov:
        total_datahist = getHistogram(histo_file,
                                      "data_obs",
                                      file_dir,
                                      mode,
                                      logx=log_x)[0]
    else:
        total_datahist = getHistogram(histo_file,
                                      "TotalProcs",
                                      file_dir,
                                      mode,
                                      logx=log_x)[0].Clone()
        for bin_ in range(1, total_datahist.GetNbinsX() + 1):
            content = total_datahist.GetBinContent(bin_)
            total_datahist.SetBinError(bin_, np.sqrt(content))

    blind_datahist = total_datahist.Clone()
    total_datahist.SetMarkerStyle(20)
    blind_datahist.SetMarkerStyle(20)
    blind_datahist.SetLineColor(1)

    total_bkg = getHistogram(histo_file,
                             "TotalBkg",
                             file_dir,
                             mode,
                             logx=log_x)[0].Clone()
    azimov_datahist = blind_datahist.Clone()
    for i in range(0, azimov_datahist.GetNbinsX() + 1):
        azimov_datahist.SetBinContent(i, -0.1)
        azimov_datahist.SetBinError(i, 0)

    azimov_datahist.SetLineColor(ROOT.kRed)
    azimov_datahist.SetMarkerColor(ROOT.kRed)

    #Blinding by hand using requested range, set to 70-110 by default
    # for 0jet category
    if not is2D and manual_blind:
        for i in range(0, total_datahist.GetNbinsX()):
            low_edge = total_datahist.GetBinLowEdge(i + 1)
            high_edge = low_edge + total_datahist.GetBinWidth(i + 1)
            if ((low_edge > float(x_blind_min)
                 and low_edge < float(x_blind_max))
                    or (high_edge > float(x_blind_min)
                        and high_edge < float(x_blind_max))):
                blind_datahist.SetBinContent(i + 1, -0.1)
                blind_datahist.SetBinError(i + 1, 0)
                c = total_bkg.GetBinContent(i + 1)
                azimov_datahist.SetBinContent(i + 1, c)
                azimov_datahist.SetBinError(i + 1, c**.5)
    # for boosted category:
    if is2D and manual_blind:
        x_blind_ind = [
            ind for ind, x in enumerate(x_bins) if 120 >= int(x) >= 70
        ]
        x_blind_ind1 = []

        dummy_list = [
            int(x) for x in np.linspace(Nxbins, Nxbins * Nxbins, Nxbins)
        ]
        for i in range(0, total_datahist.GetNbinsX()):
            if i in dummy_list:
                x_blind_ind1 = [x + i for x in x_blind_ind]
            if i in x_blind_ind or i in x_blind_ind1:
                blind_datahist.SetBinContent(i + 1, -0.1)
                blind_datahist.SetBinError(i + 1, 0)
                c = total_bkg.GetBinContent(i + 1)
                azimov_datahist.SetBinContent(i + 1, c)
                azimov_datahist.SetBinError(i + 1, c**.5)

    #Set bin errors for empty bins if required:
    if empty_bin_error:
        for i in range(1, blind_datahist.GetNbinsX() + 1):
            if blind_datahist.GetBinContent(i) == 0:
                blind_datahist.SetBinError(i, 1.8)
    #Set uniform bin errors properly for Content < 10 bins
    if args.proper_errors_uniform:
        proper_errs_dict = {
            0: 1.29,
            1: 2.38,
            2: 3.51,
            3: 4.20,
            4: 4.44,
            5: 5.06,
            6: 5.46,
            7: 6.05,
            8: 6.02,
            9: 6.46
        }
        for i in range(1, blind_datahist.GetNbinsX() + 1):
            if blind_datahist.GetBinContent(
                    i) < 9.5 and blind_datahist.GetBinContent(i) >= 0:
                new_err = proper_errs_dict[round(
                    blind_datahist.GetBinContent(i))]
                blind_datahist.SetBinError(i, new_err)

    #Normalise by bin width
    scale = 1.0
    if is2D:
        scale = 1. / 10.  # if we have an unrolled plot then we need to account for the bins being in 10 GeV units
    bkghist.Scale(scale, "width")
    sbhist.Scale(scale, "width")

    for shist in sighists:
        if mode == 'prefit':
            shist.Scale(6.0 * scale,
                        "width")  # can scale up signals here if desired
        else:
            shist.Scale(scale, "width")  # can scale up signals here if desired

    for shist in sighists:
        sbhist.Add(shist)
    #sbhist.Scale(scale,"width")
    #sbhist_alt.Scale(scale,"width")
    blind_datahist.Scale(scale, "width")
    azimov_datahist.Scale(scale, "width")

    blind_datagraph = ROOT.TGraphAsymmErrors(blind_datahist)
    azimov_datagraph = ROOT.TGraphAsymmErrors(azimov_datahist)

    channel = args.channel

    #Create stacked plot for the backgrounds
    bkg_histos = []
    for i, t in enumerate(background_schemes[channel]):
        plots = t['plot_list']
        isHist = False
        h = ROOT.TH1F()
        for j, k in enumerate(plots):
            if h.GetEntries() == 0 and getHistogram(
                    histo_file, k, file_dir, mode, False,
                    logx=log_x) is not None:
                isHist = True
                h = getHistogram(histo_file, k, file_dir, mode, logx=log_x)[0]
                h.SetName(k)
            else:
                if getHistogram(histo_file,
                                k,
                                file_dir,
                                mode,
                                False,
                                logx=log_x) is not None:
                    isHist = True
                    h.Add(
                        getHistogram(histo_file, k, file_dir, mode,
                                     logx=log_x)[0])
        h.SetFillColor(t['colour'])
        h.SetLineColor(ROOT.kBlack)
        h.SetMarkerSize(0)

        h.Scale(scale, "width")
        if isHist:
            bkg_histos.append(h)

    stack = ROOT.THStack("hs", "")
    for hists in bkg_histos:
        stack.Add(hists)

    #Setup style related things
    c2 = ROOT.TCanvas()
    c2.cd()

    if args.ratio:
        pads = plot.TwoPadSplit(0.35, 0.01, 0.01)
    else:
        pads = plot.OnePad()

    for p in pads:
        p.SetFrameLineWidth(1)

    pads[0].cd()
    if (log_y):
        pads[0].SetLogy(1)
    if (log_x):
        pads[0].SetLogx(1)

    if custom_x_range:
        if x_axis_max > bkghist.GetXaxis().GetXmax():
            x_axis_max = bkghist.GetXaxis().GetXmax()
    if args.ratio:
        if (log_x):
            pads[1].SetLogx(1)
        axish = createAxisHists(2, bkghist,
                                bkghist.GetXaxis().GetXmin(),
                                bkghist.GetXaxis().GetXmax() - 0.01)
        axish[1].GetXaxis().SetTitle(x_title)
        if is2D:
            axish[1].GetXaxis().SetLabelSize(0.03)
        axish[1].GetYaxis().SetNdivisions(4)
        axish[1].GetYaxis().SetLabelSize(0.033)
        axish[1].GetXaxis().SetLabelSize(0.033)
        if is2D:
            axish[1].GetXaxis().SetNdivisions(bkghist.GetNbinsX() / Nxbins,
                                              Nxbins, 0, False)
        axish[0].GetYaxis().SetTitleSize(0.048)
        axish[0].GetYaxis().SetLabelSize(0.033)
        axish[0].GetYaxis().SetTitleOffset(0.5)
        axish[0].GetXaxis().SetTitleSize(0)
        axish[0].GetXaxis().SetLabelSize(0)
        if is2D:
            axish[0].GetXaxis().SetNdivisions(bkghist.GetNbinsX() / Nxbins,
                                              Nxbins, 0, False)
        axish[0].GetYaxis().SetTitleSize(axish[1].GetXaxis().GetTitleSize())
        axish[0].GetXaxis().SetRangeUser(x_axis_min,
                                         bkghist.GetXaxis().GetXmax() - 0.01)
        axish[1].GetXaxis().SetRangeUser(x_axis_min,
                                         bkghist.GetXaxis().GetXmax() - 0.01)
        axish[0].GetXaxis().SetMoreLogLabels()
        axish[0].GetXaxis().SetNoExponent()
        axish[1].GetXaxis().SetMoreLogLabels()
        axish[1].GetXaxis().SetNoExponent()
        axish[1].GetXaxis().SetTitleOffset(0.85)

        if not is2D:
            axish[0].GetXaxis().SetRangeUser(
                0.,
                bkghist.GetXaxis().GetXmax() - 0.01)
            axish[1].GetXaxis().SetRangeUser(
                0.,
                bkghist.GetXaxis().GetXmax() - 0.01)

        if custom_x_range:
            axish[0].GetXaxis().SetRangeUser(x_axis_min, x_axis_max - 0.01)
            axish[1].GetXaxis().SetRangeUser(x_axis_min, x_axis_max - 0.01)
        if custom_y_range:
            axish[0].GetYaxis().SetRangeUser(y_axis_min, y_axis_max)
            axish[1].GetYaxis().SetRangeUser(y_axis_min, y_axis_max)
    else:
        axish = createAxisHists(1, bkghist,
                                bkghist.GetXaxis().GetXmin(),
                                bkghist.GetXaxis().GetXmax() - 0.01)
        if custom_x_range:
            axish[0].GetXaxis().SetRangeUser(x_axis_min, x_axis_max - 0.01)
        if custom_y_range:
            axish[0].GetYaxis().SetRangeUser(y_axis_min, y_axis_max)
    axish[0].GetYaxis().SetTitleOffset(0.5)
    axish[1].GetYaxis().SetTitleOffset(0.5)
    axish[0].GetYaxis().SetTitle("dN/dm_{#tau#tau} (1/GeV)")
    if not is2D:
        axish[0].GetYaxis().SetTitle("dN/dm_{#tau#tau} (1/GeV)")
        #axish[0].GetYaxis().SetTitle("< Events / GeV >")
        axish[0].GetYaxis().SetTitleOffset(1.5)
        axish[1].GetYaxis().SetTitleOffset(1.5)

    axish[0].GetXaxis().SetTitle(x_title)

    if not custom_y_range:
        axish[0].SetMaximum(extra_pad * bkghist.GetMaximum())
    if not custom_y_range:
        if (log_y):
            ymin = 0.1
            axish[0].SetMinimum(ymin)
        else:
            axish[0].SetMinimum(0)

    hist_indices = [0]
    for i in hist_indices:
        pads[i].cd()
        axish[i].Draw("AXIS")

        bkghist.SetMarkerSize(0)
        bkghist.SetFillColor(2001)
        bkghist.SetLineColor(1)
        bkghist.SetLineWidth(1)
        bkghist.SetFillColor(plot.CreateTransparentColor(12, 0.4))
        bkghist.SetLineColor(0)

        #stack.Draw("histsame")
        #bkghist.Draw("e2same")
        #Add signal, either model dependent or independent
        if not args.no_signal:
            sighist.SetLineColor(ROOT.kRed)
            sighist.SetLineWidth(2)
            if not is2D:
                sighist.SetLineWidth(3)
            for shist in sighists:
                for j in range(1, shist.GetNbinsX() + 1):
                    entry = shist.GetBinContent(j)
                    if entry < axish[0].GetMinimum():
                        shist.SetBinContent(j, axish[0].GetMinimum() * 1.00001)

                shist_stack = shist.Clone()
                shist_stack.SetLineColor(ROOT.kBlack)
                shist_stack.SetLineWidth(1)
                #shist_stack.SetFillStyle(1)
                shist_stack.SetFillColor(ROOT.kRed)
                #stack.Add(shist_stack) # uncomment to add to the stack
        #        shist.Draw("histsame][") # removing vertical lines at the borders of the pad; possible with the trick above
        stack.Draw("histsame")
        shist.Draw("histsame ][")
        bkghist.Draw("e2same")
        blind_datagraph_extra = blind_datagraph.Clone()
        blind_datagraph_extra.Draw("P Z 0 same")
        blind_datagraph.SetMarkerSize(0.)
        blind_datagraph.Draw("P Z 0 same")

        azimov_datagraph_extra = azimov_datagraph.Clone()
        azimov_datagraph_extra.Draw("P Z 0 same")
        azimov_datagraph.SetMarkerSize(0.)
        azimov_datagraph.Draw("P Z 0 same")

        axish[i].Draw("axissame")

    pads[0].cd()
    pads[0].SetTicks(1)
    pads[1].SetTicks(1)
    #Setup legend
    if not is2D:
        legend = plot.PositionedLegend(0.42, 0.33, 3, 0.02, 0.02)
        #def PositionedLegend(width, height, pos, offset, horizontaloffset=None):
        legend.SetTextSize(0.028)
    else:
        legend = PositionedLegendUnrolled(0.13, 0.5, 7, 0.02)
        legend.SetTextSize(0.035)
    legend.SetTextFont(42)
    legend.SetFillStyle(0)

    legend.AddEntry(total_datahist, "Observed", "PEl")
    #Drawn on legend in reverse order looks better
    bkg_histos.reverse()

    background_schemes[channel].reverse()
    leg_hists = [None] * len(bkg_histos)
    for legi, hists in enumerate(bkg_histos):
        legend.AddEntry(hists, background_schemes[channel][legi]['leg_text'],
                        "f")
    #legend.AddEntry(bkghist,"Background uncertainty","f")
    bkghist.SetLineWidth(0)
    legend.AddEntry(bkghist, "Bkg. unc.", "f")
    if is2D:
        if not mode == 'prefit':
            if not args.no_signal:
                legend.AddEntry(sighist,
                                "gg#phi @ 5.8 pb (m_{#phi}= 100 GeV)" % vars(),
                                "l")
        else:
            if not args.no_signal:
                legend.AddEntry(sighist,
                                "gg#phi @ 5.8 pb (m_{#phi}= 100 GeV)" % vars(),
                                "l")

    else:
        #if not args.no_signal: legend.AddEntry(shist_stack,"gg#phi(100 GeV) @ 5.8 pb"%vars(),"f") # uncomment if showing in the stack
        if not args.no_signal:
            legend.AddEntry(sighist,
                            "gg#phi @ 5.8 pb (m_{#phi}= 100 GeV)" % vars(),
                            "l")
    legend.Draw("same")

    latex2 = ROOT.TLatex()
    latex2.SetNDC()
    latex2.SetTextAngle(0)
    latex2.SetTextColor(ROOT.kBlack)
    latex2.SetTextFont(42)
    if not is2D:
        #latex2.SetTextSize(0.032)
        #latex2.DrawLatex(0.21,0.89,"{}, {}".format(bin_label.split(',')[0], channel_label))
        #latex3 = ROOT.TLatex()
        #latex3.SetNDC()
        #latex3.SetTextSize(0.032)
        #latex3.SetTextAngle(0)
        #latex3.SetTextColor(ROOT.kBlack)
        #latex3.SetTextFont(42)
        #if len(bin_label.split(','))>1: latex3.DrawLatex(0.21,0.84,"{}".format(bin_label.split(',')[1]))
        textsize = 0.033  #0.027
        begin_left = None
        ypos = 0.960 if "_{" in bin_label else 0.955
        latex2 = ROOT.TLatex()
        latex2.SetNDC()
        latex2.SetTextAngle(0)
        latex2.SetTextColor(ROOT.kBlack)
        latex2.SetTextSize(textsize)
        if begin_left == None:
            #begin_left = 0.145
            begin_left = 0.180
        latex2.SetTextFont(42)
        latex2.DrawLatex(begin_left, 0.960, channel_label + ', ' + bin_label)
    else:
        latex2.SetTextAlign(23)
        latex2.SetTextSize(0.05)
        latex2.DrawLatex(0.46, 0.955, "{}, {}".format(bin_label,
                                                      channel_label))

    if args.bOnly:
        #pads[0].cd()
        latex2.DrawLatex(0.54, 0.55, "Bkg. only fit")

    #CMS and lumi labels
    plot.FixTopRange(pads[0], plot.GetPadYMax(pads[0]),
                     extra_pad if extra_pad > 0 else 0.3)
    extra = cms_label
    #extra='Preliminary'
    if not is2D:
        #DrawCMSLogo(pads[0], 'CMS', extra, 0, 0.07, -0.0, 2.0, '', 0.85, relExtraDX=0.05)
        cms_scale = 1.0
        DrawCMSLogo(pads[0], 'CMS', extra, 11, 0.045, 0.05, 1.0, '', cms_scale)

        plot.DrawTitle(pads[0], lumi, 3, textSize=0.6)
    else:
        DrawCMSLogo(pads[0],
                    'CMS',
                    extra,
                    0,
                    0.07,
                    -0.0,
                    2.0,
                    '',
                    0.6,
                    relExtraDX=0.005)
        DrawTitleUnrolled(pads[0], lumi, 3, scale=0.6)

    #Add ratio plot if required
    axish[1].GetYaxis().SetTitle("Obs./Exp.")
    if args.ratio:
        ratio_bkghist = plot.MakeRatioHist(bkghist, bkghist, True, False)
        sbhist.SetLineColor(ROOT.kRed)
        sbhist_alt.SetLineColor(ROOT.kBlue)
        sbhist.SetLineWidth(2)
        sbhist_alt.SetLineWidth(2)
        if not is2D:
            sbhist.SetLineWidth(3)
            sbhist_alt.SetLineWidth(3)

        bkghist_errors = bkghist.Clone()
        #for i in range(1,bkghist_errors.GetNbinsX()+1): bkghist_errors.SetBinContent(i,bkghist.GetBinError(i))
        for i in range(1, bkghist_errors.GetNbinsX() + 1):
            bkghist_errors.SetBinContent(i, 1.)
        ratio_sighist = plot.MakeRatioHist(sbhist, bkghist, True, False)
        ratio_datahist_ = plot.MakeRatioHist(blind_datahist, bkghist, True,
                                             False)
        azimov_ratio_datahist_ = plot.MakeRatioHist(azimov_datahist, bkghist,
                                                    True, False)

        ratio_datahist = ROOT.TGraphAsymmErrors(ratio_datahist_)
        azimov_ratio_datahist = ROOT.TGraphAsymmErrors(azimov_ratio_datahist_)

        pads[1].cd()
        #pads[1].SetGrid(0,1)
        axish[1].Draw("axis")
        axish[1].SetMinimum(float(args.ratio_range.split(',')[0]))
        axish[1].SetMaximum(float(args.ratio_range.split(',')[1]))
        ratio_bkghist.SetMarkerSize(0)

        ratio_bkghist.Draw("e2same")
        ratio_datahist.Draw("P Z 0 same")
        ratio_sighist.Draw('histsame')

        if args.f_bOnly:
            bonly_histo_file = ROOT.TFile(args.f_bOnly)
            bonlyhist = getHistogram(bonly_histo_file,
                                     'TotalBkg',
                                     file_dir,
                                     mode,
                                     logx=log_x)[0]
            bonlyhist.Scale(1, "width")
            bonlyhist.SetLineColor(ROOT.kBlue)
            bonlyhist.SetLineWidth(2)
            bonlyhist.SetLineStyle(2)
            ratio_bonlyhist = plot.MakeRatioHist(bonlyhist, bkghist, True,
                                                 False)
            ratio_bonlyhist.Draw("histsame")
            pads[0].cd()
            legend.AddEntry(bonlyhist, 'Bkg. only fit', 'l')
            legend.Draw()
            #bonlyhist.Draw('histsame')
            bonlyhist.SetMarkerSize(0)
            bonlyhist.Draw('lsame')
            stack.Draw("histsame")
            shist.Draw("histsame ][")
            bkghist.Draw("e2same")
            blind_datagraph.SetMarkerSize(1)
            blind_datagraph.Draw("P Z 0 same")
            pads[1].cd()

        if args.manual_blind: azimov_ratio_datahist.Draw("P Z 0 same")
        pads[1].RedrawAxis("G")
        if is2D:
            rlegend = ROOT.TLegend(0.85, 0.27, 0.98, 0.16, '', 'NBNDC')
            rlegend.SetTextFont(42)
            rlegend.SetTextSize(0.035)
            rlegend.SetFillStyle(0)
            rlegend.AddEntry(ratio_datahist, "Obs./Exp.", "PE")
            rlegend.AddEntry("", " ", "")
            #rlegend.AddEntry(ratio_sighist,"(Sig.+Bkg.)/Bkg.","L")
        #rlegend.Draw("same")
        # Draw extra axis for explanation (use "N" for no optimisation)
        if is2D:
            extra_axis = ROOT.TGaxis(0, -0.03, 30., -0.03, 0., 300., 403, "NS")
            extra_axis.SetLabelSize(0.03)
            extra_axis.SetLabelFont(42)
            extra_axis.SetMaxDigits(3)
            extra_axis.SetTitle("m_{#tau#tau} (GeV)")
            extra_axis.SetTitleFont(42)
            extra_axis.SetTitleSize(0.035)
            extra_axis.SetTitleOffset(1.1)
            extra_axis.SetTickSize(0.08)
            extra_axis.Draw()

    pads[0].cd()
    pads[0].GetFrame().Draw()
    pads[0].RedrawAxis()

    ## Add lines after every Nxbins
    #line = ROOT.TLine()
    #line.SetLineWidth(2)
    #line.SetLineStyle(3)
    #line.SetLineColor(1)
    #x = bkghist.GetNbinsX()/Nxbins
    #x_min=bkghist.GetXaxis().GetBinLowEdge(1)
    #x_max=bkghist.GetXaxis().GetBinLowEdge(bkghist.GetNbinsX()+1)
    #x_range=x_max-x_min

    ## for now we have to hard code x=4 otherwise we have issues when the auto rebinning has been used
    #x=4
    #if is2D:
    #    for l in range(1,x):
    #        pads[0].cd()
    #        ymax = axish[0].GetMaximum()
    #        ymin = axish[0].GetMinimum()
    #        line.DrawLine(l*x_range/x,ymin,l*x_range/x,ymax)
    #        if args.ratio:
    #            pads[1].cd()
    #            ymax = axish[1].GetMaximum()
    #            ymin = axish[1].GetMinimum()
    #            line.DrawLine(l*x_range/x,ymin,l*x_range/x,ymax)

    ## Add bin labels between lines
    pads[0].cd()
    latex_bin = ROOT.TLatex()
    latex_bin.SetNDC()
    latex_bin.SetTextAngle(0)
    latex_bin.SetTextColor(ROOT.kBlack)
    latex_bin.SetTextFont(42)
    latex_bin.SetTextSize(0.035)
    if len(y_bin_labels) > 6 or ('_2_' in file_dir and len(y_bin_labels) > 5):
        latex_bin.SetTextSize(0.027)

    for i in range(0, len(y_bin_labels)):
        if i < len(y_bin_labels) - 1:
            y_bin_label = "{} #leq {} < {} {}".format(y_bin_labels[i],
                                                      y_bin_var,
                                                      y_bin_labels[i + 1],
                                                      "GeV")
            l = ROOT.gPad.GetLeftMargin()
            r = ROOT.gPad.GetRightMargin()
            #xshift = ((1-r-l)/(axish[0].GetNbinsX()/Nxbins))*i + l
            # have to hard code 4 here other wise we have problems when the autorebinning has been used
            xshift = ((1 - r - l) / (4)) * i + l
            latex_bin.DrawLatex(xshift + 0.02, 0.82, y_bin_label)
        else:
            #xshift = ((1-r-l)/(axish[0].GetNbinsX()/Nxbins))*i + l
            # have to hard code 4 here other wise we have problems when the autorebinning has been used
            xshift = ((1 - r - l) / (4)) * i + l
            y_bin_label = "{} > {} {}".format(y_bin_var, y_bin_labels[i],
                                              "GeV")
            latex_bin.DrawLatex(xshift + 0.02, 0.82, y_bin_label)

    #Save as png and pdf with some semi sensible filename
    shape_file_name = shape_file_name.replace(".root", "_%(mode)s" % vars())
    shape_file_name = shape_file_name.replace("_shapes", "")
    outname += shape_file_name + "_" + file_dir.strip("htt").strip("_")
    if (log_x):
        outname += "_logx"
    c2.SaveAs("plots/%(outname)s.pdf" % vars())

    del c2
    histo_file.Close()
Ejemplo n.º 7
0
 def PlotTestStat(self, result, name, opts, poi_vals):
     null_vals = [
         x * -2.
         for x in result.GetNullDistribution().GetSamplingDistribution()
     ]
     alt_vals = [
         x * -2.
         for x in result.GetAltDistribution().GetSamplingDistribution()
     ]
     if len(null_vals) == 0 or len(alt_vals) == 0:
         print '>> Errror in PlotTestStat for %s, null and/or alt distributions are empty'
         return
     plot.ModTDRStyle()
     canv = ROOT.TCanvas(name, name)
     pad = plot.OnePad()[0]
     min_val = min(min(alt_vals), min(null_vals))
     max_val = max(max(alt_vals), max(null_vals))
     min_plot_range = min_val - 0.05 * (max_val - min_val)
     if opts['one_sided']:
         min_plot_range = 0.
         pad.SetLogy(True)
     max_plot_range = max_val + 0.05 * (max_val - min_val)
     hist_null = ROOT.TH1F('null', 'null', 40, min_plot_range,
                           max_plot_range)
     hist_alt = ROOT.TH1F('alt', 'alt', 40, min_plot_range, max_plot_range)
     for val in null_vals:
         hist_null.Fill(val)
     for val in alt_vals:
         hist_alt.Fill(val)
     hist_alt.SetLineColor(ROOT.TColor.GetColor(4, 4, 255))
     hist_alt.SetFillColor(
         plot.CreateTransparentColor(ROOT.TColor.GetColor(4, 4, 255), 0.4))
     hist_alt.GetXaxis().SetTitle('-2 #times ln(^{}L_{%s}/^{}L_{%s})' %
                                  (opts['alt_label'], opts['null_label']))
     hist_alt.GetYaxis().SetTitle('Pseudo-experiments')
     hist_alt.Draw()
     hist_null.SetLineColor(ROOT.TColor.GetColor(252, 86, 11))
     hist_null.SetFillColor(
         plot.CreateTransparentColor(ROOT.TColor.GetColor(254, 195, 40),
                                     0.4))
     hist_null.Draw('SAME')
     val_obs = result.GetTestStatisticData() * -2.
     obs = ROOT.TArrow(val_obs, 0, val_obs,
                       hist_alt.GetMaximum() * 0.3, 0.05, '<-|')
     obs.SetLineColor(ROOT.kRed)
     obs.SetLineWidth(3)
     obs.Draw()
     plot.FixTopRange(pad, plot.GetPadYMax(pad), 0.25)
     leg = plot.PositionedLegend(0.22, 0.2, 3, 0.02)
     leg.AddEntry(hist_alt, opts['alt_label'], 'F')
     leg.AddEntry(hist_null, opts['null_label'], 'F')
     leg.AddEntry(obs, 'Observed', 'L')
     leg.Draw()
     plot.DrawCMSLogo(pad, 'CMS', opts['cms_subtitle'], 0, 0.15, 0.035, 1.2)
     pt_l = ROOT.TPaveText(0.23, 0.75, 0.33, 0.9, 'NDCNB')
     pt_l.AddText('Model:')
     pt_l.AddText('Toys:')
     pt_l.AddText('CLs+b:')
     pt_l.AddText('CLb:')
     pt_l.AddText('CLs:')
     plot.Set(pt_l, TextAlign=11, TextFont=62, BorderSize=0)
     pt_l.Draw()
     pt_r = ROOT.TPaveText(0.33, 0.75, 0.63, 0.9, 'NDCNB')
     pt_r.AddText('%s [%s = %.1f, %s = %.1f]' %
                  (opts['model_label'], opts['poi_labels'][0], poi_vals[0],
                   opts['poi_labels'][1], poi_vals[1]))
     pt_r.AddText(
         '%i (%s) + %i (%s)' %
         (result.GetNullDistribution().GetSize(), opts['null_label'],
          result.GetAltDistribution().GetSize(), opts['alt_label']))
     pt_r.AddText('%.3f #pm %.3f' %
                  (result.CLsplusb(), result.CLsplusbError()))
     pt_r.AddText('%.3f #pm %.3f' % (result.CLb(), result.CLbError()))
     pt_r.AddText('%.3f #pm %.3f' % (result.CLs(), result.CLsError()))
     plot.Set(pt_r, TextAlign=11, TextFont=42, BorderSize=0)
     pt_r.Draw()
     pad.GetFrame().Draw()
     pad.RedrawAxis()
     for fmt in opts['formats']:
         canv.SaveAs(fmt)
print cont_1sigma
for item in cont_1sigma:
    print item
print cont_2sigma
for item in cont_2sigma:
    print item

if debug is not None:
    debug.WriteTObject(hists, 'hist')
    for i, cont in enumerate(cont_1sigma):
        debug.WriteTObject(cont, 'cont_1sigma_%i' % i)
    for i, cont in enumerate(cont_2sigma):
        debug.WriteTObject(cont, 'cont_2sigma_%i' % i)

if args.sm_exp or args.bg_exp:
    legend = plot.PositionedLegend(0.47, 0.20, 3, 0.015)
else:
    legend = plot.PositionedLegend(0.3, 0.2, 3, 0.015)

pads[0].cd()
axis.Draw()
for i, p in enumerate(cont_2sigma):
    p.SetLineStyle(1)
    p.SetLineWidth(2)
    p.SetLineColor(ROOT.kBlack)
    p.SetFillColor(ROOT.kBlue - 10)
    p.SetFillStyle(1001)
    p.Draw("F SAME")
    p.Draw("L SAME")
    legend.AddEntry(cont_1sigma[0], "68% CL", "F")
    #if (i==1):
Ejemplo n.º 9
0
graph_exp.SetLineStyle(1)
#  if(mssm_log){
#      expected->SetLineColor(kBlack);
#      expected->SetLineStyle(2);
#      }
graph_exp.Draw("L")

if not args.expected_only:
    graph_obs.SetMarkerColor(ROOT.kBlack)
    graph_obs.SetMarkerSize(1.0)
    graph_obs.SetMarkerStyle(20)
    graph_obs.SetLineWidth(3)
    graph_obs.Draw("PLsame")

pads[0].cd()
legend = plot.PositionedLegend(0.5, 0.9, 2, 0.03)
legend.SetNColumns(2)
legend.SetFillStyle(1001)
legend.SetTextSize(0.15)
legend.SetTextFont(62)
legend.SetHeader("95% CL Excluded:")
if not args.expected_only:
    legend.AddEntry(graph_obs, "Observed", "L")
legend.AddEntry(innerBand, "#pm 1#sigma Expected", "F")
legend.AddEntry(graph_exp, "Expected", "L")
legend.AddEntry(outerBand, "#pm 2#sigma Expected", "F")
legend.Draw("same")

plot.DrawCMSLogo(pads[1], '', '', 11, 0.045, 0.035, 1.2)
plot.DrawTitle(pads[1], '%s' % args.title, 3)
plot.FixOverlay()
Ejemplo n.º 10
0
        relative_obs_graph.SetLineColor(ROOT.kBlue)
        relative_obs_graph.SetMarkerColor(ROOT.kBlue)
        relative_obs_graph.SetLineWidth(3)
        relative_obs_graph.SetLineStyle(2)
        relative_obs_graph.SetMarkerStyle(20)
        relative_obs_graph.Draw("PL")

pads[0].cd()
h_top = axis.Clone()
#necessary in case chosen range surrounds 0 which will cause axis to contain a horizontal line at 0
h_top.GetYaxis().SetRangeUser(0.001, 100)
plot.Set(h_top.GetXaxis(), LabelSize=0, TitleSize=0, TickLength=0)
plot.Set(h_top.GetYaxis(), LabelSize=0, TitleSize=0, TickLength=0)
h_top.Draw()

legend = plot.PositionedLegend(0.5 if args.relative or args.absolute else 0.4,
                               0.11, 3, 0.015)
plot.Set(legend, NColumns=1, Header='#bf{%.0f%% CL Excluded:}' % 95)
if not (args.relative or args.absolute):
    for i in range(len(files)):
        legend.AddEntry(exp_graph_list[i], labels[i], "PL")
elif args.relative:
    legend.SetTextSize(0.025)
    legend.AddEntry(
        relative_exp_graph, "Exp 2*|" + labels[0] + "-" + labels[1] + "|/(" +
        labels[0] + "+" + labels[1] + ")", "PL")
    if not args.expected_only:
        legend.AddEntry(
            relative_obs_graph, "Obs 2*|" + labels[0] + "-" + labels[1] +
            "|/(" + labels[0] + "+" + labels[1] + ")", "PL")
elif args.absolute:
    legend.SetTextSize(0.025)
Ejemplo n.º 11
0
# Set the style options of the pads
for padx in pads:
    # Use tick marks on oppsite axis edges
    plot.Set(padx, Tickx=1, Ticky=1, Logx=args.logx)
    if args.pad_style is not None:
        settings = {x.split('=')[0]: eval(x.split('=')[1]) for x in args.pad_style.split(',')}
        print 'Applying style options to the TPad(s):'
        print settings
        plot.Set(padx, **settings)

graphs = []
graph_sets = []

if args.higgs_bg or args.higgs_injected:
    legend = plot.PositionedLegend(0.4, 0.25, 3, 0.015)
else:
    legend = plot.PositionedLegend(0.3, 0.2, 3, 0.015)
#legend = plot.PositionedLegend(0.45, 0.10, 3, 0.015)
#plot.Set(legend, NColumns=2)

axis = None

defcols = [
    ROOT.kGreen+3, ROOT.kRed, ROOT.kBlue, ROOT.kBlack, ROOT.kYellow+2,
    ROOT.kOrange+10, ROOT.kCyan+3, ROOT.kMagenta+2, ROOT.kViolet-5, ROOT.kGray
    ]

deflines = [1, 2, 3]

if args.auto_style is not None:
Ejemplo n.º 12
0
axish[1].GetYaxis().SetRangeUser(0.93, 1.07)

if doUncerts:
    ratio_up = plot.MakeRatioHist(histo_unc_up, histo_nominal, True, False)
    ratio_down = plot.MakeRatioHist(histo_unc_down, histo_nominal, True, False)
    ratio_up.SetLineColor(ROOT.kRed)
    ratio_down.SetLineColor(ROOT.kRed)

pads[0].cd()
axish[0].Draw()
histo_nominal.Draw("SAME")
if doUncerts:
    histo_unc_up.Draw("SAME")
    histo_unc_down.Draw("SAME")
#LHE_ht_ghost.Draw("SAME")
legend = plot.PositionedLegend(0.3, 0.15, 3, 0.015)
legend.AddEntry(histo_nominal, "Nominal")
if args.uncerts is not None:
    if 'nlo' in args.uncerts:
        legend.AddEntry(histo_unc_up, "LO to NLO wt Up/Down")
    elif 'wrew' in args.uncerts:
        legend.AddEntry(histo_unc_up, "W pT reweighting Up/Down")
    elif 'scale' in args.uncerts:
        legend.AddEntry(histo_unc_up, "MuRMuF Up/Down")
legend.Draw("SAME")

pads[1].cd()
axish[1].Draw()
if doUncerts:
    ratio_up.Draw("HISTSAME")
    ratio_down.Draw("HISTSAME")
Ejemplo n.º 13
0
splusbhist.SetMarkerSize(0)
splusbhist.SetFillStyle(3944)


stack.Draw("histsame")
splusbhist.Draw("e2same")
#Add signal
if not args.no_signal:
    sighist.SetLineColor(ROOT.kRed)
    sighist.SetLineWidth(3)
    sighist.Draw("histsame")
blind_datahist.DrawCopy("e0psame")
axish[0].Draw("axissame")

#Setup legend
legend = plot.PositionedLegend(0.48,0.30,3,0.03)
plot.Set(legend, NColumns=2)
legend.SetTextFont(42)
legend.SetTextSize(0.025)
legend.SetFillColor(0)
legend.AddEntry(total_datahist,"Observation","PE")
#Drawn on legend in reverse order looks better
bkg_histos.reverse()
plot_background_schemes[channel].reverse()
for legi,hists in enumerate(bkg_histos):
    legend.AddEntry(hists,plot_background_schemes[channel][legi]['leg_text'],"f")
legend.AddEntry(splusbhist,"S+B uncertainty","f")
if not args.no_signal:
    legend.AddEntry(sighist,"H(#mu#mu)","l")
latex = ROOT.TLatex()
latex.SetNDC()
Ejemplo n.º 14
0
def HTTMassPlot(cats=[432], infile=None, infile2=None, prefit_plot=None):

    ROOT.gROOT.SetBatch(ROOT.kTRUE)
    ROOT.TH1.AddDirectory(False)

    ModTDRStyle(r=0.04, l=0.14, height=700)

    sig_schemes = ("ggH(100 GeV)#rightarrow#tau#tau @ 5.7 pb", ["TotalSig"])

    background_schemes = [
        backgroundComp("H(125 GeV)", [
            "qqH125", "bbH125", "ggH125", "ggHWW125", "qqHWW125", "WHWW125",
            "ZHWW125"
        ], ROOT.TColor.GetColor(51, 51, 230)),
        backgroundComp("Diboson", ["VVL"], ROOT.TColor.GetColor("#6F2D35")),
        backgroundComp("t#bar{t}", ["TTL"], ROOT.TColor.GetColor("#9999cc")),
        backgroundComp("Z#rightarrowll", ["ZL"],
                       ROOT.TColor.GetColor("#4496c8")),
        backgroundComp("Jet#rightarrow#tau",
                       ["jetFakes", "wFakes", "QCD", "W"],
                       ROOT.TColor.GetColor(192, 232, 100)),
        backgroundComp("#mu#rightarrow#tau embedding", ["EMB"],
                       ROOT.TColor.GetColor("#ffcc66")),
    ]

    total_datahist = infile.Get('postfit/data_obs').Clone()
    total_bkg = infile.Get('postfit/TotalBkg').Clone()
    total_sig = infile.Get('postfit/TotalSig').Clone()
    if infile2: bkgonly = infile2.Get('postfit/TotalBkg').Clone()
    if prefit_plot: prefit = prefit_plot.Get('prefit/TotalBkg').Clone()

    total_datahist.Scale(1.0, "width")
    total_bkg.Scale(1.0, "width")
    total_sig.Scale(1.0, "width")

    #Create stacked plot for the backgrounds
    bkg_histos = []

    for i, t in enumerate(background_schemes):
        plots = t['plot_list']
        h = ROOT.TH1F()

        for j, k in enumerate(plots):
            for chan in ['et', 'mt', 'tt', 'em']:
                if chan == 'em':
                    cats_ = []
                    for c in cats:
                        cats_.append(c)
                        cats_.append(c + 1)
                else:
                    cats_ = cats
                for c in cats_:
                    for y in [2016, 2017, 2018]:
                        dirname = 'htt_%(chan)s_%(c)s_%(y)s_postfit' % vars()
                        if not (isinstance(infile.Get(dirname + '/' + k),
                                           ROOT.TH1D)
                                or isinstance(infile.Get(dirname + '/' + k),
                                              ROOT.TH1F)):
                            continue

                        if h.GetEntries() == 0:
                            h = infile.Get(dirname + '/' + k).Clone()
                            h.SetName(k)
                        else:
                            h.Add(infile.Get(dirname + '/' + k).Clone())

        h.SetFillColor(t['colour'])
        h.SetLineColor(ROOT.kBlack)
        h.SetMarkerSize(0)
        h.Scale(1.0, "width")
        if h.GetName() == '': continue
        bkg_histos.append(h)

    stack = ROOT.THStack("hs", "")
    for hists in bkg_histos:
        stack.Add(hists.Clone())

    total_sig.SetFillColor(0)
    total_sig.SetLineColor(ROOT.kRed)
    total_sig.SetLineWidth(2)
    stack.Add(total_sig)

    c1 = ROOT.TCanvas()
    c1.cd()

    pads = TwoPadSplit(0.39, 0.01, 0.01)
    pads[0].cd()

    x_title = 'm_{#tau#tau} (GeV)'
    y_title = 'S/(S+B) weighted events / GeV'
    extra_pad = 0.3
    axish = createAxisHists(2, total_bkg,
                            total_bkg.GetXaxis().GetXmin(),
                            total_bkg.GetXaxis().GetXmax() - 0.0001)
    axish[1].GetXaxis().SetTitle(x_title)
    axish[1].GetXaxis().SetLabelSize(0.03)
    axish[1].GetXaxis().SetTitleSize(0.04)
    axish[1].GetYaxis().SetNdivisions(4)
    axish[1].GetYaxis().SetTitle("Obs.-Bkg.")
    axish[1].GetYaxis().SetTitleOffset(1.6)
    axish[1].GetYaxis().SetTitleSize(0.04)
    axish[1].GetYaxis().SetLabelSize(0.03)
    axish[0].GetXaxis().SetTitleSize(0)
    axish[0].GetXaxis().SetLabelSize(0)
    axish[0].GetYaxis().SetTitle(y_title)
    axish[0].GetYaxis().SetTitleOffset(1.6)
    axish[0].GetYaxis().SetTitleSize(0.04)
    axish[0].GetYaxis().SetLabelSize(0.03)
    axish[0].SetMinimum(0)
    axish[0].SetMaximum(1.1 * (1 + extra_pad) * total_bkg.GetMaximum())
    axish[0].Draw()

    stack.Draw("histsame")

    #Draw uncertainty band
    error_hist = total_bkg.Clone()
    error_hist.SetFillColor(CreateTransparentColor(12, 0.4))
    error_hist.SetLineColor(CreateTransparentColor(12, 0.4))
    error_hist.SetMarkerSize(0)
    error_hist.SetMarkerColor(CreateTransparentColor(12, 0.4))
    error_hist.Draw("e2same")

    # draw data
    total_datahist.SetMarkerStyle(20)
    total_datahist.SetLineColor(1)
    #total_datahist.Draw("E same")
    total_datahist.Draw("Esame")
    total_datahist.SetFillStyle(1)

    axish[0].Draw("axissame")

    #Setup legend
    legend = plot.PositionedLegend(0.35, 0.30, 3, 0.03)
    legend.SetTextSize(0.025)
    legend.SetTextFont(42)
    legend.SetFillStyle(0)

    legend.AddEntry(total_datahist, "Observed", "PEl")
    #Drawn on legend in reverse order looks better
    bkg_histos.reverse()

    background_schemes.reverse()
    leg_hists = [None] * len(bkg_histos)
    for legi, hists in enumerate(bkg_histos):
        legend.AddEntry(hists, background_schemes[legi]['leg_text'], "f")
    total_bkg.SetLineWidth(0)
    legend.AddEntry(error_hist, "Bkg. Uncertainty", "f")
    legend.AddEntry(total_sig, "ggH(100 GeV) @ 5.4 pb" % vars(), "l")
    legend.Draw("same")

    # add pT bin label
    bin_label = ''
    if cats[0] == 132: bin_label = 'p_{T}^{#tau#tau} < 50 GeV'
    if cats[0] == 232: bin_label = '50 #leq p_{T}^{#tau#tau} < 100 GeV'
    if cats[0] == 332: bin_label = '100 #leq p_{T}^{#tau#tau} < 200 GeV'
    if cats[0] == 432: bin_label = 'p_{T}^{#tau#tau} #geq 200 GeV'
    if len(cats) == 4: bin_label = 'p_{T}^{#tau#tau} inclusive'

    latex = ROOT.TLatex()
    latex.SetNDC()
    latex.SetTextAngle(0)
    latex.SetTextColor(ROOT.kBlack)
    latex.SetTextFont(42)
    latex.SetTextSize(0.032)
    latex.DrawLatex(0.21, 0.89, "{}".format(bin_label))

    # draw cms and lumi lable
    DrawCMSLogo(pads[0],
                'CMS',
                'Preliminary',
                0,
                0.07,
                -0.0,
                2.0,
                '',
                0.85,
                relExtraDX=0.05)
    lumi = "138 fb^{-1} (13 TeV)"
    plot.DrawTitle(pads[0], lumi, 3, textSize=0.6)

    # draw lower plot with data-bkg

    bkg_sub = SubtractData(error_hist, error_hist)
    data_sub = SubtractData(error_hist, total_datahist)
    if infile2:
        bkgonly.Scale(1.0, "width")
        bkgonly_sub = SubtractData(error_hist, bkgonly)
    if prefit_plot:
        prefit.Scale(1.0, "width")
        prefit_sub = SubtractData(error_hist, prefit)
    pads[1].cd()
    pads[1].SetGrid(0, 1)

    maxy = 0
    miny = 100000
    for i in range(1, data_sub.GetNbinsX() + 1):
        hi = data_sub.GetBinContent(i) + data_sub.GetBinError(i) * 1.2
        lo = data_sub.GetBinContent(i) - data_sub.GetBinError(i) * 1.2
        maxy = max(maxy, hi)
        miny = min(miny, lo)
    for i in range(1, bkg_sub.GetNbinsX() + 1):
        hi = bkg_sub.GetBinContent(i) + bkg_sub.GetBinError(i) * 1.2
        lo = bkg_sub.GetBinContent(i) - bkg_sub.GetBinError(i) * 1.2
        maxy = max(maxy, hi)
        miny = min(miny, lo)
    axish[1].SetMinimum(miny)
    axish[1].SetMaximum(maxy)
    axish[1].Draw("axis")

    if infile2:
        bkgonly_sub.SetLineWidth(2)
        bkgonly_sub.SetLineColor(ROOT.kBlue)
        bkgonly_sub.SetMarkerSize(0)
        bkgonly_sub.SetLineStyle(2)
        bkgonly_sub.Draw("histsame")

        #Setup legend
        legend2 = plot.PositionedLegend(0.25, 0.10, 3, 0.01)
        legend2.SetTextSize(0.025)
        legend2.SetTextFont(42)
        legend2.SetFillStyle(0)

        legend2.AddEntry(bkgonly_sub, "Bkg. only fit", "l")
        legend2.AddEntry(total_sig, "Sig.+Bkg. fit", "l")
        legend2.Draw("same")

    if prefit_plot:
        prefit_sub.SetLineWidth(3)
        prefit_sub.SetLineColor(ROOT.kMagenta)
        prefit_sub.SetMarkerSize(0)
        prefit_sub.SetLineStyle(2)
        prefit_sub.Draw("histsame")

    total_sig.Draw("histsame")
    data_sub.DrawCopy("e0same")
    bkg_sub.SetMarkerSize(0)
    bkg_sub.SetLineColor(ROOT.kBlack)
    bkg_sub.Draw("e2samehist")

    pads[1].RedrawAxis()

    pads[0].cd()
    #pads[0].GetFrame().Draw()
    pads[0].RedrawAxis()

    plot_name = 'plot'
    if len(cats) == 4: plot_name += '_cmb'
    elif cats[0] == 432: plot_name += '_GT200'
    elif cats[0] == 332: plot_name += '_100to200'
    elif cats[0] == 232: plot_name += '_50to100'
    elif cats[0] == 132: plot_name += '_0to50'
    c1.SaveAs('prop_plots/%(plot_name)s.pdf' % vars())
Ejemplo n.º 15
0
    pads = plot.OnePad()

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

graphs = []
graph_sets = []

legend = plot.PositionedLegend(0.48, 0.25, 3, 0.015)
legend.SetTextSize(0.03)

axis = None

defcols = [
    ROOT.kGreen+3, ROOT.kRed, ROOT.kBlue, ROOT.kBlack, ROOT.kYellow+2,
    ROOT.kOrange+10, ROOT.kCyan+3, ROOT.kMagenta+2, ROOT.kViolet-5, ROOT.kGray
    ]

deflines = [1, 2, 3]

if args.auto_style is not None:
    icol = {x: 0 for x in args.auto_style.split(',')}
    icol['default'] = 0
    iline = {}
Ejemplo n.º 16
0
                sighist.SetBinContent(j,axish[0].GetMinimum()*1.00001)
          sighist.Draw("histsame][") # removing vertical lines at the borders of the pad; possible with the trick above
        else: 
          sighist_ggH.SetLineColor(ROOT.kBlue)
          sighist_bbH.SetLineColor(ROOT.kBlue + 3)
          sighist_ggH.SetLineWidth(3)
          sighist_bbH.SetLineWidth(3)
          sighist_ggH.Draw("histsame")
          sighist_bbH.Draw("histsame")
    if not soverb_plot and not fractions: 
      blind_datahist.DrawCopy("e0x0same")
    axish[i].Draw("axissame")

pads[0].cd()
#Setup legend
legend = plot.PositionedLegend(0.30,0.30,3,0.03)
legend.SetTextFont(42)
legend.SetTextSize(0.025)
legend.SetFillStyle(0)

signal_legend = None
if not args.no_signal and model_dep:
    signal_legend = plot.PositionedLegend(0.16,0.04,2,0.03,0.07)
    signal_legend.SetTextFont(42)
    signal_legend.SetTextSize(0.025)
    signal_legend.SetFillStyle(0)

if not soverb_plot and not fractions: legend.AddEntry(total_datahist,"Observation","PE")
#Drawn on legend in reverse order looks better
bkg_histos.reverse()
background_schemes[channel].reverse()