示例#1
0
def test_errorbar():
    from rootpy.plotting import root2matplotlib as rplt
    h = Hist(100, -5, 5)
    h.FillRandom('gaus')
    g = Graph(h)
    rplt.errorbar(g)
    rplt.errorbar(h)
def draw_result(result, axes):
    graph = result["unfolded"]
    graph_with_systematics = result["unfolded_with_systematics"]
    madgraph = result["MADGRAPH"]
    powheg = result["POWHEG"]
    mcatnlo = result["MCATNLO"]
    # styles
    graph.markersize = 2
    graph.marker = "o"
    graph_with_systematics.markersize = 2
    graph_with_systematics.marker = "o"
    powheg.linestyle = "longdashdot"
    powheg.SetLineColor(kBlue)
    madgraph.linestyle = "solid"
    madgraph.SetLineColor(kRed + 1)
    mcatnlo.linestyle = "dotted"
    mcatnlo.SetLineColor(kMagenta + 3)

    rplt.errorbar(graph, xerr=False, emptybins=False, axes=axes, elinewidth=2, capsize=10, capthick=2, zorder=6)
    rplt.errorbar(
        graph_with_systematics,
        xerr=False,
        emptybins=False,
        axes=axes,
        elinewidth=2,
        capsize=0,
        zorder=5,
        label="unfolded data",
    )
    rplt.hist(madgraph, axes=axes, label="MADGRAPH", zorder=1)
    rplt.hist(powheg, axes=axes, label="POWHEG", zorder=2)
    rplt.hist(mcatnlo, axes=axes, label="MCATNLO", zorder=3)
示例#3
0
def plot_difference(difference, centre_of_mass, channel, variable, k_value, tau_value, output_folder, output_formats):
    stats = len(difference)
    values, errors = [], []
    add_value = values.append
    add_error = errors.append
    for value, error in difference:
        add_value(value)
        add_error(error)
    min_x, max_x = min(values), max(values)
    abs_max = int(max(abs(min_x), max_x))
    #    n_x_bins = 2 * abs_max * 10
    h_values = Hist(100, -abs_max, abs_max)
    fill_value = h_values.Fill
    for value in values:
        fill_value(value)

    plt.figure(figsize=(16, 16), dpi=200, facecolor="white")
    axes = plt.axes()
    h_values.SetMarkerSize(CMS.data_marker_size)
    rplt.errorbar(h_values, xerr=True, emptybins=True, axes=axes)

    channel_label = latex_labels.channel_latex[channel]
    var_label = latex_labels.variables_latex[variable]
    title_template = "SVD unfolding performance for unfolding of {variable}\n"
    title_template += "$\sqrt{{s}}$ = {com} TeV, {channel}, {value}"
    title = title_template.format(
        variable=var_label, com=centre_of_mass, channel=channel_label, value=get_value_title(k_value, tau_value)
    )

    plt.xlabel("$\mathrm{unfolded} - \mathrm{true}$", CMS.x_axis_title)
    plt.ylabel("number of toy experiments", CMS.y_axis_title)
    plt.tick_params(**CMS.axis_label_major)
    plt.tick_params(**CMS.axis_label_minor)
    plt.title(title, CMS.title)
    plt.tight_layout()

    for save in output_formats:
        plt.savefig(output_folder + "difference." + save)

    min_x, max_x = min(errors), max(errors)
    h_errors = Hist(1000, min_x, max_x)
    fill_value = h_errors.Fill
    for error in errors:
        fill_value(error)

    plt.figure(figsize=(16, 16), dpi=200, facecolor="white")
    axes = plt.axes()
    h_errors.SetMarkerSize(CMS.data_marker_size)
    rplt.errorbar(h_errors, xerr=True, emptybins=True, axes=axes)

    plt.xlabel("$\sigma(\mathrm{unfolded} - \mathrm{true})$", CMS.x_axis_title)
    plt.ylabel("number of toy experiments", CMS.y_axis_title)
    plt.tick_params(**CMS.axis_label_major)
    plt.tick_params(**CMS.axis_label_minor)
    plt.title(title_template, CMS.title)

    plt.tight_layout()

    for save in output_formats:
        plt.savefig(output_folder + "difference_errors." + save)
def plot_h_pull(h_pull, centre_of_mass, channel, variable, k_value, tau_value,
                output_folder, output_formats, stats=19596500, name='pull_test'):
    h_pull.Fit('gaus', 'WWSQ')
    fit_pull = h_pull.GetFunction('gaus')
    fr = fitResults(fit_pull)
    mean = (fr.mean, fr.meanError)
    sigma = (fr.sigma, fr.sigmaError)
    print('Fit data for "' + name + '"')
    print(str(fr))

    plt.figure(figsize=(16, 16), dpi=200, facecolor='white')
    axes = plt.axes()
    h_pull.SetMarkerSize(CMS.data_marker_size)
    rplt.errorbar(h_pull, xerr=True, emptybins=True, axes=axes)

    # *4 for a very smooth curve
    x = numpy.linspace(
        fit_pull.GetXmin(), fit_pull.GetXmax(), fit_pull.GetNpx() * 4)
    function_data = frompyfunc(fit_pull.Eval, 1, 1)
    plot(x, function_data(x), axes=axes, color='red', linewidth=2)

    plt.xlabel(
        '$\\frac{N^{\mathrm{unfolded}} - N^{\mathrm{true}}}{\sigma}$',
        CMS.x_axis_title)
    plt.ylabel('number of toy experiments', CMS.y_axis_title)
    plt.tick_params(**CMS.axis_label_major)
    plt.tick_params(**CMS.axis_label_minor)

    channel_label = latex_labels.channel_latex[channel]
    var_label = latex_labels.variables_latex[variable]
    title_template = 'Pull distribution for unfolding of {variable}\n'
    title_template += '$\sqrt{{s}}$ = {com} TeV, {channel}, {value}'
    title = title_template.format(
        variable=var_label,
        com=centre_of_mass,
        channel=channel_label,
        value=get_value_title(k_value, tau_value)
    )
    plt.title(title, CMS.title)

    text_template = 'entries = {stats}\n'
    text_template += 'mean = ${mean} \pm  {mean_error}$\n'
    text_template += '$\sigma = {sigma} \pm  {sigma_error}$'
    text = text_template.format(
        stats=stats,
        mean=round(mean[0], 2),
        mean_error=round(mean[1], 2),
        sigma=round(sigma[0], 2),
        sigma_error=round(sigma[1], 2),
    )
    axes.text(0.6, 0.8, text,
              verticalalignment='bottom', horizontalalignment='left',
              transform=axes.transAxes,
              color='black', fontsize=40, bbox=dict(facecolor='white', edgecolor='none', alpha=0.5))
    plt.tight_layout()

    for save in output_formats:
        plt.savefig(output_folder + name + '.' + save)

    return fr
def plot_difference(difference):
    global output_folder, output_formats
    stats = len(difference)    
    values, errors = [],[]
    add_value = values.append
    add_error = errors.append
    for value, error in difference:
        add_value(value)
        add_error(error)
    min_x, max_x = min(values), max(values)
    abs_max = int(max(abs(min_x), max_x))
#    n_x_bins = 2 * abs_max * 10    
    h_values = Hist(100, -abs_max, abs_max)
    fill_value = h_values.Fill
    for value in values:
        fill_value(value)
        
    plt.figure(figsize=(16, 16), dpi=200, facecolor='white')
    axes = plt.axes()
    h_values.SetMarkerSize(CMS.data_marker_size)
    rplt.errorbar(h_values, xerr=True, emptybins=True, axes=axes)

    channel_label = ''
    if channel == 'electron':
        channel_label = 'e+jets'
    else:
        channel_label = '$\mu$+jets'
    title_template = 'SVD unfolding performance for $%s$ \n $\sqrt{s}$ = %d TeV, %s, k value = %d' % ( latex_labels.variables_latex[variable], centre_of_mass, channel_label, k_value )
    
    plt.xlabel('$\mathrm{unfolded} - \mathrm{true}$', CMS.x_axis_title)
    plt.ylabel('number of toy experiments', CMS.y_axis_title)
    plt.tick_params(**CMS.axis_label_major)
    plt.tick_params(**CMS.axis_label_minor)
    plt.title(title_template, CMS.title)
    plt.tight_layout()  
    
    for save in output_formats:
        plt.savefig(output_folder + 'difference_stats_' + str(stats) + '.' + save)   
        
    min_x, max_x = min(errors), max(errors)
    h_errors = Hist(1000, min_x, max_x)
    fill_value = h_errors.Fill
    for error in errors:
        fill_value(error)  
        
    plt.figure(figsize=(16, 16), dpi=200, facecolor='white')
    axes = plt.axes()
    h_errors.SetMarkerSize(CMS.data_marker_size)
    rplt.errorbar(h_errors, xerr=True, emptybins=True, axes=axes)
    
    plt.xlabel('$\sigma(\mathrm{unfolded} - \mathrm{true})$', CMS.x_axis_title)
    plt.ylabel('number of toy experiments', CMS.y_axis_title)
    plt.tick_params(**CMS.axis_label_major)
    plt.tick_params(**CMS.axis_label_minor)
    plt.title(title_template, CMS.title)

    plt.tight_layout()  
    
    for save in output_formats:
        plt.savefig(output_folder + 'difference_errors_stats_' + str(stats) + '.' + save)  
def checkOnMC(unfolding, method):
    global bins, nbins
    RooUnfold.SVD_n_toy = 1000
    pulls = []
    for sub in range(1,9):
        inputFile2 = File('../data/unfolding_merged_sub%d.root' % sub, 'read')
        h_data = asrootpy(inputFile2.unfoldingAnalyserElectronChannel.measured.Rebin(nbins, 'measured', bins))
        nEvents = inputFile2.EventFilter.EventCounter.GetBinContent(1)
        lumiweight = 164.5 * 5050 / nEvents
#        print sub, nEvents
        h_data.Scale(lumiweight)
        doUnfoldingSequence(unfolding, h_data, method, '_sub%d' %sub)
        pull = unfolding.pull_inputErrorOnly()
#        unfolding.printTable()
        pulls.append(pull)
        unfolding.Reset()
    allpulls = []

    for pull in pulls:
        allpulls.extend(pull)
    h_allpulls = Hist(100,-30,30)
    filling = h_allpulls.Fill
    for entry in allpulls:
        filling(entry)
    fit = h_allpulls.Fit('gaus', 'WWS')
    h_fit = asrootpy(h_allpulls.GetFunction("gaus").GetHistogram())
    canvas = Canvas(width=1600, height=1000)
    canvas.SetLeftMargin(0.15)
    canvas.SetBottomMargin(0.15)
    canvas.SetTopMargin(0.10)
    canvas.SetRightMargin(0.05)
    h_allpulls.Draw()
    fit.Draw('same')
    canvas.SaveAs('plots/Pull_allBins_withFit.png')
    
    
    
    plt.figure(figsize=(16, 10), dpi=100)
    rplt.errorbar(h_allpulls, label=r'Pull distribution for all bins',  emptybins=False)
    rplt.hist(h_fit, label=r'fit')
    plt.xlabel('(unfolded-true)/error', CMS.x_axis_title)
    plt.ylabel('entries', CMS.y_axis_title)
    plt.title('Pull distribution for all bins', CMS.title)
    plt.tick_params(**CMS.axis_label_major)
    plt.tick_params(**CMS.axis_label_minor)
    plt.legend(numpoints=1)
    plt.savefig('plots/Pull_allBins.png')
    
    #individual bins
    for bin_i in range(nbins):
        h_pull = Hist(100,-30,30)
        for pull in pulls:
            h_pull.Fill(pull[bin_i])
        plt.figure(figsize=(16, 10), dpi=100)
        rplt.errorbar(h_pull, label=r'Pull distribution for bin %d' % (bin_i + 1), emptybins=False)
        plt.xlabel('(unfolded-true)/error', CMS.x_axis_title)
        plt.ylabel('entries', CMS.y_axis_title)
        plt.title('Pull distribution for  bin %d' % (bin_i + 1), CMS.title)
        plt.savefig('Pull_bin_%d.png' % (bin_i + 1))
def make_plots_matplotlib(histograms, category, output_folder, histname):
    global variable, variables_latex_matplotlib, measurements_latex_matplotlib, k_value
    
    channel = 'electron'
    if 'electron' in histname:
        channel = 'electron'
    elif 'muon' in histname:
        channel = 'muon'
    else:
        channel = 'combined'
        
    # plot with matplotlib
    hist_data = histograms['unfolded']
    hist_measured = histograms['measured']
    
    hist_data.markersize = 2
    hist_measured.markersize = 2
    hist_data.marker = 'o'
    hist_measured.marker = 'o'
    hist_measured.color = 'red'

    plt.figure(figsize=(14, 10), dpi=200, facecolor='white')
    axes = plt.axes()
    axes.minorticks_on()
    
    plt.xlabel('$%s$ [GeV]' % variables_latex_matplotlib[variable], CMS.x_axis_title)
    plt.ylabel(r'$\frac{1}{\sigma} \times \frac{d\sigma}{d' + variables_latex_matplotlib[variable] + '} \left[\mathrm{GeV}^{-1}\\right]$', CMS.y_axis_title)
    plt.tick_params(**CMS.axis_label_major)
    plt.tick_params(**CMS.axis_label_minor)

    rplt.errorbar(hist_data, axes=axes, label='unfolded', xerr=False)
    rplt.errorbar(hist_measured, axes=axes, label='measured', xerr=False)
    
    for key, hist in histograms.iteritems():
        if not 'unfolded' in key and not 'measured' in key:
            hist.linestyle = 'dashed'
            hist.linewidth = 2
#            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(kMagenta + 3)
            elif 'scaledown' in key:
                hist.SetLineColor(kGreen)
            rplt.hist(hist, axes=axes, label=measurements_latex_matplotlib[key])
    
    plt.legend(numpoints=1, loc='upper right', prop=CMS.legend_properties)
    plt.title(get_cms_labels_matplotlib(channel), CMS.title)
    plt.tight_layout()

    path = output_folder + str(measurement_config.centre_of_mass) + 'TeV/' + variable + '/' + category
    make_folder_if_not_exists(path)
    for output_format in output_formats:
        plt.savefig(path + '/' + histname + '_kv' + str(k_value) + '.' + output_format)
示例#8
0
def make_plot( histogram, histogram_label, histogram_properties = Histogram_properties(),
                                 save_folder = 'plots/',
                                 save_as = ['pdf', 'png'],
                                 normalise = False,
                                 draw_errorbar = False,
                                 draw_legend = True
                                 ):
    
    histogram.SetTitle( histogram_label )
#    histogram.SetMarkerSize(CMS.data_marker_size)
    # to be changed
    histogram.fillcolor = '0.75'
    histogram.fillstyle = 'solid'
    if normalise:
        histogram.Scale( 1 / histogram.Integral() )
    
    # plot with matplotlib
    plt.figure( figsize = CMS.figsize, dpi = CMS.dpi, facecolor = CMS.facecolor )
    axes = plt.axes()
    
    if draw_errorbar:
        rplt.errorbar( histogram, xerr = False, emptybins = False, axes = axes, elinewidth = 2, capsize = 10, capthick = 2 )
    else:
        rplt.hist( histogram )
    

    if draw_legend:
        plt.legend( numpoints = 1, loc = histogram_properties.legend_location, prop = CMS.legend_properties )
    
    adjust_axis_limits( axes, histogram_properties )

    x_limits = histogram_properties.x_limits
    y_limits = histogram_properties.y_limits
    if len( x_limits ) == 2:
        axes.set_xlim( xmin = x_limits[0], xmax = x_limits[1] )
    if len( y_limits ) == 2:
        axes.set_ylim( ymin = y_limits[0], ymax = y_limits[1] )
    
    if histogram_properties.set_log_y:
        axes.set_yscale( 'log', nonposy = "clip" )
        if not len( histogram_properties.y_limits ) == 2:  # if not user set y-limits, calculate the limits from the tuple values
            value_range = sorted( list( histogram.y() ) )
            for i, value in enumerate(value_range):
                if value == 0:
                    del value_range[i]
            axes.set_ylim( ymin = min(value_range)/10, ymax = max(value_range)*10 )

    set_labels( plt, histogram_properties )

    if CMS.tight_layout:
        plt.tight_layout()
    
    for save in save_as:
        plt.savefig( save_folder + histogram_properties.name + '.' + save )
    plt.close()
def plot_difference(difference):
    stats = len(difference)    
    values, errors = [],[]
    add_value = values.append
    add_error = errors.append
    for value, error in difference:
        add_value(value)
        add_error(error)
    min_x, max_x = min(values), max(values)
    abs_max = int(max(abs(min_x), max_x))
#    n_x_bins = 2 * abs_max * 10    
    h_values = Hist(100, -abs_max, abs_max)
    fill_value = h_values.Fill
    for value in values:
        fill_value(value)
        
    plt.figure(figsize=(16, 16), dpi=200, facecolor='white')
    axes = plt.axes()
    h_values.SetMarkerSize(CMS.data_marker_size)
    rplt.errorbar(h_values, xerr=True, emptybins=True, axes=axes)
    
    plt.xlabel('$\mathrm{unfolded} - \mathrm{true}$', CMS.x_axis_title)
    plt.ylabel('number of toy experiments', CMS.y_axis_title)
    plt.tick_params(**CMS.axis_label_major)
    plt.tick_params(**CMS.axis_label_minor)
    plt.title('SVD unfolding performance', CMS.title)
    plt.tight_layout()  
    
    save_folder = 'plots/'
    save_as = ['png', 'pdf']
    for save in save_as:
        plt.savefig(save_folder + 'difference_stats_' + str(stats) + '.' + save)   
        
    min_x, max_x = min(errors), max(errors)
    h_errors = Hist(1000, min_x, max_x)
    fill_value = h_errors.Fill
    for error in errors:
        fill_value(error)  
        
    plt.figure(figsize=(16, 16), dpi=200, facecolor='white')
    axes = plt.axes()
    h_errors.SetMarkerSize(CMS.data_marker_size)
    rplt.errorbar(h_errors, xerr=True, emptybins=True, axes=axes)
    
    plt.xlabel('$\sigma(\mathrm{unfolded} - \mathrm{true})$', CMS.x_axis_title)
    plt.ylabel('number of toy experiments', CMS.y_axis_title)
    plt.tick_params(**CMS.axis_label_major)
    plt.tick_params(**CMS.axis_label_minor)
    plt.title('SVD unfolding performance', CMS.title)
    plt.tight_layout()  
    
    save_folder = 'plots/'
    save_as = ['png', 'pdf']
    for save in save_as:
        plt.savefig(save_folder + 'difference_errors_stats_' + str(stats) + '.' + save)  
def make_control_region_comparison(control_region_1, control_region_2,
                                   name_region_1, name_region_2, variable='mttbar',
                                   x_label=r'$m(\mathrm{t}\bar{\mathrm{t}})$ [GeV]',
                                   x_min=300, x_max=1800,
                                   y_label='arbitrary units/ 50 GeV', y_min = 0, y_max = 0.15):
    #make copies in order not to mess with existing histograms
    control_region_1 = deepcopy(control_region_1)
    control_region_2 = deepcopy(control_region_2)
    # normalise as we are comparing shapes
    control_region_1.Scale(1 / control_region_1.Integral())
    control_region_2.Scale(1 / control_region_2.Integral())
    
    ratio = control_region_1.Clone('ratio')
    ratio.Divide(control_region_2)
    ratio.SetMarkerSize(3)
    
    control_region_1.fillcolor = 'yellow'
    control_region_2.fillcolor = 'red'
    control_region_1.fillstyle = 'solid'
    control_region_2.fillstyle = 'solid'
    
    # plot with matplotlib
    plt.figure(figsize=(16, 16), dpi=200, facecolor='white')
    gs = gridspec.GridSpec(2, 1, height_ratios=[5, 1]) 
    ax0 = plt.subplot(gs[0])
    ax0.minorticks_on()
    
    rplt.hist(control_region_1, axes=ax0)
    rplt.hist(control_region_2, axes=ax0, alpha=0.5)
    
    plt.ylabel(y_label, CMS.y_axis_title)
    plt.tick_params(**CMS.axis_label_major)
    plt.tick_params(**CMS.axis_label_minor)
    plt.title(get_title(variable), CMS.title)
    plt.legend([name_region_1 + ' (1)', name_region_2 + ' (2)'], numpoints=1, loc='upper right', prop=CMS.legend_properties)
    ax0.set_xlim(xmin=x_min, xmax=x_max)
    ax0.set_ylim(ymin=y_min, ymax=y_max)
    plt.setp(ax0.get_xticklabels(), visible=False)
    
    ax1 = plt.subplot(gs[1])
    ax1.minorticks_on()
    ax1.grid(True, 'major', linewidth=1)
    ax1.yaxis.set_major_locator(MultipleLocator(1.0))
    ax1.yaxis.set_minor_locator(MultipleLocator(0.5))
    plt.tick_params(**CMS.axis_label_major)
    plt.tick_params(**CMS.axis_label_minor)
    plt.xlabel(x_label, CMS.x_axis_title)
    plt.ylabel('(1)/(2)', CMS.y_axis_title)
    rplt.errorbar(ratio, xerr=True, emptybins=False, axes=ax1)
    ax1.set_xlim(xmin=x_min, xmax=x_max)
    ax1.set_ylim(ymin= -0.5, ymax=4)
    plt.tight_layout()
    plt.savefig(variable + '_shape_comparision.png')  
    plt.savefig(variable + '_shape_comparision.pdf')  
def draw(hist, ncols=1, nrows=1, cell=1, fig=None, figsize=(10, 5)):
    if fig is None:
        fig = plt.figure(figsize=figsize, dpi=100, facecolor='white')
    else:
        plt.figure(fig.number)
    subplot = fig.add_subplot(nrows, ncols, cell)
    subplot.ticklabel_format(style='sci', axis='y', scilimits=(0, 0))
    if isinstance(hist, r.TH2):
        rplt.hist2d(hist, axes=subplot)
    else:
        rplt.errorbar([hist], xerr=False, emptybins=False)
    # plt.show()
    return fig
示例#12
0
def draw(hist, ncols=1, nrows=1, cell=1, fig=None, figsize=goldenaspect(3), **kwargs):
    if fig is None:
        fig = plt.figure(figsize=figsize, dpi=1200, facecolor="white")
    else:
        plt.figure(fig.number)
    subplot = fig.add_subplot(nrows, ncols, cell)
    # subplot.ticklabel_format(style='sci', axis='y', scilimits=(0, 0))
    # subplot.ticklabel_format(scilimits=(0, 0))
    if isinstance(hist, R.TH2):
        rplt.hist2d(hist, axes=subplot, **kwargs)
    else:
        rplt.errorbar([hist], xerr=False, emptybins=False, **kwargs)
    # plt.show()
    return fig
def plot_central_and_systematics( channel, systematics, exclude = [], suffix = 'altogether' ):
    global variable, k_values, b_tag_bin, met_type

    plt.figure( figsize = ( 16, 16 ), dpi = 200, facecolor = 'white' )
    axes = plt.axes()
    axes.minorticks_on()
    
    hist_data_central = read_xsection_measurement_results( 'central', channel )[0]['unfolded_with_systematics']
    hist_data_central.markersize = 2  # points. Imagine, tangible units!
    hist_data_central.marker = 'o'
    
    
    plt.xlabel( '$%s$ [GeV]' % variables_latex[variable], CMS.x_axis_title )
    plt.ylabel( r'$\frac{1}{\sigma}  \frac{d\sigma}{d' + variables_latex[variable] + '} \left[\mathrm{GeV}^{-1}\\right]$', CMS.y_axis_title )
    plt.tick_params( **CMS.axis_label_major )
    plt.tick_params( **CMS.axis_label_minor )

    rplt.errorbar( hist_data_central, axes = axes, label = 'data', xerr = True )

    for systematic in sorted( systematics ):
        if systematic in exclude or systematic == 'central':
            continue

        hist_data_systematic = read_xsection_measurement_results( systematic, channel )[0]['unfolded']
        hist_data_systematic.markersize = 2
        hist_data_systematic.marker = 'o'
        colour_number = systematics.index( systematic ) + 2
        if colour_number == 10:
            colour_number = 42
        hist_data_systematic.SetMarkerColor( colour_number )
        if 'PDF' in systematic:
            rplt.errorbar( hist_data_systematic, axes = axes, label = systematic.replace( 'Weights_', ' ' ), xerr = None )
        elif met_type in systematic:
            rplt.errorbar( hist_data_systematic, axes = axes, label = met_systematics_latex[systematic.replace( met_type, '' )], xerr = None )
        else:
            rplt.errorbar( hist_data_systematic, axes = axes, label = measurements_latex[systematic], xerr = None )
            
    plt.legend( numpoints = 1, loc = 'center right', prop = {'size':25}, ncol = 2 )
    label, channel_label = get_cms_labels( channel )
    plt.title( label, CMS.title )
    # CMS text
    # note: fontweight/weight does not change anything as we use Latex text!!!
    plt.text(0.95, 0.95, r"\textbf{CMS}", transform=axes.transAxes, fontsize=42,
        verticalalignment='top',horizontalalignment='right')
    # channel text
    axes.text(0.95, 0.90, r"\emph{%s}" %channel_label, transform=axes.transAxes, fontsize=40,
        verticalalignment='top',horizontalalignment='right')
    plt.tight_layout()

    
    path = output_folder + str( measurement_config.centre_of_mass_energy ) + 'TeV/' + variable
    make_folder_if_not_exists( path )
    for output_format in output_formats:
        filename = path + '/normalised_xsection_' + channel + '_' + suffix + '_kv' + str( k_values[channel] ) + '.' + output_format
        if channel == 'combined':
            filename = filename.replace( '_kv' + str( k_values[channel] ), '' )
        plt.savefig( filename ) 

    plt.close()
    gc.collect()
