def plot_bias_in_all_bins(biases, mean_bias, centre_of_mass, channel, variable,
                          tau_value, output_folder, output_formats, bin_edges):
    h_bias = Hist(bin_edges, type='D')
    n_bins = h_bias.nbins()
    assert len(biases) == n_bins
    for i, bias in enumerate(biases):
        h_bias.SetBinContent(i + 1, bias)
    histogram_properties = Histogram_properties()
    name_mpt = 'bias_{0}_{1}_{2}TeV'
    histogram_properties.name = name_mpt.format(variable, channel,
                                                centre_of_mass)
    histogram_properties.y_axis_title = 'Bias'
    histogram_properties.x_axis_title = latex_labels.variables_latex[variable]
    title = 'pull distribution mean \& sigma for {0}'.format(tau_value)
    histogram_properties.title = title
    histogram_properties.y_limits = [0, 10]
    histogram_properties.xerr = True

    compare_measurements(
        models={'Mean bias': make_line_hist(bin_edges, mean_bias)},
        measurements={'Bias': h_bias},
        show_measurement_errors=True,
        histogram_properties=histogram_properties,
        save_folder=output_folder,
        save_as=output_formats)
def plot_bias_in_all_bins(biases, mean_bias, centre_of_mass, channel, variable,
                        tau_value, output_folder, output_formats, bin_edges):
    h_bias = Hist(bin_edges, type='D')
    n_bins = h_bias.nbins()
    assert len(biases) == n_bins
    for i, bias in enumerate(biases):
        h_bias.SetBinContent(i+1, bias)
    histogram_properties = Histogram_properties()
    name_mpt = 'bias_{0}_{1}_{2}TeV'
    histogram_properties.name = name_mpt.format(
        variable,
        channel,
        centre_of_mass
    )
    histogram_properties.y_axis_title = 'Bias'
    histogram_properties.x_axis_title = latex_labels.variables_latex[variable]
    title = 'pull distribution mean \& sigma for {0}'.format(tau_value)
    histogram_properties.title = title
    histogram_properties.y_limits = [0, 10]
    histogram_properties.xerr = True

    compare_measurements(
        models={
            'Mean bias':make_line_hist(bin_edges, mean_bias)
        },
        measurements={
            'Bias': h_bias
        },
        show_measurement_errors=True,
        histogram_properties=histogram_properties,
        save_folder=output_folder,
        save_as=output_formats)
def plot_bias(unfolded_and_truths, variable, channel, come, method):
    hp = Histogram_properties()
    hp.name = 'Bias_{channel}_{variable}_at_{come}TeV'.format(
        channel=channel,
        variable=variable,
        come=come,
    )
    v_latex = latex_labels.variables_latex[variable]
    unit = ''
    if variable in ['HT', 'ST', 'MET', 'WPT', 'lepton_pt']:
        unit = ' [GeV]'
    hp.x_axis_title = v_latex + unit
    # plt.ylabel( r, CMS.y_axis_title )
    hp.y_axis_title = 'Unfolded / Truth'
    hp.y_limits = [0.92, 1.08]
    hp.title = 'Bias for {variable}'.format(variable=v_latex)

    output_folder = 'plots/unfolding/bias_test/'

    measurements = { 'Central' : unfolded_and_truths['Central']['bias'] }

    models = {}
    for sample in unfolded_and_truths:
        if sample == 'Central' : continue
        models[sample] = unfolded_and_truths[sample]['bias']


    compare_measurements(
                         models = models,
                         measurements = measurements,
                         show_measurement_errors=True,
                         histogram_properties=hp,
                         save_folder=output_folder,
                         save_as=['pdf'],
                         match_models_to_measurements = True)
def plot_results(results):
    '''
    Takes results fo the form:
        {centre-of-mass-energy: {
            channel : {
                variable : {
                    fit_variable : {
                        test : { sample : []},
                        }
                    }
                }
            }
        }
    '''
    global options
    output_base = 'plots/fit_checks/chi2'
    for COMEnergy in results.keys():
        tmp_result_1 = results[COMEnergy]
        for channel in tmp_result_1.keys():
            tmp_result_2 = tmp_result_1[channel]
            for variable in tmp_result_2.keys():
                tmp_result_3 = tmp_result_2[variable]
                for fit_variable in tmp_result_3.keys():
                    tmp_result_4 = tmp_result_3[fit_variable]
                    # histograms should be {sample: {test : histogram}}
                    histograms = {}
                    for test, chi2 in tmp_result_4.iteritems():
                        for sample in chi2.keys():
                            if not histograms.has_key(sample):
                                histograms[sample] = {}
                            # reverse order of test and sample
                            histograms[sample][test] = value_tuplelist_to_hist(
                                chi2[sample], bin_edges_vis[variable])
                    for sample in histograms.keys():
                        hist_properties = Histogram_properties()
                        hist_properties.name = sample.replace('+',
                                                              '') + '_chi2'
                        hist_properties.title = '$\\chi^2$ distribution for fit output (' + sample + ')'
                        hist_properties.x_axis_title = '$' + latex_labels.variables_latex[
                            variable] + '$ [TeV]'
                        hist_properties.y_axis_title = '$\chi^2 = \\left({N_{fit}} - N_{{exp}}\\right)^2$'
                        hist_properties.set_log_y = True
                        hist_properties.y_limits = (1e-20, 1e20)
                        path = output_base + '/' + COMEnergy + 'TeV/' + channel + '/' + variable + '/' + fit_variable + '/'
                        if options.test:
                            path = output_base + '/test/'

                        measurements = {}
                        for test, histogram in histograms[sample].iteritems():
                            measurements[test.replace('_', ' ')] = histogram
                        compare_measurements(
                            {},
                            measurements,
                            show_measurement_errors=False,
                            histogram_properties=hist_properties,
                            save_folder=path,
                            save_as=['pdf'])
def plot_results ( results ):
    '''
    Takes results fo the form:
        {centre-of-mass-energy: {
            channel : {
                variable : {
                    fit_variable : {
                        test : { sample : []},
                        }
                    }
                }
            }
        }
    '''
    global options
    output_base = 'plots/fit_checks/chi2'
    for COMEnergy in results.keys():
        tmp_result_1 = results[COMEnergy]
        for channel in tmp_result_1.keys():
            tmp_result_2 = tmp_result_1[channel]
            for variable in tmp_result_2.keys():
                tmp_result_3 = tmp_result_2[variable]
                for fit_variable in tmp_result_3.keys():
                    tmp_result_4 = tmp_result_3[fit_variable]
                    # histograms should be {sample: {test : histogram}}
                    histograms = {}
                    for test, chi2 in tmp_result_4.iteritems():
                        for sample in chi2.keys():
                            if not histograms.has_key(sample):
                                histograms[sample] = {}
                            # reverse order of test and sample
                            histograms[sample][test] = value_tuplelist_to_hist(chi2[sample], bin_edges_vis[variable])
                    for sample in histograms.keys():
                        hist_properties = Histogram_properties()
                        hist_properties.name = sample.replace('+', '') + '_chi2'
                        hist_properties.title = '$\\chi^2$ distribution for fit output (' + sample + ')'
                        hist_properties.x_axis_title = '$' + latex_labels.variables_latex[variable] + '$ [TeV]'
                        hist_properties.y_axis_title = '$\chi^2 = \\left({N_{fit}} - N_{{exp}}\\right)^2$'
                        hist_properties.set_log_y = True
                        hist_properties.y_limits = (1e-20, 1e20)
                        path = output_base + '/' + COMEnergy + 'TeV/' + channel + '/' + variable + '/' + fit_variable + '/'
                        if options.test:
                            path = output_base + '/test/'
                        
                        measurements = {}
                        for test, histogram in histograms[sample].iteritems():
                            measurements[test.replace('_',' ')] = histogram
                        compare_measurements({}, 
                                             measurements, 
                                             show_measurement_errors = False, 
                                             histogram_properties = hist_properties, 
                                             save_folder = path, 
                                             save_as = ['pdf'])
def plot_bias(unfolded_and_truths, variable, channel, come, method, prefix, plot_systematics=False):
    hp = Histogram_properties()
    hp.name = 'Bias_{prefix}_{channel}_{variable}_at_{come}TeV'.format(
        prefix=prefix,
        channel=channel,
        variable=variable,
        come=come,
    )
    v_latex = latex_labels.variables_latex[variable]
    unit = ''
    if variable in ['HT', 'ST', 'MET', 'WPT', 'lepton_pt']:
        unit = ' [GeV]'
    hp.x_axis_title = v_latex + unit
    # plt.ylabel( r, CMS.y_axis_title )
    hp.y_axis_title = 'Unfolded / Truth'
    hp.y_limits = [0.7, 1.5]
    hp.title = 'Bias for {variable}'.format(variable=v_latex)
    hp.legend_location = (0.98, 0.95)
    output_folder = 'plots/unfolding/bias_test/'

    measurements = {}
    # measurements = { 'Central' : unfolded_and_truths['Central']['bias'] }
    # for bin in range(0, unfolded_and_truths['Central']['bias'].GetNbinsX() + 1 ):
    #     unfolded_and_truths['Central']['bias'].SetBinError(bin,0)

    models = OrderedDict()
    lineStyles = []
    for sample in unfolded_and_truths:
        if sample == 'Central' or sample == 'Nominal': 
            lineStyles.append('dashed')
        else:
            lineStyles.append('dotted')
        models[sample] = unfolded_and_truths[sample]['bias']

    if plot_systematics:
        models['systematicsup'], models['systematicsdown'] = get_systematics(variable,channel,come,method)
        lineStyles.append('solid')
        lineStyles.append('solid')

    compare_measurements(
        models = models,
        measurements = measurements,
        show_measurement_errors=True,
        histogram_properties=hp,
        save_folder=output_folder,
        save_as=['pdf'],
        line_styles_for_models = lineStyles,
        match_models_to_measurements = True
    )
def plot_fit_results(fit_results, centre_of_mass, channel, variable, k_value,
                     tau_value, output_folder, output_formats, bin_edges):
    h_mean = Hist(bin_edges, type='D')
    h_sigma = Hist(bin_edges, type='D')
    n_bins = h_mean.nbins()
    assert len(fit_results) == n_bins

    mean_abs_pull = 0
    for i, fr in enumerate(fit_results):
        mean_abs_pull += abs(fr.mean)
        h_mean.SetBinContent(i + 1, fr.mean)
        h_mean.SetBinError(i + 1, fr.meanError)
        h_sigma.SetBinContent(i + 1, fr.sigma)
        h_sigma.SetBinError(i + 1, fr.sigmaError)
    mean_abs_pull /= n_bins
    histogram_properties = Histogram_properties()
    name_mpt = 'pull_distribution_mean_and_sigma_{0}_{1}_{2}TeV'
    histogram_properties.name = name_mpt.format(
        variable,
        channel,
        centre_of_mass
    )
    histogram_properties.y_axis_title = r'$\mu_{\text{pull}}$ ($\sigma_{\text{pull}}$)'
    histogram_properties.x_axis_title = latex_labels.variables_latex[variable]
    histogram_properties.legend_location = (0.98, 0.48)
    value = get_value_title(k_value, tau_value)
    title = 'pull distribution mean \& sigma for {0}'.format(tau_value)
    histogram_properties.title = title
    histogram_properties.y_limits = [-2, 2]
    histogram_properties.xerr = True

    compare_measurements(
        models={
            # 'mean $|\mu|$':make_line_hist(bin_edges,mean_abs_pull),
            'ideal $\mu$': make_line_hist(bin_edges, 0),
            'ideal $\sigma$': make_line_hist(bin_edges, 1),
        },
        measurements={
            r'$\mu_{\text{pull}}$': h_mean,
            r'$\sigma_{\text{pull}}$': h_sigma
        },
        show_measurement_errors=True,
        histogram_properties=histogram_properties,
        save_folder=output_folder,
        save_as=output_formats)
