Beispiel #1
0
def computeDensity(input_file, tree, var, weight=None):
    branches = [var]
    if weight: branches.append(weight)
    data = root2array(input_file, tree, branches=branches)
    points = data.view((np.float64, len(data.dtype.names)))
    values = points[:, 0] if weight else points
    weights = points[:, 1] if weight else None
    print values, weights
    sumofweights = weights.sum() if weight else len(values)
    histo = Hist(25, 0, 250, type='F')
    histo.fill_array(values, weights=weights)
    fft = False if weight else True
    kde = ROOT.TKDE(len(values), array('d', values),
                    array('d', weights))  #, 0, 0, 'Binning:Unbinned')
    graph = kde.GetGraphWithErrors(500)
    for p in xrange(graph.GetN()):
        graph.SetPoint(
            p,
            graph.GetX()[p],
            graph.GetY()[p] * sumofweights * float(len(points)) / len(values))
        graph.SetPointError(
            p,
            graph.GetEX()[p],
            graph.GetEY()[p] * sumofweights * float(len(points)) / len(values))
    #graph.Scale(sumofweights*float(len(points))/len(values))
    #kde = sm.nonparametric.KDEUnivariate(values)
    #kde.fit(kernel='gau', bw='normal_reference', fft=fft, weights=weights)
    #graph = ROOT.TGraph(len(kde.support), kde.support, kde.density*sumofweights*float(len(points))/len(values))

    #histo.Scale(1./histo.integral(overflow=True))
    histo.Scale(float(len(points)) / len(values))
    histo.Scale(1, 'width')
    #graph = ROOT.TGraph(histo)
    return graph, histo
Beispiel #2
0
    def create_rootpy_hist(self,
                           vals=None,
                           bins=None,
                           hist=None,
                           norm=None,
                           upperCut=False,
                           htype=''):
        '''
		htype = VALS, ROOT or ROOTPY
		'''
        if htype == "VALS":
            h_rtpy = Hist(bins)
            for v in vals:
                h_rtpy.Fill(v)
        elif htype == "ROOTPY":
            h_rtpy = hist
        elif htype == "ROOT":
            h_rtpy = asrootpy(hist)
        else:
            print "Please provide some histograms..."
            return None

        if upperCut:
            h_rtpy = self.apply_max_cutoff(h_rtpy)
        if norm:
            h_rtpy.Scale(norm)
        return h_rtpy
Beispiel #3
0
def getDataFromFile():
    dataTemplate = inputTemplates[variable]['data'][whichBinFromFile]
    h_data = Hist(nBins, 0, nBins, title='data')
    for bin in range(1, nBins + 1):
        h_data.SetBinContent(bin, dataTemplate[bin - 1])
        pass
    h_data.Scale(absolute_eta_initialValues['data'][whichBinFromFile][0])
    return h_data
def FakeEff(in_mean, in_sigma):
    in_func = F1("TMath::Gaus(x,{},{},true)".format(in_mean, in_sigma), 0, 100)
    resolution = Hist(50, 0, 100)
    n_events = 20000000
    resolution.FillRandom(in_func.name, n_events)
    resolution.Scale(1. / n_events)
    hist = resolution.GetCumulative()
    return hist
Beispiel #5
0
 def computeHisto(self, name, bins):
     if not name in self.data or not 'Data' in self.data[name]:
         raise StandardError(
             'Cannot find data for {NAME}'.format(NAME=name))
     values = self.data[name]['Data'][0]
     weights = self.data[name]['Data'][1]
     histo = Hist(bins, type='F')
     histo.Sumw2()
     histo.fill_array(values, weights=weights)
     histo.Scale(1, 'width')
     #self.data[name]['Histo'] = histo
     self.data[name]['Histo_' + str(hash(str(bins)))] = histo
Beispiel #6
0
def getDataFromFile(variable, whichBinFromFile):
    dataTemplate = inputTemplates[variable]['data'][whichBinFromFile]
    nBins = len(inputTemplates[variable]['data'][whichBinFromFile])
    h_data = Hist(nBins, 0, nBins, title='data')
    for bin in range(1, nBins + 1):
        h_data.SetBinContent(bin, dataTemplate[bin - 1])
        pass
    h_data.Scale(absolute_eta_initialValues['data'][whichBinFromFile][0])
    h_data.Sumw2()
    for bin in range(1, nBins + 1):
        h_data.SetBinError(bin, sqrt(h_data.GetBinContent(bin)))
        pass
    return h_data
def makeDiscr(discr_dict,
              outfile,
              xtitle="discriminator",
              nbins=30,
              x_min=0,
              x_max=1):
    c = ROOT.TCanvas("c", "c", 800, 500)
    ROOT.gStyle.SetOptStat(0)
    ROOT.gPad.SetMargin(0.15, 0.1, 0.2, 0.1)
    #ROOT.gPad.SetLogy(1)
    #ROOT.gPad.SetGrid(1,1)
    ROOT.gStyle.SetGridColor(17)
    l = TLegend(0.17, 0.75, 0.88, 0.88)
    l.SetTextSize(0.055)
    l.SetBorderSize(0)
    l.SetFillStyle(0)
    l.SetNColumns(2)

    colors = [2, 4, 8, ROOT.kCyan + 2]
    counter = 0
    for leg, discr in discr_dict.iteritems():
        a = Hist(nbins, x_min, x_max)
        #fill_hist_with_ndarray(a, discr)
        a.fill_array(discr)
        a.SetLineColor(colors[counter])
        a.SetLineWidth(2)
        a.GetXaxis().SetTitle(xtitle)
        a.GetXaxis().SetLabelSize(0.05)
        a.GetXaxis().SetTitleSize(0.05)
        a.GetXaxis().SetTitleOffset(1.45)
        a.GetYaxis().SetTitle("a.u.")
        a.GetYaxis().SetTickSize(0)
        a.GetYaxis().SetLabelSize(0)
        a.GetYaxis().SetTitleSize(0.06)
        a.GetYaxis().SetTitleOffset(0.9)
        a.Scale(1. / a.Integral())
        #a.GetYaxis().SetRangeUser(0.00001,100)
        a.GetYaxis().SetRangeUser(0, 0.2)
        if counter == 0: a.draw("hist")
        else: a.draw("same hist")
        l.AddEntry(a, leg, "l")
        counter += 1

    l.Draw("same")
    c.SaveAs(outfile)