示例#14
0
def load_root_file_to_hists(root_filename):
	# with root_open(root_filename) as f:
	# 	tree = f.main_tree

	# 	for x in tree:
	# 		print x

	b = pickle.load( open("plot.p", "rb") )

	print b.GetEntries()

	rplt.errorbar(b)

	plt.show()
def make_jet_response_plot(input_file, response):
    global output_folder, output_formats, suffix
    jet_response_plot = asrootpy(input_file.Get(response))

    x_limits = [0, 200]
    y_limits = [0.8, 1.2]
    if '_eta' in response:
        x_limits = [-3, 3]
        x_title = '$\eta$(reco jet)'
    else:
        x_title = '$p_{\mathrm{T}}$(reco jet) [GeV]'

    y_title = '$p_{\mathrm{T}}$(reco jet)/$p_{\mathrm{T}}$(HLT jet)'
    save_as_name = response

    plt.figure(figsize=(20, 16), dpi=200, facecolor='white')

    ax0 = plt.axes()
    ax0.minorticks_on()
    ax0.grid(True, 'major', linewidth=2)
    ax0.grid(True, 'minor')
    plt.tick_params(**CMS.axis_label_major)
    plt.tick_params(**CMS.axis_label_minor)
    ax0.xaxis.set_major_formatter(FormatStrFormatter('%d'))
    ax0.yaxis.set_major_formatter(FormatStrFormatter('%.1f'))
    ax0.xaxis.labelpad = 12
    ax0.yaxis.labelpad = 12

    if '_prof' in response:
        rplt.errorbar(jet_response_plot, xerr=True, emptybins=True, axes=ax0)
    else:
        im = rplt.imshow(jet_response_plot, axes=ax0, cmap = cm.Blues)
        #plt.colorbar(im)
    ax0.set_xlim(x_limits)
    ax0.set_ylim(y_limits)

    plt.tick_params(**CMS.axis_label_major)
    plt.tick_params(**CMS.axis_label_minor)

    plt.xlabel(x_title, CMS.x_axis_title)
    plt.ylabel(y_title, CMS.y_axis_title)
    plt.title(r'e+jets, CMS Preliminary, $\sqrt{s}$ = 8 TeV', CMS.title)
    if '_prof' in response:
        plt.legend(['data'], numpoints=1, loc='lower right', prop=CMS.legend_properties)

    plt.tight_layout()
    
    for output_format in output_formats:
        plt.savefig(output_folder + save_as_name + '_' + suffix + '.' + output_format)  
def saveUnfolding(unfolding, outputfile, **kwargs):
    if not unfolding.unfolded_data:
        print 'Run unfold function first'
        return
    setDrawStyles(unfolding)
    # TODO: change this to be more generic
    plt.figure(figsize=(16, 10), dpi=100)
    rplt.hist(unfolding.truth, label=r'SM $\mathrm{t}\bar{\mathrm{t}}$ truth', stacked=False)
    rplt.hist(unfolding.data, label=r'$\mathrm{t}\bar{\mathrm{t}}$ from fit', stacked=False)
    rplt.errorbar(unfolding.unfolded_data, label='unfolded')
    plt.xlabel('$E_{\mathrm{T}}^{miss}$')
    plt.ylabel('Events')
    plt.title('Unfolding')
    plt.legend()
    plt.savefig(outputfile)
def plot_h_pull(h_pull, centre_of_mass, channel, variable, k_value, output_folder, output_formats, stats = 19596500, name = 'pull_test'):
    h_pull.Fit('gaus', 'WWSQ')
    fit_pull = h_pull.GetFunction('gaus')
    mean = (fit_pull.GetParameter(1), fit_pull.GetParError(1))
    sigma = (fit_pull.GetParameter(2), fit_pull.GetParError(2))
    print 'Fit data for "' + name + '"'
    print 'A:', fit_pull.GetParameter(0), '+-', fit_pull.GetParError(0)
    print 'mean:', fit_pull.GetParameter(1), '+-', fit_pull.GetParError(1)
    print 'sigma:', fit_pull.GetParameter(2), '+-', fit_pull.GetParError(2)

    fr = fitResults( fit_pull.GetParameter(0), fit_pull.GetParError(0), fit_pull.GetParameter(1), fit_pull.GetParError(1), fit_pull.GetParameter(2), fit_pull.GetParError(2))

    plt.figure(figsize=(16, 16), dpi=200, facecolor='white')
    axes = plt.axes()
    h_pull.SetMarkerSize(CMS.data_marker_size)
    rplt.errorbar(h_pull, xerr=True, emptybins=True, axes=axes)
    
    x = numpy.linspace(fit_pull.GetXmin(), fit_pull.GetXmax(), fit_pull.GetNpx()*4)#*4 for a very smooth curve
    function_data = frompyfunc(fit_pull.Eval, 1, 1)
    plot(x, function_data(x), axes=axes, color='red', linewidth=2)
    
    
    plt.xlabel('$\\frac{N^{\mathrm{unfolded}} - N^{\mathrm{true}}}{\sigma}$', CMS.x_axis_title)
    plt.ylabel('number of toy experiments', CMS.y_axis_title)
    plt.tick_params(**CMS.axis_label_major)
    plt.tick_params(**CMS.axis_label_minor)

    channel_label = ''
    if channel == 'electron':
        channel_label = 'e+jets'
    elif channel == 'muon':
        channel_label = '$\mu$+jets'
    else:
        channel_label = '$e/\mu$+jets combined'
    title_template = 'Pull distribution for unfolding of $%s$ \n $\sqrt{s}$ = %d TeV, %s, k value = %d' % ( latex_labels.variables_latex[variable], centre_of_mass, channel_label, k_value )
    plt.title(title_template, CMS.title)
    
    text = 'entries = %d \n mean = $%.2f \pm %.2f$ \n $\sigma = %.2f \pm %.2f$' % (stats, mean[0], mean[1], sigma[0], sigma[1])
    axes.text(0.6, 0.8, text,
        verticalalignment='bottom', horizontalalignment='left',
        transform=axes.transAxes,
        color='black', fontsize=40, bbox=dict(facecolor='white', edgecolor='none', alpha=0.5))
    plt.tight_layout()  
    
    for save in output_formats:
        plt.savefig(output_folder + name + '.' + save)

    return fr
def saveClosureTest(unfolding, outputfile, **kwargs):
    
    if not unfolding.unfolded_closure:
        print 'Run closureTest function first'
        return
    setDrawStyles(unfolding)
    # TODO: change this to be more generic
    plt.figure(figsize=(16, 10), dpi=100)
    rplt.hist(unfolding.truth, label=r'truth', stacked=False)
    rplt.hist(unfolding.measured, label=r'measured', stacked=False)
    rplt.errorbar(unfolding.unfolded_closure, label='unfolded')
    plt.xlabel('$E_{\mathrm{T}}^{miss}$')
    plt.ylabel('Events')
    plt.title('Unfolding closure test')
    plt.legend()
    plt.savefig('Unfolding_' + unfolding.method + '_closureTest.png')
def _plot_x_projection(hist_2D, yrange_px, lable, ax, lns, exclude_peak,
                       plot_fit, dphi_extra):
    #import ipdb; ipdb.set_trace()
    sub_px = extract_yield(hist_2D, exclude_peak)[0]
    sub_px.set_title(lable)
    if dphi_extra:
        dphi_extra.color = plt.rcParams.get('axes.color_cycle')[-1]
        lns.append(rplt.errorbar(dphi_extra, xerr=False, label=dphi_extra.title,
                                 marker='s', markersize=3))
        lower = dphi_extra.FindBin(pi/2)
        upper = dphi_extra.FindBin(3*pi/2)
        x = list(dphi_extra.x())[lower-1:upper]  # index != bin
        y1 = list(dphi_extra.y())[lower-1:upper]
        y2 = list(sub_px.y())[lower-1:upper]
        plt.fill_between(x, y1, y2, color='grey', alpha='0.5')
        diff_hist = asrootpy(sub_px - dphi_extra)
        err = Double()
        ryield = diff_hist.IntegralAndError(lower, upper, err, 'width')
        print 'excess ridge yield per rad: ', ryield, err
    lns.append(rplt.errorbar(sub_px, xerr=False, marker='d', markersize=4))
    if plot_fit:
        s_cos = sub_px.GetFunction("cos")
        d_cos = sub_px.GetFunction("double_cos")
        if False:
            print 'Fit parameters:'
            print 'single cosine: ', s_cos.GetExpFormula()
            print 'normalized chi^2: ', s_cos.GetChisquare() / s_cos.GetNDF()
            print 'Parameters: ', s_cos.GetParameter(0), s_cos.GetParameter(1)
            print 'double cosine: ', d_cos.GetExpFormula()
            print 'normalized chi^2: ', d_cos.GetChisquare() / d_cos.GetNDF()
            print 'Parameters: ', d_cos.GetParameter(0), d_cos.GetParameter(1)
        xs = np.arange(list(sub_px.x())[0], list(sub_px.x())[-1], 0.05)
        lns.append(
            plt.plot(xs, [s_cos.Eval(x) for x in xs], label='single cosing',)[0])
        lns.append(
            plt.plot(xs, [d_cos.Eval(x) for x in xs], label='double cosine')[0])
    ax.set_ylabel(
        r'$\frac{1}{N_{tr}}\frac{dN_{as}}{d\Delta \varphi}$'
        '[rad$^{-1}$]')
    ax.yaxis.labelpad = -0
    if isinstance(yrange_px, (list, tuple)):
        ax.set_ylim(yrange_px)
    else:
        ax.set_ylim(0.985*min(sub_px.y()), 1.015*max(sub_px.y()))
def make_control_region_data_mc_comparision(histograms, histogram_name,
                                            variable, x_label=r'$m(\mathrm{t}\bar{\mathrm{t}})$ [GeV]',
                                            x_min=300, x_max=1800,
                                            y_label='Events/50 GeV'):
    qcd = histograms['QCD'][histogram_name]
    ttjet = histograms['TTJet'][histogram_name]
    wjets = histograms['WJets'][histogram_name]
    zjets = histograms['ZJets'][histogram_name]
    single_top = histograms['SingleTop'][histogram_name]
    other = ttjet + wjets + zjets + single_top
    data = histograms['data'][histogram_name]
    data.SetMarkerSize(3)
    qcd.SetTitle('QCD from data')
    other.SetTitle('Combined other background')
    data.SetTitle('Data')
    
    qcd.fillcolor = 'yellow'
    other.fillcolor = 'red'
    
    qcd.fillstyle = 'solid'
    other.fillstyle = 'solid'
    stack = HistStack()
    stack.Add(other)
    stack.Add(qcd)
    
    # plot with matplotlib
    plt.figure(figsize=(16, 12), dpi=200, facecolor='white')
    axes = plt.axes()
    
    rplt.hist(stack, stacked=True, axes=axes)
    rplt.errorbar(data, xerr=False, emptybins=False, axes=axes)
    
    plt.xlabel(x_label, CMS.x_axis_title)
    plt.ylabel(y_label, CMS.y_axis_title)
    plt.tick_params(**CMS.axis_label_major)
    plt.tick_params(**CMS.axis_label_minor)
    plt.title(get_title(variable), CMS.title)
    plt.legend(numpoints=1, loc='upper right', prop=CMS.legend_properties)
    axes.set_xlim(xmin=x_min, xmax=x_max)
    axes.set_ylim(ymin=0)
    plt.tight_layout()
    plt.savefig(variable + '.png')  
    plt.savefig(variable + '.pdf')  
示例#21
0
文件: plotlib.py 项目: jpata/tthbb13
def draw_shape(f, samples, hn, **kwargs):
    rebin = kwargs.get("rebin", 1)

    hs = []
    for s in samples:
        h = f.get(s[0] + hn).Clone()
        h.Scale(1.0 / h.Integral())
        h.rebin(rebin)
        h.title = s[1]
        hs += [h]

    coloriter = iter(plt.cm.jet(np.linspace(0,1,len(hs))))

    for h in hs:
        h.color = next(coloriter)
        errorbar(h)
    plt.legend()
    for h in hs:
        hist(h, lw=1, ls="-")
示例#22
0
def plot_central_and_systematics_matplotlib(channel, systematics, exclude=[], suffix='altogether'):
    global variable, variables_latex_matplotlib, k_value, b_tag_bin

    plt.figure(figsize=(14, 10), dpi=200, facecolor='white')
    axes = plt.axes()
    axes.minorticks_on()
    
    hist_data_central = read_xsection_measurement_results('central', channel)[0]['unfolded']
    hist_data_central.markersize = 2#points. Imagine, tangible units!
    hist_data_central.marker = 'o'
    
    
    plt.xlabel('$%s$ [GeV]' % variables_latex_matplotlib[variable], CMS.x_axis_title)
    plt.ylabel(r'$\frac{1}{\sigma} \times \frac{d\sigma}{d' + variables_latex_matplotlib[variable] + '} \left[\mathrm{GeV}^{-1}\\right]$', CMS.y_axis_title)
    plt.tick_params(**CMS.axis_label_major)
    plt.tick_params(**CMS.axis_label_minor)

    rplt.errorbar(hist_data_central, axes=axes, label='data',xerr=True)

    for systematic in systematics:
        if systematic in exclude or systematic == 'central':
            continue

        hist_data_systematic = read_xsection_measurement_results(systematic, channel)[0]['unfolded']
        hist_data_systematic.markersize = 2
        hist_data_systematic.marker = 'o'
        colour_number = systematics.index(systematic)+1
        if colour_number == 10:
            colour_number = 42
        hist_data_systematic.SetMarkerColor(colour_number)
        rplt.errorbar(hist_data_systematic, axes=axes, label=systematic.replace('_',' '),
                      xerr=False)
            
    plt.legend(numpoints=1, loc='upper right', prop={'size': 24}, ncol = 2)
    plt.title(get_cms_labels_matplotlib(channel), CMS.title)
    plt.tight_layout()

    
    path = output_folder + str(measurement_config.centre_of_mass) + 'TeV/' + variable
    make_folder_if_not_exists(path)
    for output_format in output_formats:
        plt.savefig(path + '/normalised_xsection_' + channel + '_' + suffix + '_kv' + str(k_value) + '.' + output_format) 
def draw_pair(constructed, real, systematic):
    fig = plt.figure(figsize=CMS.figsize, dpi=CMS.dpi, facecolor=CMS.facecolor)
    axes = plt.axes([0.15, 0.15, 0.8, 0.8])
    axes.xaxis.set_minor_locator(AutoMinorLocator())
    axes.yaxis.set_minor_locator(AutoMinorLocator())
    axes.tick_params(which='major', labelsize=15, length=8)
    axes.tick_params(which='minor', length=4)
    axes.set_xlim(xmin=0, xmax=250)
    
    constructed.markersize=1.2
    constructed.markercolor = 'green'
    constructed.linecolor = 'green'
    real.linecolor = 'red'
    constructed.SetTitle('constructed')
    real.SetTitle('real')
    
    rplt.errorbar(constructed, xerr=False, emptybins=False, axes=axes)
    rplt.hist(real)
    
    plt.xlabel('MET [GeV]', CMS.x_axis_title)
    plt.ylabel('normalised to unit area', CMS.y_axis_title)
    plt.legend(numpoints=1, prop=CMS.legend_properties)
    plt.savefig('validation_' + systematic + '.png')
def draw_result( result, axes ):
    graph = result['unfolded']
    graph_with_systematics = result['unfolded_with_systematics']
    madgraph = result['MADGRAPH']
    powheg = result['POWHEG']
    mcatnlo = result['MCATNLO']
    # styles
    graph.markersize = 2
    graph.marker = 'o'
    graph_with_systematics.markersize = 2
    graph_with_systematics.marker = 'o'
    powheg.linestyle = 'longdashdot'
    powheg.SetLineColor( kBlue )
    madgraph.linestyle = 'solid'
    madgraph.SetLineColor( kRed + 1 )
    mcatnlo.linestyle = 'dotted'
    mcatnlo.SetLineColor( kMagenta + 3 )
    
    
    rplt.errorbar( graph, xerr = None, emptybins = False, axes = axes, elinewidth = 2, capsize = 10, capthick = 2, zorder = 6)
    rplt.errorbar( graph_with_systematics, xerr = None, emptybins = False, axes = axes, elinewidth = 2, capsize = 0, zorder = 5, label = 'unfolded data')
    rplt.hist( madgraph, axes = axes, label = 'MADGRAPH', zorder = 1 )
    rplt.hist( powheg, axes = axes, label = 'POWHEG', zorder = 2 )
    rplt.hist( mcatnlo, axes = axes, label = 'MCATNLO', zorder = 3 )
def plot_h_pull(h_pull, stats = 19596500, name = 'pull_test'):
    h_pull.Fit('gaus', 'WWSQ')
    fit_pull = h_pull.GetFunction('gaus')
    mean = (fit_pull.GetParameter(1), fit_pull.GetParError(1))
    sigma = (fit_pull.GetParameter(2), fit_pull.GetParError(2))
    print 'Fit data for "' + name + '"'
    print 'A:', fit_pull.GetParameter(0), '+-', fit_pull.GetParError(0)
    print 'mean:', fit_pull.GetParameter(1), '+-', fit_pull.GetParError(1)
    print 'sigma:', fit_pull.GetParameter(2), '+-', fit_pull.GetParError(2)
    
    plt.figure(figsize=(16, 16), dpi=200, facecolor='white')
    axes = plt.axes()
    h_pull.SetMarkerSize(CMS.data_marker_size)
    rplt.errorbar(h_pull, xerr=True, emptybins=True, axes=axes)
    
    x = numpy.linspace(fit_pull.GetXmin(), fit_pull.GetXmax(), fit_pull.GetNpx()*4)#*4 for a very smooth curve
    function_data = frompyfunc(fit_pull.Eval, 1, 1)
    plot(x, function_data(x), axes=axes, color='red', linewidth=2)
    
    
    plt.xlabel('$\\frac{\mathrm{unfolded} - \mathrm{true}}{\sigma}$', CMS.x_axis_title)
    plt.ylabel('number of toy experiments', CMS.y_axis_title)
    plt.tick_params(**CMS.axis_label_major)
    plt.tick_params(**CMS.axis_label_minor)
    plt.title('Pull distribution for SVD unfolding', CMS.title)
    text = 'entries = %d \n mean = $%.2f \pm %.2f$ \n $\sigma = %.2f \pm %.2f$' % (stats, mean[0], mean[1], sigma[0], sigma[1])
    axes.text(0.6, 0.8, text,
        verticalalignment='bottom', horizontalalignment='left',
        transform=axes.transAxes,
        color='black', fontsize=40, bbox=dict(facecolor='white', edgecolor='none', alpha=0.5))
    plt.tight_layout()  
    
    save_folder = 'plots/'
    save_as = ['png', 'pdf']
    for save in save_as:
        plt.savefig(save_folder + name + '.' + save)        
示例#26
0
def trigger_turn_on_curves_half1():

	mod_hists = parsed_linear[0]

	print(mod_hists.keys())

        colors = ["#999999", 'red', "#f781bf",  "#a65628", "#99cc00",
                  "#ff7f00", "#984ea3", "#4daf4a", "#377eb8",
                  "#e41a1c",'#8da0cb',  '#66c2a5', '#fc8d62'][:7]
	labels = [ '$ p_T^{\mathrm{Gen}} \in$ [15,30] GeV',
                   '$ p_T^{\mathrm{Gen}} \in$ [30,50] GeV',
                   '$ p_T^{\mathrm{Gen}} \in$ [50,80] GeV',
                   '$ p_T^{\mathrm{Gen}} \in$ [80,120] GeV',
                   '$ p_T^{\mathrm{Gen}} \in$ [120,170] GeV',
                   '$ p_T^{\mathrm{Gen}} \in$ [170,300] GeV',
                   '$ p_T^{\mathrm{Gen}} \in$ [300,470] GeV',
                   '$ p_T^{\mathrm{Gen}} \in$ [470,600] GeV',
                   '$ p_T^{\mathrm{Gen}} \in$ [600,800] GeV',
                   '$ p_T^{\mathrm{Gen}} \in$ [800,1000] GeV',
                   '$ p_T^{\mathrm{Gen}} \in$ [1000,1400] GeV',
                   '$ p_T^{\mathrm{Gen}} \in$ [1400,1800] GeV',
                   '$ p_T^{\mathrm{Gen}} \ge$ 1800 GeV'][:7]
	hist_labels = ['QCD_Pt-15to30_TuneZ2_7TeV_pythia6',
                       'QCD_Pt-30to50_TuneZ2_7TeV_pythia6',
                       'QCD_Pt-50to80_TuneZ2_7TeV_pythia6',
                       'QCD_Pt-80to120_TuneZ2_7TeV_pythia6',
                       'QCD_Pt-120to170_TuneZ2_7TeV_pythia6',
                       'QCD_Pt-170to300_TuneZ2_7TeV_pythia6',
                       'QCD_Pt-300to470_TuneZ2_7TeV_pythia6',
                       'QCD_Pt-470to600_TuneZ2_7TeV_pythia6',
                       'QCD_Pt-600to800_TuneZ2_7TeV_pythia6',
                       'QCD_Pt-800to1000_TuneZ2_7TeV_pythia6',
                       'QCD_Pt-1000to1400_TuneZ2_7TeV_pythia6',
                       'QCD_Pt-1400to1800_TuneZ2_7TeV_pythia6',
                       'QCD_Pt-1800_TuneZ2_7TeV_pythia6'][:7]
	colors.reverse()
	labels.reverse()
	hist_labels.reverse()


        print(len(colors), len(labels), len(hist_labels))

	for i in range( len(hist_labels)):
		
		hist = normalize_hist( mod_hists[hist_labels[i]].hist() )
		print(hist_labels[i])
		#hist = mod_hists[hist_labels[i]].hist()

		n_bins = hist.nbins()

		#print(n_bins)

		# Loop through those bins.
		for j in range(n_bins):
			current_bin_x = hist.GetBinCenter(j)
			current_bin_y = hist.GetBinContent(j),
			#print(current_bin_x, current_bin_y)

			"""
			if current_bin_x < lower_pTs[i]:
				hist.SetBinContent(j, 0.)
                        """

		hist.SetColor(colors[i])
		hist.SetTitle(labels[i])

		rplt.errorbar(hist, zorder=range(len(hist_labels))[len(hist_labels) - i - 1],
                              emptybins=False, xerr=1, yerr=1, ls='None', marker='o',
                              markersize=10, pickradius=8, capthick=5, capsize=8, elinewidth=5, alpha=1.0)
		print(i)


	extra = Rectangle((0, 0), 1, 1, fc="w", fill=False, edgecolor='none', linewidth=0)
	handles = [extra]
	labels = ["Pythia 6 Tune Z2 (Simulated) \n" + "AK5; $\left| \eta \\right| < 2.4$"]

	
	info_legend = plt.gca().legend(handles, labels, loc=7, frameon=0, borderpad=0.1, fontsize=59, bbox_to_anchor=[0.52, 0.9])

	plt.gca().add_artist(info_legend)


	plt.gca().set_xlabel("Hardest Jet $p_T$ [GeV]", fontsize=80, labelpad=50)
	plt.gca().set_ylabel("Cross Section [pb] ", fontsize=80, labelpad=25)

	plt.gca().add_artist(logo_box(0.12, 0.985))

	plt.gca().xaxis.set_minor_locator(MultipleLocator(10))
	plt.gca().set_yscale('log')

	
	handles, labels = plt.gca().get_legend_handles_labels()

	legend = plt.legend(handles[::-1], labels[::-1],  frameon=0, fontsize=55, bbox_to_anchor=[0.99, 0.99])

	ax = plt.gca().add_artist(legend)

	outside_text = plt.gca().legend( [extra], ["CMS 2011 Open Data"], frameon=0, borderpad=0, fontsize=55, bbox_to_anchor=(1.0, 1.005), loc='lower right')
	plt.gca().add_artist(outside_text)


	plt.autoscale()
	plt.gca().set_ylim(1e-3, 1e9)
	plt.gca().set_xlim(0, 700)


	
	plt.tick_params(which='major', width=5, length=25, labelsize=70)
	plt.tick_params(which='minor', width=3, length=15)

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

	plt.tight_layout()

	plt.savefig(default_dir + "qcd_all_datasets_hardest_pT_half1.pdf")

	plt.clf()