def plot_bias(unfolded_and_truths, variable, channel, come, method):
    hp = Histogram_properties()
    hp.name = 'Bias_{channel}_{variable}_at_{come}TeV'.format(
        channel=channel,
        variable=variable,
        come=come,
    )
    v_latex = latex_labels.variables_latex[variable]
    unit = ''
    if variable in ['HT', 'ST', 'MET', 'WPT', 'lepton_pt']:
        unit = ' [GeV]'
    hp.x_axis_title = v_latex + unit
    # plt.ylabel( r, CMS.y_axis_title )
    hp.y_axis_title = 'Unfolded / Truth'
    hp.y_limits = [0.85, 1.15]
    hp.title = 'Bias for {variable}'.format(variable=v_latex)

    output_folder = 'plots/unfolding/bias_test/'

    measurements = { 'Central' : unfolded_and_truths['Central']['bias'] }
    for bin in range(0, unfolded_and_truths['Central']['bias'].GetNbinsX() + 1 ):
        unfolded_and_truths['Central']['bias'].SetBinError(bin,0)

    # central_truth = unfolded_and_truths['Central']['truth']
    # for label, hists in unfolded_and_truths.iteritems():
    #     truth = hists['truth']
    #     print label
    #     for i,j in zip( list(truth.y()), list(central_truth.y())) :
    #         print abs(1-i/j)*100

    models = {}
    for sample in unfolded_and_truths:
        if sample == 'Central' : continue
        models[sample] = unfolded_and_truths[sample]['bias']


    compare_measurements(
                         models = models,
                         measurements = measurements,
                         show_measurement_errors=True,
                         histogram_properties=hp,
                         save_folder=output_folder,
                         save_as=['pdf'],
                         match_models_to_measurements = True)
def plot_fit_results(fit_results, centre_of_mass, channel, variable, k_value,
                     tau_value, output_folder, output_formats, bin_edges):
    h_mean = Hist(bin_edges, type='D')
    h_sigma = Hist(bin_edges, type='D')
    n_bins = h_mean.nbins()
    assert len(fit_results) == n_bins

    mean_abs_pull = 0
    for i, fr in enumerate(fit_results):
        mean_abs_pull += abs(fr.mean)
        h_mean.SetBinContent(i + 1, fr.mean)
        h_mean.SetBinError(i + 1, fr.meanError)
        h_sigma.SetBinContent(i + 1, fr.sigma)
        h_sigma.SetBinError(i + 1, fr.sigmaError)
    mean_abs_pull /= n_bins
    histogram_properties = Histogram_properties()
    name_mpt = 'pull_distribution_mean_and_sigma_{0}_{1}_{2}TeV'
    histogram_properties.name = name_mpt.format(variable, channel,
                                                centre_of_mass)
    histogram_properties.y_axis_title = r'$\mu_{\text{pull}}$ ($\sigma_{\text{pull}}$)'
    histogram_properties.x_axis_title = latex_labels.variables_latex[variable]
    histogram_properties.legend_location = (0.98, 0.48)
    value = get_value_title(k_value, tau_value)
    title = 'pull distribution mean \& sigma for {0}'.format(tau_value)
    histogram_properties.title = title
    histogram_properties.y_limits = [-2, 2]
    histogram_properties.xerr = True

    compare_measurements(
        models={
            # 'mean $|\mu|$':make_line_hist(bin_edges,mean_abs_pull),
            'ideal $\mu$': make_line_hist(bin_edges, 0),
            'ideal $\sigma$': make_line_hist(bin_edges, 1),
        },
        measurements={
            r'$\mu_{\text{pull}}$': h_mean,
            r'$\sigma_{\text{pull}}$': h_sigma
        },
        show_measurement_errors=True,
        histogram_properties=histogram_properties,
        save_folder=output_folder,
        save_as=output_formats)
def do_shape_check(channel, control_region_1, control_region_2, variable, normalisation, title, x_title, y_title, x_limits, y_limits,
                   name_region_1='conversions' , name_region_2='non-isolated electrons', name_region_3='fit results', rebin=1):
    global b_tag_bin
    # QCD shape comparison
    if channel == 'electron':
        histograms = get_histograms_from_files([control_region_1, control_region_2], histogram_files)
        
        region_1 = histograms[channel][control_region_1].Clone() - histograms['TTJet'][control_region_1].Clone() - histograms['V+Jets'][control_region_1].Clone() - histograms['SingleTop'][control_region_1].Clone()
        region_2 = histograms[channel][control_region_2].Clone() - histograms['TTJet'][control_region_2].Clone() - histograms['V+Jets'][control_region_2].Clone() - histograms['SingleTop'][control_region_2].Clone()
        
        region_1.Rebin(rebin)
        region_2.Rebin(rebin)
        
        histogram_properties = Histogram_properties()
        histogram_properties.name = 'QCD_control_region_comparison_' + channel + '_' + variable + '_' + b_tag_bin
        histogram_properties.title = title + ', ' + b_tag_bins_latex[b_tag_bin]
        histogram_properties.x_axis_title = x_title
        histogram_properties.y_axis_title = 'arbitrary units/(0.1)'
        histogram_properties.x_limits = x_limits
        histogram_properties.y_limits = y_limits[0]
        histogram_properties.mc_error = 0.0
        histogram_properties.legend_location = 'upper right'
        make_control_region_comparison(region_1, region_2,
                                       name_region_1=name_region_1, name_region_2=name_region_2,
                                       histogram_properties=histogram_properties, save_folder=output_folder)
        
        # QCD shape comparison to fit results
        histograms = get_histograms_from_files([control_region_1], histogram_files)
        
        region_1_tmp = histograms[channel][control_region_1].Clone() - histograms['TTJet'][control_region_1].Clone() - histograms['V+Jets'][control_region_1].Clone() - histograms['SingleTop'][control_region_1].Clone()
        region_1 = rebin_asymmetric(region_1_tmp, bin_edges_vis[variable])
        
        fit_results_QCD = normalisation[variable]['QCD']
        region_2 = value_error_tuplelist_to_hist(fit_results_QCD, bin_edges_vis[variable])
        
        histogram_properties = Histogram_properties()
        histogram_properties.name = 'QCD_control_region_comparison_' + channel + '_' + variable + '_fits_with_conversions_' + b_tag_bin
        histogram_properties.title = title + ', ' + b_tag_bins_latex[b_tag_bin]
        histogram_properties.x_axis_title = x_title
        histogram_properties.y_axis_title = 'arbitrary units/(0.1)'
        histogram_properties.x_limits = x_limits
        histogram_properties.y_limits = y_limits[1]
        histogram_properties.mc_error = 0.0
        histogram_properties.legend_location = 'upper right'
        make_control_region_comparison(region_1, region_2,
                                       name_region_1=name_region_1, name_region_2=name_region_3,
                                       histogram_properties=histogram_properties, save_folder=output_folder)
    
    histograms = get_histograms_from_files([control_region_2], histogram_files)
    
    region_1_tmp = histograms[channel][control_region_2].Clone() - histograms['TTJet'][control_region_2].Clone() - histograms['V+Jets'][control_region_2].Clone() - histograms['SingleTop'][control_region_2].Clone()
    region_1 = rebin_asymmetric(region_1_tmp, bin_edges_vis[variable])    
    
    fit_results_QCD = normalisation[variable]['QCD']
    region_2 = value_error_tuplelist_to_hist(fit_results_QCD, bin_edges_vis[variable])
    
    histogram_properties = Histogram_properties()
    histogram_properties.name = 'QCD_control_region_comparison_' + channel + '_' + variable + '_fits_with_noniso_' + b_tag_bin
    histogram_properties.title = title + ', ' + b_tag_bins_latex[b_tag_bin]
    histogram_properties.x_axis_title = x_title
    histogram_properties.y_axis_title = 'arbitrary units/(0.1)'
    histogram_properties.x_limits = x_limits
    histogram_properties.y_limits = y_limits[1]
    histogram_properties.mc_error = 0.0
    histogram_properties.legend_location = 'upper right'
    make_control_region_comparison(region_1, region_2,
                                   name_region_1=name_region_2, name_region_2=name_region_3,
                                   histogram_properties=histogram_properties, save_folder=output_folder)
