Exemplo n.º 1
0
def print_xsections_with_uncertainties(xsections, channel, toFile=True):
    global savePath, variable, k_value, met_type, b_tag_bin
    printout = '\n'
    printout += '=' * 60
    printout = '\n'
    printout += 'Results for %s variable, %s channel, k-value %s, met type %s, %s b-tag region\n' % (
        variable, channel, k_value, met_type, b_tag_bin)
    printout += '=' * 60
    printout += '\n'
    #    rows = {}
    printout += '%s bin & $\sigma_{meas}$ \\\\ \n' % variable
    printout += '\hline\n'
    uncertainties = {}
    header = 'Uncertainty'

    bins = variable_bins_ROOT[variable]
    assert (len(bins) == len(xsections['central']))

    for bin_i, variable_bin in enumerate(bins):
        header += '& %s bin %s' % (variable, variable_bin)
        centralresult = xsections['central'][bin_i]
        uncertainty = calculateTotalUncertainty(xsections, bin_i)
        uncertainty_total_plus = uncertainty['Total+'][0]
        uncertainty_total_minus = uncertainty['Total-'][0]
        uncertainty_total_plus, uncertainty_total_minus = symmetriseErrors(
            uncertainty_total_plus, uncertainty_total_minus)
        scale = 100
        central_measurement = centralresult[0]
        fit_error = centralresult[1]

        formatting = (variable_bins_latex[variable_bin],
                      central_measurement * scale, fit_error * scale,
                      uncertainty_total_plus * scale,
                      uncertainty_total_minus * scale)
        text = '%s & $%.2f \pm %.2f (fit)^{+%.2f}_{-%.2f} (sys) \cdot 10^{-2}$\\\\ \n' % formatting
        if doSymmetricErrors:
            relativeError = getRelativeError(
                central_measurement, fit_error + uncertainty_total_plus)
            formatting = (variable_bins_latex[variable_bin],
                          central_measurement * scale, fit_error * scale,
                          uncertainty_total_plus * scale)
            text = '%s & $\\left(%.2f \\pm %.2f \\text{ (fit)} \pm %.2f \\text{ (syst.)}\\right)' % formatting + '(%.2f' % (
                relativeError *
                100) + '\%) \\times 10^{-2}\, \\GeV^{-1}$\\\\ \n'
        printout += text
        for source in uncertainty.keys():
            unc_result = uncertainty[source]
            if not uncertainties.has_key(source):
                if source in metsystematics_sources:
                    uncertainties[
                        source] = metsystematics_sources_latex[source] + ' & '
                else:
                    uncertainties[source] = source + ' & '
            relativeError = getRelativeError(centralresult[0], unc_result[0])
            #            text = ' $(%.2f \pm %.2f) \cdot 10^{-2} $ ' % (unc_result[0]*scale,unc_result[1]*scale) + '(%.2f' % (relativeError * 100) + '\%) &'
            text = '%.2f' % (relativeError * 100) + '\% &'
            #            text = ' $%.2f \pm %.2f $ ' % (unc_result[0]*scale,unc_result[1]*scale) + '(%.2f' % (relativeError * 100) + '\%) &'
            uncertainties[source] += text

    printout += '\\\\ \n'
    for source in sorted(uncertainties.keys()):
        value = uncertainties[source]
        value = value.rstrip('&')
        value += '\\\\ \n'
        printout += value

    make_folder_if_not_exists(savePath + '/' + variable)
    if toFile:
        output_file = open(
            savePath + '/' + variable + '/normalised_xsection_main_result_' +
            channel + '_' + met_type + '_kv' + str(k_value) + '.tex', 'w')
        output_file.write(printout)
        output_file.close()
    else:
        print printout
