示例#1
0
def plot_pTs(pT_lower_cut=100, pT_upper_cut=10000):

    keywords = ['prescale', 'uncor_hardest_pT', 'cor_hardest_pT']

    properties = parse_file(input_analysis_file,
                            pT_lower_cut=pT_lower_cut,
                            pT_upper_cut=pT_upper_cut,
                            keywords_to_populate=keywords)

    uncorrected_pTs = properties['uncor_hardest_pT']
    corrected_pTs = properties['cor_hardest_pT']
    prescales = properties['prescale']

    corrected_pt_hist = Hist(100,
                             5,
                             1005,
                             title='Jet Energy Corrected',
                             markersize=3.0,
                             color='black')
    bin_width_corrected = (
        corrected_pt_hist.upperbound() -
        corrected_pt_hist.lowerbound()) / corrected_pt_hist.nbins()

    uncorrected_pt_hist = Hist(100,
                               5,
                               1005,
                               title='Jet Energy Uncorrected',
                               markersize=3.0,
                               color='orange')
    bin_width_uncorrected = (
        uncorrected_pt_hist.upperbound() -
        uncorrected_pt_hist.lowerbound()) / uncorrected_pt_hist.nbins()

    map(uncorrected_pt_hist.Fill, uncorrected_pTs, prescales)
    map(corrected_pt_hist.Fill, corrected_pTs, prescales)

    corrected_pt_hist.Scale(
        1.0 / (corrected_pt_hist.GetSumOfWeights() * bin_width_corrected))
    uncorrected_pt_hist.Scale(
        1.0 / (uncorrected_pt_hist.GetSumOfWeights() * bin_width_uncorrected))

    gs = gridspec.GridSpec(2, 1, height_ratios=[3, 1])

    ax0 = plt.subplot(gs[0])
    ax1 = plt.subplot(gs[1])

    data_plot = rplt.errorbar(corrected_pt_hist,
                              axes=ax0,
                              emptybins=False,
                              marker='o',
                              markersize=10,
                              pickradius=8,
                              capthick=5,
                              capsize=8,
                              elinewidth=5)
    uncorrected_data_plot = rplt.errorbar(uncorrected_pt_hist,
                                          axes=ax0,
                                          emptybins=False,
                                          marker='o',
                                          markersize=10,
                                          pickradius=8,
                                          capthick=5,
                                          capsize=8,
                                          elinewidth=5)

    data_x_errors, data_y_errors = [], []
    for x_segment in data_plot[2][0].get_segments():
        data_x_errors.append((x_segment[1][0] - x_segment[0][0]) / 2.)
    for y_segment in data_plot[2][1].get_segments():
        data_y_errors.append((y_segment[1][1] - y_segment[0][1]) / 2.)

    data_points_x = data_plot[0].get_xdata()
    data_points_y = data_plot[0].get_ydata()

    data_plot_points_x = []
    data_plot_points_y = []
    for i in range(0, len(data_points_x)):
        data_plot_points_x.append(data_points_x[i])
        data_plot_points_y.append(data_points_y[i])

    uncorrected_data_x_errors, uncorrected_data_y_errors = [], []
    for x_segment in uncorrected_data_plot[2][0].get_segments():
        uncorrected_data_x_errors.append(
            (x_segment[1][0] - x_segment[0][0]) / 2.)
    for y_segment in uncorrected_data_plot[2][1].get_segments():
        uncorrected_data_y_errors.append(
            (y_segment[1][1] - y_segment[0][1]) / 2.)

    uncorrected_data_points_x = uncorrected_data_plot[0].get_xdata()
    uncorrected_data_points_y = uncorrected_data_plot[0].get_ydata()

    uncorrected_data_plot_points_x = []
    uncorrected_data_plot_points_y = []
    for i in range(0, len(uncorrected_data_points_x)):
        uncorrected_data_plot_points_x.append(uncorrected_data_points_x[i])
        uncorrected_data_plot_points_y.append(uncorrected_data_points_y[i])

    data_to_data_y_err = [(b / m)
                          for b, m in zip(data_y_errors, data_plot_points_y)]
    data_to_data_x_err = [
        (b / m) for b, m in zip(data_x_errors, [1] * len(data_plot_points_y))
    ]

    uncorrected_to_corrected_y_err = [
        (b / m) for b, m in zip(uncorrected_data_y_errors, data_plot_points_y)
    ]
    uncorrected_to_corrected_x_err = [
        (b / m) for b, m in zip(uncorrected_data_x_errors, [1] *
                                len(data_plot_points_y))
    ]

    # Legends Begin.

    legend = ax0.legend(loc=1,
                        frameon=0,
                        fontsize=60,
                        bbox_to_anchor=[1.0, 1.0])
    ax0.add_artist(legend)

    extra = Rectangle((0, 0),
                      1,
                      1,
                      fc="w",
                      fill=False,
                      edgecolor='none',
                      linewidth=0)
    if pT_upper_cut != 10000:
        labels = [
            r"$ \textrm{Anti--}k_{t}\textrm{:}~R = 0.5$",
            r"$p_{T} \in [" + str(pT_lower_cut) + ", " + str(pT_upper_cut) +
            "]~\mathrm{GeV};\eta<2.4$"
        ]
    else:
        labels = [
            r"$ \textrm{Anti--}k_{t}\textrm{:}~R = 0.5$",
            r"$p_{T} > " + str(pT_lower_cut) + "~\mathrm{GeV};\eta<2.4$"
        ]
    ax0.legend([extra, extra],
               labels,
               loc=7,
               frameon=0,
               borderpad=0.1,
               fontsize=60,
               bbox_to_anchor=[0.92, 0.70])

    # Legends End.

    ax0.set_xlabel('$p_T~\mathrm{(GeV)}$', fontsize=75, labelpad=45)
    ax1.set_xlabel('$p_T~\mathrm{(GeV)}$', fontsize=75, labelpad=45)
    ax0.set_ylabel('$\mathrm{A.U.}$', fontsize=75, rotation=0, labelpad=75.)
    ax1.set_ylabel("Ratio           \nto           \n" + "Corrected" +
                   "           ",
                   fontsize=55,
                   rotation=0,
                   labelpad=115,
                   y=0.31)

    ab = AnnotationBbox(OffsetImage(read_png(
        get_sample_data("/home/aashish/root/macros/MODAnalyzer/mod_logo.png",
                        asfileobj=False)),
                                    zoom=0.15,
                                    resample=1,
                                    dpi_cor=1), (0.26, 0.93),
                        xycoords='figure fraction',
                        frameon=0)
    plt.gca().add_artist(ab)
    preliminary_text = "Prelim. (20\%)"
    plt.gcf().text(0.32,
                   0.9215,
                   preliminary_text,
                   fontsize=50,
                   weight='bold',
                   color='#444444',
                   multialignment='center')

    # Ratio Plot.
    uncorrected_pt_hist.Divide(corrected_pt_hist)
    corrected_pt_hist.Divide(corrected_pt_hist)

    rplt.errorbar(corrected_pt_hist,
                  xerr=data_to_data_x_err,
                  yerr=data_to_data_y_err,
                  axes=ax1,
                  emptybins=False,
                  marker='o',
                  markersize=10,
                  pickradius=8,
                  capthick=5,
                  capsize=8,
                  elinewidth=5)
    rplt.errorbar(uncorrected_pt_hist,
                  xerr=uncorrected_to_corrected_x_err,
                  yerr=uncorrected_to_corrected_y_err,
                  axes=ax1,
                  emptybins=False,
                  marker='o',
                  markersize=10,
                  pickradius=8,
                  capthick=5,
                  capsize=8,
                  elinewidth=5)

    ax0.set_yscale('log')

    ax0.autoscale(True)
    ax1.autoscale(True)

    ax0.set_ylim(10e-8, 0.5 * 10e-1)
    ax1.set_ylim(0., 2.)

    ax0.set_xlim(0, 1000)
    ax1.set_xlim(0, 1000)

    plt.gcf().set_size_inches(30, 30, forward=1)

    plt.sca(ax0)
    plt.gca().xaxis.set_minor_locator(MultipleLocator(25))
    plt.tick_params(which='major', width=5, length=25, labelsize=70)
    plt.tick_params(which='minor', width=3, length=15)

    plt.sca(ax1)
    plt.gca().xaxis.set_minor_locator(MultipleLocator(25))
    # plt.gca().yaxis.set_minor_locator(MultipleLocator(50))
    plt.tick_params(which='major', width=5, length=25, labelsize=70)
    plt.tick_params(which='minor', width=3, length=15)

    plt.tight_layout(pad=1.08, h_pad=1.08, w_pad=1.08)

    print "Printing pT spectrum with pT > " + str(
        pT_lower_cut) + " and pT < " + str(pT_upper_cut)

    plt.savefig("plots/Version 5/pT/data_pT_data_lower_" + str(pT_lower_cut) +
                "_pT_upper_" + str(pT_upper_cut) + ".pdf")
    # plt.show()
    plt.clf()