Beispiel #8
0
def get_bias_corr(region):
    if region == "ms":
        bkg_bias_fname = "/lustre/cmswork/dcastrom/projects/hh/april_2017/CMSSW_8_0_25/src/Analysis/hh2bbbb_limit/notebooks/bias_22032018_with_weights_also_mass_cut/BM0/bias_correction_mass_cut_bigset_unscaled.json"
        bkg_bias_fname = "/lustre/cmswork/dcastrom/projects/hh/april_2017/CMSSW_8_0_25/src/Analysis/hh2bbbb_limit/bias_01062018BM0/bias_correction_mass_cut_bigset_unscaled.json"
    elif region == "btag":
        bkg_bias_fname = "/lustre/cmswork/dcastrom/projects/hh/april_2017/CMSSW_8_0_25/src/Analysis/hh2bbbb_limit/notebooks/bms_btagside_err_fixed/BM0/bias_correction_bigset_unscaled.json"
    elif region == "sig_unfixed":
        bkg_bias_fname = "/lustre/cmswork/dcastrom/projects/hh/april_2017/CMSSW_8_0_25/src/Analysis/hh2bbbb_limit/notebooks/bias_22032018_with_weights_also_mass_cut/BM0/bias_correction_bigset_unscaled.json"
    else:
        bkg_bias_fname = "/lustre/cmswork/dcastrom/projects/hh/april_2017/CMSSW_8_0_25/src/Analysis/hh2bbbb_limit/bias_01062018BM0/bias_correction_bigset_unscaled.json"

    with open(bkg_bias_fname, "r") as bkg_bias_file:
        json_dict = json.load(bkg_bias_file)
        print("using bias file: ", bkg_bias_file)

    histo = Hist(json_dict['bin_edges'])
    print histo

    #hcorr = histo.Clone("h_bias_corrected")
    #hcorr.Scale(4)
    #hbias = histo.Clone("h_bias")
    for n in range(len(json_dict['bias_corr'])):
        bias = json_dict['bias_corr'][n]
        var = json_dict['var'][n]
        bias_unc = json_dict['bias_corr_unc_bs'][n]
        bias_unc_stat = json_dict['bias_corr_unc_stat'][n]

        #bkg_pred_initial = hcorr.GetBinContent(n+1)
        #if var > np.sqrt(bkg_pred_initial):
        new_bkg_pred_stat = var
        #else:
        #  new_bkg_pred_stat = np.sqrt(bkg_pred_initial)

        #new_bkg_pred_tot_unc = np.sqrt(new_bkg_pred_stat**2 + bias_unc**2 + bias_unc_stat**2)
        new_bkg_pred_tot_unc = np.sqrt(bias_unc**2 + bias_unc_stat**2)

        histo.SetBinContent(n + 1, bias)
        histo.SetBinError(n + 1, new_bkg_pred_tot_unc)

    histo.Scale(0.25)
    #hcorr.Add(hbias, -1)
    return histo
Beispiel #9
0
def plot_pTs(pT_lower_cut=100, pT_upper_cut=10000):

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    # Legends Begin.

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

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

    # Legends End.

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

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

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

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

    ax0.set_yscale('log')

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

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

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

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

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

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

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

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

    plt.savefig("plots/Version 5/pT/data_pT_data_lower_" + str(pT_lower_cut) +
                "_pT_upper_" + str(pT_upper_cut) + ".pdf")
    # plt.show()
    plt.clf()
Beispiel #10
0
if os.path.exists(sPathToFile):
    a_acceptance_fraction = pickle.load(open(sPathToFile, 'r'))
    print 'Successfully loaded acceptance fraction array!'
    #a_acor = pickle.load(open(sPathToFile_autocorrelation, 'r'))
else:
    print sPathToFile
    print 'Could not find file!'
    sys.exit()

#print a_acor

c_acceptance = Canvas()
h_acceptance = Hist(100,
                    0,
                    1,
                    name='h_acceptance',
                    title='Acceptance Fraction of Most Recent Sampler')
h_acceptance.fill_array(a_acceptance_fraction)
h_acceptance.Scale(1. / h_acceptance.Integral())
#h_acceptance.SetStats(0)
h_acceptance.Draw()
c_acceptance.Update()

raw_input('Press enter to continue...')

plot_name = '%s_acceptance_fraction' % (dir_specifier_name)
plot_name = 'yields_fit_%s' % (plot_name)