示例#27
0
def drawWithErrors2Combined(h, h_sys, h2, h2_sys, xlow, xhigh, logx, ylow,
                            yhigh, ylog, xTitle, yTitle, title, comment, file,
                            iS, ij, **kwargs):
    print("DrawWithErrors2Combined")
    ax = plt.gca()
    ax.set_xlim([xlow, xhigh])
    ax.set_ylim([ylow, yhigh])
    ax.set_xlabel(xTitle,
                  fontsize=labelsize)  #Add x-axis labels for bottom row
    ax.set_ylabel(yTitle,
                  fontsize=labelsize)  #Add x-axis labels for bottom row
    h.SetMarkerColor('black')
    h.SetLineColor('black')
    if ('pythiaW' in kwargs):
        pythiaW = kwargs.get('pythiaW')
        for x, c, l in zip(pythiaW, ("black", "red", "blue", "green"),
                           ('-', '--', '-.', ':')):
            hPythiaW = x[0]
            hPythiaW.SetMarkerColor(c)
            hPythiaW.SetLineColor(c)
            hPythiaW.SetMarkerStyle(25)
            print(x[1])
            plot = rplt.errorbar(hPythiaW,
                                 xerr=False,
                                 yerr=False,
                                 emptybins=False,
                                 fillstyle='none',
                                 axes=ax)
            line1, = plt.plot([1, 2, 3], label=x[1], linestyle=l, color=c)
            line = plot.get_children()[0]
            line.set_markerfacecolor('none')
            line.set_markeredgecolor('none')
            line.set_drawstyle('default')
            line.set_linestyle(l)
            line.set_color(c)

    if ('pythiaN' in kwargs):
        pythiaN = kwargs.get('pythiaN')
        for x, c, l in zip(pythiaN, ("black", "red", "blue", "green"),
                           ('-', '--', '-.', ':')):
            hPythiaN = x[0]
            hPythiaN.SetMarkerColor(c)
            hPythiaN.SetLineColor(c)
            hPythiaN.SetMarkerStyle(24)
            plot = rplt.errorbar(hPythiaN,
                                 xerr=False,
                                 yerr=False,
                                 emptybins=False,
                                 fillstyle='none',
                                 axes=ax,
                                 label="_{}".format(x[1]))
            line = plot.get_children()[0]
            line.set_markerfacecolor('none')
            line.set_markeredgecolor('none')
            line.set_drawstyle('default')
            line.set_linestyle(l)
            line.set_color(c)

    if ('pythiaN' in kwargs):
        h2.SetMarkerColor('red')
        h2.SetLineColor('red')
        h2.SetMarkerStyle(25)
        h.SetMarkerStyle(24)
        plot1 = rplt.errorbar(h2,
                              xerr=False,
                              emptybins=False,
                              axes=ax,
                              label='ALICE wide')
        plot2 = rplt.errorbar(h,
                              xerr=False,
                              emptybins=False,
                              axes=ax,
                              label='ALICE Narrow')
        line = plot1.get_children()[0]
        #line.set_markerfacecolor('none')
        line.set_markeredgecolor('red')
        line = plot2.get_children()[0]
        #line.set_markerfacecolor('none')
        line.set_markeredgecolor('black')
    elif ('jussiW' in kwargs):
        h2.SetMarkerColor('red')
        h2.SetLineColor('red')
        h2.SetMarkerStyle(25)
        h.SetMarkerStyle(24)
        plot1 = rplt.errorbar(h2,
                              xerr=False,
                              emptybins=False,
                              axes=ax,
                              label=r'Jet $j_\mathrm{T}$ Wide')
        plot2 = rplt.errorbar(h,
                              xerr=False,
                              emptybins=False,
                              axes=ax,
                              label=r'Jet $j_\mathrm{T}$ Narrow')
        line = plot1.get_children()[0]
        #line.set_markerfacecolor('none')
        line.set_markeredgecolor('red')
        line = plot2.get_children()[0]
        #line.set_markerfacecolor('none')
        line.set_markeredgecolor('black')
    else:
        h2.SetMarkerColor('red')
        h2.SetLineColor('red')
        h2.SetMarkerStyle(25)
        h.SetMarkerStyle(24)
        plot1 = rplt.errorbar(h2,
                              xerr=False,
                              emptybins=False,
                              axes=ax,
                              label='Wide')
        plot2 = rplt.errorbar(h,
                              xerr=False,
                              emptybins=False,
                              axes=ax,
                              label='Narrow')
        line = plot1.get_children()[0]
        #line.set_markerfacecolor('none')
        line.set_markeredgecolor('red')
        line = plot2.get_children()[0]
        #line.set_markerfacecolor('none')
        line.set_markeredgecolor('black')

    if ('jussiW' in kwargs):
        hJussiW = kwargs.get('jussiW')
        hJussiW.SetMarkerColor('red')
        hJussiW.SetLineColor('red')
        hJussiW.SetMarkerStyle(25)
        plot = rplt.errorbar(hJussiW,
                             xerr=False,
                             emptybins=False,
                             fillstyle='none',
                             axes=ax,
                             label=r'Dihadron $j_\mathrm{T}$ Wide')
        line = plot.get_children()[0]
        line.set_markerfacecolor('none')
        line.set_markeredgecolor('red')
    if ('jussiN' in kwargs):
        hJussiN = kwargs.get('jussiN')
        hJussiN.SetMarkerColor('black')
        hJussiN.SetLineColor('black')
        hJussiN.SetMarkerStyle(24)
        plot = rplt.errorbar(hJussiN,
                             xerr=False,
                             emptybins=False,
                             fillstyle='none',
                             axes=ax,
                             label=r'Dihadron $j_\mathrm{T}$ Narrow')
        line = plot.get_children()[0]
        line.set_markerfacecolor('none')
        line.set_markeredgecolor('black')

    print("Errorboxes")
    errorboxes = []
    n = h_sys.GetN()
    xs = h_sys.GetX()
    ys = h_sys.GetY()
    xerrs = h_sys.GetEX()
    yerrs = h_sys.GetEY()
    for x in (xs, ys, xerrs, yerrs):
        x.SetSize(n)
    yeC = kwargs.get('narrowE', 0)
    for x, y, xe, ye in zip(xs, ys, xerrs, yerrs):
        if (yeC > 0):
            ye2 = yeC * y
            ye = math.sqrt(ye**2 + ye2**2)
        rect = Rectangle((x - boxwidth, y - ye), boxwidth * 2, ye * 2)
        errorboxes.append(rect)

    errorboxes2 = []
    n = h2_sys.GetN()
    xs = h2_sys.GetX()
    ys = h2_sys.GetY()
    xerrs = h2_sys.GetEX()
    yerrs = h2_sys.GetEY()
    for x in (xs, ys, xerrs, yerrs):
        x.SetSize(n)

    yeC = kwargs.get('wideE', 0)
    for x, y, xe, ye in zip(xs, ys, xerrs, yerrs):
        if (yeC > 0):
            ye2 = yeC * y
            ye = math.sqrt(ye**2 + ye2**2)
        rect = Rectangle((x - boxwidth, y - ye), boxwidth * 2, ye * 2)
        errorboxes2.append(rect)

    pc = PatchCollection(errorboxes,
                         facecolor='0.65',
                         alpha=0.6,
                         edgecolor='None')
    ax.add_collection(pc)
    pc2 = PatchCollection(errorboxes2,
                          facecolor='0.65',
                          alpha=0.6,
                          edgecolor='None')
    ax.add_collection(pc2)

    print("({} - {})/9.0 + {} is {}".format(yhigh, ylow, ylow,
                                            (yhigh - ylow) / 9.0 + ylow))
    if ('titleLoc' in kwargs):
        x_tit, y_tit = kwargs.get('titleLoc')
        ax.text(x_tit,
                y_tit,
                title + '\n' + d['system'] + '\n' + d['jettype'] + '\n' +
                d['jetalg'] + '\n' + d['cut'],
                fontsize=10)

    else:
        if ('jussiW' not in kwargs):
            ax.text((xhigh - xlow) * 0.1 + xlow,
                    4 * (yhigh - ylow) / 5.0 + ylow,
                    d['system'] + '\n' + d['jettype'] + '\n' + d['jetalg'] +
                    '\n' + d['cut'],
                    fontsize=10)
        else:
            ax.text((xhigh - xlow) * 0.1 + xlow,
                    4 * (yhigh - ylow) / 5.0 + ylow,
                    d['system'] + '\n' + d['jettype'] + '\n' + d['jetalg'] +
                    '\n' + d['cut'],
                    fontsize=10)

    handles, labels = ax.get_legend_handles_labels()
    handles = [
        container.ErrorbarContainer(h, has_xerr=False, has_yerr=True)
        if isinstance(h, container.ErrorbarContainer) else h for h in handles
    ]
    #ax.legend(handles,labels,loc = 'lower left',numpoints=1)
    if (len(labels) > 4):
        ax.legend(np.delete(handles, 4),
                  np.delete(labels, 4),
                  loc='upper left')
        ax.text((xhigh - xlow) * 0.09 + xlow,
                0.57 * (yhigh - ylow) + ylow,
                "ALICE",
                weight='bold')
    else:
        ax.legend(handles, labels, loc='upper right')
        if (len(labels) > 2):
            ax.text((xhigh - xlow) * 0.770 + xlow,
                    0.66 * (yhigh - ylow) + ylow,
                    "ALICE",
                    weight='bold')
        else:
            ax.text((xhigh - xlow) * 0.770 + xlow,
                    0.80 * (yhigh - ylow) + ylow,
                    "ALICE",
                    weight='bold')
    #ax.legend(loc = 'upper left')
    ax.set_xlim([xlow, xhigh])
    ax.set_ylim([ylow, yhigh])
    ax.tick_params(which='both',
                   direction='in')  #Move ticks from outside to inside

    plt.savefig("{}.pdf".format(file), format='pdf')  #Save figure

    plt.show()  #Draw figure on screen
示例#28
0
    
    bins = array('d', [0, 25, 45, 70, 100, 1000])
    h_data = Hist(bins.tolist())
    h_data.SetBinContent(1, 2146)
    h_data.SetBinError(1, 145)
    h_data.SetBinContent(2, 3399)
    h_data.SetBinError(2, 254)
    h_data.SetBinContent(3, 3723)
    h_data.SetBinError(3, 69)
    h_data.SetBinContent(4, 2256)
    h_data.SetBinError(4, 53)
    h_data.SetBinContent(5, 1722)
    h_data.SetBinError(5, 91)
    h_data.SetTitle('input distribution')
    h_new = generate_toy_MC_from_distribution(h_data)
    h_new.SetTitle('toy MC')
    fig = plt.figure(figsize=(16, 10), dpi=100, facecolor='white')
    axes = plt.axes([0.15, 0.15, 0.8, 0.8])
    axes.xaxis.set_minor_locator(AutoMinorLocator())
    axes.yaxis.set_minor_locator(AutoMinorLocator())
    axes.tick_params(which='major', labelsize=15, length=8)
    axes.tick_params(which='minor', length=4)
    rplt.hist(h_new, axes=axes)
    rplt.errorbar(h_data, emptybins=False, axes=axes)
    plt.xlabel('Mass', position=(1., 0.), ha='right')
    plt.ylabel('Events', position=(0., 1.), va='top')
    plt.legend(numpoints=1)
    plt.savefig('toy_MC_test.png')
    print  list( h_data.y() )
    print list( h_new.y() )
示例#29
0
def draw_data_mc(tf_prefit, tf_postfit, channel, hname, processes,
                 signal_processes, **kwargs):

    # name (string) of the data process.
    # Example: "data" (real data), "data_obs" (fake data)
    #must exist in the input file
    dataname = kwargs.get("dataname", "data_obs")

    xlabel = kwargs.get("xlabel", escape_string(hname))
    xunit = kwargs.get("xunit", "")
    ylabel = kwargs.get("ylabel", "auto")
    rebin = kwargs.get("rebin", 1)
    title_extended = kwargs.get("title_extended", "")

    #legend properties
    do_legend = kwargs.get("do_legend", True)
    legend_loc = kwargs.get("legend_loc", (1.1, 0.25))
    legend_fontsize = kwargs.get("legend_fontsize", 15)

    #Dictionary of sample (string) -> color (tuple of floats) to use as colors
    #or "auto" to generate a sequence of colors
    colors = kwargs.get("colors", "auto")

    #True if you want to put the contents of the overflow bin into the last
    #visible bin of the histogram, False otherwise
    show_overflow = kwargs.get("show_overflow", False)

    #function f: TH1D -> TH1D to apply on data to blind it.
    blindFunc = kwargs.get("blindFunc", None)

    #array of up-down pairs for systematic names to use for the systematic band,
    #e.g.[("_CMS_scale_jUp", "_CMS_scale_jDown")]
    systematics = kwargs.get("systematics", [])

    print "..."

    histograms_nominal_prefit = getHistogramsPrefit(tf_prefit, processes,
                                                    hname, channel)

    print histograms_nominal_prefit

    x_min = histograms_nominal_prefit["ttbarOther"].GetXaxis().GetXmin()
    x_max = histograms_nominal_prefit["ttbarOther"].GetXaxis().GetXmax()

    #"NONE/shapes_fit_s/s53_BDT_common5_input_all_sum_pt_with_met/ttbarOther
    histograms_nominal_postfit = getHistogramsPostfit(tf_postfit, processes,
                                                      hname, channel, x_min,
                                                      x_max)

    if len(histograms_nominal_prefit) == 0:
        raise KeyError("did not find any histograms for MC")

    histograms_systematic = OrderedDict()
    #get the systematically variated histograms
    for systUp, systDown in systematics:
        histograms_systematic[systUp] = getHistograms(tf, processes,
                                                      hname + systUp)
        histograms_systematic[systDown] = getHistograms(
            tf, processes, hname + systDown)
        if len(histograms_systematic[systUp]) == 0 or len(
                histograms_systematic[systDown]) == 0:
            print "Could not read histograms for {0}".format(hname + systUp)

    processes_d = dict(processes)

    counts = {}

    for histo_dict in [histograms_nominal_prefit, histograms_nominal_postfit
                       ] + histograms_systematic.values():
        for (proc, h) in histo_dict.items():
            h.title = processes_d[proc] + " ({0:.1f})".format(h.Integral())
            counts[proc] = h.Integral()
            h.rebin(rebin)
            if show_overflow:
                fill_overflow(h)

    c = plt.figure(figsize=(6, 10))

    #Create top panel
    a1 = plt.axes([0.0, 0.6, 1.0, 0.35])

    #c.suptitle(r"$\textbf{CMS}$ preliminary $\sqrt{s} = 13$ TeV"+title_extended,
    #    y=1.02, x=0.02,
    #    horizontalalignment="left", verticalalignment="bottom", fontsize=16
    #)
    stacked_hists = mc_stack(histograms_nominal_prefit.values(),
                             histograms_systematic,
                             systematics,
                             colors=colors)

    histogram_total_mc = sum(histograms_nominal_prefit.values())
    histogram_total_mc_postfit = sum(histograms_nominal_postfit.values())

    #Create the normalized signal shape
    #histogram_signal = sum([histograms_nominal_prefit[sig] for sig in signal_processes])

    #hsig.Rebin(2)
    #if histogram_signal.Integral()>0:
    #    histogram_signal.Scale(0.2 * histogram_total_mc.Integral() / histogram_signal.Integral())
    #histogram_signal.title = processes[0][1] + " norm"
    #histogram_signal.linewidth=2
    #histogram_signal.fillstyle = None
    #draw the signal shape
    #hist([histogram_signal])

    histogram_total_mc.title = "pseudodata"
    histogram_total_mc.color = "black"

    histogram_total_bkg = sum([
        histograms_nominal_prefit[k] for k in histograms_nominal_prefit.keys()
        if k not in signal_processes
    ])

    #Get the data histogram
    data = None
    if dataname != "":

        # SL
        # input
        #data = tf_prefit.get(dataname + "_inputVar_" + channel + "_" + hname)
        # final disc
        #data = tf_prefit.get(dataname + "_" + hname + "_" + channel)
        # DL
        data = tf_prefit.get(channel + "_" + hname + "/" + dataname)

        data.rebin(rebin)
        if blindFunc:
            data = blindFunc(data)
        if show_overflow:
            fill_overflow(data)
        data.title = "data ({0:.2f})".format(data.Integral())

        #set data error to 0 in case no data (FIXME)
        for ibin in range(data.GetNbinsX()):
            if data.GetBinContent(ibin) == 0:
                data.SetBinError(ibin, 1)
        errorbar(data)

    if do_legend:
        #create nice filled legend patches for all the processes
        patches = []
        if data:
            dataline = mlines.Line2D([], [],
                                     color='black',
                                     marker='o',
                                     label=data.title)
            patches += [dataline]
        for (line1, line2), h in zip(stacked_hists["hists"],
                                     histograms_nominal_prefit.values()):
            patch = mpatches.Patch(color=line1.get_color(), label=h.title)
            patches += [patch]
        #patches += [mpatches.Patch(facecolor="none", edgecolor="black", label="stat", hatch="////////")]
        #patches += [mpatches.Patch(facecolor="none", edgecolor="gray", label="stat+syst", hatch=r"\\\\")]
        plt.legend(handles=patches,
                   loc=legend_loc,
                   numpoints=1,
                   prop={'size': legend_fontsize},
                   ncol=2,
                   frameon=False)

    #create an automatic bin width label on the y axis
    if ylabel == "auto":
        ylabel = "events"  # / {0:.2f} {1}".format(histogram_signal.get_bin_width(1), xunit)
    plt.ylabel(ylabel)

    #hide x ticks on main panel
    ticks = a1.get_xticks()
    a1.get_xaxis().set_visible(False)

    a1.set_ylim(bottom=0, top=1.1 * a1.get_ylim()[1])
    a1.grid(zorder=100000)

    plt.figtext(.73, .915, "Pre-Fit", fontsize=25)

    a3 = a1
    plt.figtext(.73, 0.515, "Post-Fit", fontsize=25)

    a3 = plt.axes([0.0, 0.20, 1.0, 0.35], sharex=a1)
    stacked_hists = mc_stack(histograms_nominal_postfit.values(),
                             histograms_systematic,
                             systematics,
                             colors=colors)

    #Get the data histogram
    data = None
    if dataname != "":
        # SL
        #input
        #data = tf_prefit.get(dataname + "_inputVar_" + channel + "_" + hname)
        # final disc
        #data = tf_prefit.get(dataname + "_" + hname + "_" + channel)
        # DL
        data = tf_prefit.get(channel + "_" + hname + "/" + dataname)

        data.rebin(rebin)
        if blindFunc:
            data = blindFunc(data)
        if show_overflow:
            fill_overflow(data)
        data.title = "data ({0:.2f})".format(data.Integral())

        #set data error to 0 in case no data (FIXME)
        for ibin in range(data.GetNbinsX()):
            if data.GetBinContent(ibin) == 0:
                data.SetBinError(ibin, 1)
        errorbar(data)

    #create an automatic bin width label on the y axis
    if ylabel == "auto":
        ylabel = "events / {0:.2f} {1}".format(
            histogram_signal.get_bin_width(1), xunit)
    plt.ylabel(ylabel)

    if do_legend:
        #create nice filled legend patches for all the processes
        patches = []
        if data:
            dataline = mlines.Line2D([], [],
                                     color='black',
                                     marker='o',
                                     label=data.title)
            patches += [dataline]
        for (line1, line2), h in zip(stacked_hists["hists"],
                                     histograms_nominal_postfit.values()):
            patch = mpatches.Patch(color=line1.get_color(), label=h.title)
            patches += [patch]
        #patches += [mpatches.Patch(facecolor="none", edgecolor="black", label="stat", hatch="////////")]
        #patches += [mpatches.Patch(facecolor="none", edgecolor="gray", label="stat+syst", hatch=r"\\\\")]
        plt.legend(handles=patches,
                   loc=legend_loc,
                   numpoints=1,
                   prop={'size': legend_fontsize},
                   ncol=2,
                   frameon=False)

    ticks = a3.get_xticks()
    a3.get_xaxis().set_visible(False)
    a3.grid(zorder=100000)

    #do ratio panel
    if data:

        a2 = plt.axes([0.0, 0.0, 1.0, 0.15], )

        a2.set_autoscale_on(False)
        a2.set_xlim(-0.7, 0.8)
        a2.set_xbound(-0.7, 0.8)

        plt.xlabel(xlabel)

        a2.grid()

        data_ratio = data.Clone()
        data_ratio.Divide(histogram_total_mc)

        data_ratio_postfit = data.Clone()
        data_ratio_postfit.Divide(histogram_total_mc_postfit)

        #In case MC was empty, set data/mc ratio to 0
        for ibin in range(data_ratio.GetNbinsX()):
            bc = histogram_total_mc.GetBinContent(ibin)
            if bc == 0:
                data_ratio.SetBinContent(ibin, 0)


#        #create also the variated band
#        bg_unc_u = stacked_hists["tot_u"]
#        bg_unc_d = stacked_hists["tot_d"]
#
#        bg_unc_u.Divide(stacked_hists["tot"])
#        bg_unc_d.Divide(stacked_hists["tot"])
#
#        bg_unc_usyst = stacked_hists["tot_usyst"]
#        bg_unc_dsyst = stacked_hists["tot_dsyst"]
#
#        bg_unc_usyst.Divide(stacked_hists["tot"])
#        bg_unc_dsyst.Divide(stacked_hists["tot"])

#blind the data also on the ratio
        if blindFunc:
            data_ratio = blindFunc(data_ratio)
        errorbar(data_ratio)
        errorbar(data_ratio_postfit,
                 ecolor='red',
                 c='red',
                 markeredgecolor='red',
                 color='red',
                 markerfacecolor='red')

        #        fill_between(
        #            bg_unc_u, bg_unc_d,
        #            color="black", hatch="////////",
        #            alpha=1.0, linewidth=0, facecolor="none", edgecolor="black", zorder=10,
        #        )
        #
        #        fill_between(
        #            bg_unc_usyst, bg_unc_dsyst,
        #            color="gray", hatch=r"\\\\",
        #            alpha=1.0, linewidth=0, facecolor="none", edgecolor="gray", zorder=10,
        #        )

        #        plt.title("data={0:.1f} pre-fit={1:.1f} post-fit={1:.1f}".format(
        #            data.Integral(),
        #            histogram_total_mc.Integral(),
        #            histogram_total_mc_postfit.Integral()
        #            ), x=1.1, y=0.8, fontsize=14, horizontalalignment="left"
        #        )

        plt.figtext(1.55,
                    0.095,
                    "Data    = {0:.1f}".format(data.Integral(), ),
                    fontsize=14,
                    horizontalalignment="left")

        plt.figtext(1.55,
                    0.07,
                    "Pre-fit  = {0:.1f}".format(
                        histogram_total_mc.Integral(), ),
                    fontsize=14,
                    horizontalalignment="left")

        plt.figtext(1.55,
                    0.045,
                    "Post-fit = {0:.1f}".format(
                        histogram_total_mc_postfit.Integral()),
                    fontsize=14,
                    horizontalalignment="left")

        plt.ylabel(r"$\frac{\mathrm{data}}{\mathrm{pred.}}$", fontsize=32)
        plt.axhline(1.0, color="black")
        a2.set_ylim(0.5, 1.5)
        #hide last tick on ratio y axes
        a2.set_yticks(a2.get_yticks()[:-1])
        #a2.set_xticks(0)

        ticks = a2.get_xticks()
        #a2.get_xaxis().set_visible(False)

        if do_legend:
            #create nice filled legend patches for all the processes
            line_prefit = mlines.Line2D([], [],
                                        color='black',
                                        marker='o',
                                        label="data/pre-fit")
            line_postfit = mlines.Line2D([], [],
                                         color='red',
                                         marker='o',
                                         label="data/post-fit")
            patches = [line_prefit, line_postfit]

            plt.legend(handles=patches,
                       loc=legend_loc,
                       numpoints=1,
                       prop={'size': legend_fontsize},
                       ncol=1,
                       frameon=False)
def make_jet_response_comparison_plot(input_files, response):
    global output_folder, output_formats, suffix

    if not '_prof' in response:
        print 'Can\'t make comparison scatter plots!'
        return

    jet_responses = {}
    for jet_response_name, file_name in input_files.iteritems():
        jet_responses.update(
            {jet_response_name: asrootpy(file_name.Get(response))})

    x_limits = [0, 200]
    y_limits = [0.7, 1.3]
    if '_eta' in response:
        x_limits = [-3, 3]
        x_title = '$\eta$(reco jet)'
    else:
        x_title = '$p_{\mathrm{T}}$(reco jet) [GeV]'

    y_title = '$p_{\mathrm{T}}$(reco jet)/$p_{\mathrm{T}}$(HLT jet)'
    save_as_name = response

    plt.figure(figsize=(20, 16), dpi=200, facecolor='white')

    ax0 = plt.axes()
    ax0.minorticks_on()
    ax0.grid(True, 'major', linewidth=2)
    ax0.grid(True, 'minor')
    plt.tick_params(**CMS.axis_label_major)
    plt.tick_params(**CMS.axis_label_minor)
    ax0.xaxis.set_major_formatter(FormatStrFormatter('%d'))
    ax0.yaxis.set_major_formatter(FormatStrFormatter('%.1f'))
    ax0.xaxis.labelpad = 12
    ax0.yaxis.labelpad = 12
    jet_response_name_list = []

    marker_face_colours = {
        0: 'black',
        1: 'red',
        2: 'blue',
        3: 'none',
        4: 'yellow'
    }
    marker_edge_colours = {
        0: 'black',
        1: 'red',
        2: 'blue',
        3: 'green',
        4: 'yellow'
    }
    markers = {0: 'o', 1: 'v', 2: '^', 3: 's', 4: '*'}
    fill_styles = {0: 'full', 1: 'full', 2: 'full', 3: 'none', 4: 'full'}
    counter = 0
    for jet_response_name, jet_response in sorted(jet_responses.iteritems()):
        rplt.errorbar(jet_response,
                      xerr=None,
                      emptybins=True,
                      axes=ax0,
                      marker=markers[counter],
                      fillstyle=fill_styles[counter],
                      markerfacecolor=marker_face_colours[counter],
                      markeredgecolor=marker_edge_colours[counter],
                      ecolor=marker_edge_colours[counter],
                      ms=15,
                      mew=3,
                      lw=2)
        jet_response_name_list.append(jet_response_name)
        counter += 1

    ax0.set_xlim(x_limits)
    ax0.set_ylim(y_limits)

    plt.tick_params(**CMS.axis_label_major)
    plt.tick_params(**CMS.axis_label_minor)

    plt.xlabel(x_title, CMS.x_axis_title)
    plt.ylabel(y_title, CMS.y_axis_title)
    plt.title(r'e+jets, CMS Preliminary, $\sqrt{s}$ = 8 TeV', CMS.title)
    plt.legend(jet_response_name_list,
               numpoints=1,
               loc='lower right',
               prop=CMS.legend_properties)

    plt.tight_layout()

    for output_format in output_formats:
        plt.savefig(output_folder + save_as_name + '_' + suffix + '.' +
                    output_format)