示例#2
0
def plot_trigger_efficiency_curves(trigger_1, trigger_2, pT_upper_limit=800):

    properties = parse_file_turn_on('/home/aashish/turn_on.dat')
    # properties = parse_file_turn_on('./trigger_proper_turn_on.dat')

    event_numbers = properties['event_number']

    pTs = properties['corrected_hardest_pts']
    trigger_names = properties['trigger_names']
    prescales = properties['prescale']

    colors = ['magenta', 'blue', 'orange', 'green', 'black', 'red']
    expected_trigger_names = [
        "HLT\_Jet180U", "HLT\_Jet140U", "HLT\_Jet100U", "HLT\_Jet70U",
        "HLT\_Jet50U", "HLT\_Jet30U"
    ]

    color = colors[expected_trigger_names.index(trigger_1.replace("_", "\_"))]

    pt_hist_trigger_1 = Hist(100,
                             0,
                             pT_upper_limit,
                             title=trigger_1[4:],
                             color=color,
                             markersize=1.0,
                             linewidth=5)
    pt_hist_trigger_2 = Hist(100,
                             0,
                             pT_upper_limit,
                             title=trigger_2[4:],
                             color=color,
                             markersize=1.0,
                             linewidth=5)

    for i in range(0, len(pTs)):
        if trigger_1 in trigger_names[i]:
            pt_hist_trigger_1.Fill(pTs[i], prescales[i])

        # The len thingy is to make sure trigger names like HLT_Jet15U_HcalNoiseFiltered_v3 are excluded.
        # if trigger_2 in trigger_names[i] and len(trigger_names[i]) > (len(trigger_2) + 3):
        if trigger_2 in trigger_names[i]:
            pt_hist_trigger_2.Fill(pTs[i], prescales[i])

    pt_hist_trigger_1.Divide(pt_hist_trigger_2)

    rplt.errorbar(pt_hist_trigger_1,
                  color=color,
                  markersize=10,
                  pickradius=8,
                  capthick=5,
                  capsize=8,
                  elinewidth=5)

    data_plot = rplt.errorbar(pt_hist_trigger_1,
                              color=color,
                              markersize=10,
                              pickradius=8,
                              capthick=5,
                              capsize=8,
                              elinewidth=5)

    data_points_x = data_plot[0].get_xdata()
    data_points_y = np.log(data_plot[0].get_ydata())

    # print data_points_y[0:5]

    fitted_poly_coeffs = np.polyfit(data_points_x, data_points_y, 1)

    print fitted_poly_coeffs

    fitted_poly = np.polynomial.Polynomial(fitted_poly_coeffs)

    x = np.arange(120, 200, 5)
    plt.plot(x, fitted_poly(x), lw=5, color="red")

    plt.gca().xaxis.set_tick_params(width=5, length=20, labelsize=70)
    plt.gca().yaxis.set_tick_params(width=5, length=20, labelsize=70)

    ab = AnnotationBbox(OffsetImage(read_png(
        get_sample_data(
            "/home/aashish/root-6.04.06/macros/MODAnalyzer/mod_logo.png",
            asfileobj=False)),
                                    zoom=0.15,
                                    resample=1,
                                    dpi_cor=1), (0.23, 0.895),
                        xycoords='figure fraction',
                        frameon=0)
    plt.gca().add_artist(ab)
    plt.gcf().text(0.29,
                   0.885,
                   "Prelim. (20\%)",
                   fontsize=50,
                   weight='bold',
                   color='#444444',
                   multialignment='center')

    plt.gcf().set_snap(1)

    # Horizontal Line.
    plt.plot(list(pt_hist_trigger_1.x()),
             [1] * len(list(pt_hist_trigger_1.x())),
             color="black",
             linewidth=5,
             linestyle="dashed")

    if trigger_1 == "HLT_L1Jet6U":
        lower_pT = 37
    elif trigger_1 == "HLT_Jet15U":
        lower_pT = 56
    elif trigger_1 == "HLT_Jet30U":
        lower_pT = 84
    elif trigger_1 == "HLT_Jet50U":
        lower_pT = 114
    elif trigger_1 == "HLT_Jet70U":
        lower_pT = 153
    elif trigger_1 == "HLT_Jet100U":
        lower_pT = 196
    else:
        lower_pT = 0

    if lower_pT != 0:
        # CMS Vertical line.
        plt.plot([lower_pT, lower_pT], [plt.gca().get_ylim()[0], 1.],
                 color=color,
                 linewidth=3,
                 linestyle="dashed")

    # # MOD Vertical line.
    # efficient_pt_x = 0.0
    # efficient_pt_y = 0.0

    # efficient_pt_x_s = []
    # efficient_pt_y_s = []

    # distance_to_previous_point_close_to_one = 0

    # for i in range(0, len(list(pt_hist_trigger_1.x()))):
    #   if abs(list(pt_hist_trigger_1.y())[i] - 1.00) < 0.1:

    #     if distance_to_previous_point_close_to_one > 25:
    #       # Last point close to one too far away.
    #       # Empty the lists.
    #       efficient_pt_x_s, efficient_pt_y_s = [], []

    #     efficient_pt_x_s.append(list(pt_hist_trigger_1.x())[i])
    #     efficient_pt_y_s.append(list(pt_hist_trigger_1.y())[i])
    #     distance_to_previous_point_close_to_one = 0

    #   else:
    #     distance_to_previous_point_close_to_one += 1

    #   if len(efficient_pt_x_s) > 75:
    #     efficient_pt_x = efficient_pt_x_s[0]
    #     efficient_pt_y = efficient_pt_y_s[0]
    #     break

    # mod_efficient_pTs = [325, 260, 196, 153, 114, 84, 50, 32]
    # mod_efficient_pT = mod_efficient_pTs[expected_trigger_names.index(trigger_1.replace("_", "\_"))]

    # plt.plot([mod_efficient_pT, mod_efficient_pT], [plt.gca().get_ylim()[0], 1.], color="purple", linewidth=3, linestyle="dashed")

    # if lower_pT != 0:
    #   plt.gca().annotate("CMS\n" + str(lower_pT) + " GeV", xy=(lower_pT, 1.), xycoords='data', xytext=(-100, 250),  textcoords='offset points', color=color, size=40, va="center", ha="center", arrowprops=dict(arrowstyle="simple", facecolor=color, zorder=9999, connectionstyle="angle3,angleA=0,angleB=90") )

    # plt.gca().annotate("MOD\n" + str(int(mod_efficient_pT)) + " GeV", xy=(mod_efficient_pT, 1.), xycoords='data', xytext=(250, 200), textcoords='offset points', color="purple", size=40, va="center", ha="center", arrowprops=dict(arrowstyle="simple", facecolor="purple", zorder=9999, connectionstyle="angle3,angleA=45,angleB=-90") )

    plt.yscale('log')
    plt.gca().set_ylim(plt.gca().get_ylim()[0], 100)

    plt.legend(frameon=0)

    plt.xlabel('$p_T~\mathrm{(GeV)}$', fontsize=55, rotation=0)
    plt.ylabel('$\mathrm{A.U.}$', fontsize=75, rotation=0, labelpad=50.)

    plt.gcf().set_size_inches(30, 21.4285714, forward=1)
    plt.gcf().set_snap(True)

    plt.tight_layout(pad=1.08, h_pad=1.08, w_pad=1.08)

    plt.savefig("plots/Version 4/trigger_efficiency_fit/efficiency_curves_" +
                trigger_1 + ".pdf")
    # plt.show()
    plt.clf()