neriX_analysis.save_plot(l_plots, c_acceptance, plot_name)
def do_analysis(chain, analyze_this, outfile, eventtype):

    # get trees from files
    #t = f.Get("Delphes")

    # get number of entries
    nentries = chain.GetEntries()

    # initialize everything here before filling histograms

    if (analyze_this['Jet.PT']):
        print "\nInitializing Jet.PT...\n"

        # create the histograms
        numJets = Hist(NBINS,
                       NLO,
                       NHI,
                       title='numJets ' + eventtype,
                       legendstyle='L')

        # interesting values to plot
        max_jetpt_per_event = Hist(PT_NBINS,
                                   PT_NLO,
                                   PT_NHI,
                                   title='Max JetPT/Event ' + eventtype,
                                   legendstyle='L')
        min_jetpt_per_event = Hist(PT_NBINS,
                                   PT_NLO,
                                   PT_NHI,
                                   title='Min JetPT/Event ' + eventtype,
                                   legendstyle='L')

    else:
        print "Skipped Jet.PT"

    if (analyze_this['Jet.BTag']):
        print "Initializing Jet.BTag...\n"

        # create the histograms
        loose = Hist(NBINS,
                     NLO,
                     NHI,
                     title='loose ' + eventtype,
                     legendstyle='L')
        medium = Hist(NBINS,
                      NLO,
                      NHI,
                      title='medium ' + eventtype,
                      legendstyle='L')
        tight = Hist(NBINS,
                     NLO,
                     NHI,
                     title='tight ' + eventtype,
                     legendstyle='L')

    else:
        print "Skipped Jet.BTag"

    if (analyze_this['Electron.PT']):
        print "Initializing Electron.PT...\n"

        # create the histograms
        numElectrons = Hist(NBINS,
                            NLO,
                            NHI,
                            title='numElectrons ' + eventtype,
                            legendstyle='L')

        # interesting values to plot
        max_ept_per_event = Hist(PT_NBINS,
                                 PT_NLO,
                                 PT_NHI,
                                 title='Max ElectronPT/Event ' + eventtype,
                                 legendstyle='L')
        min_ept_per_event = Hist(PT_NBINS,
                                 PT_NLO,
                                 PT_NHI,
                                 title='Min ElectronPT/Event ' + eventtype,
                                 legendstyle='L')

        # initialize any variable-specific constants here:

        # counter for no electrons
        noeleaf = 0

    else:
        print "Skipped Electron.PT"

    if (analyze_this['MuonTight.PT']):
        print "Initializing MuonTight.PT...\n"

        # create the histograms
        numMuons = Hist(NBINS,
                        NLO,
                        NHI,
                        title='numMuons ' + eventtype,
                        legendstyle='L')

        # interesting values to plot
        max_upt_per_event = Hist(PT_NBINS,
                                 PT_NLO,
                                 PT_NHI,
                                 title='Max MuonPT/Event ' + eventtype,
                                 legendstyle='L')
        min_upt_per_event = Hist(PT_NBINS,
                                 PT_NLO,
                                 PT_NHI,
                                 title='Min MuonPT/Event ' + eventtype,
                                 legendstyle='L')

        # initialize any variable-specific constants here:

        # counter for no electrons
        nouleaf = 0

    else:
        print "Skipped MuonTight.PT"

    if (analyze_this['MissingET.MET']):
        print "Initializing MissingET.MET...\n"

        # create the histograms
        MET = Hist(MET_NBINS,
                   MET_NLO,
                   MET_NHI,
                   title='MET ' + eventtype,
                   legendstyle='L')

    else:
        print "Skipped MissingET.MET"

    if (analyze_this['MT (NON-LEAF)']):
        print "Initializing MT...\n"

        # create the histograms
        MT = Hist(MT_NBINS,
                  MT_NLO,
                  MT_NHI,
                  title='MT ' + eventtype,
                  legendstyle='L')

    else:
        print "Skipped HT"

    if (analyze_this['HT (NON-LEAF)']):
        print "Initializing HT...\n"

        # create the histograms
        HT = Hist(HT_NBINS,
                  HT_NLO,
                  HT_NHI,
                  title='HT ' + eventtype,
                  legendstyle='L')

    else:
        print "Skipped HT"

    if (analyze_this['DELTA PHI (NON-LEAF)']):
        print "Initializing Delta Phi...\n"

        # create the histograms
        DPHI_metlep = Hist(30,
                           -1 * np.pi,
                           np.pi,
                           title='Delta Phi (MET-lep) ' + eventtype,
                           legendstyle='L')

        DPHI_metjet = Hist(30,
                           -1 * np.pi,
                           np.pi,
                           title='Delta Phi (MET-jet)' + eventtype,
                           legendstyle='L')

    else:
        print "Skipped DELTA PHI"

    if (analyze_this['DELTA R (NON-LEAF)']):
        print "Initializing Delta R...\n"

        #create histograms
        DR = Hist(50,
                  0,
                  2 * np.pi,
                  title='DELTA R ' + eventtype,
                  legendstyle='L')
    else:
        print "Skipped DELTA R"

    # Now fill histograms

    print "\nFilling histograms...\n"

    # get float version of num entries to normalize below; subtract 1 to get
    # actual integral value of hist
    norm = float(nentries - 1)

    for e in range(nentries):

        entry = chain.GetEntry(e)

        # to check whether each entry is electron or muon
        is_electron = False
        is_muon = False

        e_maxpt = 0
        e_maxpt_phi = 0

        u_maxpt = 0
        u_maxpt_phi = 0

        jet_maxpt = 0
        jet_maxpt_phi = 0
        jet_maxpt_eta = 0

        met = 0
        met_phi = 0
        met_eta = 0

        lepton_vec = []

        if (analyze_this['Electron.PT']):

            # define leaves
            var = "Electron.PT"

            leaf = chain.GetLeaf(var)
            phileaf = chain.GetLeaf('Electron.Phi')
            etaleaf = chain.GetLeaf('Electron.Eta')

            # returns phi of max pt for entry
            (e_maxpt, e_maxpt_phi, e_maxpt_eta) = fill_Electron_hist(
                chain, leaf, entry, numElectrons, min_ept_per_event,
                max_ept_per_event, phileaf, etaleaf, lepton_vec)

            #print lepton_vec

            if (leaf.GetLen() == 0):
                noeleaf += 1
                e_maxpt = INVALID
                e_maxpt_phi = INVALID
                e_maxpt_eta = INVALID
            else:
                is_electron = True

        if (analyze_this['MuonTight.PT']):

            # define leaves
            var = "MuonTight.PT"

            leaf = chain.GetLeaf(var)
            phileaf = chain.GetLeaf('MuonTight.Phi')
            etaleaf = chain.GetLeaf('MuonTight.Eta')

            (u_maxpt, u_maxpt_phi, u_maxpt_eta) = fill_Muon_hist(
                chain, leaf, entry, numMuons, min_upt_per_event,
                max_upt_per_event, phileaf, etaleaf, lepton_vec)

            if leaf.GetLen() == 0:
                nouleaf += 1
                u_maxpt = INVALID
                u_maxpt_phi = INVALID
                u_maxpt_eta = INVALID
            else:
                is_muon = True

        # Get preferred lepton for future calcs
        if e_maxpt >= u_maxpt:
            lpt = e_maxpt
            lphi = e_maxpt_phi
            leta = e_maxpt_eta
        else:
            lpt = u_maxpt
            lphi = u_maxpt_phi
            leta = u_maxpt_eta

        if (analyze_this['Jet.PT']):

            # define leaves
            var = 'Jet.PT'

            leaf = chain.GetLeaf(var)
            phileaf = chain.GetLeaf('Jet.Phi')
            etaleaf = chain.GetLeaf('Jet.Eta')

            # analyze with Jet.PT because HT is sum of Jet.PTs
            if (analyze_this['HT (NON-LEAF)']):
                HTfill = True
            else:
                HTfill = False

            # returns phi of max pt for entry
            (jet_maxpt, jet_maxpt_phi, jet_maxpt_eta) = fill_JetPT_hist(
                chain, leaf, entry, numJets, min_jetpt_per_event,
                max_jetpt_per_event, HTfill, HT, phileaf, etaleaf, lepton_vec)

            if (leaf.GetLen() == 0):
                jet_maxpt = INVALID
                jet_maxpt_phi = INVALID
                jet_maxpt_eta = INVALID

        if (analyze_this['Jet.BTag']):

            # define leaves
            var = "Jet.BTag"

            leaf = chain.GetLeaf(var)

            fill_JetBTag_hist(chain, leaf, entry, loose, medium, tight)

        if (analyze_this['MissingET.MET']):

            # define leaves
            var = "MissingET.MET"

            leaf = chain.GetLeaf(var)
            phileaf = chain.GetLeaf('MissingET.Phi')
            etaleaf = chain.GetLeaf('MissingET.Eta')

            (met, metphi, meteta) = fill_MET_hist(chain, leaf, entry, MET,
                                                  phileaf, etaleaf)

        if (analyze_this['MT (NON-LEAF)']):
            #print "ok got here"
            #print "here ",e_maxpt, e_maxpt_phi, u_maxpt, u_maxpt_phi, met, metphi

            if (not (is_muon or is_electron)):
                mt_val = 0
            else:
                #print e_maxpt, e_maxpt_phi, u_maxpt, u_maxpt_phi, met, metphi
                #print is_electron, is_muon
                mt_val = get_mt(lpt, lphi, met, metphi)

            if mt_val == 0:
                MT.Fill(INVALID)
            else:
                MT.Fill(mt_val)

        if (analyze_this['DELTA PHI (NON-LEAF)']):

            dphi_metlep_val = delta_phi(metphi, lphi)
            dphi_metjet_val = delta_phi(metphi, jet_maxpt_phi)

            DPHI_metlep.Fill(dphi_metlep_val)
            DPHI_metjet.Fill(dphi_metjet_val)

        if (analyze_this['DELTA R (NON-LEAF)']):

            dr_val = delta_R(jet_maxpt_phi, lphi, jet_maxpt_eta, leta)

            if dr_val == 0:
                dr_val = INVALID

            #elif dr_val > 3.0 and dr_val < 3.3:
            #print jet_maxpt_phi, lphi, jet_maxpt_eta, leta

            DR.Fill(dr_val)

    if (analyze_this['Jet.PT']):

        # normalize
        numJets.Scale(1 / (numJets.Integral()))
        max_jetpt_per_event.Scale(1 / (max_jetpt_per_event.Integral()))
        min_jetpt_per_event.Scale(1 / (min_jetpt_per_event.Integral()))

    if (analyze_this['Jet.BTag']):

        # normalize
        tight.Scale(1 / (tight.Integral()))
        medium.Scale(1 / (medium.Integral()))
        loose.Scale(1 / (loose.Integral()))

    if (analyze_this['Electron.PT']):

        # normalize
        numElectrons.Scale(1 / (numElectrons.Integral()))
        max_ept_per_event.Scale(1 / (max_ept_per_event.Integral()))
        min_ept_per_event.Scale(1 / (min_ept_per_event.Integral()))

        print "\nentries: " + str(nentries) + " noeleaf number: " + str(
            noeleaf)

    if (analyze_this['MuonTight.PT']):

        # normalize
        numMuons.Scale(1 / (numMuons.Integral()))
        max_upt_per_event.Scale(1 / (max_upt_per_event.Integral()))
        min_upt_per_event.Scale(1 / (min_upt_per_event.Integral()))

        print "\nentries: " + str(nentries) + " nouleaf number: " + str(
            nouleaf)

    if (analyze_this['MissingET.MET']):

        # normalize
        MET.Scale(1 / (MET.Integral()))

    if (analyze_this['MT (NON-LEAF)']):

        #normalize
        MT.Scale(1 / (MT.Integral()))

    if (analyze_this['HT (NON-LEAF)']):

        #normalize
        HT.Scale(1 / (HT.Integral()))

    if (analyze_this['DELTA PHI (NON-LEAF)']):

        #normalize
        DPHI_metlep.Scale(1 / (DPHI_metlep.Integral()))
        DPHI_metjet.Scale(1 / (DPHI_metjet.Integral()))

    if (analyze_this['DELTA R (NON-LEAF)']):

        #normalize
        DR.Scale(1 / (DR.Integral()))

    print ""
    print "\nDone!\n"

    numJets.Write(eventtype + "numJets")
    max_jetpt_per_event.Write(eventtype + "max_jetpt_per_event")
    min_jetpt_per_event.Write(eventtype + "min_jetpt_per_event")

    loose.Write(eventtype + "loose")
    medium.Write(eventtype + "medium")
    tight.Write(eventtype + "tight")

    numElectrons.Write(eventtype + "numElectrons")
    max_ept_per_event.Write(eventtype + "max_ept_per_event")
    min_ept_per_event.Write(eventtype + "min_ept_per_event")

    numMuons.Write(eventtype + "numMuons")
    max_upt_per_event.Write(eventtype + "max_upt_per_event")
    min_upt_per_event.Write(eventtype + "min_upt_per_event")

    MET.Write(eventtype + "MET")

    MT.Write(eventtype + "MT")

    HT.Write(eventtype + "HT")

    DPHI_metlep.Write(eventtype + "dphi_metlep")
    DPHI_metjet.Write(eventtype + "dphi_metjet")

    DR.Write(eventtype + "deltaR")