示例#31
0
    ax0 = plt.axes()
    ax0.minorticks_on()
    ax0.grid(True, 'major', linewidth=2)
    ax0.grid(True, 'minor')
    plt.tick_params(**CMS.axis_label_major)
    plt.tick_params(**CMS.axis_label_minor)

    ax0.xaxis.set_major_formatter(FormatStrFormatter('%d'))
    ax0.yaxis.set_major_formatter(FormatStrFormatter('%.1f'))
    ax0.xaxis.labelpad = 11
    #ax0.yaxis.labelpad = 20

    rplt.errorbar(plot_efficiency,
                  xerr=True,
                  emptybins=True,
                  axes=ax0,
                  marker='o',
                  ms=15,
                  mew=3,
                  lw=2)

    ax0.set_xlim(x_limits)
    ax0.set_ylim([0.0, 1.1])

    #add fits
    x = numpy.linspace(fit_data.GetXmin(), fit_data.GetXmax(),
                       fit_data.GetNpx())
    function_data = frompyfunc(fit_data.Eval, 1, 1)
    plot(x, function_data(x), axes=ax0, color='red', linewidth=2)

    plt.tick_params(**CMS.axis_label_major)
    plt.tick_params(**CMS.axis_label_minor)
def plot_central_and_systematics( channel, systematics, exclude = [], suffix = 'altogether' ):
    global variable, b_tag_bin, met_type

    plt.figure( figsize = ( 16, 16 ), dpi = 200, facecolor = 'white' )
    axes = plt.axes()
    if not variable in ['NJets']:
        axes.minorticks_on()

    hist_data_central = read_xsection_measurement_results( 'central', channel )[0]['unfolded_with_systematics']
    hist_data_central.markersize = 2  # points. Imagine, tangible units!
    hist_data_central.marker = 'o'

    if variable in ['NJets', 'abs_lepton_eta', 'lepton_eta']:
        plt.xlabel( '$%s$' % variables_latex[variable], CMS.x_axis_title )
        plt.ylabel( r'$\frac{1}{\sigma}  \frac{d\sigma}{d' + variables_latex[variable] + '}$', CMS.y_axis_title )
    else:
        plt.xlabel( '$%s$ [GeV]' % variables_latex[variable], CMS.x_axis_title )
        plt.ylabel( r'$\frac{1}{\sigma}  \frac{d\sigma}{d' + variables_latex[variable] + '} \left[\mathrm{GeV}^{-1}\\right]$', CMS.y_axis_title )
    plt.tick_params( **CMS.axis_label_major )
    if not variable in ['NJets']:
        plt.tick_params( **CMS.axis_label_minor )

    rplt.errorbar( hist_data_central, axes = axes, label = 'data', xerr = True )

    for systematic in sorted( systematics ):
        if systematic in exclude or systematic == 'central':
            continue

        hist_data_systematic = read_xsection_measurement_results( systematic, channel )[0]['unfolded']
        hist_data_systematic.markersize = 2
        hist_data_systematic.marker = 'o'
        colour_number = systematics.index( systematic ) + 2
        if colour_number == 10:
            colour_number = 42
        hist_data_systematic.SetMarkerColor( colour_number )
        if 'PDF' in systematic:
            rplt.errorbar( hist_data_systematic, axes = axes, label = systematic.replace( 'Weights_', ' ' ), xerr = None )
        elif met_type in systematic:
            rplt.errorbar( hist_data_systematic, axes = axes, label = measurements_latex[systematic.replace( met_type, '' )], xerr = None )
        else:
            rplt.errorbar( hist_data_systematic, axes = axes, label = measurements_latex[systematic], xerr = None )

    plt.legend( numpoints = 1, loc = 'center right', prop = {'size':25}, ncol = 2 )
    label, channel_label = get_cms_labels( channel )
    plt.title( label, CMS.title )
    # CMS text
    # note: fontweight/weight does not change anything as we use Latex text!!!
    plt.text(0.95, 0.95, r"\textbf{CMS}", transform=axes.transAxes, fontsize=42,
        verticalalignment='top',horizontalalignment='right')
    # channel text
    axes.text(0.95, 0.90, r"\emph{%s}" %channel_label, transform=axes.transAxes, fontsize=40,
        verticalalignment='top',horizontalalignment='right')
    plt.tight_layout()


    path = output_folder + str( measurement_config.centre_of_mass_energy ) + 'TeV/' + variable
    make_folder_if_not_exists( path )
    for output_format in output_formats:
        filename = path + '/normalised_xsection_' + channel + '_' + suffix + '.' + output_format

        plt.savefig( filename )

    plt.close()
    gc.collect()
示例#33
0
def main():
    parser = OptionParser(__doc__)
    parser.add_option(
        "-v",
        "--variable",
        dest="variable",
        default='MET',
        help="set the variable to analyse (MET, HT, ST, MT, WPT)")
    parser.add_option(
        "-s",
        "--centre-of-mass-energy",
        dest="CoM",
        default=8,
        help="set the centre of mass energy for analysis. Default = 8 [TeV]",
        type=int)
    parser.add_option("-o",
                      "--output",
                      dest="output_folder",
                      default='plots/unfolding_pulls',
                      help="output folder for unfolding pull plots")
    parser.add_option("-c",
                      "--channel",
                      type='string',
                      dest="channel",
                      default='combined',
                      help="channel to be analysed: electron|muon|combined")

    (options, args) = parser.parse_args()
    if len(args) == 0:
        print('No input files specified.')
        print('Run script with "-h" for usage')
        sys.exit(-1)
    files = args

    centre_of_mass = options.CoM
    variable = options.variable
    channel = options.channel
    output_folder_base = options.output_folder + '/' + \
        str(centre_of_mass) + 'TeV/' + variable + '/' + channel + '/'
    make_folder_if_not_exists(output_folder_base)
    output_formats = ['pdf']

    bins = array('d', bin_edges[variable])
    nbins = len(bins) - 1

    kValues = sorted(getkValueRange(files))

    sigmaForEachK = []
    tau = -1
    for k in kValues:
        if k is 1:
            continue

        output_folder = output_folder_base + '/kv' + str(k) + '/'
        make_folder_if_not_exists(output_folder)
        print(
            'Producing unfolding pull plots for {0} variable, k-value of {1}, channel: {2}.'
            .format(variable, k, channel))
        print('Output folder: {0}'.format(output_folder))
        pulls = get_data(files, subset='pull')

        maxSigma = 0
        minSigma = 100
        for bin_i in range(0, nbins):
            fitResults = plot_pull(pulls,
                                   centre_of_mass,
                                   channel,
                                   variable,
                                   k,
                                   tau,
                                   output_folder,
                                   output_formats,
                                   bin_index=bin_i,
                                   n_bins=nbins)
            if fitResults.sigma > maxSigma:
                maxSigma = fitResults.sigma
            if fitResults.sigma < minSigma:
                minSigma = fitResults.sigma

        # plot all bins
        allBinsFitResults = plot_pull(pulls, centre_of_mass, channel, variable,
                                      k, tau, output_folder, output_formats)

        allBinsSigma = allBinsFitResults.sigma
        sigmaForEachK.append([k, allBinsSigma, maxSigma, minSigma])
        print('All bins sigma :', allBinsFitResults.sigma)
        print('Max/min sigma :', maxSigma, minSigma)
        print('Spread :', maxSigma - minSigma)
        del pulls  # deleting to make space in memory
    print()

    kValues = list(zip(*sigmaForEachK)[0])
    kValuesup = []
    kValuesdown = []
    sigmas = list(zip(*sigmaForEachK)[1])
    sigmaups = list(zip(*sigmaForEachK)[2])
    sigmadowns = list(zip(*sigmaForEachK)[3])
    spread = []

    for i in range(0, len(sigmas)):
        spread.append((sigmaups[i] - sigmadowns[i]) / sigmas[i])
        sigmaups[i] = sigmaups[i] - sigmas[i]
        sigmadowns[i] = sigmas[i] - sigmadowns[i]
        kValuesup.append(0.5)
        kValuesdown.append(0.5)
    print(spread)
    kValueChoice = spread.index(min(spread))
    print(kValueChoice)

    graph = asrootpy(
        TGraphAsymmErrors(len(sigmas), array('d', kValues), array('d', sigmas),
                          array('d', kValuesdown), array('d', kValuesup),
                          array('d', sigmadowns), array('d', sigmaups)))
    graphSpread = asrootpy(
        TGraphAsymmErrors(len(sigmas), array('d', kValues), array('d', spread),
                          array('d', kValuesdown), array('d', kValuesup),
                          array('d', sigmadowns), array('d', sigmaups)))

    # plot with matplotlib
    plt.figure(figsize=(20, 16), dpi=200, facecolor='white')

    ax0 = plt.axes()
    ax0.minorticks_on()
    ax0.grid(True, 'major', linewidth=2)
    ax0.grid(True, 'minor')
    plt.tick_params(**CMS.axis_label_major)
    plt.tick_params(**CMS.axis_label_minor)

    ax0.xaxis.set_major_formatter(FormatStrFormatter('%d'))
    ax0.yaxis.set_major_formatter(FormatStrFormatter('%.1f'))
    ax0.xaxis.labelpad = 11

    rplt.errorbar(graph,
                  xerr=True,
                  emptybins=True,
                  axes=ax0,
                  marker='o',
                  ms=15,
                  mew=3,
                  lw=2)
    rplt.errorbar(graphSpread,
                  xerr=None,
                  yerr=False,
                  axes=ax0,
                  linestyle='-',
                  marker='s',
                  ms=10,
                  mew=1,
                  lw=2)

    for output_format in output_formats:
        print(output_folder_base)
        plt.savefig(output_folder_base + '/TESTGRAPH' + '.' + output_format)

    print(kValues)
    print(kValuesup)
    print(kValuesdown)
    print(sigmas)
    print(sigmaups)
    print(sigmadowns)
    print(sigmaForEachK)
示例#34
0
def main():
    print('Number of arguments: ', len(sys.argv), 'arguments.')
    print('Argument list:', str(sys.argv))
    filename = sys.argv[1]
    separate = int(sys.argv[2])
    if (len(sys.argv) > 3):
        start = int(sys.argv[3])
        end = int(sys.argv[4])
    else:
        start = 1
        end = 9
    n_figs = end - start
    print("Number of figs: {}".format(n_figs))
    print("Input file: ")
    print(filename)
    Mixed_FullJets_R04 = datasetMixed(
        "Full jets R=0.4",
        NFIN=0,
        range=(1, 5),
        filename=filename,
        directory='AliJJetJtTask/AliJJetJtHistManager',
        directory2='AliJJetJtTask_kEMCEJE/AliJJetJtHistManager',
        color=2,
        style=24,
        rebin=2)
    signal, jetPt = Mixed_FullJets_R04.getSubtracted('JetConeJtWeightBin',
                                                     'BgJtWeightBin',
                                                     jetpt=True)
    if (False):
        if (separate > 0):
            fig = plt.figure(1)
            ax = fig.add_subplot(1, 1, 1)
            ax.set_xscale('log')
            ax.set_yscale('log')
            ax.text(0.2,
                    0.0005,
                    d['system'] + '\n' + d['jettype'] + '\n' + d['jetalg'] +
                    '\n Jet Cone',
                    fontsize=7)
            rplt.errorbar(signal[separate],
                          xerr=False,
                          emptybins=False,
                          axes=ax,
                          label=Mixed_FullJets_R04.name(),
                          fmt='o')  #Plot jT histogram,
            ax.text(
                0.3, 1e2, r'$p_{{T,\mathrm{{jet}}}}$:'
                '\n'
                r' {:02d}-{:02d} GeV'.format(jetPt[separate][0],
                                             jetPt[separate][1]))
            ax.set_xlim([0.1, 12])
            ax.set_ylim([5e-6, 1.5e3])
            ax.legend(loc='lower left')

            plt.savefig(
                "PythonFigures/MixedFullJetsR04JetConeJtSignalJetPt{0}.pdf".
                format(separate),
                format='pdf')  #Save figure
            plt.show()  #Draw figure on screen

        else:
            n_rows = n_figs // 4
            print(n_rows)
            fig, axs = defs.makegrid(4,
                                     n_figs // 4,
                                     xlog=True,
                                     ylog=True,
                                     d=d,
                                     shareY=True,
                                     figsize=(10, 2.5))
            axs = axs.reshape(n_figs)
            axs[1].text(0.12,
                        0.002,
                        d['system'] + '\n' + d['jettype'] + '\n' +
                        d['jetalg'] + '\n Jet Cone',
                        fontsize=7)
            for jT, pT, ax, i in zip(signal[start:], jetPt[start:], axs,
                                     range(0, 9)):
                plot = rplt.errorbar(jT,
                                     xerr=False,
                                     emptybins=False,
                                     axes=ax,
                                     label=Mixed_FullJets_R04.name(),
                                     fmt='o',
                                     fillstyle='none',
                                     ecolor='blue')  #Plot jT histogram,
                line = plot.get_children()[0]
                #line.set_markerfacecolor('none')
                #line.set_markeredgecolor('red')
                ax.text(
                    0.3, 1e2, r'$p_{{T,\mathrm{{jet}}}}$:'
                    '\n'
                    r' {:02d}-{:02d} GeV'.format(pT[0], pT[1]))

                ax.set_xlim([0.1, 22])  #Set x-axis limits
                ax.set_ylim([5e-4, 2e3])  #Set y-axis limits
                ax.set_xticklabels(ax.get_xticklabels(),
                                   horizontalalignment='left')

            #axs[0].legend(loc = 'lower left')

            plt.savefig(
                "PythonFigures/MixedFullJetsR04JetConeJtSignalPtFrom{}To{}.pdf"
                .format(start, end),
                format='pdf')  #Save figure
            plt.show()  #Draw figure on screen

    fig, axs = defs.makeRatio(xlog=True,
                              ylog=True,
                              d=d,
                              shareY=False,
                              figsize=(10, 10))
    axs = axs.reshape(2)
    ax = axs[0]
    for jT, pT, i in zip(signal[start:], jetPt[start:], range(0, 9)):
        h = jT.Clone()
        h.Scale(10**i)
        h.SetMarkerColor(i)
        label = r'${:02d}\:\mathrm{{GeV}} < p_{{T,\mathrm{{jet}}}} < {:02d}\:\mathrm{{GeV}} \left(\times 10^{:01d}\right)$'.format(
            pT[0], pT[1], i)
        plot = rplt.errorbar(h,
                             xerr=False,
                             emptybins=False,
                             axes=ax,
                             label=label,
                             fmt='o',
                             fillstyle='none')  #Plot jT histogram,

    ax.set_xlim([0.1, 22])
    ax.set_ylim([5e-4, 2e8])
    ax.set_xticklabels(ax.get_xticklabels(), horizontalalignment='left')
    ax.legend(loc='lower left')

    plt.show()  #Draw figure on screen
def plot_difference(difference, centre_of_mass, channel, variable, k_value,
                    tau_value, output_folder, output_formats):
    stats = len(difference)
    values, errors = [], []
    add_value = values.append
    add_error = errors.append
    for value, error in difference:
        add_value(value)
        add_error(error)
    min_x, max_x = min(values), max(values)
    abs_max = int(max(abs(min_x), max_x))
    #    n_x_bins = 2 * abs_max * 10
    h_values = Hist(100, -abs_max, abs_max)
    fill_value = h_values.Fill
    for value in values:
        fill_value(value)

    plt.figure(figsize=(16, 16), dpi=200, facecolor='white')
    axes = plt.axes()
    h_values.SetMarkerSize(CMS.data_marker_size)
    rplt.errorbar(h_values, xerr=True, emptybins=True, axes=axes)

    channel_label = latex_labels.channel_latex[channel]
    var_label = latex_labels.variables_latex[variable]
    title_template = 'SVD unfolding performance for unfolding of {variable}\n'
    title_template += '$\sqrt{{s}}$ = {com} TeV, {channel}, {value}'
    title = title_template.format(variable=var_label,
                                  com=centre_of_mass,
                                  channel=channel_label,
                                  value=get_value_title(k_value, tau_value))

    plt.xlabel('$\mathrm{unfolded} - \mathrm{true}$', CMS.x_axis_title)
    plt.ylabel('number of toy experiments', CMS.y_axis_title)
    plt.tick_params(**CMS.axis_label_major)
    plt.tick_params(**CMS.axis_label_minor)
    plt.title(title, CMS.title)
    plt.tight_layout()

    for save in output_formats:
        plt.savefig(output_folder + 'difference_stats_' + str(stats) + '.' +
                    save)

    min_x, max_x = min(errors), max(errors)
    h_errors = Hist(1000, min_x, max_x)
    fill_value = h_errors.Fill
    for error in errors:
        fill_value(error)

    plt.figure(figsize=(16, 16), dpi=200, facecolor='white')
    axes = plt.axes()
    h_errors.SetMarkerSize(CMS.data_marker_size)
    rplt.errorbar(h_errors, xerr=True, emptybins=True, axes=axes)

    plt.xlabel('$\sigma(\mathrm{unfolded} - \mathrm{true})$', CMS.x_axis_title)
    plt.ylabel('number of toy experiments', CMS.y_axis_title)
    plt.tick_params(**CMS.axis_label_major)
    plt.tick_params(**CMS.axis_label_minor)
    plt.title(title_template, CMS.title)

    plt.tight_layout()

    for save in output_formats:
        plt.savefig(output_folder + 'difference_errors_stats_' + str(stats) +
                    '.' + save)
示例#36
0
def main():

    logjt_nmlla = [
        -0.8375, -0.68327, -0.50528, -0.32737, -0.16131, -0.042676, 0.09963,
        0.23006, 0.39612, 0.56213, 0.6451, 0.81108, 0.89409, 1.0956, 1.2022,
        1.3089, 1.4274, 1.5103, 1.6169, 1.7117, 1.7945, 1.8774, 1.9601, 2.0192,
        2.0901, 2.1372, 2.1723, 2.1957, 2.219, 2.2187
    ]
    nmlla = [
        5.6912, 4.4526, 3.4842, 2.4101, 1.7369, 1.4155, 1.0199, 0.73479,
        0.52954, 0.35149, 0.27483, 0.17508, 0.14264, 0.07711, 0.053306,
        0.03685, 0.025477, 0.017609, 0.011212, 0.0074379, 0.004735, 0.0031408,
        0.0017674, 0.0010796, 0.00060746, 0.00031475, 0.0001502, 0.000081077,
        0.000043764, 0.00002672
    ]
    jt_nmlla = [math.exp(logjt) for logjt in logjt_nmlla]
    nmlla = [y / x for x, y in zip(jt_nmlla, nmlla)]
    print(jt_nmlla)

    print('Number of arguments: ', len(sys.argv), 'arguments.')
    print('Argument list:', str(sys.argv))
    filename = sys.argv[1]
    filename2 = sys.argv[2]
    print("Input file data: ")
    print(filename)
    print("Input NMLLA: ")
    print(filename2)
    #separate = 5 #bin 5: 60-80 Gev
    Mixed_FullJets_R04 = datasetMixed(
        "Full jets R=0.4",
        NFIN=0,
        range=5,
        filename=filename,
        directory='AliJJetJtTask/AliJJetJtHistManager',
        directory2='AliJJetJtTask_kEMCEJE/AliJJetJtHistManager',
        color=2,
        style=24,
        rebin=2)
    signal, jetPt = Mixed_FullJets_R04.getSubtracted('JetConeJtWeightBin',
                                                     'BgJtWeightBin',
                                                     jetpt=True)
    for separate in range(2, 8):
        Qs = {5: 26, 4: 18, 6: 35, 7: 46, 3: 13, 2: 9}
        Q = Qs[separate]  # 9,    13,   18,   26,   36,   46
        #Jet Pt: 22.5, 32.5, 45.0, 65.0, 87.5, 115.0]
        f_nmlla = root_open(filename2, "open")
        nmlla_fromfile = f_nmlla.get('NMLLAQ{:02d}'.format(Q))
        nmlla_gluon = f_nmlla.get('NMLLA_gluonQ{:02d}'.format(Q))
        nmlla_quark = f_nmlla.get('NMLLA_quarkQ{:02d}'.format(Q))
        scale = 1 / nmlla_fromfile.Eval(1)
        print("Scale by {}".format(scale))
        nmlla_fromfile = scaleGraph(nmlla_fromfile, scale)
        nmlla_gluon = scaleGraph(nmlla_gluon, scale)
        nmlla_quark = scaleGraph(nmlla_quark, scale)
        nmlla_fromfile.SetMarkerColor(3)
        nmlla_quark.SetMarkerColor(2)
        nmlla_gluon.SetMarkerColor(3)
        nmlla_quark.SetLineColor(2)
        nmlla_gluon.SetLineColor(3)
        fit1, d1 = fitJtHisto(signal[separate], 1, separate)
        fit2, d2 = fitJtHisto(nmlla_fromfile, 1, separate)

        print(r'$p_{{T,\mathrm{{jet}}}}$:'
              '\n'
              r' {:02d}-{:02d} GeV'.format(jetPt[separate][0],
                                           jetPt[separate][1]))
        print('Data Wide RMS: {}, NMLLA Wide RMS: {}'.format(
            d1['gammaRMS'], d2['gammaRMS']))
        fig = plt.figure(1)
        ax = fig.add_subplot(1, 1, 1)
        ax.set_xscale('log')
        ax.set_yscale('log')
        ax.text(0.2,
                0.0005,
                d['system'] + '\n' + d['jettype'] + '\n' + d['jetalg'] +
                '\n Jet Cone',
                fontsize=7)
        rplt.errorbar(signal[separate],
                      xerr=False,
                      emptybins=False,
                      axes=ax,
                      label=Mixed_FullJets_R04.name(),
                      fmt='o')  #Plot jT histogram,
        rplt.errorbar(nmlla_fromfile,
                      xerr=False,
                      yerr=False,
                      emptybins=False,
                      axes=ax,
                      label="NMLLA",
                      fmt='r-',
                      markersize=0)
        #rplt.errorbar(nmlla_gluon,xerr=False,yerr=False,emptybins=False,axes=ax,label="NMLLA Gluon",fmt='r-')
        #rplt.errorbar(nmlla_quark,xerr=False,yerr=False,emptybins=False,axes=ax,label="NMLLA Quark",fmt='b-')
        if (separate == 5):
            plt.plot(jt_nmlla, nmlla, axes=ax, label="NMLLA")
        ax.text(
            0.3, 1e2, r'$p_{{T,\mathrm{{jet}}}}$:'
            '\n'
            r' {:02d}-{:02d} GeV'.format(jetPt[separate][0],
                                         jetPt[separate][1]))
        ax.set_xlim([0.1, 12])
        ax.set_ylim([5e-6, 1.5e3])
        ax.legend(loc='lower left')

        plt.savefig(
            "PythonFigures/MixedFullJetsR04JetConeJtSignalJetPt{0}WithNMLLA.pdf"
            .format(separate),
            format='pdf')  #Save figure
        plt.show()  #Draw figure on screen
    make_data_mc_comparison_plot([h3, h1, h2],
                                 ['data', 'background', 'signal'],
                                 ['black', 'green', 'red'], properties)

    properties.name += '_with_ratio'
    make_data_mc_comparison_plot([h3, h1, h2],
                                 ['data', 'background', 'signal'],
                                 ['black', 'green', 'red'],
                                 properties,
                                 show_ratio=True)

    properties.name = 'matplotlib_hist_comparison'
    properties.y_limits = [0, 0.4]
    make_control_region_comparison(h1, h2, 'background', 'signal', properties)

else:
    fig = plt.figure(figsize=(14, 10), dpi=300)  #, facecolor='white')
    axes = plt.axes()
    axes.xaxis.set_minor_locator(AutoMinorLocator())
    axes.yaxis.set_minor_locator(AutoMinorLocator())
    # axes.yaxis.set_major_locator(MultipleLocator(20))
    axes.tick_params(which='major', labelsize=15, length=8)
    axes.tick_params(which='minor', length=4)
    rplt.errorbar(h3, xerr=False, emptybins=False, axes=axes, zorder=4)
    rplt.hist(stack, stacked=True, axes=axes, zorder=1)
    plt.xlabel('Mass', position=(1., 0.), ha='right')
    plt.ylabel('Events', position=(0., 1.), va='bottom', ha='right')
    plt.legend(numpoints=1)
    plt.tight_layout()
    plt.savefig('plots/matplotlib_hist.pdf')
示例#38
0
label.SetTextFont(43)
label.SetTextSize(25)
label.SetNDC()
label.Draw()
canvas.Modified()
canvas.Update()

# plot with matplotlib
set_style('ATLAS', mpl=True)
fig = plt.figure(figsize=(7, 5), dpi=100)
axes = plt.axes()
axes.xaxis.set_minor_locator(AutoMinorLocator())
axes.yaxis.set_minor_locator(AutoMinorLocator())
axes.yaxis.set_major_locator(MultipleLocator(20))
rplt.bar(stack, stacked=True, axes=axes)
rplt.errorbar(h3, xerr=False, emptybins=False, axes=axes)
plt.xlabel('Mass', position=(1., 0.), va='bottom', ha='right')
plt.ylabel('Events', position=(0., 1.), va='top', ha='right')
axes.xaxis.set_label_coords(1., -0.20)
axes.yaxis.set_label_coords(-0.18, 1.)
leg = plt.legend()
axes.text(0.3,
          0.8,
          'matplotlib',
          verticalalignment='center',
          horizontalalignment='center',
          transform=axes.transAxes,
          fontsize=20)