def make_plots_ROOT(histograms, category, save_path, histname, channel):
    global variable, translateOptions, k_value, b_tag_bin, maximum
    ROOT.TH1.SetDefaultSumw2(False)
    ROOT.gROOT.SetBatch(True)
    ROOT.gROOT.ProcessLine("gErrorIgnoreLevel = 1001;")
    plotting.setStyle()
    gStyle.SetTitleYOffset(2.0)
    ROOT.gROOT.ForceStyle()
    canvas = Canvas(width=700, height=500)
    canvas.SetLeftMargin(0.18)
    canvas.SetBottomMargin(0.15)
    canvas.SetTopMargin(0.05)
    canvas.SetRightMargin(0.05)
    legend = plotting.create_legend(x0=0.6, y1=0.5)

    hist_data = histograms["unfolded"]
    hist_data.GetXaxis().SetTitle(translate_options[variable] + " [GeV]")
    hist_data.GetYaxis().SetTitle("#frac{1}{#sigma} #frac{d#sigma}{d" + translate_options[variable] + "} [GeV^{-1}]")
    hist_data.GetXaxis().SetTitleSize(0.05)
    hist_data.GetYaxis().SetTitleSize(0.05)
    hist_data.SetMinimum(0)
    hist_data.SetMaximum(maximum[variable])
    hist_data.SetMarkerSize(1)
    hist_data.SetMarkerStyle(8)
    plotAsym = TGraphAsymmErrors(hist_data)
    plotStatErr = TGraphAsymmErrors(hist_data)

    xsections = read_unfolded_xsections(channel)
    bins = variable_bins_ROOT[variable]
    assert len(bins) == len(xsections["central"])

    for bin_i in range(len(bins)):
        scale = 1  # / width
        centralresult = xsections["central"][bin_i]
        fit_error = centralresult[1]
        uncertainty = calculateTotalUncertainty(xsections, bin_i)
        uncertainty_total_plus = uncertainty["Total+"][0]
        uncertainty_total_minus = uncertainty["Total-"][0]
        uncertainty_total_plus, uncertainty_total_minus = symmetriseErrors(
            uncertainty_total_plus, uncertainty_total_minus
        )
        error_up = sqrt(fit_error ** 2 + uncertainty_total_plus ** 2) * scale
        error_down = sqrt(fit_error ** 2 + uncertainty_total_minus ** 2) * scale
        plotStatErr.SetPointEYhigh(bin_i, fit_error * scale)
        plotStatErr.SetPointEYlow(bin_i, fit_error * scale)
        plotAsym.SetPointEYhigh(bin_i, error_up)
        plotAsym.SetPointEYlow(bin_i, error_down)

    gStyle.SetEndErrorSize(20)
    plotAsym.SetLineWidth(2)
    plotStatErr.SetLineWidth(2)
    hist_data.Draw("P")
    plotStatErr.Draw("same P")
    plotAsym.Draw("same P Z")
    legend.AddEntry(hist_data, "unfolded", "P")

    hist_measured = histograms["measured"]
    hist_measured.SetMarkerSize(1)
    hist_measured.SetMarkerStyle(20)
    hist_measured.SetMarkerColor(2)
    # hist_measured.Draw('same P')
    # legend.AddEntry(hist_measured, 'measured', 'P')

    for key, hist in sorted(histograms.iteritems()):
        if not "unfolded" in key and not "measured" in key:
            hist.SetLineStyle(7)
            hist.SetLineWidth(2)
            # setting colours
            if "POWHEG" in key or "matchingdown" in key:
                hist.SetLineColor(kBlue)
            elif "MADGRAPH" in key or "matchingup" in key:
                hist.SetLineColor(kRed + 1)
            elif "MCATNLO" in key or "scaleup" in key:
                hist.SetLineColor(kGreen - 3)
            elif "scaledown" in key:
                hist.SetLineColor(kMagenta + 3)
            hist.Draw("hist same")
            legend.AddEntry(hist, translate_options[key], "l")

    legend.Draw()

    mytext = TPaveText(0.5, 0.97, 1, 1.01, "NDC")
    channelLabel = TPaveText(0.18, 0.97, 0.5, 1.01, "NDC")
    if "electron" in histname:
        channelLabel.AddText("e, %s, %s, k = %s" % ("#geq 4 jets", b_tag_bins_latex[b_tag_bin], k_value))
    elif "muon" in histname:
        channelLabel.AddText("#mu, %s, %s, k = %s" % ("#geq 4 jets", b_tag_bins_latex[b_tag_bin], k_value))
    else:
        channelLabel.AddText("combined, %s, %s, k = %s" % ("#geq 4 jets", b_tag_bins_latex[b_tag_bin], k_value))
    mytext.AddText("CMS Preliminary, L = %.1f fb^{-1} at #sqrt{s} = 8 TeV" % (5.8))

    mytext.SetFillStyle(0)
    mytext.SetBorderSize(0)
    mytext.SetTextFont(42)
    mytext.SetTextAlign(13)

    channelLabel.SetFillStyle(0)
    channelLabel.SetBorderSize(0)
    channelLabel.SetTextFont(42)
    channelLabel.SetTextAlign(13)
    mytext.Draw()
    channelLabel.Draw()

    canvas.Modified()
    canvas.Update()

    path = save_path + "/" + variable + "/" + category
    make_folder_if_not_exists(path)
    canvas.SaveAs(path + "/" + histname + "_kv" + str(k_value) + ".png")
    canvas.SaveAs(path + "/" + histname + "_kv" + str(k_value) + ".pdf")