def do_analysis(f, eventtype, analyze_this, outfile):

    # get trees from files
    t = f.Get("Delphes")

    # get number of entries
    nentries = t.GetEntries()

    # initialize everything here before filling histograms

    if (analyze_this['Jet.PT']):
        print "\nInitializing Jet.PT...\n"

        # create the histograms
        numJets = Hist(NBINS,
                       NLO,
                       NHI,
                       title='numJets ' + eventtype,
                       legendstyle='L')

        # interesting values to plot
        max_jetpt_per_event = Hist(PT_NBINS,
                                   PT_NLO,
                                   PT_NHI,
                                   title='Max JetPT/Event ' + eventtype,
                                   legendstyle='L')
        min_jetpt_per_event = Hist(PT_NBINS,
                                   PT_NLO,
                                   PT_NHI,
                                   title='Min JetPT/Event ' + eventtype,
                                   legendstyle='L')

    else:
        print "Skipped Jet.PT"

    if (analyze_this['Jet.BTag']):
        print "Initializing Jet.BTag...\n"

        # create the histograms
        loose = Hist(NBINS,
                     NLO,
                     NHI,
                     title='loose ' + eventtype,
                     legendstyle='L')
        medium = Hist(NBINS,
                      NLO,
                      NHI,
                      title='medium ' + eventtype,
                      legendstyle='L')
        tight = Hist(NBINS,
                     NLO,
                     NHI,
                     title='tight ' + eventtype,
                     legendstyle='L')

    else:
        print "Skipped Jet.BTag"

    if (analyze_this['Electron.PT']):
        print "Initializing Electron.PT...\n"

        # create the histograms
        numElectrons = Hist(NBINS,
                            NLO,
                            NHI,
                            title='numElectrons ' + eventtype,
                            legendstyle='L')

        # interesting values to plot
        max_ept_per_event = Hist(PT_NBINS,
                                 PT_NLO,
                                 PT_NHI,
                                 title='Max ElectronPT/Event ' + eventtype,
                                 legendstyle='L')
        min_ept_per_event = Hist(PT_NBINS,
                                 PT_NLO,
                                 PT_NHI,
                                 title='Min ElectronPT/Event ' + eventtype,
                                 legendstyle='L')

        # initialize any variable-specific constants here:

        # counter for no electrons
        noeleaf = 0

    else:
        print "Skipped Electron.PT"

    if (analyze_this['MuonTight.PT']):
        print "Initializing MuonTight.PT...\n"

        # create the histograms
        numMuons = Hist(NBINS,
                        NLO,
                        NHI,
                        title='numMuons ' + eventtype,
                        legendstyle='L')

        # interesting values to plot
        max_upt_per_event = Hist(PT_NBINS,
                                 PT_NLO,
                                 PT_NHI,
                                 title='Max MuonPT/Event ' + eventtype,
                                 legendstyle='L')
        min_upt_per_event = Hist(PT_NBINS,
                                 PT_NLO,
                                 PT_NHI,
                                 title='Min MuonPT/Event ' + eventtype,
                                 legendstyle='L')

        # initialize any variable-specific constants here:

        # counter for no electrons
        nouleaf = 0

    else:
        print "Skipped MuonTight.PT"

    if (analyze_this['MissingET.MET']):
        print "Initializing MissingET.MET...\n"

        # create the histograms
        MET = Hist(MET_NBINS,
                   MET_NLO,
                   MET_NHI,
                   title='MET ' + eventtype,
                   legendstyle='L')

    else:
        print "Skipped MissingET.MET"

    if (analyze_this['MT (NON-LEAF)']):
        print "Initializing MT...\n"

        # create the histograms
        MT = Hist(MT_NBINS,
                  MT_NLO,
                  MT_NHI,
                  title='MT ' + eventtype,
                  legendstyle='L')

    else:
        print "Skipped HT"

    if (analyze_this['HT (NON-LEAF)']):
        print "Initializing HT...\n"

        # create the histograms
        HT = Hist(HT_NBINS,
                  HT_NLO,
                  HT_NHI,
                  title='HT ' + eventtype,
                  legendstyle='L')

    else:
        print "Skipped HT"

    # Now fill histograms

    print "\nFilling histograms...\n"

    # get float version of num entries to normalize below; subtract 1 to get
    # actual integral value of hist
    norm = float(nentries - 1)

    for e in range(nentries):

        entry = t.GetEntry(e)

        # to check whether each entry is electron or muon
        is_electron = False
        is_muon = False

        e_maxpt = 0
        e_maxpt_phi = 0

        u_maxpt = 0
        u_maxpt_phi = 0

        if (analyze_this['Jet.PT']):

            # define leaves
            var = 'Jet.PT'

            leaf = t.GetLeaf(var)

            # analyze with Jet.PT because HT is sum of Jet.PTs
            if (analyze_this['HT (NON-LEAF)']):
                HTfill = True
            else:
                HTfill = False

            fill_JetPT_hist(t, leaf, entry, numJets, min_jetpt_per_event,
                            max_jetpt_per_event, HTfill, HT)

        if (analyze_this['Jet.BTag']):

            # define leaves
            var = "Jet.BTag"

            leaf = t.GetLeaf(var)

            fill_JetBTag_hist(t, leaf, entry, loose, medium, tight)

        if (analyze_this['Electron.PT']):

            # define leaves
            var = "Electron.PT"

            leaf = t.GetLeaf(var)
            phileaf = t.GetLeaf('Electron.Phi')

            # returns phi of max pt for entry
            (e_maxpt,
             e_maxpt_phi) = fill_Electron_hist(t, leaf, entry, numElectrons,
                                               min_ept_per_event,
                                               max_ept_per_event, phileaf)

            if (leaf.GetLen() == 0):
                noeleaf += 1
                e_maxpt = 0
                e_maxpt_phi = 0
            else:
                is_electron = True

        if (analyze_this['MuonTight.PT']):

            # define leaves
            var = "MuonTight.PT"

            leaf = t.GetLeaf(var)
            phileaf = t.GetLeaf('MuonTight.Phi')

            (u_maxpt, u_maxpt_phi) = fill_Muon_hist(t, leaf, entry, numMuons,
                                                    min_upt_per_event,
                                                    max_upt_per_event, phileaf)

            if leaf.GetLen() == 0:
                nouleaf += 1
                u_maxpt = 0
                u_maxpt_phi = 0
            else:
                is_muon = True

        if (analyze_this['MissingET.MET']):

            # define leaves
            var = "MissingET.MET"

            leaf = t.GetLeaf(var)
            phileaf = t.GetLeaf('MissingET.Phi')

            (met, metphi) = fill_MET_hist(t, leaf, entry, MET, phileaf)

        if (analyze_this['MT (NON-LEAF)']):
            #print "ok got here"
            #print "here ",e_maxpt, e_maxpt_phi, u_maxpt, u_maxpt_phi, met, metphi

            mt_val = get_mt(e_maxpt, e_maxpt_phi, u_maxpt, u_maxpt_phi, met,
                            metphi)
            if mt_val == 0:
                MT.Fill(INVALID)
            else:
                MT.Fill(mt_val)

            #print mt_val

    if (analyze_this['Jet.PT']):

        # normalize
        numJets.Scale(1 / norm)
        max_jetpt_per_event.Scale(1 / norm)
        min_jetpt_per_event.Scale(1 / norm)

    if (analyze_this['Jet.BTag']):

        # normalize
        tight.Scale(1 / norm)
        medium.Scale(1 / norm)
        loose.Scale(1 / norm)

    if (analyze_this['Electron.PT']):

        # normalize
        numElectrons.Scale(1 / norm)
        max_ept_per_event.Scale(1 / norm)
        min_ept_per_event.Scale(1 / norm)

        print "\nentries: " + str(nentries) + " noeleaf number: " + str(
            noeleaf)

    if (analyze_this['MuonTight.PT']):

        # normalize
        numMuons.Scale(1 / norm)
        max_upt_per_event.Scale(1 / norm)
        min_upt_per_event.Scale(1 / norm)

        print "\nentries: " + str(nentries) + " nouleaf number: " + str(
            nouleaf)

    if (analyze_this['MissingET.MET']):

        # normalize
        MET.Scale(1 / norm)

    if (analyze_this['MT (NON-LEAF)']):

        #normalize
        MT.Scale(1 / norm)

    if (analyze_this['HT (NON-LEAF)']):

        #normalize
        HT.Scale(1 / norm)

    print ""
    print "\nDone!\n"

    numJets.Write(eventtype + "numJets")
    max_jetpt_per_event.Write(eventtype + "max_jetpt_per_event")
    min_jetpt_per_event.Write(eventtype + "min_jetpt_per_event")

    loose.Write(eventtype + "loose")
    medium.Write(eventtype + "medium")
    tight.Write(eventtype + "tight")

    numElectrons.Write(eventtype + "numElectrons")
    max_ept_per_event.Write(eventtype + "max_ept_per_event")
    min_ept_per_event.Write(eventtype + "min_ept_per_event")

    numMuons.Write(eventtype + "numMuons")
    max_upt_per_event.Write(eventtype + "max_upt_per_event")
    min_upt_per_event.Write(eventtype + "min_upt_per_event")

    MET.Write(eventtype + "MET")

    MT.Write(eventtype + "MT")

    HT.Write(eventtype + "HT")
    def __return_histogram(self,
                           d_hist_info,
                           ignoreUnderflow=True,
                           useQCDControl=False,
                           useQCDSystematicControl=False):
        '''
        Takes basic histogram info and returns histo.
        Maybe this can move to ROOT_utilities?
        '''
        from rootpy.io.file import File
        from rootpy.plotting import Hist
        from dps.utils.hist_utilities import fix_overflow

        f = d_hist_info['input_file']
        tree = d_hist_info['tree']
        qcd_tree = d_hist_info["qcd_control_region"]
        qcd_tree_for_normalisation = d_hist_info["qcd_normalisation_region"]
        var = d_hist_info['branch']
        bins = d_hist_info['bin_edges']
        lumi_scale = d_hist_info['lumi_scale']
        scale = d_hist_info['scale']
        weights = d_hist_info['weight_branches']
        selection = d_hist_info['selection']

        if useQCDControl:
            # replace SR tree with CR tree
            if useQCDSystematicControl:
                tree = qcd_tree_for_normalisation
            else:
                tree = qcd_tree
            # Remove the Lepton reweighting for the datadriven qcd (SF not derived for unisolated leptons)
            for weight in weights:
                if 'Electron' in weight: weights.remove(weight)
                elif 'Muon' in weight: weights.remove(weight)

        weights = "*".join(weights)
        # Selection will return a weight 0 or 1 depending on whether event passes selection
        weights_and_selection = '( {0} ) * ( {1} )'.format(weights, selection)

        scale *= lumi_scale

        root_file = File(f)
        root_tree = root_file.Get(tree)

        root_histogram = Hist(bins)
        # Draw histogram of var for selection into root_histogram
        root_tree.Draw(var,
                       selection=weights_and_selection,
                       hist=root_histogram)
        root_histogram.Scale(scale)

        # When a tree is filled with a dummy variable, it will end up in the underflow, so ignore it
        if ignoreUnderflow:
            root_histogram.SetBinContent(0, 0)
            root_histogram.SetBinError(0, 0)

        # Fix overflow (Moves entries from overflow bin into last bin i.e. last bin not |..| but |--> )
        root_histogram = fix_overflow(root_histogram)

        root_file.Close()
        return root_histogram