if not ROOT.gROOT.IsBatch():
    plt.show()
示例#39
0
def main():

    JetPtBins = [5, 10, 20, 30, 40, 60, 80, 100, 150, 500]
    jetPtBins2 = [(JetPtBins[i], JetPtBins[i + 1]) for i in range(8)]

    Njets = 8

    topcomment = "_systematics_Triggered"
    finderName = [
        "Full jets, Anti-k_\mathrm{T} R = 0.4",
        "Charged Jets, Anti-k_\mathrm{T} R = 0.4"
    ]
    finderType = ["Full", "Charged"]
    setTitle = ["0", "1", "2", "3", "4", "5"]
    finderR = {4, 4}

    iC = 0
    logx = 1
    doWeight = 1
    mSize = 0.3
    iS = 0
    start = 4

    if (os.path.exists('RootFiles/Fig1.root')):
        inFile = "RootFiles/Fig1.root"
        inF = root_open(inFile, 'r')
        errGraph = [
            inF.Get("jTSignalJetPt_Syst{:02d}".format(ij)) for ij in range(4)
        ]
        hJtSignalGraph = [
            inF.Get("jTSignalJetPt_Stat{:02d}".format(ij)) for ij in range(4)
        ]
    else:
        f = root_open("errors_test.root", 'read')
        errGraph = [
            f.Get('JetConeJtWeightBinNFin{:02d}JetPt{:02d}_Systematics'.format(
                iS, i)) for i in range(start, Njets)
        ]  #Get jT histograms from file an array
        hJtSignalGraph = [
            f.Get('JetConeJtWeightBinNFin{:02d}JetPt{:02d}_Statistics'.format(
                iS, i)) for i in range(start, Njets)
        ]  #Get jT histograms from file an array
        outFile = "RootFiles/Fig1.root"
        outF = root_open(outFile, "w+")
        for err, signal, i in zip(errGraph, hJtSignalGraph, range(10)):
            err.SetName("jTSignalJetPt_Syst{:02d}".format(i))
            err.Write()
            signal.SetName("jTSignalJetPt_Stat{:02d}".format(i))
            signal.Write()
        outF.Close()
    scaleInterval = 1

    ylow = 5e-6
    yhigh = 5e2 * pow(10, 4 * scaleInterval)
    xlow = 0.1
    xhigh = 4.5

    #ax = plt.gca()
    fig = plt.figure(figsize=(6, 8))
    ax = plt.axes([0.2, 0.1, 0.75, 0.85])
    ax.set_xlim([xlow, xhigh])
    ax.set_ylim([ylow, yhigh])

    for ij, h, h_sys, pT in zip(range(start, Njets), hJtSignalGraph[::-1],
                                errGraph[::-1], jetPtBins2[Njets::-1]):
        print(ij)
        print("JetPt {}".format(pT))
        power = scaleInterval * (7 - ij)
        scale = pow(10, power)
        h = defs.grrScale(h, scale)
        h.SetMarkerColor(colors[ij - start])
        h.SetLineColor(colors[ij - start])
        h.SetMarkerStyle(styles[ij - start])
        label = r'${:02d}\: < p_{{\mathrm{{T,jet}}}} < {:02d}\:\mathrm{{GeV}}/c \left(\times 10^{}\right)$'.format(
            pT[0], pT[1], power)

        plot = rplt.errorbar(h,
                             xerr=False,
                             emptybins=False,
                             axes=ax,
                             label=label,
                             fmt='+')  #Plot jT histogram,
        line = plot.get_children()[0]
        if (styles[ij - 4] > 23): line.set_markerfacecolor('none')
        errorboxes = []
        n = h_sys.GetN()
        xs = h_sys.GetX()
        ys = h_sys.GetY()
        xerrs = h_sys.GetEX()
        yerrs = h_sys.GetEY()
        for x in (xs, ys, xerrs, yerrs):
            x.SetSize(n)
        for x, y, xe, ye in zip(xs, ys, xerrs, yerrs):
            rect = Rectangle((x - xe, (y - ye) * scale), xe * 2,
                             ye * 2 * scale)
            errorboxes.append(rect)
        pc = PatchCollection(errorboxes,
                             facecolor=colorsBox[ij - 4],
                             alpha=0.5,
                             edgecolor='None')
        ax.add_collection(pc)
        #print("({} - {})/9.0 + {} is {}".format(yhigh,ylow,ylow,(yhigh-ylow)/9.0+ylow))

    ax.text(1.3,
            2e5,
            d['system'] + '\n' + d['jettype'] + '\n' + d['jetalg'] + '\n' +
            d['cut'],
            fontsize=10)

    handles, labels = ax.get_legend_handles_labels()
    handles = [
        container.ErrorbarContainer(h, has_xerr=False, has_yerr=True)
        if isinstance(h, container.ErrorbarContainer) else h for h in handles
    ]
    ax.legend(handles, labels, loc='lower left', numpoints=1)
    #ax.legend(loc = 'lower left')
    ax.yaxis.set_ticks_position('both')  #Show ticks on left and right side
    ax.xaxis.set_ticks_position('both')  #Show ticks on bottom and top
    ax.tick_params(which='both',
                   direction='in')  #Move ticks from outside to inside
    ytitle = r'$\frac{1}{N_{jets}}\;\frac{1}{j_\mathrm{T}}\;\frac{\mathrm{d} N}{\mathrm{d} j_\mathrm{T}}$'
    xtitle = r'$j_\mathrm{T}\left(\mathrm{GeV}/c\right)$'
    ax.set_ylabel(ytitle, fontsize=16)
    ax.set_xlabel(xtitle, fontsize=16)

    ax.set_xlim([xlow, xhigh])
    ax.set_ylim([ylow, yhigh])
    ax.set_xscale('log')
    ax.set_yscale('log')
    plt.savefig("PythonFigures/jTwithSystematics.pdf",
                format='pdf')  #Save figure

    plt.show()  #Draw figure on screen
hTrue= Hist(40, -10.0, 10.0);
hMeas= Hist(40, -10.0, 10.0);
hTrue.SetLineColor('red')
hMeas.SetLineColor('blue')
#  Test with a Gaussian, mean 0 and width 2.
for i in xrange(10000):
    xt= gRandom.Gaus (0.0, 2.0)
    x= smear (xt);
    hTrue.Fill(xt);
    if x!=None: hMeas.Fill(x);

print "==================================== UNFOLD ==================================="
unfold= RooUnfoldBayes     (response, hMeas, 4);    #  OR
# unfold= RooUnfoldSvd     (response, hMeas, 20);   #  OR
# unfold= RooUnfoldTUnfold (response, hMeas);

hReco= unfold.Hreco();
h_unfolded = asrootpy(hReco)
unfold.PrintTable (cout, hTrue);

plt.figure(figsize=(16, 12), dpi=100)
rplt.hist(hTrue, label='truth', stacked=False)
rplt.hist(hMeas, label='measured', stacked=False)
rplt.errorbar(h_unfolded, label='unfolded')
plt.xlabel('var')
plt.ylabel('Events')
plt.title('Unfolding')
plt.legend()
plt.savefig('plots/RooUnfoldBayesExample.png')
print 'Done'
'''
Created on 29 Oct 2012

@author: kreczko
'''
from ROOT import TH1F
from rootpy.plotting import Hist
import rootpy.plotting.root2matplotlib as rplt
import matplotlib.pyplot as plt

#updated from http://rootpy.org/qa/questions/80/how-to-create-a-histogram-with-asymmetric-bins
bins = [0, 25, 45, 70, 100, 2000]
nbins = len(bins) - 1

rootpyhist = Hist(bins)
for bin_i in range(nbins):
    rootpyhist.SetBinContent(bin_i + 1, bin_i+1)
    rootpyhist.SetBinError(bin_i +1, (bin_i + 1)*0.1)

plt.figure(figsize=(16, 10), dpi=100)
plt.figure(1)
rplt.errorbar(rootpyhist, label='test')
plt.xlabel('x')
plt.ylabel('y')
plt.title('Testing')
plt.legend(numpoints=1)
plt.axis([bins[0], bins[-1], 0, nbins*1.2])
plt.savefig('plots/AsymBinsExample.png')
print 'Done'
示例#42
0
def drawSignal(signals, systematics, names, colors, styles, jetPt):

    if (n_figs == 2):
        fig, axs = defs.makeRatio(xlog=True,
                                  ylog=True,
                                  d=d,
                                  shareY=False,
                                  figsize=(5, 7.5),
                                  grid=False)
    else:
        fig, axs = defs.makegrid(n_figs / 2,
                                 2,
                                 xlog=True,
                                 ylog=True,
                                 d=d,
                                 shareY=False,
                                 figsize=(10, 7.5) if n_figs == 4 else
                                 (n_figs * 15 / 8, 7.5))
    axs = axs.reshape(n_figs)
    if (n_figs == 2):
        pT = jetPt[start]
        axs[0].text(
            0.8,
            7,
            d['system'] + '\n' + d['jettype'] + '\n' + d['jetalg'] + '\n' +
            d['cut'] + '\n' +
            r'${:02d}\: < p_{{\mathrm{{T,jet}}}} < {:02d}\:\mathrm{{GeV}}/c$'.
            format(pT[0], pT[1]),
            fontsize=11)
    else:
        axs[1].text(0.12,
                    0.00002,
                    d['system'] + '\n' + d['jettype'] + '\n' + d['jetalg'] +
                    '\n' + d['cut'],
                    fontsize=11)
    for signal, system, name, color, j in zip(signals, systematics, names,
                                              colors, range(10)):
        for jT, syst, pT, ax, i in zip(signal[start:], system[start:],
                                       jetPt[start:], axs[0:n_figs / 2],
                                       range(0, 9)):
            jT.SetMarkerColor(color)
            jT.SetMarkerStyle(styles[j])
            jT.SetLineColor(color)
            plot = rplt.errorbar(jT,
                                 xerr=False,
                                 emptybins=False,
                                 axes=ax,
                                 label=name,
                                 fmt='o',
                                 fillstyle='none')  #Plot jT histogram,
            line = plot.get_children()[0]
            line.set_markersize(mSize)
            if (styles[j] > 23):
                line.set_markerfacecolor('none')
                #line.set_markeredgecolor(color)
                line.set_color(color)
            if (n_figs > 2):
                ax.text(
                    0.5, 1e2,
                    r'${:02d}\: < p_{{\mathrm{{T,jet}}}} < {:02d}\:\mathrm{{GeV}}/c$'
                    .format(pT[0], pT[1]))
            ax.set_xlim([xlow, 10])  #Set x-axis limits
            ax.set_ylim([1e-5, 2e3])  #Set y-axis limits
            errorboxes = []
            for box in syst:
                x1, x2, y1, y2, yc, error, ratio, ratioerror = box

                rect = Rectangle((x1, y1), x2 - x1, y2 - y1)
                errorboxes.append(rect)
            pc = PatchCollection(errorboxes,
                                 facecolor=colorsBox[j],
                                 alpha=0.5,
                                 edgecolor=colorsBox[j])
            ax.add_collection(pc)
            ax.grid(False)

        ratios = []
        if (j > 0):
            for syst, sig, div, ax in zip(system[start:], signal[start:],
                                          signals[0],
                                          axs[n_figs / 2:n_figs + 1]):
                ratioBoxes = []
                N = div.GetNbinsX()
                for box, i in zip(syst, range(1, N)):
                    y = div.GetBinContent(i)
                    x1, x2, y1, y2, yc, error, ratio, ratioerror = box
                    rect = Rectangle((x1, ratio - ratioerror), x2 - x1,
                                     ratioerror * 2)
                    ratioBoxes.append(rect)

                pc = PatchCollection(ratioBoxes,
                                     facecolor=colorsBox[j],
                                     alpha=0.5,
                                     edgecolor=colorsBox[j])
                ax.add_collection(pc)

        if j > 0:
            for jT, div in zip(signal, signals[0]):
                h = jT.Clone()
                h.Divide(div)
                ratios.append(h)
            axs[n_figs / 2].set_ylabel(
                'Ratio to {}'.format(names[0]), fontsize=12
            )  #Add y-axis labels to left- and righmost subfigures
            if (n_figs > 4):
                axs[-1].set_ylabel('Ratio to {}'.format(names[0]), fontsize=12)
            for ratio, pT, ax in zip(ratios[start:], jetPt[start:],
                                     axs[n_figs / 2:n_figs + 1]):
                plot = rplt.errorbar(ratio,
                                     xerr=False,
                                     emptybins=False,
                                     axes=ax,
                                     label='Ratio',
                                     fmt='o')  #Plot ratio histogram,
                ax.plot([0, 10], [1, 1], 'k--')

                line = plot.get_children()[0]
                line.set_markersize(mSize)
                if (styles[j] > 23):
                    line.set_markerfacecolor('none')
                line.set_color(color)
                #if(i == 0):
                ax.set_yscale('linear')
                ax.set_xlim([xlow, 10])  #Set x-axis limits
                ax.set_ylim([0.1, 2.5])  #Set y-axis limits
                ax.grid(False)
    handles, labels = axs[0].get_legend_handles_labels()
    handles = [
        container.ErrorbarContainer(h, has_xerr=False, has_yerr=True)
        if isinstance(h, container.ErrorbarContainer) else h for h in handles
    ]
    axs[0].legend(handles,
                  labels,
                  loc='lower left',
                  numpoints=1,
                  prop={'family': 'monospace'})
    #axs[0].legend(loc = 'lower left')
    axs[0].text(0.11, 3e2, "ALICE", weight='bold')
    fig.align_labels()
    plt.savefig("PythonFigures/HighMJetConeJtSignalPtFrom{}To{}.pdf".format(
        start, end),
                format='pdf')  #Save figure
    plt.show()  #Draw figure on screen
示例#43
0
def trigger_turn_on_curves():

    #mod_hists = parsed_linear[0]

    colors = [
        'green', 'magenta', 'blue', 'red', 'orange', '#cecece', 'yellow',
        'cyan', 'purple'
    ]
    labels = [
        "Jet370", "Jet300", "Jet240", "Jet190", "Jet150", "Jet110", "Jet80",
        "Jet60", "Jet30"
    ]
    hist_labels = [
        "HLT_Jet370", "HLT_Jet300", "HLT_Jet240", "HLT_Jet190", "HLT_Jet150",
        "HLT_Jet110", "HLT_Jet80", "HLT_Jet60", "HLT_Jet30"
    ]
    lower_pTs = [370, 300, 240, 190, 150, 110, 80, 60, 30]

    for i in range(len(hist_labels)):

        # hist = normalize_hist( mod_hists[hist_labels[i]].hist() )
        hist = mod_hists[hist_labels[i]].hist()

        n_bins = hist.nbins()

        # Loop through those bins.
        for j in range(n_bins):
            current_bin_x = hist.GetBinCenter(j)
            current_bin_y = hist.GetBinContent(j),

            if current_bin_x < lower_pTs[i]:
                hist.SetBinContent(j, 0.)

        hist.SetColor(colors[i])
        hist.SetTitle(labels[i])

        rplt.errorbar(hist,
                      zorder=range(len(hist_labels))[len(hist_labels) - i - 1],
                      emptybins=False,
                      xerr=1,
                      yerr=1,
                      ls='None',
                      marker='o',
                      markersize=10,
                      pickradius=8,
                      capthick=5,
                      capsize=8,
                      elinewidth=5,
                      alpha=1.0)

    # Info about R, pT_cut, etc.
    extra = Rectangle((0, 0),
                      1,
                      1,
                      fc="w",
                      fill=False,
                      edgecolor='none',
                      linewidth=0)
    handles = [extra]
    labels = ["AK5; $\left| \eta \\right| < 2.5$"]
    info_legend = plt.gca().legend(handles,
                                   labels,
                                   loc=7,
                                   frameon=0,
                                   borderpad=0.1,
                                   fontsize=60,
                                   bbox_to_anchor=[0.28, 0.92])
    plt.gca().add_artist(info_legend)

    plt.gca().set_xlabel("Trigger Jet $p_T$ [GeV]", fontsize=70, labelpad=50)
    plt.gca().set_ylabel("Rescaled Events", fontsize=70, labelpad=25)

    plt.gca().add_artist(logo_box(0.105, 0.99))

    plt.gca().xaxis.set_minor_locator(MultipleLocator(10))
    plt.gca().set_yscale('log')

    handles, labels = plt.gca().get_legend_handles_labels()

    legend = plt.legend(handles[::-1],
                        labels[::-1],
                        frameon=0,
                        fontsize=60,
                        bbox_to_anchor=[0.97, 0.99])

    ax = plt.gca().add_artist(legend)

    outside_text = plt.gca().legend([extra], ["CMS 2011 Open Data"],
                                    frameon=0,
                                    borderpad=0,
                                    fontsize=50,
                                    bbox_to_anchor=(1.0, 1.005),
                                    loc='lower right')
    plt.gca().add_artist(outside_text)

    plt.autoscale()
    plt.gca().set_ylim(1e2, 1e10)

    plt.tick_params(which='major', width=5, length=25, labelsize=70)
    plt.tick_params(which='minor', width=3, length=15)

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

    plt.tight_layout()

    plt.savefig(default_dir + "trigger_turn_on.pdf")

    plt.clf()
示例#44
0
def main():

    start = 4
    end = 8
    n_figs = end - start
    title = "Full jets R=0.4"
    if (os.path.exists('./RootFiles/Fig0.root')):
        inFile = "RootFiles/Fig0.root"
        inF = root_open(inFile, 'r')
        signal = [inF.Get("jTSignalJetPt{:02d}".format(i)) for i in range(8)]
        jetPt = [
            (int(
                re.search(r'p_{T,jet} : ([\d]*)\.[\d] - ([\d]*).[\d]*',
                          h.GetTitle(), re.M | re.I).group(1)),
             int(
                 re.search(r'p_{T,jet} : ([\d]*)\.[\d] - ([\d]*).[\d]*',
                           h.GetTitle(), re.M | re.I).group(2)))
            for h in signal
        ]  #Use regular expressions to extract jet pT range from histogram titles

    else:
        filename = "CF_pPb_legotrain/legotrain_CF_pPb_1839_20180613_LHC13bcde.root"

        print("Number of figs: {}".format(n_figs))
        print("Input file: ")
        print(filename)
        Mixed_FullJets_R04 = datasetMixed(
            title,
            NFIN=0,
            range=(1, 5),
            filename=filename,
            directory='AliJJetJtTask/AliJJetJtHistManager',
            directory2='AliJJetJtTask_kEMCEJE/AliJJetJtHistManager',
            color=2,
            style=24,
            rebin=2)
        signal, jetPt = Mixed_FullJets_R04.getSubtracted('JetConeJtWeightBin',
                                                         'BgJtWeightBin',
                                                         jetpt=True)

        outFile = "Fig0.root"
        outF = root_open(outFile, "w+")
        for s, i in zip(signal, range(10)):
            s.SetName("jTSignalJetPt{:02d}".format(i))
            s.Write()
        outF.Close()

    n_rows = n_figs // 4
    fig, axs = defs.makegrid(4,
                             n_figs // 4,
                             xlog=True,
                             ylog=True,
                             d=d,
                             shareY=True,
                             figsize=(10, 2.5))
    axs = axs.reshape(n_figs)
    axs[1].text(0.12,
                0.002,
                d['system'] + '\n' + d['jettype'] + '\n' + d['jetalg'] +
                '\n Jet Cone',
                fontsize=7)
    for jT, pT, ax, i in zip(signal[start:], jetPt[start:], axs, range(0, 9)):
        plot = rplt.errorbar(jT,
                             xerr=False,
                             emptybins=False,
                             axes=ax,
                             label=title,
                             fmt='o',
                             fillstyle='none',
                             ecolor='blue')  #Plot jT histogram,
        line = plot.get_children()[0]
        #line.set_markerfacecolor('none')
        #line.set_markeredgecolor('red')
        ax.text(
            0.3, 1e2, r'$p_{{T,\mathrm{{jet}}}}$:'
            '\n'
            r' {:02d}-{:02d} GeV'.format(pT[0], pT[1]))

        ax.set_xlim([0.1, 22])  #Set x-axis limits
        ax.set_ylim([5e-4, 2e3])  #Set y-axis limits
        ax.set_xticklabels(ax.get_xticklabels(), horizontalalignment='left')

    plt.savefig(
        "PythonFigures/MixedFullJetsR04JetConeJtSignalPtFrom{}To{}.pdf".format(
            start, end),
        format='pdf')  #Save figure
    plt.show()  #Draw figure on screen
示例#45
0
def trigger_efficiency_plot():
	mod_hists = parsed_linear[0]

	lower = 0
	upper = 10

	
	colors = ["#e41a1c", "#377eb8", "#4daf4a", "#984ea3", "#ff7f00", "#99cc00", "#a65628", "#f781bf","#999999" ]
	labels = ["Jet370 / Jet300", "Jet300 / Jet240", "Jet240 / Jet190",
                  "Jet190 / Jet150", "Jet150 / Jet110", "Jet110 / Jet80",
                  "Jet80 / Jet60", "Jet60 / Jet30"]
	hist_labels = [("HLT_Jet370", "HLT_Jet300"),("HLT_Jet300", "HLT_Jet240"),
                       ("HLT_Jet240", "HLT_Jet190"), ("HLT_Jet190", "HLT_Jet150"),
                       ("HLT_Jet150", "HLT_Jet110"), ("HLT_Jet110", "HLT_Jet80"),
                       ("HLT_Jet80", "HLT_Jet60"), ("HLT_Jet60", "HLT_Jet30") ]
	#lower_pTs = [370, 300, 240, 190, 150, 110, 80, 60, 30]
	lower_pTs = [390, 310, 270, 210, 150, 110, 90, 0, 0]
	#lower_pTs = [0]*9
	#lower_pTs = [0 , 420 - 20 , 350-20, 275- 20, 220 -20, 190-20, 130-20, 110-20, 70-20]
        upper_pTs = [1000000, 480, 390, 310, 270, 210, 150, 110, 90]
       # upper_pTs = [10000000]*9


	# rplt.hist(mod_hists[0].hist())

	plots = []
	for i in range(len(hist_labels)):
		
		first_hist, second_hist = mod_hists[hist_labels[i][0]], mod_hists[hist_labels[i][1]]

		ratio_hist = first_hist.hist() / second_hist.hist()

		ratio_hist.SetColor(colors[i])
		ratio_hist.SetTitle(labels[i])

		#rplt.errorbar(ratio_hist, emptybins=False, xerr=1, yerr=1, ls='None', marker='o', markersize=10, pickradius=8, capthick=5, capsize=8, elinewidth=5, alpha=1.0)
		plots.append( rplt.errorbar(ratio_hist, emptybins=True, alpha=0.) )


	for i in range(len(plots)):
	    data_plot = plots[i]

	    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()

	    filtered_x, filtered_y, filtered_x_err, filtered_y_err = [], [], [], []
	    for x, y, xerr, yerr in zip(data_points_x, data_points_y, data_x_errors, data_y_errors):
	      if x > lower_pTs[i] and x < upper_pTs[i]:
                print(lower_pTs[i], upper_pTs[i])
	        filtered_x.append(x)
	        filtered_y.append(y)
	        filtered_x_err.append(xerr)
	        filtered_y_err.append(yerr)

	    plt.errorbar(filtered_x, filtered_y, zorder=range(len(plots))[len(plots) - i - 1], color=colors[i], markeredgecolor=colors[i], label=labels[i], xerr=filtered_x_err, yerr=filtered_y_err, ls='None', alpha=1.0, marker='o', markersize=10, pickradius=8, capthick=5, capsize=8, elinewidth=5)


	extra = Rectangle((0, 0), 1, 1, fc="w", fill=False, edgecolor='none', linewidth=0)

	plt.autoscale()
	#plt.gca().set_ylim(1e-3, 7e4)
	plt.gca().set_xlim(0, 800)




	cms_turn_on_pTs = [480, 390, 310, 270, 210, 150, 110, 90]
	for i in range(len(cms_turn_on_pTs)):

		if cms_turn_on_pTs[i] != 0:
			source = "MOD"
			#plt.gca().annotate(str(cms_turn_on_pTs[i]) + " GeV", xy=(cms_turn_on_pTs[i], 1.), xycoords='data', xytext=(-100, 350),  textcoords='offset points', color=colors[i], size=50, va="center", ha="center", arrowprops=dict(arrowstyle="simple", facecolor=colors[i], zorder=99, connectionstyle="angle3,angleA=0,angleB=90") )
                if i == 7:
                        plt.plot([ cms_turn_on_pTs[i], cms_turn_on_pTs[i] ], [ 1e0, 1.09 ], lw=10, ls="dashed", color=colors[i])
                elif i == 6:
                        plt.plot([ cms_turn_on_pTs[i], cms_turn_on_pTs[i] ], [ 1e0, 1.11 ], lw=10, ls="dashed", color=colors[i])
                elif i == 5:
                        plt.plot([ cms_turn_on_pTs[i], cms_turn_on_pTs[i] ], [ 1e0, 1.13], lw=10, ls="dashed", color=colors[i])
                elif i == 4:
                        plt.plot([ cms_turn_on_pTs[i], cms_turn_on_pTs[i] ], [ 1e0, 1.15], lw=10, ls="dashed", color=colors[i])
                elif i == 3:
                        plt.plot([ cms_turn_on_pTs[i], cms_turn_on_pTs[i] ], [ 1e0, 1.17 ], lw=10, ls="dashed", color=colors[i])
                elif i == 2:
                        plt.plot([ cms_turn_on_pTs[i], cms_turn_on_pTs[i] ], [ 1e0, 1.19 ], lw=10, ls="dashed", color=colors[i])
                elif i == 1:
                        plt.plot([ cms_turn_on_pTs[i], cms_turn_on_pTs[i] ], [ 1e0, 1.21], lw=10, ls="dashed", color=colors[i])
                elif i == 0:
                        plt.plot([ cms_turn_on_pTs[i], cms_turn_on_pTs[i] ], [ 1e0, 1.23], lw=10, ls="dashed", color=colors[i])
                size_val = 60

                if i == 7:
                    plt.gca().text((cms_turn_on_pTs[i] ), 1.09 + 0.007, str(cms_turn_on_pTs[i]) , color=colors[i], horizontalalignment='center', size = size_val)
                elif i == 6:
                    plt.gca().text((cms_turn_on_pTs[i] ), 1.11 + 0.007, str(cms_turn_on_pTs[i]), color=colors[i], horizontalalignment='center', size = size_val)
                elif i == 5:
                    plt.gca().text((cms_turn_on_pTs[i]),  1.13 + 0.007, str(cms_turn_on_pTs[i]) , color=colors[i], horizontalalignment='center', size = size_val)
                elif i == 4:
                    plt.gca().text((cms_turn_on_pTs[i] ),  1.15 + 0.007, str(cms_turn_on_pTs[i]), color=colors[i], horizontalalignment='center', size = size_val)
                elif i == 3:
                    plt.gca().text((cms_turn_on_pTs[i]), 1.17 + 0.007, str(cms_turn_on_pTs[i]) , color=colors[i], horizontalalignment='center', size = size_val)
                elif i == 2:
                    plt.gca().text((cms_turn_on_pTs[i] ),  1.19 + 0.007, str(cms_turn_on_pTs[i]) , color=colors[i], horizontalalignment='center', size = size_val)
                elif i == 1:
                    plt.gca().text((cms_turn_on_pTs[i]),  1.21 + 0.007, str(cms_turn_on_pTs[i]) , color=colors[i], horizontalalignment='center', size = size_val)
                elif i == 0:
                    plt.gca().text((cms_turn_on_pTs[i]), 1.23 + 0.007, str(cms_turn_on_pTs[i]) , color=colors[i], horizontalalignment='center', size = size_val)

        
	# Horizontal Line.
	plt.plot([0] + list(mod_hists[hist_labels[len(hist_labels)-1][0]].hist().x()), [1] * (1 + len(list(mod_hists[hist_labels[len(hist_labels)-1][0]].hist().x()))), color="black", linewidth=5, linestyle="dashed")


	# Info about R, pT_cut, etc.
	
	handles = [extra]
	labels = ["AK5; $\left| \eta \\right| < 2.4$"]
	info_legend = plt.gca().legend(handles, labels, loc=7, frameon=0, borderpad=0.1, fontsize=60, bbox_to_anchor=[0.35, 0.92])
	plt.gca().add_artist(info_legend)


	plt.gca().set_xlabel("Trigger Jet $p_T$ [GeV]", fontsize=70, labelpad=50)
	plt.gca().set_ylabel("Cross Section Ratio", fontsize=70, labelpad=50)

	plt.gca().add_artist(logo_box(0.1, 0.98))

	plt.gca().xaxis.set_minor_locator(MultipleLocator(10))
	plt.gca().set_yscale('linear')
	plt.gca().set_ylim(0.7, 1.3)
	plt.gca().set_xlim(0.0, 800)



	handles, labels = plt.gca().get_legend_handles_labels()
	print(labels[::-1])
	legend = plt.legend(handles[::-1][:-8], labels[::-1][:-8], fontsize=40, frameon=0, bbox_to_anchor=[0.99, 0.99])
	ax = plt.gca().add_artist(legend)


	outside_text = plt.gca().legend( [extra], ["CMS 2011 Open Data"], frameon=0, borderpad=0, fontsize=50, bbox_to_anchor=(1.0, 1.005), loc='lower right')
	plt.gca().add_artist(outside_text)
	

	plt.tick_params(which='major', width=5, length=25, labelsize=70)
	plt.tick_params(which='minor', width=3, length=15)

	plt.tight_layout()

	plt.gcf().set_size_inches(27, 27, forward=1)
	plt.savefig(default_dir + "trigger_efficiency.pdf")

	plt.clf()