示例#3
0
def makeComparisionPage(histodicts, fileNames, fileDescr, separateFiles):
    """
    Prepares a canvas comparing multiple histograms: plotting all in one pad and their ratios in the second
    """
    import rootpy
    from rootpy.plotting import Hist, Canvas, Legend
    import ROOT
    from ROOT import gPad
    log = logging.getLogger('pyroplot')
    cans = {}
    colors = [
        ROOT.kBlue, ROOT.kRed + 1, ROOT.kViolet - 1, ROOT.kOrange + 7,
        ROOT.kGreen - 7, ROOT.kOrange - 6, ROOT.kPink - 9, ROOT.kTeal - 6,
        ROOT.kBlue + 4, ROOT.kAzure + 2
    ]
    log.info("Drawing histograms ..")
    # prepare set of histograms to compare to the reference on (the first)
    # loop over the reference set of histos (sorted by key):
    for hidx, refname in enumerate(sorted(histodicts[0].keys())):
        # prepare canvas
        if separateFiles:
            log.debug("Creating new canvas with index %d." % (hidx))
            c = Canvas(600, 270)
            cans[refname] = c
            c.Divide(3, 1)
            c.cd(1)
        if not separateFiles and (hidx) % 4 == 0:
            log.debug("Creating new canvas with index %d." % (hidx / 3))
            # start a new canvas
            c = Canvas(600, 800)
            cans[refname] = c
            c.Divide(3, 4)
        # prepare histograms for drawing
        log.debug("Drawing histogram #" + str(hidx + 1) + " (" + refname +
                  ") on canvas #" + str(len(cans)))
        hists = []
        ratiohists = []
        hiter = iter(histodicts)
        # special treatment for tprofile: prepare the reference projection for the ratio
        if histodicts[0][refname].__class__.__name__ == "Profile":
            refProj = histodicts[0][refname].ProjectionX()
            refProj.SetName("reference_proj")
        for idx, h in enumerate(hiter):
            # make sure we have this histogram loaded:
            if not refname in h:
                continue
            # access the corresponding histogram of the other files at the same hidx as used for ref
            h[refname].color = colors[idx]
            h[refname].linestyle = idx
            hists.append(h[refname])
            # prepare ratio is this is not the first (i.e. reference) histogram
            if idx:
                # special treatment for TProfile:
                if h[refname].__class__.__name__ == "Profile":
                    myratio = Hist(h[refname].nbins(), h[refname].lowerbound(),
                                   h[refname].upperbound())  #dummy hist
                    myratioproj = h[refname].ProjectionX()
                    myratioproj.SetName("cmp_hist_proj" + str(idx))
                    try:
                        myratio.divide(myratioproj, refProj)
                    except rootpy.ROOTError, e:
                        log.error(
                            "Calculation of ratio for histogram %s caused ROOTError exception ('%s')"
                            % (h[refname].GetName(), e.msg))
                        break
                    myratio.color = colors[idx]
                else:
                    myratio = h[refname].clone(
                    )  # make sure that the ratio has the right type
                    try:
                        myratio.Divide(
                            h[refname],
                            histodicts[0][refname])  # divide by reference hist
                    except rootpy.ROOTError, e:
                        log.error(
                            "Calculation of ratio for histogram %s caused ROOTError exception ('%s')"
                            % (h[refname].GetName(), e.msg))
                        break
                myratio.yaxis.SetTitle("(h_{cmp} - h_{ref})/h_{ref}")
                myratio.SetTitle("ratio to reference")
                myratio.SetMaximum(2)
                myratio.SetMinimum(0)
                myratio.SetStats(0)
                ratiohists.append(myratio)