Beispiel #14
0
def plot_cmssw_charge_occupancy_variations(REGION, useFullDist=True):
    '''
	Data highOcc vs SCD vs SCD Po(N)
	'''
    make_folder_if_not_exists('plots/InputChargePoissonMatching/')
    OCC = REGION_DETAILS[REGION]['Occ_Data']

    hs_to_plot = []
    rs_to_plot = []
    occupancies_to_test = []
    colors = ['blue', 'red', 'darkgreen', 'magenta']

    if useFullDist:
        f_hist = 'input/landau_scd_290118_orig.root'
        occupancies_to_test = [OCC * 10, OCC * 20, OCC * 50, OCC * 100]
    else:
        f_hist = 'input/landau_scd_290118_cut.root'
        occupancies_to_test = [OCC * 5, OCC * 10, OCC * 20, OCC * 50]

    with root_open(f_hist) as f:
        h = asrootpy(f.Get(REGION).Clone())
        h.SetDirectory(0)
        l_edges = list(h.xedges())

    # with root_open('input/landau_lowPUTracks_290118_orig.root') as f:
    # 	h_data_PU0 = asrootpy(f.Get(REGION).Clone())
    # 	h_data_PU0.SetDirectory(0)
    # 	h_data_PU0.Scale(1 /h_data_PU0.integral(xbin1=21,xbin2=200))
    # 	hs_to_plot.append({
    # 		'hist'		: h_data_PU0,
    # 		'label' 	: 'lowPU Strips from Tracks',
    # 		# 'color'		: '0.5',
    # 		'color'		: 'grey',
    # 		'type' 		: 'Data'
    # 	})

    # with root_open('input/landau_lowPUClusters_290118_orig.root') as f:
    # 	h_data_lowOcc = asrootpy(f.Get(REGION).Clone())
    # 	h_data_lowOcc.SetDirectory(0)
    # 	h_data_lowOcc.Scale(1 /h_data_lowOcc.integral(xbin1=21,xbin2=200))
    # 	hs_to_plot.append({
    # 		'hist'		: h_data_lowOcc,
    # 		'label' 	: 'lowOcc Strips from Clusters',
    # 		# 'color'		: '0',
    # 		'color'		: 'brown',
    # 		'type' 		: 'Data'
    # 	})

    with root_open(
            'input/landau_clusterData_010218_VFPFix_True_orig.root') as f:
        h_data_highOcc = asrootpy(f.Get(REGION).Clone())
        h_data_highOcc.SetDirectory(0)
        h_data_highOcc.Scale(1 / h_data_highOcc.integral(xbin1=21, xbin2=200))
        hs_to_plot.append({
            'hist': h_data_highOcc,
            'label': 'highOcc Strips from Clusters',
            # 'color'		: '0',
            'color': 'black',
            'type': 'Data'
        })

    hist_scd = Hist(l_edges)

    h_tests = []
    for occ, col in zip(occupancies_to_test, colors):
        h_tmp = {
            'occ': occ,
            'hist': Hist(l_edges),
            'color': col,
        }
        h_tests.append(h_tmp)

    i = 0
    while i < 250000:
        v = return_strip_charge_from_Poisson(h,
                                             OCC,
                                             add_noise=False,
                                             add_truncation=True)
        hist_scd.Fill(v)
        for h_test in h_tests:
            v_occ = return_strip_charge_from_Poisson(h,
                                                     h_test['occ'],
                                                     add_noise=False,
                                                     add_truncation=True,
                                                     cut_charge=True)
            if not v_occ < 10000: h_test['hist'].Fill(v_occ)
        i = i + 1

    # Normalising between 10000-100000
    hist_scd.Scale(1 / hist_scd.integral(xbin1=21, xbin2=200))
    for h_test in h_tests:
        h_test['hist'].Scale(1 / h_test['hist'].integral(xbin1=21, xbin2=200))

    scd = ''
    if useFullDist:
        scd = 'SCD'
    else:
        scd = 'Cut SCD'

    r_scd = h_data_highOcc.Clone()
    r_scd.SetDirectory(0)
    r_scd.Divide(hist_scd)
    hs_to_plot.append({
        'hist':
        hist_scd,
        'label':
        '{SCD} sampled Po({OCC})'.format(SCD=scd, OCC=OCC),
        'color':
        'black',
        'type':
        'SCD'
    })
    rs_to_plot.append({
        'hist': r_scd,
        'label': '',
        'color': 'black',
        'type': 'Ratio'
    })
    for h_test in h_tests:
        r = h_data_highOcc.Clone()
        r.SetDirectory(0)
        r.Divide(h_test['hist'])
        hs_to_plot.append({
            'hist':
            h_test['hist'],
            'label':
            '{SCD} sampled Po({OCC})'.format(SCD=scd, OCC=h_test['occ']),
            'color':
            h_test['color'],
            'line':
            'solid',
            'type':
            'CMSSW'
        })
        rs_to_plot.append({
            'hist': r,
            'label': '',
            'color': h_test['color'],
            'type': 'Ratio'
        })

    fig = plt.figure()
    fig.suptitle(
        "Charge Deposition from Simulation using Sampling from {SCD} distribution"
        .format(SCD=scd),
        fontsize=14,
        fontweight='bold')

    gs = gridspec.GridSpec(2,
                           1,
                           height_ratios=[5, 1],
                           wspace=0.025,
                           hspace=0.025)
    ax = plt.subplot(gs[0])
    plt.title(REGION.replace("_", " ") + " normalised 10,000-70,000",
              loc='right')

    for h_info in hs_to_plot:
        if 'Data' in h_info['type']:
            rplt.hist(
                h_info['hist'],
                label=h_info['label'],
                color=h_info['color'],
                alpha=0.35,
                fill=True,
                zorder=0,
            )
        if 'SCD' in h_info['type']:
            rplt.errorbar(
                h_info['hist'],
                label=h_info['label'],
                markerfacecolor=h_info['color'],
                markersize=3,
                xerr=False,
                yerr=False,
                elinewidth=0,
                emptybins=False,
                zorder=len(hs_to_plot),
            )
        if 'CMSSW' in h_info['type']:
            rplt.step(h_info['hist'],
                      label=h_info['label'],
                      color=h_info['color'],
                      linestyle=h_info['line'])

    ax.set_ylim([0.0001, 1.])
    # ax.set_xlim([10000,70000])
    ax.set_xlim([0.1, 70000])
    ax.set_yscale("log", nonposy='clip')
    ax.set_ylabel('N')
    # ax.set_xlabel('Charge (e)')
    plt.setp(ax.get_xticklabels(), visible=False)

    leg = ax.legend(loc='upper right', numpoints=1, prop={'size': 10}, ncol=2)
    leg.draw_frame(False)

    ax_ratio = plt.subplot(gs[1])
    ax_ratio.axhline(1, color='black')
    for r_info in rs_to_plot:
        rplt.errorbar(
            r_info['hist'],
            label=r_info['label'],
            markerfacecolor=r_info['color'],
            markersize=6,
            markeredgewidth=0,
            xerr=False,
            yerr=False,
            elinewidth=0,
            emptybins=False,
            axes=ax_ratio,
        )

    ax_ratio.set_ylim([0, 2])
    ax_ratio.set_xlim([0.1, 70000])
    # ax_ratio.set_xlim([10000,70000])
    ax_ratio.set_xlabel('Charge deposited on APV in a bx(e) ')
    ax_ratio.set_ylabel(
        r'$\frac{\mathrm{Data\ High\ Occ}}{\mathrm{SCD\ Sampling}}$')

    gs.tight_layout(fig, rect=[0, 0.03, 1, 0.95])
    filename = 'CMSSWSimChargeFrom{SCD}_'.format(
        SCD=scd.replace(" ", "")) + REGION
    fig.savefig('plots/InputChargePoissonMatching/' + filename + '.pdf',
                bbox_inches='tight')
    fig.clf()
    plt.close()
    gc.collect()