示例#46
0
def make_plots( histograms, category, output_folder, histname, show_ratio = False, show_generator_ratio = False, show_before_unfolding = False, utype = 'normalised', preliminary=True ):
    global variable, phase_space

    channel = ''
    if 'electron' in histname:
        channel = 'electron'
    elif 'muon' in histname:
        channel = 'muon'
    else:
        channel = 'combined'

    # Initailise data histograms
    hist_data = histograms['unfolded']
    hist_data.markersize = 2
    hist_data.marker = 'o'
    if category == 'central':
        hist_data_with_systematics = histograms['unfolded_with_systematics']
        hist_data_with_systematics.markersize = 2
        hist_data_with_systematics.marker = 'o'

    # Create base figure to be plotted
    plt.figure( figsize = CMS.figsize, dpi = CMS.dpi, facecolor = CMS.facecolor )

    # Split into 3 for MC/Data ratio and generator ratio and plot
    if show_ratio and show_generator_ratio:
        gs = gridspec.GridSpec( 3, 1, height_ratios = [5, 1, 1] )
        axes = plt.subplot( gs[0] )
    # Split into 2 for MC/Data ratio or generator Ratio and plot
    elif show_ratio or show_generator_ratio:
        gs = gridspec.GridSpec( 2, 1, height_ratios = [4, 1] )
        axes = plt.subplot( gs[0] )
    # Just 1 for plot and setup x axis labels
    else:
        axes = plt.axes()
        x_label = '${}$'.format(variables_latex[variable])
        if variable in ['HT', 'ST', 'MET', 'WPT', 'lepton_pt']:
            x_label += ' [GeV]'
        plt.xlabel( x_label, CMS.x_axis_title )

    # set y axis x-section labels
    y_label = ''
    xsectionUnit = ''
    if utype == 'absolute':
        y_label = r'$\frac{d\sigma}{d' + variables_latex[variable] + '}\ '
        xsectionUnit = 'pb'
    else :
        y_label = r'$\frac{1}{\sigma}  \frac{d\sigma}{d' + variables_latex[variable] + '}\ '

    if variable in ['HT', 'ST', 'MET', 'WPT', 'lepton_pt']:
        if xsectionUnit is '':
            y_label += '\scriptstyle(\mathrm{GeV}^{-1})$'
            pass
        else:
            y_label += '\scriptstyle(\mathrm{'
            y_label += xsectionUnit
            y_label += '}\ \mathrm{GeV}^{-1})$'
    elif xsectionUnit is not '':
        y_label += '\scriptstyle(\mathrm{'
        y_label += xsectionUnit
        y_label += '})$'
    plt.ylabel( y_label, CMS.y_axis_title )

    # Set up ticks on axis. Minor ticks on axis for non NJet variables
    plt.tick_params( **CMS.axis_label_major )
    if not variable in ['NJets']:
        axes.minorticks_on()
        plt.tick_params( **CMS.axis_label_minor )

    # Set raw unfolded data with stat+unfolding uncertianty to be visible
    hist_data.visible = True
    # axes.set_yscale('log')
    # Set raw unfolded data with systematic uncertianty to be visible
    # label = 'do_not_show' = do not show in legend
    if category == 'central':
        hist_data_with_systematics.visible = True
        rplt.errorbar( 
            hist_data_with_systematics, 
            axes = axes, 
            label = 'do_not_show', 
            xerr = None, 
            capsize = 0, 
            elinewidth = 2, 
            zorder = len( histograms ) + 1 
        )
    
    # Show stat+unf uncertainty on plot
    rplt.errorbar( hist_data, 
        axes = axes, 
        label = 'do_not_show', 
        xerr = None, 
        capsize = 15, 
        capthick = 3, 
        elinewidth = 2, 
        zorder = len( histograms ) + 2 
    )
    # And one for a nice legend entry
    rplt.errorbar( hist_data, 
        axes = axes, 
        label = 'data', 
        xerr = None, 
        yerr = False, 
        capsize = 0, 
        elinewidth = 2, 
        zorder = len( histograms ) + 3 
    )

    dashes = {}
    for key, hist in sorted( histograms.items() ):
        zorder = sorted( histograms, reverse = False ).index( key )

        # Ordering such that systematic uncertainties are plotted first then central powhegPythia then data
        if key == 'TTJets_powhegPythia8' and zorder != len(histograms) - 3:
            zorder = len(histograms) - 3
        elif key != 'TTJets_powhegPythia8' and not 'unfolded' in key:
            while zorder >= len(histograms) - 3:
                zorder = zorder - 1 

        # Colour and style of MC hists
        if not 'unfolded' in key and not 'measured' in key:
            hist.linewidth = 4
            linestyle = None

            if 'powhegPythia8' in key:
                linestyle = 'solid'
                dashes[key] = None
                hist.SetLineColor( 633 )
            elif 'powhegHerwig' in key or 'isr' in key or 'hdamp' in key:
                hist.SetLineColor( kBlue )
                dashes[key] = [25,5,5,5,5,5,5,5]
            elif 'amcatnloPythia8' in key or 'fsr' in key or 'scale' in key:
                hist.SetLineColor( 807 )
                dashes[key] = [20,5]
            elif 'madgraphMLM' in key or 'renormalisation' in key or 'topPt' in key:
                hist.SetLineColor( 417 )
                dashes[key] = [5,5]
            elif 'factorisation' in key or 'ue' in key:
                hist.SetLineColor( 100 )
                dashes[key] = [10,10]
            elif 'combined' in key or 'semiLepBr' in key:
                hist.SetLineColor( 200 )
                dashes[key] = [20,10]
            elif 'semiLepBr' in key or 'mass' in key:
                hist.SetLineColor( 300 )
                dashes[key] = [20,10,10,10]
            elif 'frag' in key or 'Frag' in key:
                hist.SetLineColor( 400 )
                dashes[key] = [10,10,5,5]
            elif 'erdOn' in key:
                hist.SetLineColor( 500 )
                dashes[key] = [10,10,5,5,5,5]

            if linestyle != None:
                hist.linestyle = linestyle

            # Add hist to plot
            line, h = rplt.hist( hist, axes = axes, label = measurements_latex[key], zorder = zorder )

            # Set the dashes and lines
            if dashes[key] != None:
                line.set_dashes(dashes[key])
                h.set_dashes(dashes[key])

    handles, labels = axes.get_legend_handles_labels()
    
    # Making data first in the legend
    data_label_index = labels.index( 'data' )
    data_handle = handles[data_label_index]
    labels.remove( 'data' )
    handles.remove( data_handle )
    labels.insert( 0, 'data' )
    handles.insert( 0, data_handle )

    # Order the rest of the labels in the legend
    new_handles, new_labels = [], []
    zipped = dict( zip( labels, handles ) )
    labelOrder = ['data', 
        measurements_latex['TTJets_powhegPythia8'],
        measurements_latex['TTJets_amcatnloPythia8'],
        measurements_latex['TTJets_powhegHerwig'],
        measurements_latex['TTJets_madgraphMLM'],
        measurements_latex['TTJets_scaleup'], 
        measurements_latex['TTJets_scaledown'],
        measurements_latex['TTJets_massup'],
        measurements_latex['TTJets_massdown'],
        measurements_latex['TTJets_ueup'],
        measurements_latex['TTJets_uedown'],
        measurements_latex['TTJets_fsrup'],
        measurements_latex['TTJets_fsrdown'],
        measurements_latex['TTJets_isrdown'],
        measurements_latex['TTJets_isrup'],
        # measurements_latex['TTJets_alphaSup'],
        # measurements_latex['TTJets_alphaSdown'],
        measurements_latex['TTJets_topPt'],
        measurements_latex['TTJets_factorisationup'],
        measurements_latex['TTJets_factorisationdown'],
        measurements_latex['TTJets_renormalisationup'],
        measurements_latex['TTJets_renormalisationdown'],
        measurements_latex['TTJets_combinedup'],
        measurements_latex['TTJets_combineddown'],
        measurements_latex['TTJets_hdampup'],
        measurements_latex['TTJets_hdampdown'],
        measurements_latex['TTJets_erdOn'],
        measurements_latex['TTJets_QCDbased_erdOn'],
        measurements_latex['TTJets_GluonMove'],
        measurements_latex['TTJets_semiLepBrup'],
        measurements_latex['TTJets_semiLepBrdown'],
        measurements_latex['TTJets_fragup'],
        measurements_latex['TTJets_fragdown'],
        measurements_latex['TTJets_petersonFrag'],
    ]
    for label in labelOrder:
        if label in labels:
            new_handles.append(zipped[label])
            if label == 'data':
                new_labels.append(measurements_latex['data'])
            else:
                new_labels.append(label)

    # Location of the legend
    legend_location = (0.95, 0.82)
    prop = CMS.legend_properties
    if variable == 'MT':
        legend_location = (0.05, 0.82)
    elif variable == 'ST':
        legend_location = (0.97, 0.82)
    elif variable == 'WPT':
        legend_location = (1.0, 0.84)
    elif variable == 'abs_lepton_eta' or variable =='abs_lepton_eta_coarse':
        legend_location = (0.97, 0.87)
    elif variable == 'NJets':
        # Reduce size of NJets legend
        prop = {'size':30}

    # Add legend to plot
    plt.legend( new_handles, new_labels, 
        numpoints = 1, 
        prop = prop, 
        frameon = False, 
        bbox_to_anchor=legend_location,
        bbox_transform=plt.gcf().transFigure 
    )

    # Title and CMS labels
    # note: fontweight/weight does not change anything as we use Latex text!!!
    label, channel_label = get_cms_labels( channel )
    plt.title( label,loc='right', **CMS.title )

    # Locations of labels
    logo_location = (0.05, 0.97)
    channel_location = ( 0.05, 0.9)
    if preliminary:
        prelim_location = (0.05, 0.9)
        channel_location = ( 0.5, 0.97)
        # preliminary
        plt.text(prelim_location[0], prelim_location[1], 
            r"\emph{Preliminary}",
            transform=axes.transAxes, 
            fontsize=42,
            verticalalignment='top',
            horizontalalignment='left'
        )

    # if variable == 'WPT':
    #     logo_location = (0.05, 0.97)
    #     prelim_location = (0.05, 0.9)
    #     channel_location = (0.5, 0.97)
    # elif variable == 'abs_lepton_eta':
    #     logo_location = (0.05, 0.97)
    #     prelim_location = (0.05, 0.9)
    #     channel_location = ( 0.5, 0.97)

    # Add labels to plot
    plt.text(logo_location[0], logo_location[1], 
        r"\textbf{CMS}", 
        transform=axes.transAxes, 
        fontsize=42,
        verticalalignment='top',
        horizontalalignment='left'
    )


    # channel text
    plt.text(channel_location[0], channel_location[1], 
        r"%s"%channel_label, 
        transform=axes.transAxes, 
        fontsize=40,
        verticalalignment='top',
        horizontalalignment='left'
    )

    # Set y limits on plot
    ylim = axes.get_ylim()
    if ylim[0] < 0:
        axes.set_ylim( ymin = 0.)
    axes.set_ylim(ymax = ylim[1]*1.1)
    if variable == 'abs_lepton_eta' or variable == 'abs_lepton_eta_coarse':
        axes.set_ylim(ymax = ylim[1]*1.6)

    # Now to show either of the ratio plots
    if show_ratio:
        # Set previous x axis ticks and labels to invisible
        plt.setp( axes.get_xticklabels(), visible = False )
        # Go to ratio subplot
        ax1 = plt.subplot( gs[1] )

        # setting the x_limits identical to the main plot
        x_limits = axes.get_xlim()
        ax1.set_xlim(x_limits)

        # Setting tick marks
        ax1.yaxis.set_major_locator( MultipleLocator( 0.5 ) )
        plt.tick_params( **CMS.axis_label_major )
        # if not variable in ['NJets']:
        #     ax1.minorticks_on()
        #     ax1.yaxis.set_minor_locator( MultipleLocator( 0.1 ) )
        #     plt.tick_params( **CMS.axis_label_minor )

        # x axis labels as before
        x_label = '${}$'.format(variables_latex[variable])
        if variable in ['HT', 'ST', 'MET', 'WPT', 'lepton_pt']:
            x_label += ' (GeV)'

        if not show_generator_ratio:
            plt.xlabel( x_label, CMS.x_axis_title )

        y_label = '$\\displaystyle\\frac{\\mathrm{pred.}}{\\mathrm{data}}$'
        plt.ylabel( y_label, CMS.y_axis_title_small )
        ax1.yaxis.set_label_coords(-0.115, 0.7)

        # Draw a horizontal line at y=1 for data
        plt.axhline(y = 1, color = 'black', linewidth = 2)

        # Create ratios and plot to subplot
        for key, hist in sorted( histograms.iteritems() ):
            if not 'unfolded' in key and not 'measured' in key:
                ratio = hist.Clone()
                ratio.Divide( hist_data )
                line, h = rplt.hist( ratio, axes = ax1, label = 'do_not_show' )
                if dashes[key] != None:
                    line.set_dashes(dashes[key])
                    h.set_dashes(dashes[key])

        # Now for the error bands
        stat_lower = hist_data.Clone()
        stat_upper = hist_data.Clone()
        syst_lower = hist_data.Clone()
        syst_upper = hist_data.Clone()

        # Plot relative error bands on data in the ratio plot
        stat_errors = graph_to_value_errors_tuplelist(hist_data)
        if category == 'central':
            syst_errors = graph_to_value_errors_tuplelist(hist_data_with_systematics)

        for bin_i in range( 1, hist_data.GetNbinsX() + 1 ):
            stat_value, stat_error, _ = stat_errors[bin_i-1]
            stat_rel_error = stat_error/stat_value
            stat_lower.SetBinContent( bin_i, 1 - stat_rel_error )
            stat_upper.SetBinContent( bin_i, 1 + stat_rel_error )
            if category == 'central':
                syst_value, syst_error_down, syst_error_up  = syst_errors[bin_i-1]
                syst_rel_error_down = syst_error_down/syst_value
                syst_rel_error_up = syst_error_up/syst_value
                syst_lower.SetBinContent( bin_i, 1 - syst_rel_error_down )
                syst_upper.SetBinContent( bin_i, 1 + syst_rel_error_up )

        # Colour
        if category == 'central':
            rplt.fill_between( 
                syst_lower, 
                syst_upper, 
                ax1,
                color = 'gold' 
            )
        rplt.fill_between(
            stat_upper, 
            stat_lower, 
            ax1, 
            color = '0.75',
        )

        # Add legend
        loc = 'upper left'
        if variable == 'MET':
            loc = 'lower left'
        elif variable == 'HT':
            loc = 'lower center'
        elif variable == 'ST':
            loc = 'lower center'
        elif variable == 'WPT':
            loc = 'lower left'
        elif variable == 'NJets':
            loc = 'lower left'
        elif variable == 'abs_lepton_eta' or variable == 'abs_lepton_eta_coarse':
            loc = 'upper left'
        elif variable == 'lepton_pt':
            loc = 'lower left'

        # legend for ratio plot
        p_stat = mpatches.Patch(facecolor='0.75', label='Stat.', edgecolor='black' )
        p_stat_and_syst = mpatches.Patch(facecolor='gold', label=r'Stat. $\oplus$ Syst.', edgecolor='black' )
        l1 = ax1.legend(
            handles = [p_stat, p_stat_and_syst], 
            loc = loc,
            frameon = False, 
            prop = {'size':26},
            ncol = 2
        )
        ax1.add_artist(l1)

        # Setting y limits and tick parameters
        if variable == 'MET':
            ax1.set_ylim( ymin = 0.6, ymax = 1.4 )
            ax1.yaxis.set_major_locator( MultipleLocator( 0.2 ) )
            ax1.yaxis.set_minor_locator( MultipleLocator( 0.1 ) )
        if variable == 'MT':
            ax1.set_ylim( ymin = 0.8, ymax = 1.2 )
            ax1.yaxis.set_major_locator( MultipleLocator( 0.2 ) )
            ax1.yaxis.set_minor_locator( MultipleLocator( 0.1 ) )
        elif variable == 'HT':
            ax1.set_ylim( ymin = 0.6, ymax = 1.4 )
            ax1.yaxis.set_major_locator( MultipleLocator( 0.2 ) )
            ax1.yaxis.set_minor_locator( MultipleLocator( 0.1 ) )
        elif variable == 'ST':
            ax1.set_ylim( ymin = 0.6, ymax = 1.4 )
            ax1.yaxis.set_major_locator( MultipleLocator( 0.2 ) )
            ax1.yaxis.set_minor_locator( MultipleLocator( 0.1 ) )
        elif variable == 'WPT':
            ax1.set_ylim( ymin = 0.6, ymax = 1.4 )
            ax1.yaxis.set_major_locator( MultipleLocator( 0.2 ) )
            ax1.yaxis.set_minor_locator( MultipleLocator( 0.1 ) )
        elif variable == 'NJets':
            ax1.set_ylim( ymin = 0.6, ymax = 1.4 )
            ax1.yaxis.set_major_locator( MultipleLocator( 0.2 ) )
            ax1.yaxis.set_minor_locator( MultipleLocator( 0.1 ) )
        elif variable == 'abs_lepton_eta' or variable == 'abs_lepton_eta_coarse':
            ax1.set_ylim( ymin = 0.6, ymax = 1.4 )
            ax1.yaxis.set_major_locator( MultipleLocator( 0.2 ) )
            ax1.yaxis.set_minor_locator( MultipleLocator( 0.1 ) )
        elif variable == 'lepton_pt':
            ax1.set_ylim( ymin = 0.6, ymax = 1.4 )
            ax1.yaxis.set_major_locator( MultipleLocator( 0.2 ) )
            ax1.yaxis.set_minor_locator( MultipleLocator( 0.1 ) )


    if show_generator_ratio:

        ax2 = None

        # Remove Data/MC Ratio Axis
        if show_ratio:
            plt.setp( ax1.get_xticklabels(), visible = False ) 
            ax2 = plt.subplot( gs[2] )
        else:
            plt.setp( axes.get_xticklabels(), visible = False )
            ax2 = plt.subplot( gs[1] )

        # setting the x_limits identical to the main plot
        x_limits = axes.get_xlim()
        ax2.set_xlim(x_limits)

        # Setting ticks
        ax2.yaxis.set_major_locator( MultipleLocator( 0.5 ) )
        plt.tick_params( **CMS.axis_label_major )
        if not variable in ['NJets']:
            ax2.minorticks_on()
            ax2.yaxis.set_minor_locator( MultipleLocator( 0.1 ) )
            plt.tick_params( **CMS.axis_label_minor )

        # x axis labels as before
        x_label = '${}$'.format(variables_latex[variable])
        if variable in ['HT', 'ST', 'MET', 'WPT', 'lepton_pt']:
            x_label += ' [GeV]'
        plt.xlabel( x_label, CMS.x_axis_title )

        y_label = 'Ratio to \n$' + measurements_latex['TTJets_powhegPythia8'] + '$'
        plt.ylabel( y_label, CMS.y_axis_title_tiny )

        #draw a horizontal line at y=1 for central MC
        plt.axhline(y = 1, color = 'black', linewidth = 2)

        central_mc = histograms['TTJets_powhegPythia8']
        for key, hist in sorted( histograms.iteritems() ):

            if not 'measured' in key:

                ratio = None
                if not 'unfolded_with_systematics' in key:
                    ratio = hist.Clone()
                    ratio.Divide( central_mc ) #divide by central mc sample
                else:
                    ratio = central_mc.Clone()
                    syst_errors = graph_to_value_errors_tuplelist(hist)
                    for bin_i in range( 1, ratio.GetNbinsX() + 1 ):
                        syst_value, syst_error_down, syst_error_up  = syst_errors[bin_i-1]

                        mc = central_mc.GetBinContent(bin_i)
                        data = list(hist.y())[bin_i-1]

                        ratio.SetBinContent( bin_i, data / mc)
                        ratio.SetBinError( bin_i, syst_error_down / mc )

                if not 'unfolded' in key:
                    line, h = rplt.hist( ratio, axes = ax2, label = 'do_not_show' )
                    if dashes[key] != None:
                        line.set_dashes(dashes[key])
                        h.set_dashes(dashes[key])
                elif 'unfolded_with_systematics' in key:
                        ratio.markersize = 2
                        ratio.marker = 'o'
                        ratio.color = 'black'
                        rplt.errorbar( 
                            ratio, 
                            axes = ax2, 
                            label = 'do_not_show', 
                            xerr = None, 
                            capsize = 0, 
                            elinewidth = 2, 
                            zorder = len( histograms ) + 10
                        )
                else:
                    ratio.markersize = 2
                    ratio.marker = 'o'

                    rplt.errorbar( ratio, 
                        axes = ax2, 
                        label = 'do_not_show', 
                        xerr = None, 
                        capsize = 15, 
                        capthick = 3, 
                        elinewidth = 2, 
                        zorder = len( histograms ) + 9
                    )


        if variable == 'MET':
            ax2.set_ylim( ymin = 0.8, ymax = 1.2 )
            ax2.yaxis.set_major_locator( MultipleLocator( 0.5 ) )
            ax2.yaxis.set_minor_locator( MultipleLocator( 0.1 ) )
        if variable == 'MT':
            ax2.set_ylim( ymin = 0.8, ymax = 1.2 )
            ax2.yaxis.set_major_locator( MultipleLocator( 0.2 ) )
            ax2.yaxis.set_minor_locator( MultipleLocator( 0.1 ) )
        elif variable == 'HT':
            ax2.set_ylim( ymin = 0.7, ymax = 1.3 )
            ax2.yaxis.set_major_locator( MultipleLocator( 0.2 ) )
            ax2.yaxis.set_minor_locator( MultipleLocator( 0.1 ) )
        elif variable == 'ST':
            ax2.set_ylim( ymin = 0.7, ymax = 1.5 )
            ax2.yaxis.set_major_locator( MultipleLocator( 0.5 ) )
            ax2.yaxis.set_minor_locator( MultipleLocator( 0.1 ) )
        elif variable == 'WPT':
            ax2.set_ylim( ymin = 0.8, ymax = 1.2 )
            ax2.yaxis.set_major_locator( MultipleLocator( 0.5 ) )
            ax2.yaxis.set_minor_locator( MultipleLocator( 0.1 ) )
        elif variable == 'NJets':
            ax2.set_ylim( ymin = 0.7, ymax = 1.5 )
        elif variable == 'abs_lepton_eta' or variable == 'abs_lepton_eta_coarse':
            ax2.set_ylim( ymin = 0.8, ymax = 1.2 )
            ax2.yaxis.set_major_locator( MultipleLocator( 0.2 ) )
            ax2.yaxis.set_minor_locator( MultipleLocator( 0.1 ) )
        elif variable == 'lepton_pt':
            ax2.set_ylim( ymin = 0.8, ymax = 1.3 )
            ax2.yaxis.set_major_locator( MultipleLocator( 0.2 ) )
            ax2.yaxis.set_minor_locator( MultipleLocator( 0.1 ) )


    if CMS.tight_layout:
        plt.tight_layout()

    # Save the plots
    path = '{output_folder}/xsections/{phaseSpace}/{variable}/'
    path = path.format(
        output_folder = output_folder,
        phaseSpace = phase_space,
        variable = variable
    )
    make_folder_if_not_exists( path )
    for output_format in output_formats:
        filename = path + '/' + histname + '.' + output_format
        plt.savefig( filename )

    del hist_data
    if 'central' in category: del hist_data_with_systematics
    plt.close()
    gc.collect()
    return