def make_ttbarReco_plot(
    channel,
    x_axis_title,
    y_axis_title,
    signal_region_tree,
    control_region_tree,
    branchName,
    name_prefix,
    x_limits,
    nBins,
    use_qcd_data_region=False,
    y_limits=[],
    y_max_scale=1.2,
    rebin=1,
    legend_location=(0.98, 0.78),
    cms_logo_location='right',
    log_y=False,
    legend_color=False,
    ratio_y_limits=[0.3, 1.7],
    normalise=False,
):
    global output_folder, measurement_config, category, normalise_to_fit
    global preliminary, norm_variable, sum_bins, b_tag_bin, histogram_files

    # Input files, normalisations, tree/region names
    qcd_data_region = ''
    title = title_template % (measurement_config.new_luminosity / 1000.,
                              measurement_config.centre_of_mass_energy)
    normalisation = None
    if channel == 'electron':
        histogram_files['data'] = measurement_config.data_file_electron_trees
        histogram_files[
            'QCD'] = measurement_config.electron_QCD_MC_category_templates_trees[
                category]
        if normalise_to_fit:
            normalisation = normalisations_electron[norm_variable]
        if use_qcd_data_region:
            qcd_data_region = 'QCDConversions'
    if channel == 'muon':
        histogram_files['data'] = measurement_config.data_file_muon_trees
        histogram_files[
            'QCD'] = measurement_config.muon_QCD_MC_category_templates_trees[
                category]
        if normalise_to_fit:
            normalisation = normalisations_muon[norm_variable]
        if use_qcd_data_region:
            qcd_data_region = 'QCD non iso mu+jets ge3j'

    histograms = get_histograms_from_trees(
        trees=[signal_region_tree, control_region_tree],
        branch=branchName,
        weightBranch='1',
        files=histogram_files,
        nBins=nBins,
        xMin=x_limits[0],
        xMax=x_limits[-1])

    selection = 'SolutionCategory == 0'
    histogramsNoSolution = get_histograms_from_trees(
        trees=[signal_region_tree],
        branch=branchName,
        weightBranch='1',
        selection=selection,
        files=histogram_files,
        nBins=nBins,
        xMin=x_limits[0],
        xMax=x_limits[-1])

    selection = 'SolutionCategory == 1'
    histogramsCorrect = get_histograms_from_trees(trees=[signal_region_tree],
                                                  branch=branchName,
                                                  weightBranch='1',
                                                  selection=selection,
                                                  files=histogram_files,
                                                  nBins=nBins,
                                                  xMin=x_limits[0],
                                                  xMax=x_limits[-1])

    selection = 'SolutionCategory == 2'
    histogramsNotSL = get_histograms_from_trees(trees=[signal_region_tree],
                                                branch=branchName,
                                                weightBranch='1',
                                                selection=selection,
                                                files=histogram_files,
                                                nBins=nBins,
                                                xMin=x_limits[0],
                                                xMax=x_limits[-1])

    selection = 'SolutionCategory == 3'
    histogramsNotReco = get_histograms_from_trees(trees=[signal_region_tree],
                                                  branch=branchName,
                                                  weightBranch='1',
                                                  selection=selection,
                                                  files=histogram_files,
                                                  nBins=nBins,
                                                  xMin=x_limits[0],
                                                  xMax=x_limits[-1])

    selection = 'SolutionCategory > 3'
    histogramsWrong = get_histograms_from_trees(trees=[signal_region_tree],
                                                branch=branchName,
                                                weightBranch='1',
                                                selection=selection,
                                                files=histogram_files,
                                                nBins=nBins,
                                                xMin=x_limits[0],
                                                xMax=x_limits[-1])

    # Split histograms up into signal/control (?)
    signal_region_hists = {}
    inclusive_control_region_hists = {}
    for sample in histograms.keys():
        signal_region_hists[sample] = histograms[sample][signal_region_tree]
        if use_qcd_data_region:
            inclusive_control_region_hists[sample] = histograms[sample][
                control_region_tree]

    prepare_histograms(histograms,
                       rebin=1,
                       scale_factor=measurement_config.luminosity_scale)
    prepare_histograms(histogramsNoSolution,
                       rebin=1,
                       scale_factor=measurement_config.luminosity_scale)
    prepare_histograms(histogramsCorrect,
                       rebin=1,
                       scale_factor=measurement_config.luminosity_scale)
    prepare_histograms(histogramsNotSL,
                       rebin=1,
                       scale_factor=measurement_config.luminosity_scale)
    prepare_histograms(histogramsNotReco,
                       rebin=1,
                       scale_factor=measurement_config.luminosity_scale)
    prepare_histograms(histogramsWrong,
                       rebin=1,
                       scale_factor=measurement_config.luminosity_scale)

    qcd_from_data = signal_region_hists['QCD']

    # Which histograms to draw, and properties
    histograms_to_draw = [
        signal_region_hists['data'], qcd_from_data,
        signal_region_hists['V+Jets'], signal_region_hists['SingleTop'],
        histogramsNoSolution['TTJet'][signal_region_tree],
        histogramsNotSL['TTJet'][signal_region_tree],
        histogramsNotReco['TTJet'][signal_region_tree],
        histogramsWrong['TTJet'][signal_region_tree],
        histogramsCorrect['TTJet'][signal_region_tree]
    ]
    histogram_lables = [
        'data',
        'QCD',
        'V+Jets',
        'Single-Top',
        samples_latex['TTJet'] + ' - no solution',
        samples_latex['TTJet'] + ' - not SL',
        samples_latex['TTJet'] + ' - not reconstructible',
        samples_latex['TTJet'] + ' - wrong reco',
        samples_latex['TTJet'] + ' - correct',
    ]
    histogram_colors = [
        'black', 'yellow', 'green', 'magenta', 'black', 'burlywood',
        'chartreuse', 'blue', 'red'
    ]

    histogram_properties = Histogram_properties()
    histogram_properties.name = name_prefix + b_tag_bin
    if category != 'central':
        histogram_properties.name += '_' + category
    histogram_properties.title = title
    histogram_properties.x_axis_title = x_axis_title
    histogram_properties.y_axis_title = y_axis_title
    histogram_properties.x_limits = x_limits
    histogram_properties.y_limits = y_limits
    histogram_properties.y_max_scale = y_max_scale
    histogram_properties.xerr = None
    # workaround for rootpy issue #638
    histogram_properties.emptybins = True
    if b_tag_bin:
        histogram_properties.additional_text = channel_latex[
            channel] + ', ' + b_tag_bins_latex[b_tag_bin]
    else:
        histogram_properties.additional_text = channel_latex[channel]
    histogram_properties.legend_location = legend_location
    histogram_properties.cms_logo_location = cms_logo_location
    histogram_properties.preliminary = preliminary
    histogram_properties.set_log_y = log_y
    histogram_properties.legend_color = legend_color
    if ratio_y_limits:
        histogram_properties.ratio_y_limits = ratio_y_limits

    if normalise_to_fit:
        histogram_properties.mc_error = get_normalisation_error(normalisation)
        histogram_properties.mc_errors_label = 'fit uncertainty'
    else:
        histogram_properties.mc_error = mc_uncertainty
        histogram_properties.mc_errors_label = 'MC unc.'

    # Actually draw histograms
    make_data_mc_comparison_plot(
        histograms_to_draw,
        histogram_lables,
        histogram_colors,
        histogram_properties,
        save_folder=output_folder,
        show_ratio=False,
        normalise=normalise,
    )
    histogram_properties.name += '_with_ratio'
    loc = histogram_properties.legend_location
    # adjust legend location as it is relative to canvas!
    histogram_properties.legend_location = (loc[0], loc[1] + 0.05)
    make_data_mc_comparison_plot(
        histograms_to_draw,
        histogram_lables,
        histogram_colors,
        histogram_properties,
        save_folder=output_folder,
        show_ratio=True,
        normalise=normalise,
    )
Esempio n. 12
0
# plot with matplotlib
plot_with_plotting_script = True

if plot_with_plotting_script:
	properties = Histogram_properties()
	properties.name = 'matplotlib_hist'
	properties.x_axis_title = 'Mass'
	properties.y_axis_title = 'Events'
	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)
def make_ttbarReco_plot( channel, x_axis_title, y_axis_title,
              signal_region_tree,
              control_region_tree,
              branchName,
              name_prefix, x_limits, nBins,
              use_qcd_data_region = False,
              y_limits = [],
              y_max_scale = 1.2,
              rebin = 1,
              legend_location = ( 0.98, 0.78 ), cms_logo_location = 'right',
              log_y = False,
              legend_color = False,
              ratio_y_limits = [0.3, 1.7],
              normalise = False,
              ):
    global output_folder, measurement_config, category, normalise_to_fit
    global preliminary, norm_variable, sum_bins, b_tag_bin, histogram_files

    # Input files, normalisations, tree/region names
    qcd_data_region = ''
    title = title_template % ( measurement_config.new_luminosity / 1000., measurement_config.centre_of_mass_energy )
    normalisation = None
    if channel == 'electron':
        histogram_files['data'] = measurement_config.data_file_electron_trees
        histogram_files['QCD'] = measurement_config.electron_QCD_MC_category_templates_trees[category]
        if normalise_to_fit:
            normalisation = normalisations_electron[norm_variable]
        if use_qcd_data_region:
            qcd_data_region = 'QCDConversions'
    if channel == 'muon':
        histogram_files['data'] = measurement_config.data_file_muon_trees
        histogram_files['QCD'] = measurement_config.muon_QCD_MC_category_templates_trees[category]
        if normalise_to_fit:
            normalisation = normalisations_muon[norm_variable]
        if use_qcd_data_region:
            qcd_data_region = 'QCD non iso mu+jets ge3j'

    histograms = get_histograms_from_trees( trees = [signal_region_tree, control_region_tree], branch = branchName, weightBranch = '1', files = histogram_files, nBins = nBins, xMin = x_limits[0], xMax = x_limits[-1] )

    selection = 'SolutionCategory == 0'
    histogramsNoSolution = get_histograms_from_trees( trees = [signal_region_tree], branch = branchName, weightBranch = '1', selection = selection, files = histogram_files, nBins = nBins, xMin = x_limits[0], xMax = x_limits[-1] )

    selection = 'SolutionCategory == 1'
    histogramsCorrect = get_histograms_from_trees( trees = [signal_region_tree], branch = branchName, weightBranch = '1', selection = selection, files = histogram_files, nBins = nBins, xMin = x_limits[0], xMax = x_limits[-1] )

    selection = 'SolutionCategory == 2'
    histogramsNotSL = get_histograms_from_trees( trees = [signal_region_tree], branch = branchName, weightBranch = '1', selection = selection, files = histogram_files, nBins = nBins, xMin = x_limits[0], xMax = x_limits[-1] )

    selection = 'SolutionCategory == 3'
    histogramsNotReco = get_histograms_from_trees( trees = [signal_region_tree], branch = branchName, weightBranch = '1', selection = selection, files = histogram_files, nBins = nBins, xMin = x_limits[0], xMax = x_limits[-1] )

    selection = 'SolutionCategory > 3'
    histogramsWrong = get_histograms_from_trees( trees = [signal_region_tree], branch = branchName, weightBranch = '1', selection = selection, files = histogram_files, nBins = nBins, xMin = x_limits[0], xMax = x_limits[-1] )

    # Split histograms up into signal/control (?)
    signal_region_hists = {}
    inclusive_control_region_hists = {}
    for sample in histograms.keys():
        signal_region_hists[sample] = histograms[sample][signal_region_tree]
        if use_qcd_data_region:
            inclusive_control_region_hists[sample] = histograms[sample][control_region_tree]

    prepare_histograms( histograms, rebin = 1, scale_factor = measurement_config.luminosity_scale )
    prepare_histograms( histogramsNoSolution, rebin = 1, scale_factor = measurement_config.luminosity_scale )
    prepare_histograms( histogramsCorrect, rebin = 1, scale_factor = measurement_config.luminosity_scale )
    prepare_histograms( histogramsNotSL, rebin = 1, scale_factor = measurement_config.luminosity_scale )
    prepare_histograms( histogramsNotReco, rebin = 1, scale_factor = measurement_config.luminosity_scale )
    prepare_histograms( histogramsWrong, rebin = 1, scale_factor = measurement_config.luminosity_scale )

    qcd_from_data = signal_region_hists['QCD']

    # Which histograms to draw, and properties
    histograms_to_draw = [signal_region_hists['data'], qcd_from_data,
                          signal_region_hists['V+Jets'],
                          signal_region_hists['SingleTop'],
                          histogramsNoSolution['TTJet'][signal_region_tree],
                          histogramsNotSL['TTJet'][signal_region_tree],
                          histogramsNotReco['TTJet'][signal_region_tree],
                          histogramsWrong['TTJet'][signal_region_tree],
                          histogramsCorrect['TTJet'][signal_region_tree]
                          ]
    histogram_lables = ['data', 'QCD', 'V+Jets', 'Single-Top', 
                        samples_latex['TTJet'] + ' - no solution',
                        samples_latex['TTJet'] + ' - not SL',
                        samples_latex['TTJet'] + ' - not reconstructible',
                        samples_latex['TTJet'] + ' - wrong reco',
                        samples_latex['TTJet'] + ' - correct',
                        ]
    histogram_colors = ['black', 'yellow', 'green', 'magenta',
                        'black',
                        'burlywood',
                        'chartreuse',
                        'blue',
                        'red'
                        ]

    histogram_properties = Histogram_properties()
    histogram_properties.name = name_prefix + b_tag_bin
    if category != 'central':
        histogram_properties.name += '_' + category
    histogram_properties.title = title
    histogram_properties.x_axis_title = x_axis_title
    histogram_properties.y_axis_title = y_axis_title
    histogram_properties.x_limits = x_limits
    histogram_properties.y_limits = y_limits
    histogram_properties.y_max_scale = y_max_scale
    histogram_properties.xerr = None
    # workaround for rootpy issue #638
    histogram_properties.emptybins = True
    if b_tag_bin:
        histogram_properties.additional_text = channel_latex[channel] + ', ' + b_tag_bins_latex[b_tag_bin]
    else:
        histogram_properties.additional_text = channel_latex[channel]
    histogram_properties.legend_location = legend_location
    histogram_properties.cms_logo_location = cms_logo_location
    histogram_properties.preliminary = preliminary
    histogram_properties.set_log_y = log_y
    histogram_properties.legend_color = legend_color
    if ratio_y_limits:
        histogram_properties.ratio_y_limits = ratio_y_limits

    if normalise_to_fit:
        histogram_properties.mc_error = get_normalisation_error( normalisation )
        histogram_properties.mc_errors_label = 'fit uncertainty'
    else:
        histogram_properties.mc_error = mc_uncertainty
        histogram_properties.mc_errors_label = 'MC unc.'

    # Actually draw histograms
    make_data_mc_comparison_plot( histograms_to_draw, histogram_lables, histogram_colors,
                                 histogram_properties, save_folder = output_folder,
                                 show_ratio = False, normalise = normalise,
                                 )
    histogram_properties.name += '_with_ratio'
    loc = histogram_properties.legend_location
    # adjust legend location as it is relative to canvas!
    histogram_properties.legend_location = ( loc[0], loc[1] + 0.05 )
    make_data_mc_comparison_plot( histograms_to_draw, histogram_lables, histogram_colors,
                                 histogram_properties, save_folder = output_folder,
                                 show_ratio = True, normalise = normalise,
                                 )