Beispiel #15
0
h_t2 = Hist(nBins, 0, nBins, title=t2Name)
h_t3 = Hist(nBins, 0, nBins, title=t3Name)
h_t4 = Hist(nBins, 0, nBins, title=t4Name)
h_data = Hist(nBins, 0, nBins, title='data')

if useTemplatesFromFile:
    templates = getTemplatesFromFile()

    for bin in range(1, nBins + 1):
        h_t1.SetBinContent(bin, templates[0][bin - 1])
        h_t2.SetBinContent(bin, templates[1][bin - 1])
        h_t3.SetBinContent(bin, templates[2][bin - 1])
        h_t4.SetBinContent(bin, templates[3][bin - 1])
        pass

    h_t1.Scale(absolute_eta_initialValues[t1Name][whichBinFromFile][0])
    h_t2.Scale(absolute_eta_initialValues[t2Name][whichBinFromFile][0])
    h_t3.Scale(absolute_eta_initialValues[t3Name][whichBinFromFile][0])
    h_t4.Scale(absolute_eta_initialValues[t4Name][whichBinFromFile][0])
else:
    # Fill the histograms
    h_t1Shape.SetBinContent(1, 20)
    h_t1Shape.SetBinContent(2, 20)
    h_t1Shape.SetBinContent(3, 20)
    h_t1Shape.SetBinContent(4, 50)
    h_t1Shape.SetBinContent(5, 50)
    h_t1Shape.SetBinContent(6, 100)
    h_t1Shape.SetBinContent(7, 100)
    h_t1Shape.SetBinContent(8, 50)
    h_t1Shape.SetBinContent(9, 50)
    h_t1Shape.SetBinContent(10, 40)