示例#47
0
    # axes = plt.subplot()

    try:

        axes.set_yscale('log')
        rplt.bar(stack,
                 stacked=True,
                 axes=axes,
                 yerr=False,
                 alpha=0.5,
                 rasterized=True,
                 ec='grey',
                 linewidth=1)
        if hists['Data'].Integral():
            rplt.errorbar(hists['Data'],
                          xerr=False,
                          emptybins=False,
                          axes=axes)
    except:
        # print "no data events..."
        # continue
        pass

    for signalsample in signalsamples:
        # print signalsample
        # print plottedsignals[histogramName.split("_")[0]  ]
        skip = 1
        if any([
                thissig in signalsample
                for thissig in plottedsignals[histogramName.split("_")[0]]
        ]):
            skip = 0
示例#48
0
def plot_hardest_pt_corresponding_triggers():

    properties = parse_file(input_analysis_file, pT_lower_cut=0)

    pTs = properties['cor_hardest_pT']
    trigger_names = properties['trigger_name']
    prescales = properties['prescale']

    expected_trigger_names = [
        "HLT_Jet180U", "HLT_Jet140U", "HLT_Jet100U", "HLT_Jet70U",
        "HLT_Jet50U", "HLT_Jet30U", "HLT_Jet15U"
    ]
    labels = [
        "Jet180u", "Jet140u", "Jet100u", "Jet70u", "Jet50u", "Jet30u", "Jet15u"
    ]

    colors = ['purple', 'orange', 'brown', 'red', 'blue', 'magenta', 'green']

    pt_hists = []
    for i in range(0, len(expected_trigger_names)):
        pt_hists.append(
            Hist(50,
                 0,
                 1000,
                 title=labels[i].upper(),
                 markersize=1.0,
                 color=colors[i],
                 linewidth=5))

    found = False
    for i in range(0, len(pTs)):
        found = False
        for j in range(0, len(expected_trigger_names)):
            if expected_trigger_names[j] in trigger_names[i]:
                pt_hists[j].Fill(pTs[i], prescales[i])
                found = True

        if not found:
            print trigger_names[i]
            pt_hists[len(pt_hists) - 1].Fill(pTs[i], prescales[i])

    for k in range(0, len(pt_hists)):
        rplt.errorbar(pt_hists[k],
                      marker='o',
                      markersize=10,
                      pickradius=8,
                      capthick=5,
                      capsize=8,
                      elinewidth=5)

    plt.yscale('log')
    plt.autoscale(True)

    plt.gca().set_ylim(0.1, 10e8)

    plt.legend(loc=0, frameon=0)

    plt.xlabel('$p_T \mathrm{(GeV)}$', fontsize=65)

    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)

    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.20, 0.845),
                        xycoords='figure fraction',
                        frameon=0)
    plt.gca().add_artist(ab)
    preliminary_text = "Prelim. (20\%)"
    plt.gcf().text(0.265,
                   0.835,
                   preliminary_text,
                   fontsize=50,
                   weight='bold',
                   color='#444444',
                   multialignment='center')

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

    plt.savefig("plots/" + get_version(input_analysis_file) +
                "/hardest_pT_corresponding_triggers.pdf")
    # plt.show()
    plt.clf()
示例#49
0
            "hists/output/%s/hist-%s.root.root" %
            (signalsample, "_".join(signalsample.split("_")[:2])))
        try:
            hists[signalsample] = signalfile.Get(histogramName).Clone(
                signalsample)
            hists[signalsample].SetTitle(
                r"%s" % signalsample.replace("_", " ").replace("SRAll", ""))

            if makeCutFlowTables:
                cutflows[hists[signalsample].GetTitle(
                )] = cutFlowTools.histToCutFlow(hists[signalsample])

            rplt.errorbar(hists[signalsample],
                          axes=axes,
                          yerr=False,
                          xerr=False,
                          alpha=0.9,
                          fmt="--",
                          markersize=0)
            hists[signalsample].Scale(1. /
                                      hists[signalsample].GetBinContent(1))
            rplt.errorbar(hists[signalsample],
                          axes=axes2,
                          yerr=False,
                          xerr=False,
                          alpha=0.9,
                          fmt="--",
                          markersize=0)
            print "%s %f" % (signalsample, hists[signalsample].Integral())
        except:
            continue
示例#50
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()
示例#51
0
    
    bins = array('d', [0, 25, 45, 70, 100, 1000])
    h_data = Hist(bins.tolist())
    h_data.SetBinContent(1, 2146)
    h_data.SetBinError(1, 145)
    h_data.SetBinContent(2, 3399)
    h_data.SetBinError(2, 254)
    h_data.SetBinContent(3, 3723)
    h_data.SetBinError(3, 69)
    h_data.SetBinContent(4, 2256)
    h_data.SetBinError(4, 53)
    h_data.SetBinContent(5, 1722)
    h_data.SetBinError(5, 91)
    h_data.SetTitle('input distribution')
    h_new = generate_toy_MC_from_distribution(h_data)
    h_new.SetTitle('toy MC')
    fig = plt.figure(figsize=(16, 10), dpi=100, facecolor='white')
    axes = plt.axes([0.15, 0.15, 0.8, 0.8])
    axes.xaxis.set_minor_locator(AutoMinorLocator())
    axes.yaxis.set_minor_locator(AutoMinorLocator())
    axes.tick_params(which='major', labelsize=15, length=8)
    axes.tick_params(which='minor', length=4)
    rplt.hist(h_new, axes=axes)
    rplt.errorbar(h_data, emptybins=False, axes=axes)
    plt.xlabel('Mass', position=(1., 0.), ha='right')
    plt.ylabel('Events', position=(0., 1.), va='top')
    plt.legend(numpoints=1)
    plt.savefig('toy_MC_test.png')
    print  list( h_data.y() )
    print list( h_new.y() )
示例#52
0
hMeas = Hist(40, -10.0, 10.0)
hTrue.SetLineColor('red')
hMeas.SetLineColor('blue')
#  Test with a Gaussian, mean 0 and width 2.
for i in xrange(10000):
    xt = gRandom.Gaus(0.0, 2.0)
    x = smear(xt)
    hTrue.Fill(xt)
    if x != None: hMeas.Fill(x)

print "==================================== UNFOLD ==================================="
unfold = RooUnfoldBayes(response, hMeas, 4)
#  OR
# unfold= RooUnfoldSvd     (response, hMeas, 20);   #  OR
# unfold= RooUnfoldTUnfold (response, hMeas);

hReco = unfold.Hreco()
h_unfolded = asrootpy(hReco)
unfold.PrintTable(cout, hTrue)

plt.figure(figsize=(16, 12), dpi=100)
rplt.hist(hTrue, label='truth', stacked=False)
rplt.hist(hMeas, label='measured', stacked=False)
rplt.errorbar(h_unfolded, label='unfolded')
plt.xlabel('var')
plt.ylabel('Events')
plt.title('Unfolding')
plt.legend()
plt.savefig('plots/RooUnfoldBayesExample.png')
print 'Done'
示例#53
0
def main(): 
  
  JetPtBins = [5,10,20,30,40,60,80,100,150,500]
  jetPt = [(JetPtBins[i],JetPtBins[i+1]) for i in range(8)]
  print(jetPt)
  #JetPtCenter = [7.5,15,25,35,50,70,90,125,325]
  JetPtCenter = [6.5,12.45,23.34,33.83,46.75,67.73,88.01,116.11,194.61]
  LeadPtMode = [2.0,3.0,5.6,8.9,9.9,14.8,20.7,26.0,34.6]
  LeadPtMean = [2.35,3.72,6.66,9.59,13.58,17.98,23.27,27.55,31.68]
  LeadPtError = [0.93,1.69,3.18,4.43,6.74,8.34,9.68,10.27,10.55]
  JetPtError = [2.5,5,5,5,10,10,10,25,175]
  JetPtLeadPtG = Graph(len(JetPtCenter)) #Gives jet pT as a function of leading pT
  JetPtLeadPtGerr = Graph(len(JetPtCenter))
  LeadPtJetPtG = Graph(len(JetPtCenter))
  LeadPtJetPtGerr = Graph(len(JetPtCenter))
  for i,(x,y,e) in enumerate(zip(LeadPtMean,JetPtCenter,JetPtError)):
    JetPtLeadPtG.SetPoint(i,x,y)
    JetPtLeadPtGerr.SetPoint(i,x,e)
  for i,(x,y,e) in enumerate(zip(JetPtCenter,LeadPtMean,LeadPtError)):
    LeadPtJetPtG.SetPoint(i,x,y)
    LeadPtJetPtGerr.SetPoint(i,x,e)
  
  Njets = 8
  

  
  
  topcomment = "_systematics_Triggered"
  
  finderName = ["Full jets, Anti-k_\mathrm{T} R = 0.4","Charged Jets, Anti-k_\mathrm{T} R = 0.4"]
  finderType = ["Full","Charged"]
  setTitle = ["0","1","2","3","4","5"]
  finderR = {4,4}
  
  iC = 0
  logx = 1
  doWeight = 1
  iS = 0

  f = root_open("errors_test.root", 'read')

  gGausRMS = f.Get("gGausRMS{:02d}".format(iS))
  gGausRMSerr = f.Get("gGausRMS{:02d}_Systematics".format(iS))
  gGausYield = f.Get("gGausYield{:02d}".format(iS))
  gGausYielderr = f.Get("gGausYield{:02d}_Systematics".format(iS))
  gGammaRMS = f.Get("gGammaRMS{:02d}".format(iS))
  gGammaRMSerr = f.Get("gGammaRMS{:02d}_Systematics".format(iS))
  gGammaYield = f.Get("gGammaYield{:02d}".format(iS))
  gGammaYielderr = f.Get("gGammaYield{:02d}_Systematics".format(iS))
  
  start = 4
  iS = 0
  stats = [None if ij < start else f.Get("JetConeJtWeightBinNFin{:02d}JetPt{:02d}_Statistics".format(iS,ij)) for ij in range(8)]
  fits = [None if ij < start else f.Get("JetConeJtWeightBinNFin{:02d}JetPt{:02d}_FitFunction".format(iS,ij)) for ij in range(8)]
  print(fits)


  print(stats)

  n_figs = 2
  
  
  
#   if(n_figs == 2):
#     fig,axs = defs.makeRatio(xlog=True,ylog=True,d=d,shareY=False,figsize = (5,6),grid=False)
#   else:
#     fig, axs = defs.makegrid(n_figs/2,2,xlog=True,ylog=True,d=d,shareY=False,figsize= (10,7.5) if n_figs == 4 else (n_figs*15/8,7.5) )
#   axs = axs.reshape(n_figs)
#   if(n_figs == 2):
#     pT = jetPt[start]
#     print(pT)
#     axs[0].text(0.8,7,d['system'] +'\n'+  d['jettype'] +'\n'+ d['jetalg'] + '\n' + d['cut'] + '\n' + r'${:02d}\:\mathrm{{GeV}}/c < p_{{\mathrm{{T,jet}}}} < {:02d}\:\mathrm{{GeV}}/c$'.format(pT[0],pT[1]),fontsize = 10)
#   else:
#     axs[1].text(0.12,0.002,d['system'] +'\n'+  d['jettype'] +'\n'+ d['jetalg'] + '\n' + d['cut'],fontsize = 11)
#   
  ratios = []
  xs2 = []

  for jT,pT,ij,fit in zip(stats[start:],jetPt[start:],range(start,9),fits[start:]):
    color = colors[1]
    fig,axs = defs.makeRatio(xlog=True,ylog=True,d=d,shareY=False,figsize = (5,6),grid=False)
    axs = axs.reshape(n_figs)
    axs[0].text(0.8,7,d['system'] +'\n'+  d['jettype'] +'\n'+ d['jetalg'] + '\n' + d['cut'] + '\n' + r'${:02d}\:\mathrm{{GeV}}/c < p_{{\mathrm{{T,jet}}}} < {:02d}\:\mathrm{{GeV}}/c$'.format(pT[0],pT[1]),fontsize = 10)
    ax = axs[0]
    xs = np.arange(0,xhigh,0.01).tolist()
    for ii in range(6):
      print(fit.GetParameter(ii))
    #B2 is Gauss normalization
    #B3 is Gamma normalization
    gauss = fit.Clone()
    gauss.SetParameter(3,0)
    gamma = fit.Clone()
    gamma.SetParameter(0,0)
    ys = [fit.Eval(x) for x in xs]
    ys2 = [gauss.Eval(x) for x in xs]
    ys3 = [gamma.Eval(x) for x in xs]
    ax.plot(xs,ys2,'b:',label="Narrow")
    ax.plot(xs,ys3,'r--',label="Wide")
    ax.plot(xs,ys,'k',label="Total")

    jT.SetMarkerColor(color)
    jT.SetMarkerStyle(24)
    jT.SetLineColor(color)
    jT.SetMarkerSize(mSize)
    plot = rplt.errorbar(jT,xerr=False,emptybins=False,axes=ax,label="ALICE",fmt='o',fillstyle='none') #Plot jT histogram, 
    line = plot.get_children()[0]
    line.set_markersize(mSize)
    if(True):
      line.set_markerfacecolor('none')
      #line.set_markeredgecolor(color)
      line.set_color(color)
#     line.set_markerfacecolor('none')
#     line.set_markeredgecolor(colors[c])
#     line.set_markerfacecolor('none')
#     line.set_markeredgecolor('none')
#     line.set_drawstyle('default')
#     line.set_linestyle('dashed')  
#     line.set_color(colors[c])
    if(n_figs > 2):
      ax.text(0.5,1e2,r'${:02d}\:\mathrm{{GeV}} < p_{{\mathrm{{T,jet}}}} < {:02d}\:\mathrm{{GeV}}$'.format(pT[0],pT[1])) 
    ax.set_xlim([xlow,xhigh]) #Set x-axis limits
    ax.set_ylim([1e-6,2e3]) #Set y-axis limits
    #ax.set_xticklabels(ax.get_xticklabels(),horizontalalignment='left')
    x_ = Double()
    y1 = Double()
    xe = Double()
    ye = Double()
    NC = jT.GetN()
    y2 = []
    y2e = []
    xs=[]
    ex = []
    for ii in range(NC):
      jT.GetPoint(ii,x_,y1)
      xe = jT.GetErrorX(ii)
      ye = jT.GetErrorY(ii)
      x1 = x_*1.0
      xs.append(x1)
      ex.append(xe)
      if(y1 > 0):
        y2.append(y1/fit.Eval(x1))
        y2e.append(ye/fit.Eval(x1))
      else:
        y2.append(0)
        y2e.append(0)
    #ratio = jT.Clone()
    ratio= Graph(NC)

    print(xs[::5])
    print(y2[::5])
    print(ex[::5])
    print(y2e[::5])
    for x0,y0,x0e,y0e,i in zip(xs,y2,ex,y2e,range(NC)):
      ratio.SetPoint(i,x0,y0)
      ratio.SetPointError(i,x0e,x0e,y0e,y0e)
    ratios.append(ratio)
    print(ratio)
    ax = axs[1]
  #for ratio,pT,ax,color in zip(ratios,jetPt[start:],axs[n_figs/2:n_figs+1],colors[1:]):
    
    print("Debug")
    ratio.SetMarkerColor(color)
    ratio.SetLineColor(color)
    ratio.SetMarkerStyle(24)
    ax.plot([0,20],[1,1],'k--')
    #ratio.SetMarkerSize(mSize)
    plot = rplt.errorbar(ratio,xerr=False,emptybins=False,axes=ax,label=r"Ratio",fmt='o',fillstyle='none') #Plot jT histogram, 
    line = plot.get_children()[0]
    line.set_markersize(mSize)
    if(True):
      line.set_markerfacecolor('none')
      #line.set_markeredgecolor(color)
      line.set_color(color)
    #ax.plot(xs2,ratio)
    ax.set_yscale('linear')
    ax.set_xlim([xlow,xhigh]) #Set x-axis limits
    ax.set_ylim([0,2.75]) #Set y-axis limits  
    ax.set_ylabel('Signal/Fit',fontsize=14) #Add y-axis labels to left- and righmost subfigures

    
    handles, labels = axs[0].get_legend_handles_labels()
    handles = [handles[3],handles[2],handles[0],handles[1]]
    labels = [labels[3],labels[2],labels[0],labels[1]]
  
    handles = [container.ErrorbarContainer(h,has_xerr=False,has_yerr=True) if isinstance(h, container.ErrorbarContainer) else h for h in handles]
    axs[0].legend(handles,labels,loc = 'lower left',numpoints=1)
  
    axs[0].text(0.11,3e2,"ALICE",weight='bold')
  
    fig.align_labels()
    print("Save PythonFigures/JtSignalFinalFitJetPt{}.pdf".format(ij))
    plt.savefig("PythonFigures/JtSignalFinalFitJetPt{}.pdf".format(ij),format='pdf') #Save figure
    plt.show() #Draw figure on screen
h1.fillcolor = 'green'
h1.linecolor = 'green'
h1.linewidth = 0

h2.fillstyle = 'solid'
h2.fillcolor = 'red'
h2.linecolor = 'red'
h2.linewidth = 0

stack = HistStack()
stack.Add(h1)
stack.Add(h2)

ratio = h3 / (h1 + h2)
ratio = Hist.divide(h3, h1 + h2)

# plot with matplotlib

plt.figure(figsize=(16, 12), dpi=200)
subplot(211)
rplt.bar(stack, stacked=True)
rplt.errorbar(h3, xerr=False, emptybins=False)
plt.xlabel('Mass', position=(1., 0.), ha='right', fontsize=24)
plt.ylabel('Events', position=(0., 1.), va='top', fontsize=24)
plt.tick_params(**CMS.axis_label_major)
plt.tick_params(**CMS.axis_label_minor)
plt.legend(numpoints=1)
subplot(212)
rplt.errorbar(ratio, emptybins=False)
plt.savefig('plots/Hist_with_dataMCRatio_pylab.png')
示例#55
0
    hl1 = f.Get("btagCSV_l_{0}__rec".format(bin))
    hc1 = f.Get("btagCSV_c_{0}__rec".format(bin))
    hb1 = f.Get("btagCSV_b_{0}__rec".format(bin))

    hl2 = f.Get("btagBDT_l_{0}__rec".format(bin))
    hc2 = f.Get("btagBDT_c_{0}__rec".format(bin))
    hb2 = f.Get("btagBDT_b_{0}__rec".format(bin))

    for h in [hl1, hc1, hb1, hl2, hc2, hb2]:
        h.Rebin(10)
        h.Scale(1.0 / h.Integral())
    plt.figure(figsize=(6,6))
    hl1.color = "green"
    hc1.color = "blue"
    hb1.color = "red"
    rplt.errorbar(hl1, label="udsg")
    rplt.errorbar(hc1, label="c")
    rplt.errorbar(hb1, label="b")
    plt.yscale("log")
    plt.legend(loc="best", numpoints=1, frameon=False)
    plt.grid()
    plt.ylim(0.001,1.0)
    plt.xlabel("CSV b-discriminator")
    plt.ylabel("fraction of jets")
    svfg("plots/btagCSV_{0}.pdf".format(bin))

    plt.figure(figsize=(6,6))
    hl2.color = "green"
    hc2.color = "blue"
    hb2.color = "red"
    rplt.errorbar(hl2, color="green")
示例#56
0
def trigger_prescales():
    mod_hists = parsed_linear[0]

    prescale_hists = {}
    for key, value in mod_hists.items():
        if "prescale" in key:
            prescale_hists[key.split("_prescale")[0]] = value

    colors = [
        'green', 'magenta', 'blue', 'red', 'orange', '#cecece', 'yellow',
        'cyan', 'purple'
    ][::-1]
    legend_labels = [
        "Jet370", "Jet300", "Jet240", "Jet190", "Jet150", "Jet110", "Jet80",
        "Jet60", "Jet30"
    ][::-1]
    hist_labels = [
        "HLT_Jet370", "HLT_Jet300", "HLT_Jet240", "HLT_Jet190", "HLT_Jet150",
        "HLT_Jet110", "HLT_Jet80", "HLT_Jet60", "HLT_Jet30"
    ][::-1]

    plots = []
    for i in range(len(hist_labels)):
        mod_hist = prescale_hists[hist_labels[i]]
        hist = mod_hist.hist()

        hist.SetColor(colors[i])
        hist.SetTitle(legend_labels[i])
        hist.SetLineWidth(5)

        # plots.append( rplt.hist(hist, linewidth=10) )

        # , markeredgecolor=colors[i], label=labels[i], xerr=filtered_x_err, yerr=filtered_y_err, ls='None', alpha=1.0, marker='o'
        plots.append(
            rplt.errorbar(hist,
                          linewidth=5,
                          markeredgecolor=colors[i],
                          marker="o",
                          markersize=15,
                          pickradius=20,
                          yerr=False,
                          capthick=5,
                          capsize=8,
                          elinewidth=5))

    plt.autoscale()
    plt.gca().set_ylim(1e1, 5e8)
    plt.gca().set_xlim(0.5, 1e6)

    average_prescales = [
        1.00, 1.00, 4.15, 27.80, 74.71, 575.46, 2151.41, 9848.00, 239202.97
    ][::-1]
    for i in range(0, len(hist_labels)):

        plt.plot([average_prescales[i], average_prescales[i]], [3e1, 1e2],
                 lw=10,
                 ls="dashed",
                 color=colors[i])

        plt.gca().text((average_prescales[i]),
                       2e1,
                       str(average_prescales[i]),
                       color=colors[i],
                       horizontalalignment='center')

    # # Info about R, pT_cut, etc.
    extra = Rectangle((0, 0),
                      1,
                      1,
                      fc="w",
                      fill=False,
                      edgecolor='none',
                      linewidth=0)
    handles = [extra]
    labels = ["AK5; $\left| \eta \\right| < 2.5$"]
    info_legend = plt.gca().legend(handles,
                                   labels,
                                   frameon=0,
                                   borderpad=0.1,
                                   fontsize=60,
                                   bbox_to_anchor=[0.30, 0.98])
    plt.gca().add_artist(info_legend)

    plt.gca().set_xlabel("Trigger Prescale", fontsize=70, labelpad=10)
    plt.gca().set_ylabel("Events", fontsize=70, labelpad=50)

    plt.gca().add_artist(logo_box(0.103, 1.00))

    plt.gca().set_xscale('log')
    plt.gca().set_yscale('log')

    handles = plots
    legend = plt.legend(handles,
                        legend_labels,
                        fontsize=60,
                        frameon=0,
                        bbox_to_anchor=[0.99, 0.99])
    ax = plt.gca().add_artist(legend)

    # plt.gca().xaxis.set_major_formatter(mpl.ticker.ScalarFormatter(useMathText=False))

    outside_text = plt.gca().legend([extra], ["CMS 2011 Open Data"],
                                    frameon=0,
                                    borderpad=0,
                                    fontsize=50,
                                    bbox_to_anchor=(1.0, 1.005),
                                    loc='lower right')
    plt.gca().add_artist(outside_text)

    plt.tick_params(which='major', width=5, length=25, labelsize=70, pad=10)
    plt.tick_params(which='minor', width=3, length=15)

    # plt.tight_layout()

    plt.gcf().set_size_inches(30, 24, forward=1)
    plt.savefig(default_dir + "trigger_prescales.pdf")

    plt.clf()