def plotHistograms(
		histogram_files, 
		var_to_plot,
		output_folder):
	'''
	'''
	global measurement_config

	weightBranchSignalRegion  = 'EventWeight * PUWeight * BJetWeight'
	weightBranchControlRegion = 'EventWeight'

	# Names of QCD regions to use
	qcd_data_region             = ''
	qcd_data_region_electron    = 'QCD non iso e+jets'
	qcd_data_region_muon        = 'QCD non iso mu+jets 1p5to3'

	sr_e_tree = 'TTbar_plus_X_analysis/EPlusJets/Ref selection/AnalysisVariables'
	sr_mu_tree = 'TTbar_plus_X_analysis/MuPlusJets/Ref selection/AnalysisVariables'
	cr_e_tree = 'TTbar_plus_X_analysis/EPlusJets/{}/AnalysisVariables'.format(qcd_data_region_electron)
	cr_mu_tree = 'TTbar_plus_X_analysis/MuPlusJets/{}/AnalysisVariables'.format(qcd_data_region_muon)
	
	print "Trees : "
	print "\t {}".format(sr_e_tree)
	print "\t {}".format(sr_mu_tree)
	print "\t {}".format(cr_e_tree)
	print "\t {}".format(cr_mu_tree)

	histogram_files_electron            = dict(histogram_files)
	histogram_files_electron['data']    = measurement_config.data_file_electron
	histogram_files_electron['QCD']     = measurement_config.electron_QCD_MC_trees

	histogram_files_muon                = dict(histogram_files)
	histogram_files_muon['data']        = measurement_config.data_file_muon
	histogram_files_muon['QCD']         = measurement_config.muon_QCD_MC_trees

	signal_region_hists = {}
	control_region_hists = {}

	for var in var_to_plot:
		selectionSignalRegion = '{} >= 0'.format(var)

		# Print all the weights applied to this plot 
		print "Variable : {}".format(var)
		print "Weight applied : {}".format(weightBranchSignalRegion)
		print "Selection applied : {}".format(selectionSignalRegion)

		histograms_electron = get_histograms_from_trees( 
			trees = [sr_e_tree], 
			branch = var, 
			weightBranch = weightBranchSignalRegion + ' * ElectronEfficiencyCorrection', 
			files = histogram_files_electron, 
			nBins = 20, 
			xMin = control_plots_bins[var][0], 
			xMax = control_plots_bins[var][-1], 
			selection = selectionSignalRegion 
		)
		histograms_muon = get_histograms_from_trees( 
			trees = [sr_mu_tree], 
			branch = var, 
			weightBranch = weightBranchSignalRegion + ' * MuonEfficiencyCorrection', 
			files = histogram_files_muon, 
			nBins = 20, 
			xMin = control_plots_bins[var][0], 
			xMax = control_plots_bins[var][-1], 
			selection = selectionSignalRegion 
		)
		histograms_electron_QCDControlRegion = get_histograms_from_trees( 
			trees = [cr_e_tree], 
			branch = var, 
			weightBranch = weightBranchControlRegion, 
			files = histogram_files_electron, 
			nBins = 20, 
			xMin = control_plots_bins[var][0], 
			xMax = control_plots_bins[var][-1], 
			selection = selectionSignalRegion 
		)
		histograms_muon_QCDControlRegion     = get_histograms_from_trees( 
			trees = [cr_mu_tree], 
			branch = var, 
			weightBranch = weightBranchControlRegion, 
			files = histogram_files_muon, 
			nBins = 20, 
			xMin = control_plots_bins[var][0], 
			xMax = control_plots_bins[var][-1], 
			selection = selectionSignalRegion 
		)

		# Combine the electron and muon histograms
		for sample in histograms_electron:
			h_electron = histograms_electron[sample][sr_e_tree]
			h_muon     = histograms_muon[sample][sr_mu_tree]
			h_qcd_electron = histograms_electron_QCDControlRegion[sample][cr_e_tree]
			h_qcd_muon     = histograms_muon_QCDControlRegion[sample][cr_mu_tree]

			signal_region_hists[sample] = h_electron + h_muon
			control_region_hists[sample] = h_qcd_electron + h_qcd_muon

		# NORMALISE TO LUMI
		prepare_histograms( 
			signal_region_hists, 
			scale_factor = measurement_config.luminosity_scale 
		)
		prepare_histograms( 
			control_region_hists, 
			scale_factor = measurement_config.luminosity_scale 
		)

		# BACKGROUND SUBTRACTION FOR QCD
		qcd_from_data = None
		qcd_from_data = clean_control_region( 
			control_region_hists,
			subtract = ['TTJet', 'V+Jets', 'SingleTop'] 
		)

		# DATA DRIVEN QCD
		nBins = signal_region_hists['QCD'].GetNbinsX()
		n, error = signal_region_hists['QCD'].integral(0,nBins+1,error=True)
		n_qcd_predicted_mc_signal = ufloat( n, error)

		n, error = control_region_hists['QCD'].integral(0,nBins+1,error=True)
		n_qcd_predicted_mc_control = ufloat( n, error)

		n, error = qcd_from_data.integral(0,nBins+1,error=True)
		n_qcd_control_region = ufloat( n, error)

		dataDrivenQCDScale = n_qcd_predicted_mc_signal / n_qcd_predicted_mc_control
		qcd_from_data.Scale( dataDrivenQCDScale.nominal_value )
		signal_region_hists['QCD'] = qcd_from_data

		# PLOTTING
		histograms_to_draw = []
		histogram_lables   = []
		histogram_colors   = []

		histograms_to_draw = [
			# signal_region_hists['data'], 
			# qcd_from_data,
			# signal_region_hists['V+Jets'],
			signal_region_hists['SingleTop'],
			signal_region_hists['ST_s'],
			signal_region_hists['ST_t'],
			signal_region_hists['ST_tW'],
			signal_region_hists['STbar_t'],
			signal_region_hists['STbar_tW'],
			# signal_region_hists['TTJet'],
		]
		histogram_lables   = [
			'data',
			# 'QCD', 
			# 'V+Jets', 
			# 'Single-Top', 
			'ST-s', 
			'ST-t', 
			'ST-tW', 
			'STbar-t', 
			'STbar-tW', 
			# samples_latex['TTJet'],
		]
		histogram_colors   = [
			colours['data'], 
			# colours['QCD'], 
			# colours['V+Jets'], 
			# colours['Single-Top'],
			colours['ST_s'],
			colours['ST_t'],
			colours['ST_tW'],
			colours['STbar_t'],
			colours['STbar_tW'], 
			# colours['TTJet'],
		]

		# Find maximum y of samples
		maxData = max( list(signal_region_hists['SingleTop'].y()) )
		y_limits = [0, maxData * 1.5]
		log_y = False
		if log_y:
			y_limits = [0.1, maxData * 100 ]

		# Lumi title of plots
		title_template = '%.1f fb$^{-1}$ (%d TeV)'
		title = title_template % ( measurement_config.new_luminosity/1000., measurement_config.centre_of_mass_energy )
		x_axis_title = '$%s$ [GeV]' % variables_latex[var]
		y_axis_title = 'Events/(%i GeV)' % binWidth(control_plots_bins[var])

		# More histogram settings to look semi decent
		histogram_properties = Histogram_properties()
		histogram_properties.name                   = var + '_with_ratio'
		histogram_properties.title                  = title
		histogram_properties.x_axis_title           = x_axis_title
		histogram_properties.y_axis_title           = y_axis_title
		histogram_properties.x_limits               = control_plots_bins[var]
		histogram_properties.y_limits               = y_limits
		histogram_properties.y_max_scale            = 1.4
		histogram_properties.xerr                   = None
		histogram_properties.emptybins              = True
		histogram_properties.additional_text        = channel_latex['combined']
		histogram_properties.legend_location        = ( 0.9, 0.73 )
		histogram_properties.cms_logo_location      = 'left'
		histogram_properties.preliminary            = True
		histogram_properties.set_log_y              = log_y
		histogram_properties.legend_color           = False
		histogram_properties.ratio_y_limits     	= [0.1,1.9]
		if log_y: histogram_properties.name += '_logy'
		loc = histogram_properties.legend_location
		histogram_properties.legend_location = ( loc[0], loc[1] + 0.05 )

		make_data_mc_comparison_plot( 
			histograms_to_draw, 
			histogram_lables, 
			histogram_colors,
			histogram_properties, 
			save_folder = output_folder,
			show_ratio = True, 
		)

		histogram_properties.name                   = var + '_ST_TTJet_Shape'
		if log_y: histogram_properties.name += '_logy'
		histogram_properties.y_axis_title           = 'Normalised Distribution'
		histogram_properties.y_limits               = [0,0.5]

		make_shape_comparison_plot( 
			shapes = [
				signal_region_hists['TTJet'],
				signal_region_hists['ST_t'],
				signal_region_hists['ST_tW'],
				signal_region_hists['ST_s'],
				signal_region_hists['STbar_t'],
				signal_region_hists['STbar_tW'], 
			],
			names = [
				samples_latex['TTJet'],
				'Single-Top t channel',
				'Single-Top tW channel',
				'Single-Top s channel',
				'Single-AntiTop t channel',
				'Single-AntiTop tW channel',
			],
			colours = [
				colours['TTJet'],
				colours['ST_t'],
				colours['ST_tW'],
				colours['ST_s'],
				colours['STbar_t'],
				colours['STbar_tW'],
			],
			histogram_properties = histogram_properties,
			save_folder = output_folder,
			fill_area = False,
			add_error_bars = False,
			save_as = ['pdf'],
			make_ratio = True, 
			alpha = 1,
		)
		print_output(signal_region_hists, output_folder, var, 'combined')
	return