def make_plots_ROOT(histograms, category, save_path, histname, channel):
    global variable, translateOptions, k_value, b_tag_bin, maximum
    ROOT.TH1.SetDefaultSumw2(False)
    ROOT.gROOT.SetBatch(True)
    ROOT.gROOT.ProcessLine('gErrorIgnoreLevel = 1001;')
    plotting.setStyle()
    gStyle.SetTitleYOffset(2.)
    ROOT.gROOT.ForceStyle()
    canvas = Canvas(width=700, height=500)
    canvas.SetLeftMargin(0.18)
    canvas.SetBottomMargin(0.15)
    canvas.SetTopMargin(0.05)
    canvas.SetRightMargin(0.05)
    legend = plotting.create_legend(x0=0.6, y1=0.5)

    hist_data = histograms['unfolded']
    hist_data.GetXaxis().SetTitle(translate_options[variable] + ' [GeV]')
    hist_data.GetYaxis().SetTitle('#frac{1}{#sigma} #frac{d#sigma}{d' +
                                  translate_options[variable] + '} [GeV^{-1}]')
    hist_data.GetXaxis().SetTitleSize(0.05)
    hist_data.GetYaxis().SetTitleSize(0.05)
    hist_data.SetMinimum(0)
    hist_data.SetMaximum(maximum[variable])
    hist_data.SetMarkerSize(1)
    hist_data.SetMarkerStyle(8)
    plotAsym = TGraphAsymmErrors(hist_data)
    plotStatErr = TGraphAsymmErrors(hist_data)

    xsections = read_unfolded_xsections(channel)
    bins = variable_bins_ROOT[variable]
    assert (len(bins) == len(xsections['central']))

    for bin_i in range(len(bins)):
        scale = 1  # / width
        centralresult = xsections['central'][bin_i]
        fit_error = centralresult[1]
        uncertainty = calculateTotalUncertainty(xsections, bin_i)
        uncertainty_total_plus = uncertainty['Total+'][0]
        uncertainty_total_minus = uncertainty['Total-'][0]
        uncertainty_total_plus, uncertainty_total_minus = symmetriseErrors(
            uncertainty_total_plus, uncertainty_total_minus)
        error_up = sqrt(fit_error**2 + uncertainty_total_plus**2) * scale
        error_down = sqrt(fit_error**2 + uncertainty_total_minus**2) * scale
        plotStatErr.SetPointEYhigh(bin_i, fit_error * scale)
        plotStatErr.SetPointEYlow(bin_i, fit_error * scale)
        plotAsym.SetPointEYhigh(bin_i, error_up)
        plotAsym.SetPointEYlow(bin_i, error_down)

    gStyle.SetEndErrorSize(20)
    plotAsym.SetLineWidth(2)
    plotStatErr.SetLineWidth(2)
    hist_data.Draw('P')
    plotStatErr.Draw('same P')
    plotAsym.Draw('same P Z')
    legend.AddEntry(hist_data, 'unfolded', 'P')

    hist_measured = histograms['measured']
    hist_measured.SetMarkerSize(1)
    hist_measured.SetMarkerStyle(20)
    hist_measured.SetMarkerColor(2)
    #hist_measured.Draw('same P')
    #legend.AddEntry(hist_measured, 'measured', 'P')

    for key, hist in sorted(histograms.iteritems()):
        if not 'unfolded' in key and not 'measured' in key:
            hist.SetLineStyle(7)
            hist.SetLineWidth(2)
            # setting colours
            if 'POWHEG' in key or 'matchingdown' in key:
                hist.SetLineColor(kBlue)
            elif 'MADGRAPH' in key or 'matchingup' in key:
                hist.SetLineColor(kRed + 1)
            elif 'MCATNLO' in key or 'scaleup' in key:
                hist.SetLineColor(kGreen - 3)
            elif 'scaledown' in key:
                hist.SetLineColor(kMagenta + 3)
            hist.Draw('hist same')
            legend.AddEntry(hist, translate_options[key], 'l')

    legend.Draw()

    mytext = TPaveText(0.5, 0.97, 1, 1.01, "NDC")
    channelLabel = TPaveText(0.18, 0.97, 0.5, 1.01, "NDC")
    if 'electron' in histname:
        channelLabel.AddText(
            "e, %s, %s, k = %s" %
            ("#geq 4 jets", b_tag_bins_latex[b_tag_bin], k_value))
    elif 'muon' in histname:
        channelLabel.AddText(
            "#mu, %s, %s, k = %s" %
            ("#geq 4 jets", b_tag_bins_latex[b_tag_bin], k_value))
    else:
        channelLabel.AddText(
            "combined, %s, %s, k = %s" %
            ("#geq 4 jets", b_tag_bins_latex[b_tag_bin], k_value))
    mytext.AddText("CMS Preliminary, L = %.1f fb^{-1} at #sqrt{s} = 8 TeV" %
                   (5.8))

    mytext.SetFillStyle(0)
    mytext.SetBorderSize(0)
    mytext.SetTextFont(42)
    mytext.SetTextAlign(13)

    channelLabel.SetFillStyle(0)
    channelLabel.SetBorderSize(0)
    channelLabel.SetTextFont(42)
    channelLabel.SetTextAlign(13)
    mytext.Draw()
    channelLabel.Draw()

    canvas.Modified()
    canvas.Update()

    path = save_path + '/' + variable + '/' + category
    make_folder_if_not_exists(path)
    canvas.SaveAs(path + '/' + histname + '_kv' + str(k_value) + '.png')
    canvas.SaveAs(path + '/' + histname + '_kv' + str(k_value) + '.pdf')