Beispiel #16
0
def makeDiscr(train_discr_dict, discr_dict, outfile, xtitle="discriminator"):
    c = ROOT.TCanvas("c", "c", 800, 500)
    ROOT.gStyle.SetOptStat(0)
    ROOT.gPad.SetMargin(0.15, 0.1, 0.2, 0.1)
    #ROOT.gPad.SetLogy(1)
    #ROOT.gPad.SetGrid(1,1)
    ROOT.gStyle.SetGridColor(17)
    l = TLegend(0.17, 0.75, 0.88, 0.88)
    l.SetTextSize(0.055)
    l.SetBorderSize(0)
    l.SetFillStyle(0)
    l.SetNColumns(2)

    colors = [2, 1, 4, ROOT.kCyan + 2]
    counter = 0
    for leg, discr in train_discr_dict.iteritems():
        a = Hist(30, 0, 1)
        #fill_hist_with_ndarray(a, discr)
        a.fill_array(discr)
        a.SetLineColor(colors[counter])
        a.SetLineWidth(2)
        a.GetXaxis().SetTitle(xtitle)
        a.GetXaxis().SetLabelSize(0.05)
        a.GetXaxis().SetTitleSize(0.06)
        a.GetXaxis().SetTitleOffset(1.45)
        a.GetYaxis().SetTitle("a.u.")
        a.GetYaxis().SetTickSize(0)
        a.GetYaxis().SetLabelSize(0)
        a.GetYaxis().SetTitleSize(0.06)
        a.GetYaxis().SetTitleOffset(0.9)
        a.Scale(1. / a.Integral())
        #a.GetYaxis().SetRangeUser(0.00001,100)
        a.GetYaxis().SetRangeUser(0, 0.9)
        if counter == 0: a.draw("hist")
        else: a.draw("same hist")
        l.AddEntry(a, leg, "l")
        counter += 1

    counter = 0
    for leg, discr in discr_dict.iteritems():
        a = Hist(30, 0, 1)
        #fill_hist_with_ndarray(a, discr)
        a.fill_array(discr)
        a.SetLineColor(colors[counter])
        a.SetMarkerColor(colors[counter])
        a.SetMarkerStyle(34)
        a.SetMarkerSize(1.8)
        a.SetLineWidth(2)
        a.GetXaxis().SetTitle(xtitle)
        a.GetXaxis().SetLabelSize(0.05)
        a.GetXaxis().SetTitleSize(0.06)
        a.GetXaxis().SetTitleOffset(1.45)
        a.GetYaxis().SetTitle("a.u.")
        a.GetYaxis().SetTickSize(0)
        a.GetYaxis().SetLabelSize(0)
        a.GetYaxis().SetTitleSize(0.06)
        a.GetYaxis().SetTitleOffset(0.9)
        a.Scale(1. / a.Integral())
        #a.GetYaxis().SetRangeUser(0.00001,100)
        a.GetYaxis().SetRangeUser(0, 0.4)
        a.draw("same p X0")
        l.AddEntry(a, leg, "p")
        counter += 1

    # counter = 0


#     for leg,discr in train_discr_dict.iteritems():
#         d = Hist(30, 0, 1)
#         d.fill_array(discr)
#         d.SetLineColor(colors[counter])
#         d.SetLineWidth(2)
#         l.AddEntry(d,leg,"l")
#
#         b = Hist(30, 0, 1)
#         d.fill_array(discr_dict[leg.split(" ")[0] + " test"])
#         b.SetLineColor(colors[counter])
#         b.SetMarkerColor(colors[counter])
#         b.SetMarkerStyle(34)
#         b.SetMarkerSize(1.8)
#         b.SetLineWidth(2)
#         l.AddEntry(b,leg,"p")
#         counter += 1

    l.Draw("same")

    c.SaveAs(outfile)