def make_correlation_plot_from_file( channel, variable, fit_variables, CoM, title, x_title, y_title, x_limits, y_limits, rebin = 1, save_folder = 'plots/fitchecks/', save_as = ['pdf', 'png'] ):
# global b_tag_bin
    parameters = ["TTJet", "SingleTop", "V+Jets", "QCD"]
    parameters_latex = []
    for template in parameters:
        parameters_latex.append(samples_latex[template])
        
    input_file = open( "logs/01_%s_fit_%dTeV_%s.log" % ( variable, CoM, fit_variables ), "r" )
    # cycle through the lines in the file
    for line_number, line in enumerate( input_file ):
        # for now, only make plots for the fits for the central measurement
        if "central" in line:
            # matrix we want begins 11 lines below the line with the measurement ("central")
            line_number = line_number + 11
            break
    input_file.close()
    
    #Note: For some reason, the fit outputs the correlation matrix with the templates in the following order:
    #parameter1: QCD
    #parameter2: SingleTop
    #parameter3: TTJet
    #parameter4: V+Jets
        
    for variable_bin in variable_bins_ROOT[variable]:
        weights = {}
        if channel == 'electron':
            #formula to calculate the number of lines below "central" to access in each loop
            number_of_lines_down = (variable_bins_ROOT[variable].index( variable_bin ) * 12)

            #Get QCD correlations
            matrix_line = linecache.getline( "logs/01_%s_fit_%dTeV_%s.log" % ( variable, CoM, fit_variables ), line_number + number_of_lines_down )
            weights["QCD_QCD"] = matrix_line.split()[2]
            weights["QCD_SingleTop"] = matrix_line.split()[3]
            weights["QCD_TTJet"] = matrix_line.split()[4]
            weights["QCD_V+Jets"] = matrix_line.split()[5]

            #Get SingleTop correlations
            matrix_line = linecache.getline( "logs/01_%s_fit_%dTeV_%s.log" % ( variable, CoM, fit_variables ), line_number + number_of_lines_down + 1 )
            weights["SingleTop_QCD"] = matrix_line.split()[2]
            weights["SingleTop_SingleTop"] = matrix_line.split()[3]
            weights["SingleTop_TTJet"] = matrix_line.split()[4]
            weights["SingleTop_V+Jets"] = matrix_line.split()[5]

            #Get TTJet correlations
            matrix_line = linecache.getline( "logs/01_%s_fit_%dTeV_%s.log" % ( variable, CoM, fit_variables ), line_number + number_of_lines_down + 2 )
            weights["TTJet_QCD"] = matrix_line.split()[2]
            weights["TTJet_SingleTop"] = matrix_line.split()[3]            
            weights["TTJet_TTJet"] = matrix_line.split()[4]
            weights["TTJet_V+Jets"] = matrix_line.split()[5]

            #Get V+Jets correlations
            matrix_line = linecache.getline( "logs/01_%s_fit_%dTeV_%s.log" % ( variable, CoM, fit_variables ), line_number + number_of_lines_down + 3 )
            weights["V+Jets_QCD"] = matrix_line.split()[2]
            weights["V+Jets_SingleTop"] = matrix_line.split()[3]
            weights["V+Jets_TTJet"] = matrix_line.split()[4]
            weights["V+Jets_V+Jets"] = matrix_line.split()[5]

        if channel == 'muon':
            #formula to calculate the number of lines below "central" to access in each bin loop
            number_of_lines_down =  ( len( variable_bins_ROOT [variable] ) * 12 ) + ( variable_bins_ROOT[variable].index( variable_bin ) * 12 )
            
            #Get QCD correlations
            matrix_line = linecache.getline( "logs/01_%s_fit_%dTeV_%s.log" % ( variable, CoM, fit_variables ), line_number + number_of_lines_down )
            weights["QCD_QCD"] = matrix_line.split()[2]
            weights["QCD_SingleTop"] = matrix_line.split()[3]
            weights["QCD_TTJet"] = matrix_line.split()[4]
            weights["QCD_V+Jets"] = matrix_line.split()[5]

            #Get SingleTop correlations
            matrix_line = linecache.getline( "logs/01_%s_fit_%dTeV_%s.log" % ( variable, CoM, fit_variables ), line_number + number_of_lines_down + 1 )
            weights["SingleTop_QCD"] = matrix_line.split()[2]
            weights["SingleTop_SingleTop"] = matrix_line.split()[3]
            weights["SingleTop_TTJet"] = matrix_line.split()[4]
            weights["SingleTop_V+Jets"] = matrix_line.split()[5]

            #Get TTJet correlations
            matrix_line = linecache.getline( "logs/01_%s_fit_%dTeV_%s.log" % ( variable, CoM, fit_variables ), line_number + number_of_lines_down + 2 )
            weights["TTJet_QCD"] = matrix_line.split()[2]
            weights["TTJet_SingleTop"] = matrix_line.split()[3]
            weights["TTJet_TTJet"] = matrix_line.split()[4]
            weights["TTJet_V+Jets"] = matrix_line.split()[5]
            
            #Get V+Jets correlations
            matrix_line = linecache.getline( "logs/01_%s_fit_%dTeV_%s.log" % ( variable, CoM, fit_variables ), line_number + number_of_lines_down + 3 )
            weights["V+Jets_QCD"] = matrix_line.split()[2]
            weights["V+Jets_SingleTop"] = matrix_line.split()[3]
            weights["V+Jets_TTJet"] = matrix_line.split()[4]
            weights["V+Jets_V+Jets"] = matrix_line.split()[5]

        #Create histogram
        histogram_properties = Histogram_properties()
        histogram_properties.title = title
        histogram_properties.name = 'Correlations_' + channel + '_' + variable + '_' + variable_bin
        histogram_properties.y_axis_title = y_title
        histogram_properties.x_axis_title = x_title
        histogram_properties.y_limits = y_limits
        histogram_properties.x_limits = x_limits
        histogram_properties.mc_error = 0.0
        histogram_properties.legend_location = 'upper right'

        #initialise 2D histogram
        a = Hist2D( 4, 0, 4, 4, 0, 4 )
        #fill histogram
        for i in range( len( parameters ) ):
            for j in range( len( parameters ) ):
                a.fill( float( i ), float( j ), float( weights["%s_%s" % ( parameters[i], parameters[j] )] ) )
        # create figure
        plt.figure( figsize = CMS.figsize, dpi = CMS.dpi, facecolor = CMS.facecolor )
        # make subplot(?) 
        fig, ax = plt.subplots( nrows = 1, ncols = 1 )
        rplt.hist2d( a )
        plt.subplots_adjust( right = 0.8 )

        #Set labels and formats for titles and axes
        plt.ylabel( histogram_properties.y_axis_title )
        plt.xlabel( histogram_properties.x_axis_title )
        plt.title( histogram_properties.title )
        x_limits = histogram_properties.x_limits
        y_limits = histogram_properties.y_limits
        ax.set_xticklabels( parameters_latex )
        ax.set_yticklabels( parameters_latex )
        ax.set_xticks( [0.5, 1.5, 2.5, 3.5] )
        ax.set_yticks( [0.5, 1.5, 2.5, 3.5] )
        plt.setp( ax.get_xticklabels(), visible = True )
        plt.setp( ax.get_yticklabels(), visible = True )

        #create and draw colour bar to the right of the main plot
        im = rplt.imshow( a, axes = ax, vmin = -1.0, vmax = 1.0 )
        #set location and dimensions (left, lower, width, height)
        cbar_ax = fig.add_axes( [0.85, 0.10, 0.05, 0.8] )
        fig.colorbar( im, cax = cbar_ax )

        for xpoint in range( len( parameters ) ):
            for ypoint in range( len( parameters ) ):
                correlation_value = weights["%s_%s" % ( parameters[xpoint], parameters[ypoint] )]
                ax.annotate( correlation_value, xy = ( xpoint + 0.5, ypoint + 0.5 ), ha = 'center', va = 'center', bbox = dict( fc = 'white', ec = 'none' ) )
        for save in save_as:
            plt.savefig( save_folder + histogram_properties.name + '.' + save )
        plt.close(fig)
    plt.close('all')