def plot_efficiencies(efficiency_data, efficiency_mc, scale_factor,
                      fit_data, fit_mc, fit_SF, fit_function,
                      x_limits, x_title, y_title, save_as_name):    
    # plot with matplotlib
    plt.figure(figsize=(16, 16), dpi=200, facecolor='white')
    gs = gridspec.GridSpec(2, 1, height_ratios=[5, 1]) 

    ax0 = plt.subplot(gs[0])
    ax0.minorticks_on()
    ax0.grid(True, 'major', linewidth=2)
    ax0.grid(True, 'minor')
    plt.tick_params(**CMS.axis_label_major)
    plt.tick_params(**CMS.axis_label_minor)
    
    ax0.yaxis.set_major_formatter(FormatStrFormatter('%.1f'))
    
    rplt.errorbar(efficiency_data, xerr=True, emptybins=True, axes=ax0)
    rplt.errorbar(efficiency_mc, xerr=False, emptybins=True, axes=ax0)
    
    ax0.set_xlim(x_limits)
    
    plt.ylabel(y_title, CMS.y_axis_title)
    
    plt.title(r'e+jets, CMS Preliminary, $\mathcal{L}$ = 5.1 fb$^{-1}$ at $\sqrt{s}$ = 7 TeV', CMS.title)
    plt.legend(['data', r'$\mathrm{t}\bar{\mathrm{t}}$ MC'], numpoints=1, loc='lower right', prop=CMS.legend_properties)
    
    #add fits
    x = numpy.linspace(fit_data.GetXmin(), fit_data.GetXmax(), fit_data.GetNpx())
    function_data = frompyfunc(fit_data.Eval, 1, 1)
    plot(x, function_data(x), axes=ax0, color = 'black', linewidth = 2)
    
    x = numpy.linspace(fit_mc.GetXmin(), fit_mc.GetXmax(), fit_mc.GetNpx())
    function_mc = frompyfunc(fit_mc.Eval, 1, 1)
    plot(x, function_mc(x), axes=ax0, color = 'red', linewidth = 2)
    
    ax1 = plt.subplot(gs[1])
    #disable labels for plot 1
    plt.setp(ax0.get_xticklabels(minor = True), visible=False)
    plt.setp(ax0.get_xticklabels(), visible=False)
    
    ax1.minorticks_on()
    ax1.grid(True, 'major', linewidth=2)
    ax1.grid(True, 'minor')

    ax1.yaxis.set_major_locator(MultipleLocator(1.))
    ax1.yaxis.set_minor_locator(MultipleLocator(0.5))
    ax1.yaxis.set_major_formatter(FormatStrFormatter('%.1f'))

    ax1.xaxis.set_major_formatter(FormatStrFormatter('%d'))
    plt.tick_params(**CMS.axis_label_major)
    plt.tick_params(**CMS.axis_label_minor)

    plt.xlabel(x_title, CMS.x_axis_title)
    plt.ylabel('data/MC', CMS.y_axis_title)
    
    rplt.errorbar(scale_factor, xerr=True, emptybins=False, axes=ax1)
    
    ax1.set_xlim(x_limits)
    #add fit formulas
    ax0.text(0.1, 0.15, '$\epsilon$ = ' + get_fitted_function_str(fit_data, fit_function),
        verticalalignment='bottom', horizontalalignment='left',
        transform=ax0.transAxes,
        color='black', fontsize=60, bbox = dict(facecolor = 'white', edgecolor = 'none', alpha = 0.5))
    ax0.text(0.1, 0.05, '$\epsilon$ = ' + get_fitted_function_str(fit_mc, fit_function),
        verticalalignment='bottom', horizontalalignment='left',
        transform=ax0.transAxes,
        color='red', fontsize=60, bbox = dict(facecolor = 'white', edgecolor = 'none', alpha = 0.5))
    
    ax1.text(0.1, 0.10, '$\epsilon$ = ' + get_fitted_function_str(fit_SF, fit_function),
        verticalalignment='bottom', horizontalalignment='left',
        transform=ax1.transAxes,
        color='green', fontsize=60, bbox = dict(facecolor = 'white', edgecolor = 'none', alpha = 0.5))
    
    #add scale factor fit
    x = numpy.linspace(fit_SF.GetXmin(), fit_SF.GetXmax(), fit_SF.GetNpx())
    function_SF = frompyfunc(fit_SF.Eval, 1, 1)
    plot(x, function_SF(x), axes=ax1, color = 'green', linewidth = 2)
    
    if 'jet_pt' in trigger_under_study:
        ax1.xaxis.set_minor_formatter(FormatStrFormatter('%d'))
        plt.draw()
        labels = [item.get_text() for item in ax1.get_xmajorticklabels()]
        minor_labels = [item.get_text() for item in ax1.get_xminorticklabels()]
        new_labels, new_minor_labels = [], []
        keep_labels = ['20','50','100','150','200']
        for label in labels:
            if not label in keep_labels:
                label = ''
            new_labels.append(label)
        for label in minor_labels:
            if not label in keep_labels:
                label = ''
            new_minor_labels.append(label)
        ax1.set_xticklabels(new_labels)
        ax1.set_xticklabels(new_minor_labels, minor = True)
        
    plt.tight_layout()
    
    for output_format in output_formats:
        plt.savefig(output_folder + save_as_name + '_efficiency_matplot.' + output_format)  
示例#58
0
def trigger_efficiency_plot():
    mod_hists = parsed_linear[0]

    colors = [
        'green', 'magenta', 'blue', 'red', 'orange', '#cecece', 'yellow',
        'cyan', 'purple'
    ]
    labels = [
        "Jet140U / 100U", "Jet100U / 70U", "Jet70U / 50U", "Jet50U / 30U",
        "Jet30U / 15U\_HNF", ""
    ]
    labels = [
        "Jet370 / Jet300", "Jet300 / Jet240", "Jet240 / Jet190",
        "Jet190 / Jet150", "Jet150 / Jet110", "Jet 110 / Jet80",
        "Jet80 / Jet60", "Jet60 / Jet30"
    ]
    hist_labels = [("HLT_Jet370", "HLT_Jet300"), ("HLT_Jet300", "HLT_Jet240"),
                   ("HLT_Jet240", "HLT_Jet190"), ("HLT_Jet190", "HLT_Jet150"),
                   ("HLT_Jet150", "HLT_Jet110"), ("HLT_Jet110", "HLT_Jet80"),
                   ("HLT_Jet80", "HLT_Jet60"), ("HLT_Jet60", "HLT_Jet30")]
    lower_pTs = [370, 300, 240, 190, 150, 110, 80, 60, 30]

    # rplt.hist(mod_hists[0].hist())

    plots = []
    for i in range(len(hist_labels)):

        first_hist, second_hist = mod_hists[hist_labels[i][0]], mod_hists[
            hist_labels[i][1]]

        ratio_hist = first_hist.hist() / second_hist.hist()

        ratio_hist.SetColor(colors[i])
        ratio_hist.SetTitle(labels[i])

        # rplt.errorbar(ratio_hist, emptybins=False, xerr=1, yerr=1, ls='None', marker='o', markersize=10, pickradius=8, capthick=5, capsize=8, elinewidth=5, alpha=1.0)
        plots.append(rplt.errorbar(ratio_hist, emptybins=True, alpha=0.))

    for i in range(len(plots)):
        data_plot = plots[i]

        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()

        filtered_x, filtered_y, filtered_x_err, filtered_y_err = [], [], [], []
        for x, y, xerr, yerr in zip(data_points_x, data_points_y,
                                    data_x_errors, data_y_errors):
            if x > lower_pTs[i]:
                filtered_x.append(x)
                filtered_y.append(y)
                filtered_x_err.append(xerr)
                filtered_y_err.append(yerr)

        plt.errorbar(filtered_x,
                     filtered_y,
                     zorder=range(len(plots))[len(plots) - i - 1],
                     color=colors[i],
                     markeredgecolor=colors[i],
                     label=labels[i],
                     xerr=filtered_x_err,
                     yerr=filtered_y_err,
                     ls='None',
                     alpha=1.0,
                     marker='o',
                     markersize=10,
                     pickradius=8,
                     capthick=5,
                     capsize=8,
                     elinewidth=5)

    extra = Rectangle((0, 0),
                      1,
                      1,
                      fc="w",
                      fill=False,
                      edgecolor='none',
                      linewidth=0)

    plt.autoscale()
    plt.gca().set_ylim(1e-3, 7e4)
    """
	cms_turn_on_pTs = [250, 200, 150, 120, 70]
	for i in range(0, len(hist_labels)):

		'''
		if cms_turn_on_pTs[i] != 0:
			source = "MOD"
			plt.gca().annotate(str(cms_turn_on_pTs[i]) + " GeV", xy=(cms_turn_on_pTs[i], 1.), xycoords='data', xytext=(-100, 350),  textcoords='offset points', color=colors[i], size=50, va="center", ha="center", arrowprops=dict(arrowstyle="simple", facecolor=colors[i], zorder=99, connectionstyle="angle3,angleA=0,angleB=90") )
		'''

		plt.plot([ cms_turn_on_pTs[i], cms_turn_on_pTs[i] ], [ 1e0, 2e1 ], lw=10, ls="dashed", color=colors[i])

		plt.gca().text((cms_turn_on_pTs[i]), 3e1, str(cms_turn_on_pTs[i]) + " GeV", color=colors[i], horizontalalignment='center')

        """
    # Horizontal Line.
    plt.plot([0] + list(mod_hists[hist_labels[i][0]].hist().x()),
             [1] * (1 + len(list(mod_hists[hist_labels[i][0]].hist().x()))),
             color="black",
             linewidth=5,
             linestyle="dashed")

    # Info about R, pT_cut, etc.

    handles = [extra]
    labels = ["AK5; $\left| \eta \\right| < 2.5$"]
    info_legend = plt.gca().legend(handles,
                                   labels,
                                   loc=7,
                                   frameon=0,
                                   borderpad=0.1,
                                   fontsize=60,
                                   bbox_to_anchor=[0.28, 0.92])
    plt.gca().add_artist(info_legend)

    plt.gca().set_xlabel("Trigger Jet $p_T$ [GeV]", fontsize=70, labelpad=50)
    plt.gca().set_ylabel("Ratio", fontsize=70, labelpad=50)

    plt.gca().add_artist(logo_box(0.114, 0.98))

    plt.gca().xaxis.set_minor_locator(MultipleLocator(10))
    plt.gca().set_yscale('log')

    handles, labels = plt.gca().get_legend_handles_labels()
    legend = plt.legend(handles[::-1][:-5],
                        labels[::-1][:-5],
                        fontsize=60,
                        frameon=0,
                        bbox_to_anchor=[0.99, 0.99])
    ax = plt.gca().add_artist(legend)

    outside_text = plt.gca().legend([extra], ["CMS 2011 Open Data"],
                                    frameon=0,
                                    borderpad=0,
                                    fontsize=50,
                                    bbox_to_anchor=(1.0, 1.005),
                                    loc='lower right')
    plt.gca().add_artist(outside_text)

    plt.tick_params(which='major', width=5, length=25, labelsize=70)
    plt.tick_params(which='minor', width=3, length=15)

    plt.tight_layout()

    plt.gcf().set_size_inches(30, 24, forward=1)
    plt.savefig(default_dir + "trigger_efficiency.pdf")

    plt.clf()
示例#59
0
    #             )

    save_hdict("sob.root", hists)

    #Now the plotting part
    tf = rootpy.io.File("sob.root")

    h_bkg_s = tf.Get("total_background_sob_shapes_fit_s")
    h_bkg_b = tf.Get("total_background_sob_shapes_fit_b")
    h_sig_s = tf.Get("total_signal_sob_shapes_fit_s")
    h_sig_p = tf.Get("total_signal_sob_shapes_prefit")

    h_data = tf.Get("data_obs_sob_shapes_prefit")

    rplt.hist(h_bkg_s)
    rplt.errorbar(h_data)

    color_signal = (40.0 / 255.0, 154.0 / 255.0, 249.0 / 255.0)

    plt.figure(figsize=(4, 4))

    a1 = plt.axes([0.0, 0.20, 1.0, 0.8])
    plot_data = rplt.errorbar(h_data,
                              marker="o",
                              color="black",
                              label="data",
                              capsize=0)

    #rplt.hist(hs2["bkg"] + hs2["sig"], fill=True, color="blue", lw=0);
    plot_bkg = rplt.hist(h_bkg_s, lw=2, linecolor="black", label="Background")
    h_bkg_b.linestyle = "dashed"
def make_plots( histograms, category, output_folder, histname, show_ratio = True, show_before_unfolding = False ):
    global variable, phase_space

    channel = 'electron'
    if 'electron' in histname:
        channel = 'electron'
    elif 'muon' in histname:
        channel = 'muon'
    else:
        channel = 'combined'

    # plot with matplotlib
    hist_data = histograms['unfolded']
    if category == 'central':
        hist_data_with_systematics = histograms['unfolded_with_systematics']
    hist_measured = histograms['measured']

    hist_data.markersize = 2
    hist_data.marker = 'o'

    if category == 'central':
        hist_data_with_systematics.markersize = 2
        hist_data_with_systematics.marker = 'o'

    hist_measured.markersize = 2
    hist_measured.marker = 'o'
    hist_measured.color = 'red'

    plt.figure( figsize = CMS.figsize, dpi = CMS.dpi, facecolor = CMS.facecolor )
    if show_ratio:
        gs = gridspec.GridSpec( 2, 1, height_ratios = [5, 1] )
        axes = plt.subplot( gs[0] )
    else:
        axes = plt.axes()
        if variable in ['NJets', 'abs_lepton_eta', 'lepton_eta']:
            plt.xlabel( '$%s$' % variables_latex[variable], CMS.x_axis_title )
        else:
            plt.xlabel( '$%s$ [GeV]' % variables_latex[variable], CMS.x_axis_title )
    if not variable in ['NJets']:
        axes.minorticks_on()
    if variable in ['NJets', 'abs_lepton_eta', 'lepton_eta']:
        plt.ylabel( r'$\frac{1}{\sigma}  \frac{d\sigma}{d' + variables_latex[variable] + '}$', CMS.y_axis_title )
    else:
        plt.ylabel( r'$\frac{1}{\sigma}  \frac{d\sigma}{d' + variables_latex[variable] + '} \left[\mathrm{GeV}^{-1}\\right]$', CMS.y_axis_title )
    plt.tick_params( **CMS.axis_label_major )
    if not variable in ['NJets']:
        plt.tick_params( **CMS.axis_label_minor )

    hist_data.visible = True
    if category == 'central':
        hist_data_with_systematics.visible = True
        rplt.errorbar( hist_data_with_systematics, axes = axes, label = 'do_not_show', xerr = None, capsize = 0, elinewidth = 2, zorder = len( histograms ) + 1 )
    rplt.errorbar( hist_data, axes = axes, label = 'do_not_show', xerr = None, capsize = 15, capthick = 3, elinewidth = 2, zorder = len( histograms ) + 2 )
    rplt.errorbar( hist_data, axes = axes, label = 'data', xerr = None, yerr = False, zorder = len( histograms ) + 3 )  # this makes a nicer legend entry

    if show_before_unfolding:
        rplt.errorbar( hist_measured, axes = axes, label = 'data (before unfolding)', xerr = None, zorder = len( histograms ) )

    dashes = {}
    for key, hist in sorted( histograms.items() ):
        zorder = sorted( histograms, reverse = False ).index( key )
        if key == 'powhegPythia8' and zorder != len(histograms) - 3:
            zorder = len(histograms) - 3
        elif key != 'powhegPythia8' and not 'unfolded' in key:
            while zorder >= len(histograms) - 3:
                zorder = zorder - 1 

        if not 'unfolded' in key and not 'measured' in key:
            hist.linewidth = 4
            # setting colours
            linestyle = None
            if 'amcatnlo_HERWIG' in key or 'massdown' in key:
                hist.SetLineColor( kBlue )
                dashes[key] = [25,5,5,5,5,5,5,5]
            elif 'madgraphMLM' in key or 'scaledown' in key:
                hist.SetLineColor( 417 )
                dashes[key] = [5,5]
            elif 'MADGRAPH_ptreweight' in key:
                hist.SetLineColor( kBlack )
            elif 'powhegPythia8' in key:
                linestyle = 'solid'
                dashes[key] = None
                hist.SetLineColor( 633 )
            elif 'massup' in key or 'amcatnlo' in key:
                hist.SetLineColor( 807 )
                dashes[key] = [20,5]
            elif 'MCATNLO' in key or 'scaleup' in key:
                hist.SetLineColor( 619 )
                dashes[key] = [5,5,10,5]

            if linestyle != None:
                hist.linestyle = linestyle
            line, h = rplt.hist( hist, axes = axes, label = measurements_latex[key], zorder = zorder )

            if dashes[key] != None:
                line.set_dashes(dashes[key])
                h.set_dashes(dashes[key])

    handles, labels = axes.get_legend_handles_labels()
    # making data first in the list
    data_label_index = labels.index( 'data' )
    data_handle = handles[data_label_index]
    labels.remove( 'data' )
    handles.remove( data_handle )
    labels.insert( 0, 'data' )
    handles.insert( 0, data_handle )

    new_handles, new_labels = [], []
    zipped = dict( zip( labels, handles ) )
    labelOrder = ['data', 
        measurements_latex['powhegPythia8'],
        measurements_latex['amcatnlo'],
        measurements_latex['amcatnlo_HERWIG'],
        measurements_latex['madgraphMLM'],
        measurements_latex['scaleup'], 
        measurements_latex['scaledown'],
        measurements_latex['massup'],
        measurements_latex['massdown']
    ]
    for label in labelOrder:
        if label in labels:
            new_handles.append(zipped[label])
            new_labels.append(label)

    legend_location = (0.97, 0.82)
    if variable == 'MT':
        legend_location = (0.05, 0.82)
    elif variable == 'ST':
        legend_location = (0.97, 0.82)
    elif variable == 'WPT':
        legend_location = (1.0, 0.84)
    elif variable == 'abs_lepton_eta':
        legend_location = (1.0, 0.94)
    plt.legend( new_handles, new_labels, numpoints = 1, prop = CMS.legend_properties, frameon = False, bbox_to_anchor=legend_location,
                bbox_transform=plt.gcf().transFigure )
    label, channel_label = get_cms_labels( channel )
    # title
    plt.title( label,loc='right', **CMS.title )
    # CMS text
    # note: fontweight/weight does not change anything as we use Latex text!!!
    logo_location = (0.05, 0.98)
    prelim_location = (0.05, 0.92)
    channel_location = ( 0.05, 0.86)
    if variable == 'WPT':
        logo_location = (0.03, 0.98)
        prelim_location = (0.03, 0.92)
        channel_location = (0.03, 0.86)
    elif variable == 'abs_lepton_eta':
        logo_location = (0.03, 0.98)
        prelim_location = (0.03, 0.92)
        channel_location = (0.03, 0.86)
    plt.text(logo_location[0], logo_location[1], r"\textbf{CMS}", transform=axes.transAxes, fontsize=42,
        verticalalignment='top',horizontalalignment='left')
    # preliminary
    plt.text(prelim_location[0], prelim_location[1], r"\emph{Preliminary}",
                 transform=axes.transAxes, fontsize=42,
                 verticalalignment='top',horizontalalignment='left')
    # channel text
    plt.text(channel_location[0], channel_location[1], r"\emph{%s}" %channel_label, transform=axes.transAxes, fontsize=40,
        verticalalignment='top',horizontalalignment='left')
    ylim = axes.get_ylim()
    if ylim[0] < 0:
        axes.set_ylim( ymin = 0.)
    if variable == 'WPT':
        axes.set_ylim(ymax = ylim[1]*1.3)
    elif variable == 'abs_lepton_eta':
        axes.set_ylim(ymax = ylim[1]*1.3)
    else :
        axes.set_ylim(ymax = ylim[1]*1.2)


    if show_ratio:
        plt.setp( axes.get_xticklabels(), visible = False )
        ax1 = plt.subplot( gs[1] )
        if not variable in ['NJets']:
            ax1.minorticks_on()
        #ax1.grid( True, 'major', linewidth = 1 )
        # setting the x_limits identical to the main plot
        x_limits = axes.get_xlim()
        ax1.set_xlim(x_limits)
        ax1.yaxis.set_major_locator( MultipleLocator( 0.5 ) )
        if not variable in ['NJets']:
            ax1.yaxis.set_minor_locator( MultipleLocator( 0.1 ) )

        if variable in ['NJets', 'abs_lepton_eta', 'lepton_eta']:
            plt.xlabel('$%s$' % variables_latex[variable], CMS.x_axis_title )
        else:
            plt.xlabel( '$%s$ [GeV]' % variables_latex[variable], CMS.x_axis_title )

        plt.tick_params( **CMS.axis_label_major )
        if not variable in ['NJets']:
            plt.tick_params( **CMS.axis_label_minor )
        plt.ylabel( '$\\frac{\\textrm{pred.}}{\\textrm{data}}$', CMS.y_axis_title )
        ax1.yaxis.set_label_coords(-0.115, 0.8)
        #draw a horizontal line at y=1 for data
        plt.axhline(y = 1, color = 'black', linewidth = 2)

        for key, hist in sorted( histograms.iteritems() ):
            if not 'unfolded' in key and not 'measured' in key:
                ratio = hist.Clone()
                ratio.Divide( hist_data ) #divide by data
                line, h = rplt.hist( ratio, axes = ax1, label = 'do_not_show' )
                if dashes[key] != None:
                    h.set_dashes(dashes[key])

        stat_lower = hist_data.Clone()
        stat_upper = hist_data.Clone()
        syst_lower = hist_data.Clone()
        syst_upper = hist_data.Clone()

        # plot error bands on data in the ratio plot
        stat_errors = graph_to_value_errors_tuplelist(hist_data)
        if category == 'central':
            syst_errors = graph_to_value_errors_tuplelist(hist_data_with_systematics)
        for bin_i in range( 1, hist_data.GetNbinsX() + 1 ):
            stat_value, stat_error, _ = stat_errors[bin_i-1]
            stat_rel_error = stat_error/stat_value
            stat_lower.SetBinContent( bin_i, 1 - stat_rel_error )
            stat_upper.SetBinContent( bin_i, 1 + stat_rel_error )
            if category == 'central':
                syst_value, syst_error_down, syst_error_up  = syst_errors[bin_i-1]
                syst_rel_error_down = syst_error_down/syst_value
                syst_rel_error_up = syst_error_up/syst_value
                syst_lower.SetBinContent( bin_i, 1 - syst_rel_error_down )
                syst_upper.SetBinContent( bin_i, 1 + syst_rel_error_up )
        if category == 'central':
            rplt.fill_between( syst_lower, syst_upper, ax1,
                               color = 'yellow' )

        rplt.fill_between( stat_upper, stat_lower, ax1, color = '0.75',
                            )

        loc = 'upper left'
        # if variable in ['ST']:
        #     loc = 'upper right'
        # legend for ratio plot
        p_stat = mpatches.Patch(facecolor='0.75', label='Stat.', edgecolor='black' )
        p_stat_and_syst = mpatches.Patch(facecolor='yellow', label=r'Stat. $\oplus$ Syst.', edgecolor='black' )
        l1 = ax1.legend(handles = [p_stat, p_stat_and_syst], loc = loc,
                     frameon = False, prop = {'size':26}, ncol = 2)

        # ax1.legend(handles = [p_stat_and_syst], loc = 'lower left',
        #              frameon = False, prop = {'size':30})
        ax1.add_artist(l1)

        if variable == 'MET':
            ax1.set_ylim( ymin = 0.8, ymax = 1.2 )
            ax1.yaxis.set_major_locator( MultipleLocator( 0.5 ) )
#             ax1.yaxis.set_minor_locator( MultipleLocator( 0.1 ) )
        if variable == 'MT':
            ax1.set_ylim( ymin = 0.8, ymax = 1.2 )
            ax1.yaxis.set_major_locator( MultipleLocator( 0.2 ) )
            ax1.yaxis.set_minor_locator( MultipleLocator( 0.1 ) )
        elif variable == 'HT':
            ax1.set_ylim( ymin = 0.8, ymax = 1.37 )
            ax1.yaxis.set_major_locator( MultipleLocator( 0.2 ) )
            ax1.yaxis.set_minor_locator( MultipleLocator( 0.1 ) )
        elif variable == 'ST':
            ax1.set_ylim( ymin = 0.7, ymax = 1.5 )
            ax1.yaxis.set_major_locator( MultipleLocator( 0.5 ) )
            ax1.yaxis.set_minor_locator( MultipleLocator( 0.1 ) )
        elif variable == 'WPT':
            ax1.set_ylim( ymin = 0.8, ymax = 1.2 )
            ax1.yaxis.set_major_locator( MultipleLocator( 0.5 ) )
            ax1.yaxis.set_minor_locator( MultipleLocator( 0.1 ) )
        elif variable == 'NJets':
            ax1.set_ylim( ymin = 0.7, ymax = 1.5 )
        elif variable == 'abs_lepton_eta':
            ax1.set_ylim( ymin = 0.8, ymax = 1.2 )
            ax1.yaxis.set_major_locator( MultipleLocator( 0.2 ) )
            ax1.yaxis.set_minor_locator( MultipleLocator( 0.1 ) )
        elif variable == 'lepton_pt':
            ax1.set_ylim( ymin = 0.8, ymax = 1.3 )
            ax1.yaxis.set_major_locator( MultipleLocator( 0.2 ) )
            ax1.yaxis.set_minor_locator( MultipleLocator( 0.1 ) )

    if CMS.tight_layout:
        plt.tight_layout()

    path = '{output_folder}/{centre_of_mass_energy}TeV/{phaseSpace}/{variable}/'
    path = path.format(
            output_folder = output_folder,
            centre_of_mass_energy = measurement_config.centre_of_mass_energy,
            phaseSpace = phase_space,
            variable = variable
            )
    make_folder_if_not_exists( path )
    for output_format in output_formats:
        filename = path + '/' + histname + '.' + output_format
        plt.savefig( filename )

    del hist_data, hist_measured
    plt.close()
    gc.collect()