def print_xsections_with_uncertainties(xsections, channel, toFile=True):
    global savePath, variable, k_value, met_type, b_tag_bin
    printout = "\n"
    printout += "=" * 60
    printout = "\n"
    printout += "Results for %s variable, %s channel, k-value %s, met type %s, %s b-tag region\n" % (
        variable,
        channel,
        k_value,
        met_type,
        b_tag_bin,
    )
    printout += "=" * 60
    printout += "\n"
    #    rows = {}
    printout += "%s bin & $\sigma_{meas}$ \\\\ \n" % variable
    printout += "\hline\n"
    uncertainties = {}
    header = "Uncertainty"

    bins = variable_bins_ROOT[variable]
    assert len(bins) == len(xsections["central"])

    for bin_i, variable_bin in enumerate(bins):
        header += "& %s bin %s" % (variable, variable_bin)
        centralresult = xsections["central"][bin_i]
        uncertainty = calculateTotalUncertainty(xsections, bin_i)
        uncertainty_total_plus = uncertainty["Total+"][0]
        uncertainty_total_minus = uncertainty["Total-"][0]
        uncertainty_total_plus, uncertainty_total_minus = symmetriseErrors(
            uncertainty_total_plus, uncertainty_total_minus
        )
        scale = 100
        central_measurement = centralresult[0]
        fit_error = centralresult[1]

        formatting = (
            variable_bins_latex[variable_bin],
            central_measurement * scale,
            fit_error * scale,
            uncertainty_total_plus * scale,
            uncertainty_total_minus * scale,
        )
        text = "%s & $%.2f \pm %.2f (fit)^{+%.2f}_{-%.2f} (sys) \cdot 10^{-2}$\\\\ \n" % formatting
        if doSymmetricErrors:
            relativeError = getRelativeError(central_measurement, fit_error + uncertainty_total_plus)
            formatting = (
                variable_bins_latex[variable_bin],
                central_measurement * scale,
                fit_error * scale,
                uncertainty_total_plus * scale,
            )
            text = (
                "%s & $\\left(%.2f \\pm %.2f \\text{ (fit)} \pm %.2f \\text{ (syst.)}\\right)" % formatting
                + "(%.2f" % (relativeError * 100)
                + "\%) \\times 10^{-2}\, \\GeV^{-1}$\\\\ \n"
            )
        printout += text
        for source in uncertainty.keys():
            unc_result = uncertainty[source]
            if not uncertainties.has_key(source):
                if source in metsystematics_sources:
                    uncertainties[source] = metsystematics_sources_latex[source] + " & "
                else:
                    uncertainties[source] = source + " & "
            relativeError = getRelativeError(centralresult[0], unc_result[0])
            #            text = ' $(%.2f \pm %.2f) \cdot 10^{-2} $ ' % (unc_result[0]*scale,unc_result[1]*scale) + '(%.2f' % (relativeError * 100) + '\%) &'
            text = "%.2f" % (relativeError * 100) + "\% &"
            #            text = ' $%.2f \pm %.2f $ ' % (unc_result[0]*scale,unc_result[1]*scale) + '(%.2f' % (relativeError * 100) + '\%) &'
            uncertainties[source] += text

    printout += "\\\\ \n"
    for source in sorted(uncertainties.keys()):
        value = uncertainties[source]
        value = value.rstrip("&")
        value += "\\\\ \n"
        printout += value

    make_folder_if_not_exists(savePath + "/" + variable)
    if toFile:
        output_file = open(
            savePath
            + "/"
            + variable
            + "/normalised_xsection_main_result_"
            + channel
            + "_"
            + met_type
            + "_kv"
            + str(k_value)
            + ".tex",
            "w",
        )
        output_file.write(printout)
        output_file.close()
    else:
        print printout