def do_shape_check(channel,
                   control_region_1,
                   control_region_2,
                   variable,
                   normalisation,
                   title,
                   x_title,
                   y_title,
                   x_limits,
                   y_limits,
                   name_region_1='conversions',
                   name_region_2='non-isolated electrons',
                   name_region_3='fit results',
                   rebin=1):
    global b_tag_bin
    # QCD shape comparison
    if channel == 'electron':
        histograms = get_histograms_from_files(
            [control_region_1, control_region_2], histogram_files)

        region_1 = histograms[channel][control_region_1].Clone(
        ) - histograms['TTJet'][control_region_1].Clone(
        ) - histograms['V+Jets'][control_region_1].Clone(
        ) - histograms['SingleTop'][control_region_1].Clone()
        region_2 = histograms[channel][control_region_2].Clone(
        ) - histograms['TTJet'][control_region_2].Clone(
        ) - histograms['V+Jets'][control_region_2].Clone(
        ) - histograms['SingleTop'][control_region_2].Clone()

        region_1.Rebin(rebin)
        region_2.Rebin(rebin)

        histogram_properties = Histogram_properties()
        histogram_properties.name = 'QCD_control_region_comparison_' + channel + '_' + variable + '_' + b_tag_bin
        histogram_properties.title = title + ', ' + b_tag_bins_latex[b_tag_bin]
        histogram_properties.x_axis_title = x_title
        histogram_properties.y_axis_title = 'arbitrary units/(0.1)'
        histogram_properties.x_limits = x_limits
        histogram_properties.y_limits = y_limits[0]
        histogram_properties.mc_error = 0.0
        histogram_properties.legend_location = 'upper right'
        make_control_region_comparison(
            region_1,
            region_2,
            name_region_1=name_region_1,
            name_region_2=name_region_2,
            histogram_properties=histogram_properties,
            save_folder=output_folder)

        # QCD shape comparison to fit results
        histograms = get_histograms_from_files([control_region_1],
                                               histogram_files)

        region_1_tmp = histograms[channel][control_region_1].Clone(
        ) - histograms['TTJet'][control_region_1].Clone(
        ) - histograms['V+Jets'][control_region_1].Clone(
        ) - histograms['SingleTop'][control_region_1].Clone()
        region_1 = rebin_asymmetric(region_1_tmp, bin_edges_vis[variable])

        fit_results_QCD = normalisation[variable]['QCD']
        region_2 = value_error_tuplelist_to_hist(fit_results_QCD,
                                                 bin_edges_vis[variable])

        histogram_properties = Histogram_properties()
        histogram_properties.name = 'QCD_control_region_comparison_' + channel + '_' + variable + '_fits_with_conversions_' + b_tag_bin
        histogram_properties.title = title + ', ' + b_tag_bins_latex[b_tag_bin]
        histogram_properties.x_axis_title = x_title
        histogram_properties.y_axis_title = 'arbitrary units/(0.1)'
        histogram_properties.x_limits = x_limits
        histogram_properties.y_limits = y_limits[1]
        histogram_properties.mc_error = 0.0
        histogram_properties.legend_location = 'upper right'
        make_control_region_comparison(
            region_1,
            region_2,
            name_region_1=name_region_1,
            name_region_2=name_region_3,
            histogram_properties=histogram_properties,
            save_folder=output_folder)

    histograms = get_histograms_from_files([control_region_2], histogram_files)

    region_1_tmp = histograms[channel][control_region_2].Clone(
    ) - histograms['TTJet'][control_region_2].Clone(
    ) - histograms['V+Jets'][control_region_2].Clone(
    ) - histograms['SingleTop'][control_region_2].Clone()
    region_1 = rebin_asymmetric(region_1_tmp, bin_edges_vis[variable])

    fit_results_QCD = normalisation[variable]['QCD']
    region_2 = value_error_tuplelist_to_hist(fit_results_QCD,
                                             bin_edges_vis[variable])

    histogram_properties = Histogram_properties()
    histogram_properties.name = 'QCD_control_region_comparison_' + channel + '_' + variable + '_fits_with_noniso_' + b_tag_bin
    histogram_properties.title = title + ', ' + b_tag_bins_latex[b_tag_bin]
    histogram_properties.x_axis_title = x_title
    histogram_properties.y_axis_title = 'arbitrary units/(0.1)'
    histogram_properties.x_limits = x_limits
    histogram_properties.y_limits = y_limits[1]
    histogram_properties.mc_error = 0.0
    histogram_properties.legend_location = 'upper right'
    make_control_region_comparison(region_1,
                                   region_2,
                                   name_region_1=name_region_2,
                                   name_region_2=name_region_3,
                                   histogram_properties=histogram_properties,
                                   save_folder=output_folder)
def make_plot( channel, x_axis_title, y_axis_title,
              signal_region_tree,
              control_region_tree,
              branchName,
              name_prefix, x_limits, nBins,
              use_qcd_data_region = False,
              compare_qcd_signal_with_data_control = False,
              y_limits = [],
              y_max_scale = 1.3,
              rebin = 1,
              legend_location = ( 0.98, 0.78 ), cms_logo_location = 'right',
              log_y = False,
              legend_color = False,
              ratio_y_limits = [0.3, 2.5],
              normalise = False,
              ):
    global output_folder, measurement_config, category, normalise_to_fit
    global preliminary, norm_variable, sum_bins, b_tag_bin, histogram_files

    controlToCompare = []
    if 'electron' in channel :
        controlToCompare =  ['QCDConversions', 'QCD non iso e+jets']
    elif 'muon' in channel :
        controlToCompare =  ['QCD iso > 0.3', 'QCD 0.12 < iso <= 0.3']

    histogramsToCompare = {}
    for qcd_data_region in controlToCompare:
        print 'Doing ',qcd_data_region
        # Input files, normalisations, tree/region names
        title = title_template % ( measurement_config.new_luminosity, measurement_config.centre_of_mass_energy )
        normalisation = None
        weightBranchSignalRegion = 'EventWeight'
        if 'electron' in channel:
            histogram_files['data'] = measurement_config.data_file_electron_trees
            histogram_files['QCD'] = measurement_config.electron_QCD_MC_category_templates_trees[category]
            if normalise_to_fit:
                normalisation = normalisations_electron[norm_variable]
            # if use_qcd_data_region:
            #     qcd_data_region = 'QCDConversions'
            #     # qcd_data_region = 'QCD non iso e+jets'
            if not 'QCD' in channel and not 'NPU' in branchName:
                weightBranchSignalRegion += ' * ElectronEfficiencyCorrection'
        if 'muon' in channel:
            histogram_files['data'] = measurement_config.data_file_muon_trees
            histogram_files['QCD'] = measurement_config.muon_QCD_MC_category_templates_trees[category]
            if normalise_to_fit:
                normalisation = normalisations_muon[norm_variable]
            # if use_qcd_data_region:
            #     qcd_data_region = 'QCD iso > 0.3'
            if not 'QCD' in channel and not 'NPU' in branchName:
                weightBranchSignalRegion += ' * MuonEfficiencyCorrection'

        if not "_NPUNoWeight" in name_prefix:
            weightBranchSignalRegion += ' * PUWeight'

        if not "_NBJetsNoWeight" in name_prefix:
            weightBranchSignalRegion += ' * BJetWeight'

        selection = '1'
        if branchName == 'abs(lepton_eta)' :
            selection = 'lepton_eta > -10'
        else:
            selection = '%s >= 0' % branchName
        # if 'QCDConversions' in signal_region_tree:
        #     selection += '&& isTightElectron'
        # print selection
        histograms = get_histograms_from_trees( trees = [signal_region_tree, control_region_tree], branch = branchName, weightBranch = weightBranchSignalRegion, files = histogram_files, nBins = nBins, xMin = x_limits[0], xMax = x_limits[-1], selection = selection )
        histograms_QCDControlRegion = None
        if use_qcd_data_region:
            qcd_control_region = signal_region_tree.replace( 'Ref selection', qcd_data_region )
            histograms_QCDControlRegion = get_histograms_from_trees( trees = [qcd_control_region], branch = branchName, weightBranch = 'EventWeight', files = histogram_files, nBins = nBins, xMin = x_limits[0], xMax = x_limits[-1], selection = selection )

        # Split histograms up into signal/control (?)
        signal_region_hists = {}
        control_region_hists = {}
        for sample in histograms.keys():
            signal_region_hists[sample] = histograms[sample][signal_region_tree]

            if compare_qcd_signal_with_data_control:
                if sample is 'data':
                    signal_region_hists[sample] = histograms[sample][control_region_tree]
                elif sample is 'QCD' :
                    signal_region_hists[sample] = histograms[sample][signal_region_tree]
                else:
                    del signal_region_hists[sample]

            if use_qcd_data_region:
                control_region_hists[sample] = histograms_QCDControlRegion[sample][qcd_control_region]

        # Prepare histograms
        if normalise_to_fit:
            # only scale signal region to fit (results are invalid for control region)
            prepare_histograms( signal_region_hists, rebin = rebin,
                                scale_factor = measurement_config.luminosity_scale,
                                normalisation = normalisation )
        elif normalise_to_data:
            totalMC = 0
            for sample in signal_region_hists:
                if sample is 'data' : continue
                totalMC += signal_region_hists[sample].Integral()
            newScale = signal_region_hists['data'].Integral() / totalMC

            prepare_histograms( signal_region_hists, rebin = rebin,
                                scale_factor = newScale,
                               )
        else:
            print measurement_config.luminosity_scale
            prepare_histograms( signal_region_hists, rebin = rebin,
                                scale_factor = measurement_config.luminosity_scale )
            prepare_histograms( control_region_hists, rebin = rebin,
                                scale_factor = measurement_config.luminosity_scale )

        # Use qcd from data control region or not
        qcd_from_data = None
        if use_qcd_data_region:
            qcd_from_data = clean_control_region( control_region_hists,

                              subtract = ['TTJet', 'V+Jets', 'SingleTop'] )
            # Normalise control region correctly
            nBins = signal_region_hists['QCD'].GetNbinsX()
            n, error = signal_region_hists['QCD'].integral(0,nBins+1,error=True)
            n_qcd_predicted_mc_signal = ufloat( n, error)

            n, error = control_region_hists['QCD'].integral(0,nBins+1,error=True)
            n_qcd_predicted_mc_control = ufloat( n, error)

            n, error = qcd_from_data.integral(0,nBins+1,error=True)
            n_qcd_control_region = ufloat( n, error)

            if not n_qcd_control_region == 0:
                dataDrivenQCDScale = n_qcd_predicted_mc_signal / n_qcd_predicted_mc_control
                print 'Overall scale : ',dataDrivenQCDScale
                qcd_from_data.Scale( dataDrivenQCDScale.nominal_value )
                signalToControlScale = n_qcd_predicted_mc_signal / n_qcd_control_region
                dataToMCscale = n_qcd_control_region / n_qcd_predicted_mc_control
                print "Signal to control :",signalToControlScale
                print "QCD scale : ",dataToMCscale
        else:
            qcd_from_data = signal_region_hists['QCD']

        # Which histograms to draw, and properties
        histograms_to_draw = []
        histogram_lables = []
        histogram_colors = []

        if compare_qcd_signal_with_data_control :
            histograms_to_draw = [signal_region_hists['data'], qcd_from_data ]
            histogram_lables = ['data', 'QCD']
            histogram_colors = ['black', 'yellow']
        else :
            histograms_to_draw = [signal_region_hists['data'], qcd_from_data,
                                  signal_region_hists['V+Jets'],
                                  signal_region_hists['SingleTop'],
                                  signal_region_hists['TTJet']]
            histogram_lables = ['data', 'QCD', 'V+Jets', 'Single-Top', samples_latex['TTJet']]
            histogram_colors = [colours['data'], colours['QCD'], colours['V+Jets'], colours['Single-Top'], colours['TTJet'] ]

        
        print list(qcd_from_data.y())
        histogramsToCompare[qcd_data_region] = qcd_from_data

    print histogramsToCompare
    histogram_properties = Histogram_properties()
    histogram_properties.name = 'QCD_control_region_comparison_' + channel + '_' + branchName
    histogram_properties.title = title
    histogram_properties.x_axis_title = x_axis_title
    histogram_properties.y_axis_title = y_axis_title
    histogram_properties.x_limits = x_limits
    histogram_properties.y_limits = y_limits
    histogram_properties.mc_error = 0.0
    histogram_properties.legend_location = ( 0.98, 0.78 )
    histogram_properties.ratio_y_limits = ratio_y_limits
    if 'electron' in channel:
        make_control_region_comparison(histogramsToCompare['QCDConversions'], histogramsToCompare['QCD non iso e+jets'],
                                       name_region_1='Conversions', name_region_2='Non Iso',
                                       histogram_properties=histogram_properties, save_folder=output_folder)
    elif 'muon' in channel:
        make_control_region_comparison(histogramsToCompare['QCD iso > 0.3'], histogramsToCompare['QCD 0.12 < iso <= 0.3'],
                                       name_region_1='QCD iso > 0.3', name_region_2='QCD 0.12 < iso <= 0.3',
                                       histogram_properties=histogram_properties, save_folder=output_folder)