Beispiel #17
0
def run_landaus(title, folder_path, d_mip_variables, data_charge_inputs):
    '''
	Plot any landaus
	'''
    print "- - - - - - - - - - - - - - - - - - -"
    print "Plotting Data Simulation Comparisons"
    print "- - - - - - - - - - - - - - - - - - -"
    ########################################################################################################################
    ### Fill ROOTPY Hists
    ########################################################################################################################
    charge_deposited_hist = Hist(data_charge_inputs['edges'])
    for v in d_mip_variables['q_Deposited_e']:
        charge_deposited_hist.Fill(v)
    charge_deposited_hist.Scale(1 / charge_deposited_hist.Integral())

    unweighted_charge_deposited_hist = Hist(data_charge_inputs['edges'])
    for v in d_mip_variables['q_ClusterDeposited_e']:
        unweighted_charge_deposited_hist.Fill(v)
    unweighted_charge_deposited_hist.Scale(
        1 / unweighted_charge_deposited_hist.Integral())

    charge_read_hist = Hist(data_charge_inputs['edges'])
    for v in d_mip_variables['q_Read_e']:
        charge_read_hist.Fill(v)
    charge_read_hist.Scale(1 / charge_read_hist.Integral())

    charge_weight_hist = Hist(data_charge_inputs['edges_stripClusterFraction'])
    for v in d_mip_variables['q_Weight_e']:
        charge_weight_hist.Fill(v)
    charge_weight_hist.Scale(1 / charge_weight_hist.Integral())

    ########################################################################################################################
    ### Charge Weighting
    ########################################################################################################################
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    rplt.hist(
        data_charge_inputs['hist_stripClusterFraction_normed'],
        histtype='step',
        facecolor='red',
        edgecolor='red',
        fill=True,
        alpha=0.5,
        label='Strip-Cluster Distribution',
    )
    rplt.hist(
        charge_weight_hist,
        histtype='step',
        facecolor='blue',
        edgecolor='blue',
        fill=True,
        alpha=0.5,
        label='Scaling Distribution applied to Simulated Charge Deposition ',
    )
    ax.set_ylim([0, 0.1])
    ax.set_xlabel('Charge [e]')
    ax.set_ylabel('N')
    fig.suptitle('Strip-Cluster Charge Distribution',
                 fontsize=14,
                 fontweight='bold')
    plt.title(title, loc='right')
    leg = plt.legend(loc='best')
    leg.draw_frame(False)
    fig.savefig(folder_path + 'MC_Data_ChargeWeighting_Norm.pdf',
                bbox_inches='tight')
    fig.clf()
    plt.close()
    gc.collect()

    # ########################################################################################################################
    # ### Data STRIP vs Cluster Charge
    # ########################################################################################################################
    # fig = plt.figure()
    # ax = fig.add_subplot(1, 1, 1)
    # rplt.hist(
    # 	data_charge_inputs['hist_clusterCharge'],
    # 	histtype='step',
    # 	facecolor='orange',
    # 	edgecolor='orange',
    # 	fill = True,
    # 	alpha=0.5,
    # 	label='Cluster Charge Distribution in Data',
    # )
    # rplt.hist(
    # 	data_charge_inputs['hist_stripCharge'],
    # 	histtype='step',
    # 	facecolor='red',
    # 	edgecolor='red',
    # 	fill = True,
    # 	alpha=0.5,
    # 	label='Strip Charge Distribution in Data',
    # )
    # # ax.set_ylim([0,0.15])
    # ax.set_xlabel('Charge [e]')
    # ax.set_ylabel('N')
    # fig.suptitle('Strip v Cluster Charge Deposition in Data', fontsize=14, fontweight='bold')
    # plt.title(title, loc='right')
    # leg = plt.legend(loc='best')
    # leg.draw_frame(False)
    # fig.savefig(folder_path+'Data_StripCluster.pdf', bbox_inches='tight')
    # fig.clf()
    # plt.close()
    # gc.collect()

    ########################################################################################################################
    ### Data STRIP vs Cluster Charge
    ########################################################################################################################
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    rplt.hist(
        data_charge_inputs['hist_clusterCharge_normed'],
        histtype='step',
        facecolor='orange',
        edgecolor='orange',
        fill=True,
        alpha=0.5,
        label='Cluster Charge Distribution in Data',
    )
    rplt.hist(
        data_charge_inputs['hist_stripCharge_normed'],
        histtype='step',
        facecolor='red',
        edgecolor='red',
        fill=True,
        alpha=0.5,
        label='Strip Charge Distribution in Data',
    )
    ax.set_ylim([0, 0.15])
    ax.set_xlabel('Charge [e]')
    ax.set_ylabel('N')
    fig.suptitle('Strip v Cluster Charge in Data',
                 fontsize=14,
                 fontweight='bold')
    plt.title(title, loc='right')
    leg = plt.legend(loc='best')
    leg.draw_frame(False)
    fig.savefig(folder_path + 'Data_StripCluster_Norm.pdf',
                bbox_inches='tight')
    fig.clf()
    plt.close()
    gc.collect()

    ########################################################################################################################
    ### Simulation STRIP vs Cluster Charge
    ########################################################################################################################
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    rplt.hist(
        unweighted_charge_deposited_hist,
        histtype='step',
        facecolor='green',
        edgecolor='green',
        fill=True,
        alpha=0.5,
        label='Cluster Charge Distribution in Simulation',
    )
    rplt.hist(
        charge_deposited_hist,
        histtype='step',
        facecolor='blue',
        edgecolor='blue',
        fill=True,
        alpha=0.5,
        label='Strip Charge Distribution in Simulation',
    )
    ax.set_ylim([0, 0.1])
    ax.set_xlabel('Charge [e]')
    ax.set_ylabel('N')
    fig.suptitle('Strip v Cluster Charge Deposition in Simulation',
                 fontsize=14,
                 fontweight='bold')
    plt.title(title, loc='right')
    leg = plt.legend(loc='best')
    leg.draw_frame(False)
    fig.savefig(folder_path + 'MC_ChargeDeposition_Norm.pdf',
                bbox_inches='tight')
    fig.clf()
    plt.close()
    gc.collect()

    ########################################################################################################################
    ### Simulation STRIP vs Cluster Charge. Input vs Output Distirbutions
    ########################################################################################################################
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    rplt.hist(
        charge_deposited_hist,
        histtype='step',
        facecolor='blue',
        edgecolor='blue',
        fill=True,
        alpha=0.5,
        label='Strip Charge Distribution in Simulation',
    )
    rplt.hist(
        charge_read_hist,
        histtype='step',
        facecolor='purple',
        edgecolor='purple',
        fill=True,
        alpha=0.5,
        label='Strip Charge Distribution in Simulation from APV Gain',
    )
    ax.set_ylim([0, 0.1])
    ax.set_xlabel('Charge [e]')
    ax.set_ylabel('N')
    fig.suptitle(
        'Simulated Charge Deposition Comparison with Readout from Gain',
        fontsize=14,
        fontweight='bold')
    plt.title(title, loc='right')
    leg = plt.legend(loc='best')
    leg.draw_frame(False)
    fig.savefig(folder_path + 'MC_ChargeDepositionFromGain_Norm.pdf',
                bbox_inches='tight')
    fig.clf()
    plt.close()
    gc.collect()

    ########################################################################################################################
    ### Strip Charge Deposition From Data vs MC
    ########################################################################################################################
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    rplt.hist(
        charge_read_hist,
        histtype='step',
        facecolor='blue',
        edgecolor='blue',
        fill=True,
        alpha=0.5,
        label='Strip Charge Distribution in Simulation',
    )
    rplt.hist(
        data_charge_inputs['hist_stripCharge_normed'],
        histtype='step',
        facecolor='red',
        edgecolor='red',
        fill=True,
        alpha=0.5,
        label='Strip Charge Distribution in Data',
    )
    # plt.axvline(x=7500, linewidth=1, color='r', label = 'Min Threshold')
    # plt.axvline(x=1500, linewidth=1, color='g', label = 'Min Threshold')
    # plt.axvline(x=3000, linewidth=1, color='b', label = 'Min Threshold')
    # plt.axvline(x=2000, linewidth=1, color='orange', label = 'Min Threshold')

    ax.set_ylim([0, 0.1])
    ax.set_xlabel('Charge [e]')
    ax.set_ylabel('N')
    fig.suptitle('Strip Charge Deposition Data vs Simulation',
                 fontsize=14,
                 fontweight='bold')
    plt.title(title, loc='right')
    leg = plt.legend(loc='best')
    leg.draw_frame(False)
    fig.savefig(folder_path + 'MC_Data_StripChargeDeposition_Norm.pdf',
                bbox_inches='tight')
    fig.clf()
    plt.close()
    gc.collect()

    ########################################################################################################################
    ### Cluster Charge Deposition From Data vs MC
    ########################################################################################################################
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    rplt.hist(
        data_charge_inputs['hist_clusterCharge_normed'],
        histtype='step',
        facecolor='orange',
        edgecolor='orange',
        fill=True,
        alpha=0.5,
        label='Cluster Charge Distribution in Data',
    )
    rplt.hist(
        unweighted_charge_deposited_hist,
        histtype='step',
        facecolor='green',
        edgecolor='green',
        fill=True,
        alpha=0.5,
        label='Cluster Charge Distribution in Simulation',
    )
    ax.set_ylim([0, 0.1])
    ax.set_xlabel('Charge [e]')
    ax.set_ylabel('N')
    fig.suptitle('Cluster Charge Deposition Data vs Simulation',
                 fontsize=14,
                 fontweight='bold')
    plt.title(title, loc='right')
    leg = plt.legend(loc='best')
    leg.draw_frame(False)
    fig.savefig(folder_path + 'MC_Data_ClusterChargeDeposition_Norm.pdf',
                bbox_inches='tight')
    fig.clf()
    plt.close()
    gc.collect()

    # ########################################################################################################################
    # ### Cluster Charge Vs Charge Splitting
    # ########################################################################################################################
    # fig = plt.figure()
    # ax = fig.add_subplot(1, 1, 1)
    # plt.scatter(
    # 	d_mip_variables['q_ClusterDeposited_e'],
    # 	d_mip_variables['q_Weight_e'],
    # )
    # ax.set_xlim([0,8000000])
    # ax.set_ylim([0,1])
    # ax.set_xlabel('Cluster Charge [e]')
    # ax.set_ylabel('Strip Charge [e]')

    # # ax.set_ylabel('N')
    # fig.suptitle('Cluster Charge vs Strip Charge [Simulation]', fontsize=14, fontweight='bold')
    # plt.title(title, loc='right')
    # # leg = plt.legend(loc='best')
    # # leg.draw_frame(False)
    # fig.savefig(folder_path+'TEST.pdf', bbox_inches='tight')
    # fig.clf()
    # plt.close()
    # gc.collect()

    ########################################################################################################################
    ### All Charge Distributions
    ########################################################################################################################
    fig = plt.figure()
    ax = fig.add_subplot(1, 1, 1)
    rplt.hist(
        data_charge_inputs['hist_clusterCharge_normed'],
        histtype='step',
        facecolor='orange',
        edgecolor='orange',
        fill=True,
        alpha=0.5,
        label='Cluster Charge Distribution in Data',
    )
    rplt.hist(
        data_charge_inputs['hist_stripCharge_normed'],
        histtype='step',
        facecolor='red',
        edgecolor='red',
        fill=True,
        alpha=0.5,
        label='Strip Charge Distribution in Data',
    )
    rplt.hist(
        unweighted_charge_deposited_hist,
        histtype='step',
        facecolor='blue',
        edgecolor='blue',
        fill=True,
        alpha=0.5,
        label='Cluster Charge Distribution in Simulation',
    )
    rplt.hist(
        charge_read_hist,
        histtype='step',
        facecolor='purple',
        edgecolor='purple',
        fill=True,
        alpha=0.5,
        label='Strip Charge Distribution in Simulation from APV Gain',
    )

    ax.set_ylim([0, 0.05])
    ax.set_xlabel('Charge [e]')
    ax.set_ylabel('N')
    fig.suptitle('Strip and Cluster Distributions in Simulation and Data',
                 fontsize=14,
                 fontweight='bold')
    plt.title(title, loc='right')
    leg = plt.legend(loc='best')
    leg.draw_frame(False)
    fig.savefig(folder_path + 'MC_Data_ChargeComparison_Norm.pdf',
                bbox_inches='tight')
    fig.clf()
    plt.close()
    gc.collect()

    return