Esempio n. 18
0
def plotHistograms(histogram_files, var_to_plot, output_folder):
    '''
	'''
    global measurement_config

    weightBranchSignalRegion = 'EventWeight * PUWeight * BJetWeight'
    weightBranchControlRegion = 'EventWeight'

    # Names of QCD regions to use
    qcd_data_region = ''
    qcd_data_region_electron = 'QCD non iso e+jets'
    qcd_data_region_muon = 'QCD non iso mu+jets 1p5to3'

    sr_e_tree = 'TTbar_plus_X_analysis/EPlusJets/Ref selection/AnalysisVariables'
    sr_mu_tree = 'TTbar_plus_X_analysis/MuPlusJets/Ref selection/AnalysisVariables'
    cr_e_tree = 'TTbar_plus_X_analysis/EPlusJets/{}/AnalysisVariables'.format(
        qcd_data_region_electron)
    cr_mu_tree = 'TTbar_plus_X_analysis/MuPlusJets/{}/AnalysisVariables'.format(
        qcd_data_region_muon)

    print "Trees : "
    print "\t {}".format(sr_e_tree)
    print "\t {}".format(sr_mu_tree)
    print "\t {}".format(cr_e_tree)
    print "\t {}".format(cr_mu_tree)

    histogram_files_electron = dict(histogram_files)
    histogram_files_electron['data'] = measurement_config.data_file_electron
    histogram_files_electron['QCD'] = measurement_config.electron_QCD_MC_trees

    histogram_files_muon = dict(histogram_files)
    histogram_files_muon['data'] = measurement_config.data_file_muon
    histogram_files_muon['QCD'] = measurement_config.muon_QCD_MC_trees

    signal_region_hists = {}
    control_region_hists = {}

    for var in var_to_plot:
        selectionSignalRegion = '{} >= 0'.format(var)

        # Print all the weights applied to this plot
        print "Variable : {}".format(var)
        print "Weight applied : {}".format(weightBranchSignalRegion)
        print "Selection applied : {}".format(selectionSignalRegion)

        histograms_electron = get_histograms_from_trees(
            trees=[sr_e_tree],
            branch=var,
            weightBranch=weightBranchSignalRegion +
            ' * ElectronEfficiencyCorrection',
            files=histogram_files_electron,
            nBins=20,
            xMin=control_plots_bins[var][0],
            xMax=control_plots_bins[var][-1],
            selection=selectionSignalRegion)
        histograms_muon = get_histograms_from_trees(
            trees=[sr_mu_tree],
            branch=var,
            weightBranch=weightBranchSignalRegion +
            ' * MuonEfficiencyCorrection',
            files=histogram_files_muon,
            nBins=20,
            xMin=control_plots_bins[var][0],
            xMax=control_plots_bins[var][-1],
            selection=selectionSignalRegion)
        histograms_electron_QCDControlRegion = get_histograms_from_trees(
            trees=[cr_e_tree],
            branch=var,
            weightBranch=weightBranchControlRegion,
            files=histogram_files_electron,
            nBins=20,
            xMin=control_plots_bins[var][0],
            xMax=control_plots_bins[var][-1],
            selection=selectionSignalRegion)
        histograms_muon_QCDControlRegion = get_histograms_from_trees(
            trees=[cr_mu_tree],
            branch=var,
            weightBranch=weightBranchControlRegion,
            files=histogram_files_muon,
            nBins=20,
            xMin=control_plots_bins[var][0],
            xMax=control_plots_bins[var][-1],
            selection=selectionSignalRegion)

        # Combine the electron and muon histograms
        for sample in histograms_electron:
            h_electron = histograms_electron[sample][sr_e_tree]
            h_muon = histograms_muon[sample][sr_mu_tree]
            h_qcd_electron = histograms_electron_QCDControlRegion[sample][
                cr_e_tree]
            h_qcd_muon = histograms_muon_QCDControlRegion[sample][cr_mu_tree]

            signal_region_hists[sample] = h_electron + h_muon
            control_region_hists[sample] = h_qcd_electron + h_qcd_muon

        # NORMALISE TO LUMI
        prepare_histograms(signal_region_hists,
                           scale_factor=measurement_config.luminosity_scale)
        prepare_histograms(control_region_hists,
                           scale_factor=measurement_config.luminosity_scale)

        # BACKGROUND SUBTRACTION FOR QCD
        qcd_from_data = None
        qcd_from_data = clean_control_region(
            control_region_hists, subtract=['TTJet', 'V+Jets', 'SingleTop'])

        # DATA DRIVEN QCD
        nBins = signal_region_hists['QCD'].GetNbinsX()
        n, error = signal_region_hists['QCD'].integral(0,
                                                       nBins + 1,
                                                       error=True)
        n_qcd_predicted_mc_signal = ufloat(n, error)

        n, error = control_region_hists['QCD'].integral(0,
                                                        nBins + 1,
                                                        error=True)
        n_qcd_predicted_mc_control = ufloat(n, error)

        n, error = qcd_from_data.integral(0, nBins + 1, error=True)
        n_qcd_control_region = ufloat(n, error)

        dataDrivenQCDScale = n_qcd_predicted_mc_signal / n_qcd_predicted_mc_control
        qcd_from_data.Scale(dataDrivenQCDScale.nominal_value)
        signal_region_hists['QCD'] = qcd_from_data

        # PLOTTING
        histograms_to_draw = []
        histogram_lables = []
        histogram_colors = []

        histograms_to_draw = [
            # signal_region_hists['data'],
            # qcd_from_data,
            # signal_region_hists['V+Jets'],
            signal_region_hists['SingleTop'],
            signal_region_hists['ST_s'],
            signal_region_hists['ST_t'],
            signal_region_hists['ST_tW'],
            signal_region_hists['STbar_t'],
            signal_region_hists['STbar_tW'],
            # signal_region_hists['TTJet'],
        ]
        histogram_lables = [
            'data',
            # 'QCD',
            # 'V+Jets',
            # 'Single-Top',
            'ST-s',
            'ST-t',
            'ST-tW',
            'STbar-t',
            'STbar-tW',
            # samples_latex['TTJet'],
        ]
        histogram_colors = [
            colours['data'],
            # colours['QCD'],
            # colours['V+Jets'],
            # colours['Single-Top'],
            colours['ST_s'],
            colours['ST_t'],
            colours['ST_tW'],
            colours['STbar_t'],
            colours['STbar_tW'],
            # colours['TTJet'],
        ]

        # Find maximum y of samples
        maxData = max(list(signal_region_hists['SingleTop'].y()))
        y_limits = [0, maxData * 1.5]
        log_y = False
        if log_y:
            y_limits = [0.1, maxData * 100]

        # Lumi title of plots
        title_template = '%.1f fb$^{-1}$ (%d TeV)'
        title = title_template % (measurement_config.new_luminosity / 1000.,
                                  measurement_config.centre_of_mass_energy)
        x_axis_title = '$%s$ [GeV]' % variables_latex[var]
        y_axis_title = 'Events/(%i GeV)' % binWidth(control_plots_bins[var])

        # More histogram settings to look semi decent
        histogram_properties = Histogram_properties()
        histogram_properties.name = var + '_with_ratio'
        histogram_properties.title = title
        histogram_properties.x_axis_title = x_axis_title
        histogram_properties.y_axis_title = y_axis_title
        histogram_properties.x_limits = control_plots_bins[var]
        histogram_properties.y_limits = y_limits
        histogram_properties.y_max_scale = 1.4
        histogram_properties.xerr = None
        histogram_properties.emptybins = True
        histogram_properties.additional_text = channel_latex['combined']
        histogram_properties.legend_location = (0.9, 0.73)
        histogram_properties.cms_logo_location = 'left'
        histogram_properties.preliminary = True
        histogram_properties.set_log_y = log_y
        histogram_properties.legend_color = False
        histogram_properties.ratio_y_limits = [0.1, 1.9]
        if log_y: histogram_properties.name += '_logy'
        loc = histogram_properties.legend_location
        histogram_properties.legend_location = (loc[0], loc[1] + 0.05)

        make_data_mc_comparison_plot(
            histograms_to_draw,
            histogram_lables,
            histogram_colors,
            histogram_properties,
            save_folder=output_folder,
            show_ratio=True,
        )

        histogram_properties.name = var + '_ST_TTJet_Shape'
        if log_y: histogram_properties.name += '_logy'
        histogram_properties.y_axis_title = 'Normalised Distribution'
        histogram_properties.y_limits = [0, 0.5]

        make_shape_comparison_plot(
            shapes=[
                signal_region_hists['TTJet'],
                signal_region_hists['ST_t'],
                signal_region_hists['ST_tW'],
                signal_region_hists['ST_s'],
                signal_region_hists['STbar_t'],
                signal_region_hists['STbar_tW'],
            ],
            names=[
                samples_latex['TTJet'],
                'Single-Top t channel',
                'Single-Top tW channel',
                'Single-Top s channel',
                'Single-AntiTop t channel',
                'Single-AntiTop tW channel',
            ],
            colours=[
                colours['TTJet'],
                colours['ST_t'],
                colours['ST_tW'],
                colours['ST_s'],
                colours['STbar_t'],
                colours['STbar_tW'],
            ],
            histogram_properties=histogram_properties,
            save_folder=output_folder,
            fill_area=False,
            add_error_bars=False,
            save_as=['pdf'],
            make_ratio=True,
            alpha=1,
        )
        print_output(signal_region_hists, output_folder, var, 'combined')
    return
def drawHistograms( dictionaryOfHistograms, uncertaintyBand, config, channel, variable ) :
    histograms_to_draw = [
        dictionaryOfHistograms['Data'],
        dictionaryOfHistograms['QCD'],
        dictionaryOfHistograms['V+Jets'],
        dictionaryOfHistograms['SingleTop'],
        dictionaryOfHistograms['TTJet'],
    ]

    histogram_lables   = [
        'data',
        'QCD', 
        'V+jets', 
        'single-top', 
        samples_latex['TTJet'],
    ]

    histogram_colors   = [
        colours['data'], 
        colours['QCD'], 
        colours['V+Jets'], 
        colours['Single-Top'], 
        colours['TTJet'],
    ]


    # Find maximum y of samples
    maxData = max( list(histograms_to_draw[0].y()) )
    y_limits = [0, maxData * 1.4]

    # More histogram settings to look semi decent
    histogram_properties = Histogram_properties()
    histogram_properties.name                   = '{channel}_{variable}'.format(channel = channel, variable=variable)
    histogram_properties.title                  = '$%.1f$ fb$^{-1}$ (%d TeV)' % ( config.new_luminosity/1000., config.centre_of_mass_energy )
    histogram_properties.x_axis_title           = variables_latex[variable]
    histogram_properties.y_axis_title           = 'Events'
    if variable in ['HT', 'ST', 'MET', 'WPT', 'lepton_pt']:
        histogram_properties.y_axis_title       = 'Events / {binWidth} GeV'.format( binWidth=binWidth )
        histogram_properties.x_axis_title           = '{variable} (GeV)'.format( variable = variables_latex[variable] )


    histogram_properties.x_limits               = [ reco_bin_edges[0], reco_bin_edges[-1] ]
    histogram_properties.y_limits               = y_limits
    histogram_properties.y_max_scale            = 1.3
    histogram_properties.xerr                   = None
    # workaround for rootpy issue #638
    histogram_properties.emptybins              = True
    histogram_properties.additional_text        = channel_latex[channel.lower()]
    histogram_properties.legend_location        = ( 0.9, 0.73 )
    histogram_properties.cms_logo_location      = 'left'
    histogram_properties.preliminary            = True
    # histogram_properties.preliminary            = False
    histogram_properties.set_log_y              = False
    histogram_properties.legend_color           = False
    histogram_properties.ratio_y_limits     = [0.5, 1.5]

    # Draw histogram with ratio plot
    histogram_properties.name += '_with_ratio'
    loc = histogram_properties.legend_location
    # adjust legend location as it is relative to canvas!
    histogram_properties.legend_location = ( loc[0], loc[1] + 0.05 )

    make_data_mc_comparison_plot( 
        histograms_to_draw, 
        histogram_lables, 
        histogram_colors,
        histogram_properties, 
        save_folder = 'plots/control_plots_with_systematic/',
        show_ratio = True, 
        normalise = False,
        systematics_for_ratio = uncertaintyBand,
        systematics_for_plot = uncertaintyBand,
    )

    histogram_properties.set_log_y = True
    histogram_properties.y_limits = [0.1, y_limits[-1]*100 ]
    histogram_properties.legend_location = ( 0.9, 0.9 )
    histogram_properties.name += '_logY'
    make_data_mc_comparison_plot( 
        histograms_to_draw, 
        histogram_lables, 
        histogram_colors,
        histogram_properties, 
        save_folder = 'plots/control_plots_with_systematic/logY/',
        show_ratio = True, 
        normalise = False,
        systematics_for_ratio = uncertaintyBand,
        systematics_for_plot = uncertaintyBand,
    )    
Esempio n. 20
0
def make_correlation_plot_from_file(channel,
                                    variable,
                                    fit_variables,
                                    CoM,
                                    title,
                                    x_title,
                                    y_title,
                                    x_limits,
                                    y_limits,
                                    rebin=1,
                                    save_folder='plots/fitchecks/',
                                    save_as=['pdf', 'png']):
    # global b_tag_bin
    parameters = ["TTJet", "SingleTop", "V+Jets", "QCD"]
    parameters_latex = []
    for template in parameters:
        parameters_latex.append(samples_latex[template])

    input_file = open(
        "logs/01_%s_fit_%dTeV_%s.log" % (variable, CoM, fit_variables), "r")
    # cycle through the lines in the file
    for line_number, line in enumerate(input_file):
        # for now, only make plots for the fits for the central measurement
        if "central" in line:
            # matrix we want begins 11 lines below the line with the measurement ("central")
            line_number = line_number + 11
            break
    input_file.close()

    #Note: For some reason, the fit outputs the correlation matrix with the templates in the following order:
    #parameter1: QCD
    #parameter2: SingleTop
    #parameter3: TTJet
    #parameter4: V+Jets

    for variable_bin in variable_bins_ROOT[variable]:
        weights = {}
        if channel == 'electron':
            #formula to calculate the number of lines below "central" to access in each loop
            number_of_lines_down = (
                variable_bins_ROOT[variable].index(variable_bin) * 12)

            #Get QCD correlations
            matrix_line = linecache.getline(
                "logs/01_%s_fit_%dTeV_%s.log" % (variable, CoM, fit_variables),
                line_number + number_of_lines_down)
            weights["QCD_QCD"] = matrix_line.split()[2]
            weights["QCD_SingleTop"] = matrix_line.split()[3]
            weights["QCD_TTJet"] = matrix_line.split()[4]
            weights["QCD_V+Jets"] = matrix_line.split()[5]

            #Get SingleTop correlations
            matrix_line = linecache.getline(
                "logs/01_%s_fit_%dTeV_%s.log" % (variable, CoM, fit_variables),
                line_number + number_of_lines_down + 1)
            weights["SingleTop_QCD"] = matrix_line.split()[2]
            weights["SingleTop_SingleTop"] = matrix_line.split()[3]
            weights["SingleTop_TTJet"] = matrix_line.split()[4]
            weights["SingleTop_V+Jets"] = matrix_line.split()[5]

            #Get TTJet correlations
            matrix_line = linecache.getline(
                "logs/01_%s_fit_%dTeV_%s.log" % (variable, CoM, fit_variables),
                line_number + number_of_lines_down + 2)
            weights["TTJet_QCD"] = matrix_line.split()[2]
            weights["TTJet_SingleTop"] = matrix_line.split()[3]
            weights["TTJet_TTJet"] = matrix_line.split()[4]
            weights["TTJet_V+Jets"] = matrix_line.split()[5]

            #Get V+Jets correlations
            matrix_line = linecache.getline(
                "logs/01_%s_fit_%dTeV_%s.log" % (variable, CoM, fit_variables),
                line_number + number_of_lines_down + 3)
            weights["V+Jets_QCD"] = matrix_line.split()[2]
            weights["V+Jets_SingleTop"] = matrix_line.split()[3]
            weights["V+Jets_TTJet"] = matrix_line.split()[4]
            weights["V+Jets_V+Jets"] = matrix_line.split()[5]

        if channel == 'muon':
            #formula to calculate the number of lines below "central" to access in each bin loop
            number_of_lines_down = (len(variable_bins_ROOT[variable]) * 12) + (
                variable_bins_ROOT[variable].index(variable_bin) * 12)

            #Get QCD correlations
            matrix_line = linecache.getline(
                "logs/01_%s_fit_%dTeV_%s.log" % (variable, CoM, fit_variables),
                line_number + number_of_lines_down)
            weights["QCD_QCD"] = matrix_line.split()[2]
            weights["QCD_SingleTop"] = matrix_line.split()[3]
            weights["QCD_TTJet"] = matrix_line.split()[4]
            weights["QCD_V+Jets"] = matrix_line.split()[5]

            #Get SingleTop correlations
            matrix_line = linecache.getline(
                "logs/01_%s_fit_%dTeV_%s.log" % (variable, CoM, fit_variables),
                line_number + number_of_lines_down + 1)
            weights["SingleTop_QCD"] = matrix_line.split()[2]
            weights["SingleTop_SingleTop"] = matrix_line.split()[3]
            weights["SingleTop_TTJet"] = matrix_line.split()[4]
            weights["SingleTop_V+Jets"] = matrix_line.split()[5]

            #Get TTJet correlations
            matrix_line = linecache.getline(
                "logs/01_%s_fit_%dTeV_%s.log" % (variable, CoM, fit_variables),
                line_number + number_of_lines_down + 2)
            weights["TTJet_QCD"] = matrix_line.split()[2]
            weights["TTJet_SingleTop"] = matrix_line.split()[3]
            weights["TTJet_TTJet"] = matrix_line.split()[4]
            weights["TTJet_V+Jets"] = matrix_line.split()[5]

            #Get V+Jets correlations
            matrix_line = linecache.getline(
                "logs/01_%s_fit_%dTeV_%s.log" % (variable, CoM, fit_variables),
                line_number + number_of_lines_down + 3)
            weights["V+Jets_QCD"] = matrix_line.split()[2]
            weights["V+Jets_SingleTop"] = matrix_line.split()[3]
            weights["V+Jets_TTJet"] = matrix_line.split()[4]
            weights["V+Jets_V+Jets"] = matrix_line.split()[5]

        #Create histogram
        histogram_properties = Histogram_properties()
        histogram_properties.title = title
        histogram_properties.name = 'Correlations_' + channel + '_' + variable + '_' + variable_bin
        histogram_properties.y_axis_title = y_title
        histogram_properties.x_axis_title = x_title
        histogram_properties.y_limits = y_limits
        histogram_properties.x_limits = x_limits
        histogram_properties.mc_error = 0.0
        histogram_properties.legend_location = 'upper right'

        #initialise 2D histogram
        a = Hist2D(4, 0, 4, 4, 0, 4)
        #fill histogram
        for i in range(len(parameters)):
            for j in range(len(parameters)):
                a.fill(
                    float(i), float(j),
                    float(weights["%s_%s" % (parameters[i], parameters[j])]))
        # create figure
        plt.figure(figsize=CMS.figsize, dpi=CMS.dpi, facecolor=CMS.facecolor)
        # make subplot(?)
        fig, ax = plt.subplots(nrows=1, ncols=1)
        rplt.hist2d(a)
        plt.subplots_adjust(right=0.8)

        #Set labels and formats for titles and axes
        plt.ylabel(histogram_properties.y_axis_title)
        plt.xlabel(histogram_properties.x_axis_title)
        plt.title(histogram_properties.title)
        x_limits = histogram_properties.x_limits
        y_limits = histogram_properties.y_limits
        ax.set_xticklabels(parameters_latex)
        ax.set_yticklabels(parameters_latex)
        ax.set_xticks([0.5, 1.5, 2.5, 3.5])
        ax.set_yticks([0.5, 1.5, 2.5, 3.5])
        plt.setp(ax.get_xticklabels(), visible=True)
        plt.setp(ax.get_yticklabels(), visible=True)

        #create and draw colour bar to the right of the main plot
        im = rplt.imshow(a, axes=ax, vmin=-1.0, vmax=1.0)
        #set location and dimensions (left, lower, width, height)
        cbar_ax = fig.add_axes([0.85, 0.10, 0.05, 0.8])
        fig.colorbar(im, cax=cbar_ax)

        for xpoint in range(len(parameters)):
            for ypoint in range(len(parameters)):
                correlation_value = weights["%s_%s" % (parameters[xpoint],
                                                       parameters[ypoint])]
                ax.annotate(correlation_value,
                            xy=(xpoint + 0.5, ypoint + 0.5),
                            ha='center',
                            va='center',
                            bbox=dict(fc='white', ec='none'))
        for save in save_as:
            plt.savefig(save_folder + histogram_properties.name + '.' + save)
        plt.close(fig)
    plt.close('all')
plot_with_plotting_script = True

if plot_with_plotting_script:
    properties = Histogram_properties()
    properties.name = "matplotlib_hist"
    properties.x_axis_title = "Mass"
    properties.y_axis_title = "Events"
    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, 0.0), ha="right")
    plt.ylabel("Events", position=(0.0, 1.0), va="bottom", ha="right")
    plt.legend(numpoints=1)