Пример #1
0
    def GetfromLHAPDF(self, gen):
        if not self.SetupLHAPDF():
            return 0, None
        ## Default PDF used for 2017 and 2018 production
        if self.pset is None:
            self.pset = lhapdf.getPDFSet(
                "NNPDF31_nnlo_as_0118")  # ErrorType: replicas
            self.pdfs = self.pset.mkPDFs()

        npar = self.pset.errorType.count(
            "+")  # number of parameter variations (alphaS, etc.)
        if npar > 0:
            print("Last %d members are parameter variations\n" % (2 * npar))

        ## Fill vectors xgAll and xuAll using all PDF members.
        pdfweights = [0.0 for i in range(self.pset.size)]

        x1_cen = self.pdfs[0].xfxQ(gen.id1, gen.x1, gen.scalePDF)
        x2_cen = self.pdfs[0].xfxQ(gen.id2, gen.x2, gen.scalePDF)
        normweight = x1_cen * x2_cen
        for imem in range(self.pset.size):
            x1_imem = self.pdfs[imem].xfxQ(gen.id1, gen.x1, gen.scalePDF)
            x2_imem = self.pdfs[imem].xfxQ(gen.id2, gen.x2, gen.scalePDF)
            pdfweights[imem] = x1_imem * x2_imem / normweight
        return self.pset.size, pdfweights
Пример #2
0
def main(
		pdfset,
		flavours,
		output_filename,
		n_points,
		q,
		q2,  # q2 instead of q
		members,
		folder):
	"""evaluate a PDF set and write the resuling TGraph to disk"""

	if folder is not None and not os.path.exists(folder):
		os.makedirs(folder)
	out = ROOT.TFile((folder+"/" if folder is not None else "") + output_filename, "RECREATE")
	x_values = np.logspace(-4, -0.01, n_points)  # TODO get min, max x from PDF set

	## Version info, search paths, and metadata
	print "LHAPDF version", lhapdf.version()
	lhapdf.pathsPrepend(os.getcwd())
	lhapdf.setVerbosity(0)
	print "LHAPDF paths",lhapdf.paths()
	pset = lhapdf.getPDFSet(pdfset)
	print pset.description
	n_members = pset.size
	if members is not None:
		n_members=members

	# iterate over flavours, get pdfgraph, write
	for flavour in flavours:
		tgraph = get_pdf_tgraph(pset, flavour, x_values, n_points, n_members, q, q2)
		tgraph.Write(partondict[flavour].replace(' ', '_'))

	print "Written to", output_filename
	out.Close()
Пример #3
0
def generate_pdf(pdfname):
    pdf, pdf_index = [], []
    pdfset = lhapdf.getPDFSet(f"{pdfname}")
    for i in range(1, pdfset.size):
        pdf_index.append(i)
    for i in range(0, pdfset.size):
        pdf.append(pdfset.mkPDF(i))
    return pdf, pdf_index
Пример #4
0
def generate_random_pdf(pdfname, compression_size):
    pdf, pdf_index = [], []
    pdfset = lhapdf.getPDFSet(f"{pdfname}")
    for i in range(1, compression_size):
        pdf_index.append(i)
    indices = np.random.choice(pdfset.size, compression_size, replace=False)
    for i in range(0, compression_size):
        pdf.append(pdfset.mkPDF(indices[i]))
    return pdf, pdf_index
Пример #5
0
Файл: pdf.py Проект: claria/plot
    def _read_lhapdf(self, lhgrid_filename):
        pdf = {}
        global pdfs
        pdfset = lhapdf.getPDFSet(lhgrid_filename)
        if not lhgrid_filename in pdfs:
            print 'cache it.'
            print pdfs.keys()
            pdfs[lhgrid_filename] = pdfset.mkPDFs()
        else:
            print 'is already cached'

        for flavor in self._flavors:
            pdf[flavor] = self._get_lhapdf_flavor(flavor, pdfs[lhgrid_filename])
        return pdf
Пример #6
0
def f2p_lhapdf(x, q2, select='CT14nnlo'):
    pdf_set = lhapdf.getPDFSet(select)
    pdfs = pdf_set.mkPDFs()

    d, ed = numpy.empty_like(x), numpy.empty_like(x)
    dbar, edbar = numpy.empty_like(x), numpy.empty_like(x)
    u, eu = numpy.empty_like(x), numpy.empty_like(x)
    ubar, eubar = numpy.empty_like(x), numpy.empty_like(x)
    s, es = numpy.empty_like(x), numpy.empty_like(x)

    for ix, xx in enumerate(x):
        d[ix], ed[ix] = _parton_lhapdf(1, xx, q2, pdf_set, pdfs)
        dbar[ix], edbar[ix] = _parton_lhapdf(-1, xx, q2, pdf_set, pdfs)
        u[ix], eu[ix] = _parton_lhapdf(2, xx, q2, pdf_set, pdfs)
        ubar[ix], eubar[ix] = _parton_lhapdf(-2, xx, q2, pdf_set, pdfs)
        s[ix], es[ix] = _parton_lhapdf(3, xx, q2, pdf_set, pdfs)

    result = ((2 / 3)**2 * (u + ubar) + (1 / 3)**2 * (d + dbar) + (1 / 3)**2 * 2 * s)
    error = numpy.sqrt((2 / 3)**4 * (eu**2 + eubar**2) + (1 / 3)**4 * (ed**2 + edbar**2) + (1 / 3)**4 * 4 * es**2)

    return result, error
Пример #7
0
def generate_gp(prior):
    """ Generate the GP from an input `prior` PDF """

    # Get PDFSet and replicas (split is to avoid replica 0)
    pdfset = lhapdf.getPDFSet(prior)
    replicas = pdfset.mkPDFs()[1:]

    # Initial scale and x-grid
    Q0 = float(pdfset.get_entry("QMin"))
    xs, nx = XGRID, len(XGRID)

    # Available flavours
    flavours = get_active_flavours(pdfset, Q0)
    nfl = len(flavours)

    print(f"{Fore.GREEN}Sampling {nx} x-points at initial scale: {Q0} GeV")
    grid_points = list(itertools.product(flavours, xs))
    pdf_values = np.empty([nfl * nx, len(replicas)])
    for irep, rep in enumerate(replicas):
        for ipt, pt in enumerate(grid_points):
            pdf_values[ipt][irep] = rep.xfxQ(pt[0], pt[1], Q0)

    print("Computing stats")
    mean = np.mean(pdf_values, axis=1)
    covariance = np.cov(pdf_values)

    # Condition covariance matrix a bit
    # Should use attempt on multivariate_normal instead
    min_eig = np.min(np.real(np.linalg.eigvals(covariance)))
    while min_eig < 0:
        print(Fore.YELLOW)
        print("WARNING: Covariance matrix not positive-semidefinite")
        print(f"Minimum eigenvalue: {min_eig}")
        print("Introducing regulator...")
        covariance -= 100 * min_eig * np.eye(*covariance.shape)
        min_eig = np.min(np.real(np.linalg.eigvals(covariance)))
        print(f"New minimum: {min_eig}")

    return GPPDF(prior, mean, covariance, Q0, flavours, xs)
Пример #8
0
def MeasureNominal(t, mytree, pass_sys):
    bpos_ = []
    jetpos_ = []
    jets_ = ROOT.vector('TLorentzVector')()
    ordered_jets_ = ROOT.vector('TLorentzVector')()
    bestcomb_ = []
    corrcomb_ = []
    corrb_ = []
    corrlight_ = []
    if (t.njets >= 7 and t.nBCSVM >= 2 and t.njets <= 14) or pass_sys:
        if sample != 'data':
            mytree.variables['weight'][0] = np.sign(t.genWeight)
            mytree.variables['puweight'][0] = t.puWeight
            mytree.variables['puweight_Up'][0] = t.puWeightUp
            mytree.variables['puweight_Down'][0] = t.puWeightDown

            mytree.variables['trigweight'][0] = t.triggerWeight
            mytree.variables['trigweight_Up'][0] = t.triggerWeightUp
            mytree.variables['trigweight_Down'][0] = t.triggerWeightDown
            mytree.variables['btagweight'][0] = t.btagWeightCSV
            mytree.variables['qgweight'][0] = t.qgWeight
            mytree.variables['qgweight_Up'][0] = 2 * t.qgWeight - 1
            mytree.variables['qgweight_Down'][0] = 1.0
            mytree.variables['btagweight_jesPileUpPtBB_Down'][
                0] = t.btagWeightCSV_down_jesPileUpPtBB
            mytree.variables['btagweight_jesFlavorQCD_Down'][
                0] = t.btagWeightCSV_down_jesFlavorQCD
            mytree.variables['btagweight_jesAbsoluteScale_Down'][
                0] = t.btagWeightCSV_down_jesAbsoluteScale
            mytree.variables['btagweight_jesPileUpPtRef_Down'][
                0] = t.btagWeightCSV_down_jesPileUpPtRef
            mytree.variables['btagweight_jesRelativeFSR_Down'][
                0] = t.btagWeightCSV_down_jesRelativeFSR
            mytree.variables['btagweight_jesTimePtEta_Down'][
                0] = t.btagWeightCSV_down_jesTimePtEta
            mytree.variables['btagweight_hf_Down'][0] = t.btagWeightCSV_down_hf
            mytree.variables['btagweight_cferr1_Down'][
                0] = t.btagWeightCSV_down_cferr1
            mytree.variables['btagweight_cferr2_Down'][
                0] = t.btagWeightCSV_down_cferr2
            mytree.variables['btagweight_jes_Down'][
                0] = t.btagWeightCSV_down_jes
            mytree.variables['btagweight_jesAbsoluteMPFBias_Down'][
                0] = t.btagWeightCSV_down_jesAbsoluteMPFBias
            mytree.variables['btagweight_lf_Down'][0] = t.btagWeightCSV_down_lf
            mytree.variables['btagweight_jesPileUpPtEC1_Down'][
                0] = t.btagWeightCSV_down_jesPileUpPtEC1
            mytree.variables['btagweight_lfstats2_Down'][
                0] = t.btagWeightCSV_down_lfstats2
            mytree.variables['btagweight_lfstats1_Down'][
                0] = t.btagWeightCSV_down_lfstats1
            mytree.variables['btagweight_hfstats2_Down'][
                0] = t.btagWeightCSV_down_hfstats2
            mytree.variables['btagweight_hfstats1_Down'][
                0] = t.btagWeightCSV_down_hfstats1
            mytree.variables['btagweight_jesPileUpDataMC_Down'][
                0] = t.btagWeightCSV_down_jesPileUpDataMC

            mytree.variables['btagweight_jesPileUpPtBB_Up'][
                0] = t.btagWeightCSV_up_jesPileUpPtBB
            mytree.variables['btagweight_jesFlavorQCD_Up'][
                0] = t.btagWeightCSV_up_jesFlavorQCD
            mytree.variables['btagweight_jesAbsoluteScale_Up'][
                0] = t.btagWeightCSV_up_jesAbsoluteScale
            mytree.variables['btagweight_jesPileUpPtRef_Up'][
                0] = t.btagWeightCSV_up_jesPileUpPtRef
            mytree.variables['btagweight_jesRelativeFSR_Up'][
                0] = t.btagWeightCSV_up_jesRelativeFSR
            mytree.variables['btagweight_jesTimePtEta_Up'][
                0] = t.btagWeightCSV_up_jesTimePtEta
            mytree.variables['btagweight_hf_Up'][0] = t.btagWeightCSV_up_hf
            mytree.variables['btagweight_cferr1_Up'][
                0] = t.btagWeightCSV_up_cferr1
            mytree.variables['btagweight_cferr2_Up'][
                0] = t.btagWeightCSV_up_cferr2
            mytree.variables['btagweight_jes_Up'][0] = t.btagWeightCSV_up_jes
            mytree.variables['btagweight_jesAbsoluteMPFBias_Up'][
                0] = t.btagWeightCSV_up_jesAbsoluteMPFBias
            mytree.variables['btagweight_lf_Up'][0] = t.btagWeightCSV_up_lf
            mytree.variables['btagweight_jesPileUpPtEC1_Up'][
                0] = t.btagWeightCSV_up_jesPileUpPtEC1
            mytree.variables['btagweight_hfstats2_Up'][
                0] = t.btagWeightCSV_up_hfstats2
            mytree.variables['btagweight_hfstats1_Up'][
                0] = t.btagWeightCSV_up_hfstats1
            mytree.variables['btagweight_lfstats2_Up'][
                0] = t.btagWeightCSV_up_lfstats2
            mytree.variables['btagweight_lfstats1_Up'][
                0] = t.btagWeightCSV_up_lfstats1
            mytree.variables['btagweight_jesPileUpDataMC_Up'][
                0] = t.btagWeightCSV_up_jesPileUpDataMC
            mytree.variables['LHEPDFweight'][0] = 1.0
            mytree.variables['LHE_factweight'][0] = 1.0
            mytree.variables['LHE_renormweight'][0] = 1.0
        else:
            mytree.variables['weight'][0] = 1

        if 'ttbar' in sample:
            nnpdfSet = lhapdf.getPDFSet("NNPDF30_nlo_as_0118")
            pdfset = [1.0]
            mytree.variables['LHE_factweight_Up'][0] = t.LHE_weights_scale_wgt[
                0]
            mytree.variables['LHE_factweight_Down'][
                0] = t.LHE_weights_scale_wgt[1]
            mytree.variables['LHE_renormweight_Up'][
                0] = t.LHE_weights_scale_wgt[2]
            mytree.variables['LHE_renormweight_Down'][
                0] = t.LHE_weights_scale_wgt[3]
            #for nlhe in range(t.nLHE_weights_scale):
            #      mytree.variables['LHE_scale'][nlhe]=t.LHE_weights_scale_wgt[nlhe]

            for nlhe in range(t.nLHE_weights_pdf - 2):
                pdfset.append(t.LHE_weights_pdf_wgt[nlhe])

            pdfUnc = nnpdfSet.uncertainty(pdfset)

            mytree.variables['LHEPDFweight_Up'][
                0] = pdfUnc.central + pdfUnc.errplus
            mytree.variables['LHEPDFweight_Down'][
                0] = pdfUnc.central - pdfUnc.errminus

        ntopjets = ntoptaggedjets = 0
        nbjets = 0
        nljets = 0

        bdtcomb = -999999999
        chi2comb = 999999999

        mytree.variables['nPVs'][0] = t.nPVs
        mytree.variables['sphericity'][0] = t.sphericity
        mytree.variables['C'][0] = t.C
        mytree.variables['minjetpt'][0] = t.jets_pt[t.njets - 1]

        mytree.variables['jets_dRavg'][0] = sum(t.jets_dRave) / t.njets
        drmin_list = [x for x in t.jets_dRmin if x > 0]
        if len(drmin_list) > 0:
            mytree.variables['jets_dRmin'][0] = min(
                [x for x in t.jets_dRmin if x > 0])
        else:
            mytree.variables['jets_dRmin'][0] = 0
        mytree.variables['jets_dRmax'][0] = max(t.jets_dRmax)
        if sample == 'QCD': mytree.variables['isQCD'][0] = 1
        else: mytree.variables['isQCD'][0] = 0

        #mytree.variables['girth'][0] = ptR/(t.ht)**2
        if 'ttbar' in sample or 'theory' in sample:
            mytree.variables['ttCls'][0] = t.ttCls
        else:
            mytree.variables['ttCls'][0] = -1
        mytree.variables['ht'][0] = t.ht
        #mytree.variables['all_mass'][0] = t.invmass
        #mytree.variables['closest_mass'][0] = t.mjjmin
        mytree.variables['jet5pt'][0] = t.jets_pt[5]
        mytree.variables['n_jets'][0] = t.njets
        mytree.variables['n_bjets'][0] = t.nBCSVM
        mytree.variables['n_addJets'][0] = t.njets - 6
        #mytree.variables['n_topjets'][0] = ntopjets
        mytree.variables['qgLR'][0] = -100
        mytree.variables['centrality'][0] = t.centrality
        mytree.variables['aplanarity'][0] = t.aplanarity
        mytree.variables['meanDeltaRbtag'][0] = t.mean_dr_btag
        mytree.variables['meanCSVbtag'][0] = t.mean_bdisc
        mytree.variables['meanCSV'][0] = t.mean_bdisc_btag
        mytree.variables['btagLR3b'][0] = t.btag_LR_3b_2b_btagCSV
        mytree.variables['btagLR4b'][0] = t.btag_LR_4b_2b_btagCSV
        mytree.variables['nBCSVM'][0] = t.nBCSVM

        qgLR3b = t.qg_LR_3b_flavour_4q_0q
        qgLR4b = t.qg_LR_4b_flavour_4q_0q

        if t.nBCSVM == 3:
            mytree.variables['qgLR'][0] = qgLR3b
            # if t.mem_ttbb_FH_4w2h1t_p  > 0: mytree.variables['memttbb'][0] = -TMath.Log10(t.mem_ttbb_FH_4w2h1t_p)
            # else: mytree.variables['memttbb'][0] = -10
            # #print mytree.variables['memttbb'][0]
            # if nljets == 4:
            #       mytree.variables['qgLR'][0] = t.qg_LR_3b_flavour_4q_0q
            # elif nljets >= 5:
            #       mytree.variables['qgLR'][0] = t.qg_LR_3b_flavour_5q_0q
        if t.nBCSVM >= 4:
            mytree.variables['qgLR'][0] = qgLR4b
            # if t.mem_ttbb_FH_4w2h2t_p  > 0: mytree.variables['memttbb'][0] = -TMath.Log10(t.mem_ttbb_FH_4w2h2t_p)
            # else: mytree.variables['memttbb'][0] = -10
            # #print mytree.variables['memttbb'][0]
            # if nljets == 4: mytree.variables['qgLR'][0] = t.qg_LR_4b_flavour_4q_0q
            # elif nljets >= 5: mytree.variables['qgLR'][0] = t.qg_LR_4b_flavour_5q_0q
        else:
            # mytree.variables['memttbb'][0] = -TMath.Log10(t.mem_ttbb_FH_4w2h1t_p) if t.mem_ttbb_FH_4w2h1t_p >0 else -10
            mytree.variables['qgLR'][0] = qgLR3b

        if sample != 'ttH':
            tthcut = t.json and (t.HLT_ttH_FH or t.HLT_BIT_HLT_PFJet450_v
                                 ) and t.ht > 500 and t.jets_pt[5] > 40
        else:
            tthcut = t.json and (
                t.HLT_ttH_FH) and t.ht > 500 and t.jets_pt[5] > 40
        if sample == 'ttbar':
            for itophad in range(t.ngenTopHad):
                mytree.variables['genTopHad_pt'][itophad] = t.genTopHad_pt[
                    itophad]
            mytree.variables['topweight'][0] = np.exp(
                0.5 * (t.ngenTopLep * 0.0843616 - 0.000743051 *
                       np.sum(t.genTopLep_pt) + t.ngenTopHad * 0.0843616 -
                       0.000743051 * np.sum(t.genTopHad_pt))) * (t.jets_pt[0] /
                                                                 t.jets_pt[0])
            mytree.variables['topweight_Up'][0] = np.exp(0.5 * (
                t.ngenTopLep * 0.00160296 - 0.000411375 * sum(t.genTopLep_pt) +
                t.ngenTopHad * 0.00160296 - 0.000411375 * sum(t.genTopHad_pt)))
            mytree.variables['topweight_Down'][0] = np.exp(
                0.5 *
                (t.ngenTopLep * 0.16712 - 0.00107473 * sum(t.genTopLep_pt) +
                 t.ngenTopHad * 0.16712 - 0.00107473 * sum(t.genTopHad_pt)))

        if not (t.njets >= 7 and t.nBCSVM >= 2 and tthcut and t.njets <= 14):
            return 0

        for i in range(0, t.njets):  #find the b-tagged jets
            jet = ROOT.TLorentzVector()
            jet.SetPtEtaPhiM(t.jets_pt[i], t.jets_eta[i], t.jets_phi[i],
                             t.jets_mass[i])

            jets_.push_back(jet)
            if sample != 'data':
                if abs(t.jets_mcMatchId[i]) == 6:
                    if abs(t.jets_mcFlavour[i]
                           ) == 5 and t.jets_matchFlag[i] == 1:
                        corrb_.append(i)
                    elif t.jets_matchFlag[i] == 0:
                        corrlight_.append(i)

        alljets = range(t.njets)
        if len(corrb_) == 2 and len(corrlight_) == 4:
            mytree.variables['existCorrect'][0] = 1
            corrcomb_ = JetComb(4, 2, corrlight_, corrb_)
            for ii, c in enumerate(corrcomb_[0]):
                mytree.variables['corr_comb'][ii] = c
        else:
            mytree.variables['existCorrect'][0] = 0
        mytree.variables['hasbCorrect'][0] = 0

        allcomb_ = JetComb(t.njets, 0, alljets)

        mytree.variables['hasCorrect'][0] = 0
        BDT_classes = [0, 0, 0]
        printing = 0
        highest = 0
        bestcat = 0
        #print comb_, 'comb_'
        meanBDTttbar = sumprob = 0
        maxbdt = 0

        # print 'start comb'
        # watch.Print()

        for comb in allcomb_:
            UpdateVariables(comb, jets_, mytree.variables, MVA_Only)
            if mytree.variables['prob_chi2'][0] < probcut: continue
            #if mytree.variables['simple_chi2'][0] < chi2cut: continue

            if comb in corrcomb_:
                mytree.variables['hasCorrect'][0] = 1
            w1.UpdateParam(jets_[comb[2]] + jets_[comb[3]])
            top1.UpdateParam(jets_[comb[0]] + jets_[comb[3]] + jets_[comb[2]])
            w2.UpdateParam(jets_[comb[5]] + jets_[comb[4]])
            top2.UpdateParam(jets_[comb[1]] + jets_[comb[4]] + jets_[comb[5]])
            b1.UpdateParam(jets_[comb[0]])
            b2.UpdateParam(jets_[comb[1]])
            lp1.UpdateParam(jets_[comb[2]])
            lp2.UpdateParam(jets_[comb[3]])
            lq1.UpdateParam(jets_[comb[4]])
            lq2.UpdateParam(jets_[comb[5]])

            BDT_Value = reader.EvaluateMVA("BDT_Comb")

            if BDT_Value > bdtcomb:
                mytree.variables['BDT_Comb'][0] = BDT_Value
                bdtcomb = BDT_Value
                bestcomb_ = comb
                if bestcomb_ in corrcomb_: mytree.variables['isCorrect'][0] = 1
                else: mytree.variables['isCorrect'][0] = 0
                # if sample !='data':
                #       mytree.variables['n_sumIDtop'][0] = t.jets_mcMatchId[comb[0]]
                #       mytree.variables['n_sumIDtop'][1] = t.jets_mcMatchId[comb[2]]
                #       mytree.variables['n_sumIDtop'][2] = t.jets_mcMatchId[comb[3]]
                #       mytree.variables['n_sumIDtop'][3] = t.jets_mcMatchId[comb[1]]
                #       mytree.variables['n_sumIDtop'][4] = t.jets_mcMatchId[comb[4]]
                #       mytree.variables['n_sumIDtop'][5] = t.jets_mcMatchId[comb[5]]

        if len(bestcomb_) == 0: return 0
        # print 'finish comb'
        # watch.Print()

        for ii, c in enumerate(bestcomb_):
            mytree.variables['best_comb'][ii] = c

        UpdateVariables(bestcomb_, jets_, mytree.variables, MVA_Only)

        b1.UpdateParam(jets_[bestcomb_[0]])
        b2.UpdateParam(jets_[bestcomb_[1]])
        lp1.UpdateParam(jets_[bestcomb_[2]])
        lp2.UpdateParam(jets_[bestcomb_[3]])
        lq1.UpdateParam(jets_[bestcomb_[4]])
        lq2.UpdateParam(jets_[bestcomb_[5]])
        w1.UpdateParam(jets_[bestcomb_[2]] + jets_[bestcomb_[3]])
        top1.UpdateParam(jets_[bestcomb_[0]] + jets_[bestcomb_[3]] +
                         jets_[bestcomb_[2]])
        w2.UpdateParam(jets_[bestcomb_[5]] + jets_[bestcomb_[4]])
        top2.UpdateParam(jets_[bestcomb_[1]] + jets_[bestcomb_[4]] +
                         jets_[bestcomb_[5]])
        tt.UpdateParam(jets_[bestcomb_[0]] + jets_[bestcomb_[1]] +
                       jets_[bestcomb_[2]] + jets_[bestcomb_[3]] +
                       jets_[bestcomb_[4]] + jets_[bestcomb_[5]])

        #print 'nominal'
        #mytree.Print(useQCD)
        mytree.variables['BDT_CWoLa'][0] = readerQCD.EvaluateMVA("BDT_QCD")

        return 1
    else:
        return 0
Пример #9
0
def get_sys(input_h5_name):
    input_h5 = h5py.File(input_h5_name, 'r')

    print(list(input_h5.keys()))
    print(list(input_h5['Histo1D'].keys()))
    # print(input_h5[h1d_keyname+'/|MC_GENERIC|Pt'][:])
    # for key in input_h5.keys():
    #     print(key)

    observables = []
    for key_name in all_data_keynames:
        values = input_h5[key_name]
        for value in values:
            observables.append(value)
    print("total {} observables".format(len(observables)))

    variations = input_h5[variation_keyname]
    n_variations = len(variations)
    print("total {} variations".format(n_variations))
    # print(variations[:])
    # return

    binids = input_h5[binid_keyname]
    print(binids.shape)
    print(binids[0])
    n_bins = len(binids)
    print("total {} bins".format(n_bins))

    nominal_pdf_id = find_nomial_pdfid(input_h5)
    nominal_pdf_name = pset_name(nominal_pdf_id)
    scale_sys_name = "QCDScales"

    n_exp_internal_pdf_vars = -1
    pdfs_variations = collections.defaultdict(lambda: 0)
    sys_variation_idx = collections.defaultdict(list)

    for idx, variation in enumerate(variations):
        if "MUR1_MUF1" in variation:
            pdf_id = get_pdf_id(variation)
            pdf_name = pset_name(pdf_id)
            pdfs_variations[pdf_name] += 1
            sys_variation_idx[pdf_name].append(idx)

        if str(nominal_pdf_id) in variation:
            sys_variation_idx[scale_sys_name].append(idx)

    print("nominal PDF:", nominal_pdf_name)
    n_external_pdfs = 0
    for key, value in pdfs_variations.items():
        print("{}: {} variations".format(key, value))
        print("\t", sys_variation_idx[key])
        if key != nominal_pdf_name:
            n_external_pdfs += 1
    print("{} external PDFs".format(n_external_pdfs))

    install_pdfs(list(pdfs_variations.keys()))
    pset = lhapdf.getPDFSet(nominal_pdf_name)
    pdfs_ = pset.mkPDFs()
    n_exp_internal_pdf_vars = len(pdfs_)

    # evaluate the PDF sys
    obs_values = get_obs_values(input_h5)
    pdf_sys = np.full((n_bins, 3), fill_value=invalid_number, dtype=np.float32)
    nominal_pdf = lhapdf.getPDFSet(nominal_pdf_name)
    cl = 68
    internal_pdf_sys = np.apply_along_axis(
        lambda x: nominal_pdf.uncertainty(
            x[sys_variation_idx[nominal_pdf_name]], cl).errsymm, 1, obs_values)
    print(internal_pdf_sys[1])
    print(internal_pdf_sys.shape)
    # external PDF sets
    external_pdf_values = np.zeros((n_bins, n_external_pdfs + 1),
                                   dtype=np.float32)
    inorm = -1
    idx = 0
    for key, value in pdfs_variations.items():
        print(key, value)
        if key == nominal_pdf_name:
            inorm = idx
        if value > 1:
            this_pdf = lhapdf.getPDFSet(key)
            external_pdf_values[:, idx] = np.apply_along_axis(
                lambda x: this_pdf.uncertainty(x[sys_variation_idx[key]], cl).
                central, 1, obs_values)
        else:
            external_pdf_values[:, idx] = obs_values[:,
                                                     sys_variation_idx[key][0]]
        idx += 1

    external_diff = external_pdf_values - external_pdf_values[:,
                                                              inorm].reshape(
                                                                  -1, 1)
    # print(np.any(np.nonzero(external_diff[:, inorm])))
    external_pdf_sys = np.amax(external_diff, axis=1)
    pdf_sys[:, 0] = internal_pdf_sys
    pdf_sys[:, 1] = external_pdf_sys
    pdf_sys[:, 2] = np.amax(pdf_sys[:, 0:2], axis=1)

    scale_diff = obs_values[:, sys_variation_idx[
        scale_sys_name]] - obs_values[:, 0].reshape(-1, 1)
    scale_sys = np.amax(scale_diff, axis=1)

    out_file = h5py.File("Rivet_pdfsys.h5", 'w')
    out_file.create_dataset("pdfsys", data=pdf_sys, dtype=np.float32)
    out_file.create_dataset("scalesys", data=scale_sys, dtype=np.float32)
    out_file.close()

    input_h5.close()
Пример #10
0
def lhapdf_xfs(pdf_name, xs, flavors, Q2):
    pdf_information = lhapdf.getPDFSet(pdf_name)
    n_xs = len(xs)
    Q = np.sqrt(Q2)

    if (pdf_information.errorType == 'hessian') or (pdf_information.errorType
                                                    == 'symmhessian'):
        ## 'lhapdf.getPDFSet("ABMP16_3_nlo").errorType' is 'symmhessian'
        pdf_0 = lhapdf.mkPDF(pdf_name, 0)
        xfs = {}
        for flavor in flavors:
            xfs[flavor] = {
                'center': np.zeros(n_xs),
                'difference': np.zeros(n_xs)
            }
        for i in range(1, ((pdf_information.size - 1) / 2) + 1):
            pdf_plus = lhapdf.mkPDF(pdf_name, 2 * i)
            pdf_minus = lhapdf.mkPDF(pdf_name, 2 * i - 1)
            for j in range(n_xs):
                for flavor in flavors:
                    if flavor == 'uv':
                        xfs[flavor]['center'][j] = pdf_0.xfxQ(
                            2, xs[j], Q) - pdf_0.xfxQ(-2, xs[j], Q)
                        xfs[flavor]['difference'][j] += (
                            pdf_plus.xfxQ(2, xs[j], Q) -
                            pdf_plus.xfxQ(-2, xs[j], Q) -
                            (pdf_minus.xfxQ(2, xs[j], Q) -
                             pdf_minus.xfxQ(-2, xs[j], Q)))**2.0
                    elif flavor == 'dv':
                        xfs[flavor]['center'][j] = pdf_0.xfxQ(
                            1, xs[j], Q) - pdf_0.xfxQ(-1, xs[j], Q)
                        xfs[flavor]['difference'][j] += (
                            pdf_plus.xfxQ(1, xs[j], Q) -
                            pdf_plus.xfxQ(-1, xs[j], Q) -
                            (pdf_minus.xfxQ(1, xs[j], Q) -
                             pdf_minus.xfxQ(-1, xs[j], Q)))**2.0
                    elif flavor == 'u':
                        xfs[flavor]['center'][j] = pdf_0.xfxQ(2, xs[j], Q)
                        xfs[flavor]['difference'][j] += (
                            pdf_plus.xfxQ(2, xs[j], Q) -
                            pdf_minus.xfxQ(2, xs[j], Q))**2.0
                    elif flavor == 'd':
                        xfs[flavor]['center'][j] = pdf_0.xfxQ(1, xs[j], Q)
                        xfs[flavor]['difference'][j] += (
                            pdf_plus.xfxQ(1, xs[j], Q) -
                            pdf_minus.xfxQ(1, xs[j], Q))**2.0
                    elif flavor == 'd/u':
                        xfs[flavor]['center'][j] = pdf_0.xfxQ(
                            1, xs[j], Q) / pdf_0.xfxQ(2, xs[j], Q)
                        xfs[flavor]['difference'][j] += (
                            (pdf_plus.xfxQ(1, xs[j], Q) -
                             pdf_minus.xfxQ(1, xs[j], Q)) /
                            pdf_0.xfxQ(2, xs[j], Q))**2.0
                    elif flavor == 'db+ub':
                        xfs[flavor]['center'][j] = pdf_0.xfxQ(
                            -1, xs[j], Q) + pdf_0.xfxQ(-2, xs[j], Q)
                        xfs[flavor]['difference'][j] += (
                            pdf_plus.xfxQ(-1, xs[j], Q) +
                            pdf_plus.xfxQ(-2, xs[j], Q) -
                            (pdf_minus.xfxQ(-1, xs[j], Q) +
                             pdf_minus.xfxQ(-2, xs[j], Q)))**2.0
                    elif flavor == 'db-ub':
                        xfs[flavor]['center'][j] = pdf_0.xfxQ(
                            -1, xs[j], Q) - pdf_0.xfxQ(-2, xs[j], Q)
                        xfs[flavor]['difference'][j] += (
                            pdf_plus.xfxQ(-1, xs[j], Q) -
                            pdf_plus.xfxQ(-2, xs[j], Q) -
                            (pdf_minus.xfxQ(-1, xs[j], Q) -
                             pdf_minus.xfxQ(-2, xs[j], Q)))**2.0
                    elif flavor == 's+sb':
                        xfs[flavor]['center'][j] = pdf_0.xfxQ(
                            3, xs[j], Q) + pdf_0.xfxQ(-3, xs[j], Q)
                        xfs[flavor]['difference'][j] += (
                            pdf_plus.xfxQ(3, xs[j], Q) +
                            pdf_plus.xfxQ(-3, xs[j], Q) -
                            (pdf_minus.xfxQ(3, xs[j], Q) +
                             pdf_minus.xfxQ(-3, xs[j], Q)))**2.0
                    elif flavor == 'g':
                        xfs[flavor]['center'][j] = pdf_0.xfxQ(21, xs[j], Q)
                        xfs[flavor]['difference'][j] += (
                            pdf_plus.xfxQ(21, xs[j], Q) -
                            pdf_minus.xfxQ(21, xs[j], Q))**2.0
                    elif flavor == 'rs':
                        if pdf_name == 'CJ15nlo':
                            ## R_s is set to be 0.4 in CJ15
                            xfs[flavor]['center'][j] = 0.4
                            xfs[flavor]['difference'][j] += 0.0
                        else:
                            xfs[flavor]['center'][j] = (pdf_0.xfxQ(
                                3, xs[j], Q) + pdf_0.xfxQ(-3, xs[j], Q)) / (
                                    pdf_0.xfxQ(-1, xs[j], Q) +
                                    pdf_0.xfxQ(-2, xs[j], Q))
                            xfs[flavor]['difference'][j] += ((pdf_plus.xfxQ(3, xs[j], Q) + pdf_plus.xfxQ(-3, xs[j], Q) - (pdf_minus.xfxQ(3, xs[j], Q) + pdf_minus.xfxQ(-3, xs[j], Q))) / \
                                (pdf_0.xfxQ(-1, xs[j], Q) + pdf_0.xfxQ(-2, xs[j], Q))) ** 2.0

        for flavor in flavors:
            xfs[flavor]['difference'] = 0.5 * np.sqrt(
                xfs[flavor]['difference'])

    elif pdf_information.errorType == 'replicas':
        pdf_all = lhapdf.mkPDFs(pdf_name)

        xfs = {}
        xfs_temp = {}
        for flavor in flavors:
            xfs[flavor] = {'center': [], 'difference': []}
        for i in range(n_xs):
            for flavor in flavors:
                xfs_temp[flavor] = []
            for pdf_individual in pdf_all:
                for flavor in flavors:
                    if flavor == 'uv':
                        xfs_temp[flavor].append(
                            pdf_individual.xfxQ(2, xs[i], Q) -
                            pdf_individual.xfxQ(-2, xs[i], Q))
                    elif flavor == 'dv':
                        xfs_temp[flavor].append(
                            pdf_individual.xfxQ(1, xs[i], Q) -
                            pdf_individual.xfxQ(-1, xs[i], Q))
                    elif flavor == 'u':
                        xfs_temp[flavor].append(
                            pdf_individual.xfxQ(2, xs[i], Q))
                    elif flavor == 'd':
                        xfs_temp[flavor].append(
                            pdf_individual.xfxQ(1, xs[i], Q))
                    elif flavor == 'd/u':
                        xfs_temp[flavor].append(
                            pdf_individual.xfxQ(1, xs[i], Q) /
                            pdf_individual.xfxQ(2, xs[i], Q))
                    elif flavor == 'db+ub':
                        xfs_temp[flavor].append(
                            pdf_individual.xfxQ(-1, xs[i], Q) +
                            pdf_individual.xfxQ(-2, xs[i], Q))
                    elif flavor == 'db-ub':
                        xfs_temp[flavor].append(
                            pdf_individual.xfxQ(-1, xs[i], Q) -
                            pdf_individual.xfxQ(-2, xs[i], Q))
                    elif flavor == 's+sb':
                        xfs_temp[flavor].append(
                            pdf_individual.xfxQ(3, xs[i], Q) +
                            pdf_individual.xfxQ(-3, xs[i], Q))
                    elif flavor == 'g':
                        xfs_temp[flavor].append(
                            pdf_individual.xfxQ(21, xs[i], Q))
                    elif flavor == 'rs':
                        xfs_temp[flavor].append(
                            (pdf_individual.xfxQ(3, xs[i], Q) +
                             pdf_individual.xfxQ(-3, xs[i], Q)) /
                            (pdf_individual.xfxQ(-1, xs[i], Q) +
                             pdf_individual.xfxQ(-2, xs[i], Q)))

            for flavor in flavors:
                xfs[flavor]['center'].append(np.mean(xfs_temp[flavor], axis=0))
                xfs[flavor]['difference'].append(
                    np.std(xfs_temp[flavor], axis=0))

        for flavor in flavors:
            xfs[flavor]['center'] = np.array(xfs[flavor]['center'])
            xfs[flavor]['difference'] = np.array(xfs[flavor]['difference'])

    return xfs
Пример #11
0
 def __missing__(self, key):
     el = self[key] = lhapdf.getPDFSet(key)
     return el
Пример #12
0
#! /usr/bin/env python

## Python LHAPDF6 usage example for PDF uncertainty code (G. Watt, 24/04/2014).
## Extended in July 2015 for ErrorType values ending in "+as".
## Modified in September 2015 for more general ErrorType values:
## number of parameter variations determined by counting "+" symbols.

from __future__ import print_function, division
import lhapdf

x = 0.1
q = 100.0
pset = lhapdf.getPDFSet("CT10nnlo")  # ErrorType: hessian
#pset = lhapdf.getPDFSet("abm12lhc_5_nnlo") # ErrorType: symmhessian
#pset = lhapdf.getPDFSet("NNPDF30_nnlo_as_0118") # ErrorType: replicas
#pset = lhapdf.getPDFSet("NNPDF30_nnlo_nf_5_pdfas") # ErrorType: replicas+as
pdfs = pset.mkPDFs()
nmem = pset.size - 1

print()
print("Error type = ", pset.errorType)
print("Error conf level = ", pset.errorConfLevel)
print()

npar = pset.errorType.count(
    "+")  # number of parameter variations (alphaS, etc.)
if npar > 0:
    print("Last %d members are parameter variations\n" % (2 * npar))

## Fill vectors xgAll and xuAll using all PDF members.
xgAll = [0.0 for i in range(pset.size)]
"CITo2Mu_Lam40TeVConLL_M800to1300" : 0.014510,
"CITo2Mu_Lam40TeVConLR_M800to1300" : 0.014520,
"CITo2Mu_Lam40TeVConRR_M800to1300" : 0.014540,
"CITo2Mu_Lam40TeVDesLL_M800to1300" : 0.013790,
"CITo2Mu_Lam40TeVDesLR_M800to1300" : 0.013730,
"CITo2Mu_Lam40TeVDesRR_M800to1300" : 0.013750,

'2016_CITo2Mu_Lam16TeVDesRR_M300':0.550000,
'2016_CITo2Mu_Lam16TeVDesRR_M800':0.013670,
'2016_CITo2Mu_Lam16TeVDesRR_M1300':0.002403,
'2016_CITo2Mu_Lam16TeVConRR_M300':0.583500,
'2016_CITo2Mu_Lam16TeVConRR_M800':0.019120,
'2016_CITo2Mu_Lam16TeVConRR_M1300':0.003939,
}

pdfsetRef = lhapdf.getPDFSet("NNPDF31_nnlo_as_0118")
pdfset31LO = lhapdf.getPDFSet("NNPDF31_lo_as_0118")
pdfset31LO13 = lhapdf.getPDFSet("NNPDF31_lo_as_0130")
pdfset30NNLO = lhapdf.getPDFSet("NNPDF30_nnlo_as_0118")
pdfset30LO = lhapdf.getPDFSet("NNPDF30_lo_as_0118")
pdfset30LO13 = lhapdf.getPDFSet("NNPDF30_lo_as_0130")
pdfset23LO = lhapdf.getPDFSet("NNPDF23_lo_as_0130_qed")
# ~ print (pdfset.description)
pdfReplicasRef = pdfsetRef.mkPDFs()
pdfReplicas31LO = pdfset31LO.mkPDFs()
pdfReplicas31LO13 = pdfset31LO13.mkPDFs()
pdfReplicas30LO = pdfset30LO.mkPDFs()
pdfReplicas30LO13 = pdfset30LO13.mkPDFs()
pdfReplicas30NNLO = pdfset30NNLO.mkPDFs()
pdfReplicas23LO = pdfset23LO.mkPDFs()
Пример #14
0
    w    = 0.00407   #Higgs total decay width
#   w    = 0.00374   #Higgs total decay width
    Ncg  = 8         #Number of colors for gluon
    Nsg  = 2         #Number of spin projections for gluon

    E = sqrt(shat)  
    bw  = 1./Ncg**2 * 1./Nsg**2 *  16*pi/shat *  w**2/4/( (E-mH)**2 + w**2/4) * Bin * Bout
    bw *= 2   #magic factor due to identical gluons

    return bw * ge2mb

# Define PDF to be used

name = "MRST2007lomod"	
name = "MRST2004qed_proton"	
pdf = lhapdf.getPDFSet(name).mkPDF(0)

# Define histograms to be filed, `dmH` half of the generated mass widht, `dy` is half of the rapidity interval of the interest

dmH = 0.100
dy = 5
hEta  = TH1D("eta", "Eta of H", 20, -dy, dy)
hMass = TH1D("mass", "Mass of H", 61, mH-dmH, mH+dmH)

# Define the beam energy of the protons

Eb = 6500

# Define the number of points to be generated

npoints = 1200000
Пример #15
0
#! /usr/bin/env python

## Python LHAPDF6 usage example for PDF uncertainty code (G. Watt, 24/04/2014)

import lhapdf

x = 0.1
q = 100.0
pset = lhapdf.getPDFSet("CT10nnlo")
#pset = lhapdf.getPDFSet("NNPDF23_nnlo_as_0118")
pdfs = pset.mkPDFs()
nmem = pset.size - 1

print
print "Error type = ", pset.errorType
print "Error conf level = ", pset.errorConfLevel

## Fill vectors xgAll and xuAll using all PDF members.
xgAll = [0.0 for i in xrange(pset.size)]
xuAll = [0.0 for i in xrange(pset.size)]
for imem in xrange(pset.size):
    xgAll[imem] = pdfs[imem].xfxQ(21, x, q)
    xuAll[imem] = pdfs[imem].xfxQ(2, x, q)
    # print imem, xgAll[imem], xuAll[imem]

## Calculate 1-sigma PDF uncertainty on gluon distribution.
unc = pset.uncertainty(xgAll)
print "xg = %.4g + %.4g - %.4g (+- %.4g)" % (unc.central, unc.errplus, unc.errminus, unc.errsymm)
print "Scale = %.4g" % unc.scale

## Calculate 1-sigma PDF uncertainty on up-quark distribution.
Пример #16
0
@author: hkaveh
"""

import nuSolutions as nu
import ROOT as r
import lhapdf
import numpy as np
import math
from operator import itemgetter
print lhapdf.version()
lhapdf.pathsPrepend("/home/hkaveh/")
print lhapdf.availablePDFSets()
print lhapdf.paths()

pset = lhapdf.getPDFSet('NNPDF23_nlo_as_0118')
print pset.description
p = lhapdf.mkPDF('NNPDF23_nlo_as_0118')
def get_dalitz_prob(lep,top,mb,mw):
    mte = lep.Dot( top );
    mt = top.M();
    mt2 = mt * mt;
    mb2 = mb * mb;
    mw2 = mw * mw;
    mt2_mb2 = mt2 - mb2;

    return 4. * mt*lep.E() * ( mt2 - mb2 - 2. * mt*lep.E() ) /( mt2_mb2 * mt2_mb2 + mw2 * ( mt2 - mb2 ) - 2. * mw2 * mw2 )

def getweight(lep_p,lep_m,nu1,nu2,bquark1,bquark2):
    
    t1 = lep_p + nu1 + bquark1;
Пример #17
0
def MeasureNominal(t, mytree, pass_sys):
    bpos_ = []
    jetpos_ = []
    jets_ = ROOT.vector('TLorentzVector')()
    ordered_jets_ = ROOT.vector('TLorentzVector')()
    bestcomb_ = []
    corrcomb_ = []
    corrb_ = []
    corrlight_ = []
    if (t.njets >= 7 and t.nBCSVM >= 2) or pass_sys:
        if sample != 'data':
            mytree.variables['weight'][0] = np.sign(t.genWeight)
            mytree.variables['puweight'][0] = t.puWeight
            mytree.variables['puweight_Up'][0] = t.puWeightUp
            mytree.variables['puweight_Down'][0] = t.puWeightDown

            mytree.variables['trigweight'][0] = t.triggerWeight
            mytree.variables['trigweight_Up'][0] = t.triggerWeightUp
            mytree.variables['trigweight_Down'][0] = t.triggerWeightDown
            mytree.variables['btagweight'][0] = t.btagWeightCSV
            mytree.variables['qgweight'][0] = t.qgWeight
            mytree.variables['qgweight_Up'][0] = 2 * t.qgWeight - 1
            mytree.variables['qgweight_Down'][0] = 1.0
            mytree.variables['btagweight_jesPileUpPtBB_Down'][
                0] = t.btagWeightCSV_down_jesPileUpPtBB
            mytree.variables['btagweight_jesFlavorQCD_Down'][
                0] = t.btagWeightCSV_down_jesFlavorQCD
            mytree.variables['btagweight_jesAbsoluteScale_Down'][
                0] = t.btagWeightCSV_down_jesAbsoluteScale
            mytree.variables['btagweight_jesPileUpPtRef_Down'][
                0] = t.btagWeightCSV_down_jesPileUpPtRef
            mytree.variables['btagweight_jesRelativeFSR_Down'][
                0] = t.btagWeightCSV_down_jesRelativeFSR
            mytree.variables['btagweight_jesTimePtEta_Down'][
                0] = t.btagWeightCSV_down_jesTimePtEta
            mytree.variables['btagweight_hf_Down'][0] = t.btagWeightCSV_down_hf
            mytree.variables['btagweight_cferr1_Down'][
                0] = t.btagWeightCSV_down_cferr1
            mytree.variables['btagweight_cferr2_Down'][
                0] = t.btagWeightCSV_down_cferr2
            mytree.variables['btagweight_jes_Down'][
                0] = t.btagWeightCSV_down_jes
            mytree.variables['btagweight_jesAbsoluteMPFBias_Down'][
                0] = t.btagWeightCSV_down_jesAbsoluteMPFBias
            mytree.variables['btagweight_lf_Down'][0] = t.btagWeightCSV_down_lf
            mytree.variables['btagweight_jesPileUpPtEC1_Down'][
                0] = t.btagWeightCSV_down_jesPileUpPtEC1
            mytree.variables['btagweight_lfstats2_Down'][
                0] = t.btagWeightCSV_down_lfstats2
            mytree.variables['btagweight_lfstats1_Down'][
                0] = t.btagWeightCSV_down_lfstats1
            mytree.variables['btagweight_hfstats2_Down'][
                0] = t.btagWeightCSV_down_hfstats2
            mytree.variables['btagweight_hfstats1_Down'][
                0] = t.btagWeightCSV_down_hfstats1
            mytree.variables['btagweight_jesPileUpDataMC_Down'][
                0] = t.btagWeightCSV_down_jesPileUpDataMC

            mytree.variables['btagweight_jesPileUpPtBB_Up'][
                0] = t.btagWeightCSV_up_jesPileUpPtBB
            mytree.variables['btagweight_jesFlavorQCD_Up'][
                0] = t.btagWeightCSV_up_jesFlavorQCD
            mytree.variables['btagweight_jesAbsoluteScale_Up'][
                0] = t.btagWeightCSV_up_jesAbsoluteScale
            mytree.variables['btagweight_jesPileUpPtRef_Up'][
                0] = t.btagWeightCSV_up_jesPileUpPtRef
            mytree.variables['btagweight_jesRelativeFSR_Up'][
                0] = t.btagWeightCSV_up_jesRelativeFSR
            mytree.variables['btagweight_jesTimePtEta_Up'][
                0] = t.btagWeightCSV_up_jesTimePtEta
            mytree.variables['btagweight_hf_Up'][0] = t.btagWeightCSV_up_hf
            mytree.variables['btagweight_cferr1_Up'][
                0] = t.btagWeightCSV_up_cferr1
            mytree.variables['btagweight_cferr2_Up'][
                0] = t.btagWeightCSV_up_cferr2
            mytree.variables['btagweight_jes_Up'][0] = t.btagWeightCSV_up_jes
            mytree.variables['btagweight_jesAbsoluteMPFBias_Up'][
                0] = t.btagWeightCSV_up_jesAbsoluteMPFBias
            mytree.variables['btagweight_lf_Up'][0] = t.btagWeightCSV_up_lf
            mytree.variables['btagweight_jesPileUpPtEC1_Up'][
                0] = t.btagWeightCSV_up_jesPileUpPtEC1
            mytree.variables['btagweight_lfstats2_Up'][
                0] = t.btagWeightCSV_up_lfstats2
            mytree.variables['btagweight_lfstats1_Up'][
                0] = t.btagWeightCSV_up_lfstats1
            mytree.variables['btagweight_hfstats2_Up'][
                0] = t.btagWeightCSV_up_hfstats2
            mytree.variables['btagweight_hfstats1_Up'][
                0] = t.btagWeightCSV_up_hfstats1
            mytree.variables['btagweight_jesPileUpDataMC_Up'][
                0] = t.btagWeightCSV_up_jesPileUpDataMC
            mytree.variables['LHEPDFweight'][0] = 1.0
            mytree.variables['LHE_factweight'][0] = 1.0
            mytree.variables['LHE_renormweight'][0] = 1.0

        else:
            mytree.variables['weight'][0] = 1

        ntopjets = ntoptaggedjets = 0
        if sample == 'ttbar':
            nnpdfSet = lhapdf.getPDFSet("NNPDF30_nlo_as_0118")
            pdfset = [1.0]
            mytree.variables['LHE_factweight_Up'][0] = t.LHE_weights_scale_wgt[
                0]
            mytree.variables['LHE_factweight_Down'][
                0] = t.LHE_weights_scale_wgt[1]
            mytree.variables['LHE_renormweight_Up'][
                0] = t.LHE_weights_scale_wgt[2]
            mytree.variables['LHE_renormweight_Down'][
                0] = t.LHE_weights_scale_wgt[3]
            #for nlhe in range(t.nLHE_weights_scale):
            #      mytree.variables['LHE_scale'][nlhe]=t.LHE_weights_scale_wgt[nlhe]

            for nlhe in range(t.nLHE_weights_pdf - 2):
                pdfset.append(t.LHE_weights_pdf_wgt[nlhe])

            pdfUnc = nnpdfSet.uncertainty(pdfset)

            mytree.variables['LHEPDFweight_Up'][
                0] = pdfUnc.central + pdfUnc.errplus
            mytree.variables['LHEPDFweight_Down'][
                0] = pdfUnc.central - pdfUnc.errminus

        mytree.variables['nPVs'][0] = t.nPVs
        mytree.variables['sphericity'][0] = t.sphericity
        mytree.variables['C'][0] = t.C
        mytree.variables['minjetpt'][0] = t.jets_pt[t.njets - 1]

        mytree.variables['jets_dRavg'][0] = sum(t.jets_dRave) / t.njets
        drmin_list = [x for x in t.jets_dRmin if x > 0]
        if len(drmin_list) > 0:
            mytree.variables['jets_dRmin'][0] = min(
                [x for x in t.jets_dRmin if x > 0])
        else:
            mytree.variables['jets_dRmin'][0] = 0
        mytree.variables['jets_dRmax'][0] = max(t.jets_dRmax)
        if sample == 'QCD': mytree.variables['isQCD'][0] = 1
        else: mytree.variables['isQCD'][0] = 0

        #mytree.variables['girth'][0] = ptR/(t.ht)**2
        if 'ttbar' in sample or 'theory' in sample:
            mytree.variables['ttCls'][0] = t.ttCls
        else:
            mytree.variables['ttCls'][0] = -1
        mytree.variables['ht'][0] = t.ht
        #mytree.variables['all_mass'][0] = t.invmass
        #mytree.variables['closest_mass'][0] = t.mjjmin
        mytree.variables['jet5pt'][0] = t.jets_pt[5]
        mytree.variables['n_jets'][0] = t.njets
        mytree.variables['n_bjets'][0] = t.nBCSVM
        mytree.variables['n_addJets'][0] = t.njets - 6
        #mytree.variables['n_topjets'][0] = ntopjets
        mytree.variables['qgLR'][0] = -100
        mytree.variables['centrality'][0] = t.centrality
        mytree.variables['aplanarity'][0] = t.aplanarity
        mytree.variables['meanDeltaRbtag'][0] = t.mean_dr_btag
        mytree.variables['meanCSVbtag'][0] = t.mean_bdisc
        mytree.variables['meanCSV'][0] = t.mean_bdisc_btag
        mytree.variables['btagLR3b'][0] = t.btag_LR_3b_2b_btagCSV
        mytree.variables['btagLR4b'][0] = t.btag_LR_4b_2b_btagCSV
        mytree.variables['nBCSVM'][0] = t.nBCSVM
        mytree.variables['chi2'][0] = t.chi2
        mytree.variables['prob_chi2'][0] = TMath.Prob(t.chi2, 4)

        qgLR3b = t.qg_LR_3b_flavour_4q_0q
        qgLR4b = t.qg_LR_4b_flavour_4q_0q

        if t.nBCSVM == 3:
            mytree.variables['qgLR'][0] = qgLR3b
            # if t.mem_ttbb_FH_4w2h1t_p  > 0: mytree.variables['memttbb'][0] = -TMath.Log10(t.mem_ttbb_FH_4w2h1t_p)
            # else: mytree.variables['memttbb'][0] = -10
            # #print mytree.variables['memttbb'][0]
            # if nljets == 4:
            #       mytree.variables['qgLR'][0] = t.qg_LR_3b_flavour_4q_0q
            # elif nljets >= 5:
            #       mytree.variables['qgLR'][0] = t.qg_LR_3b_flavour_5q_0q
        if t.nBCSVM >= 4:
            mytree.variables['qgLR'][0] = qgLR4b
            # if t.mem_ttbb_FH_4w2h2t_p  > 0: mytree.variables['memttbb'][0] = -TMath.Log10(t.mem_ttbb_FH_4w2h2t_p)
            # else: mytree.variables['memttbb'][0] = -10
            # #print mytree.variables['memttbb'][0]
            # if nljets == 4: mytree.variables['qgLR'][0] = t.qg_LR_4b_flavour_4q_0q
            # elif nljets >= 5: mytree.variables['qgLR'][0] = t.qg_LR_4b_flavour_5q_0q
        else:
            # mytree.variables['memttbb'][0] = -TMath.Log10(t.mem_ttbb_FH_4w2h1t_p) if t.mem_ttbb_FH_4w2h1t_p >0 else -10
            mytree.variables['qgLR'][0] = qgLR3b

        if sample != 'ttH':
            tthcut = t.json and (t.HLT_ttH_FH or t.HLT_BIT_HLT_PFJet450_v
                                 ) and t.ht > 500 and t.jets_pt[5] > 40
        else:
            tthcut = t.json and (
                t.HLT_ttH_FH) and t.ht > 500 and t.jets_pt[5] > 40

        mytree.variables['hasCorrect'][0] = -1
        printing = 0
        highest = 0
        bestcat = 0
        #print comb_, 'comb_'
        meanBDTttbar = sumprob = 0
        maxbdt = 0

        # print 'start comb'
        # watch.Print()

        if 'ttbar' in sample:
            for itophad in range(t.ngenTopHad):
                mytree.variables['genTopHad_pt'][itophad] = t.genTopHad_pt[
                    itophad]
            mytree.variables['topweight'][0] = np.exp(
                0.5 * (t.ngenTopLep * 0.0843616 - 0.000743051 *
                       np.sum(t.genTopLep_pt) + t.ngenTopHad * 0.0843616 -
                       0.000743051 * np.sum(t.genTopHad_pt))) * (t.jets_pt[0] /
                                                                 t.jets_pt[0])
            mytree.variables['topweight_Up'][0] = np.exp(0.5 * (
                t.ngenTopLep * 0.00160296 - 0.000411375 * sum(t.genTopLep_pt) +
                t.ngenTopHad * 0.00160296 - 0.000411375 * sum(t.genTopHad_pt)))
            mytree.variables['topweight_Down'][0] = np.exp(
                0.5 *
                (t.ngenTopLep * 0.16712 - 0.00107473 * sum(t.genTopLep_pt) +
                 t.ngenTopHad * 0.16712 - 0.00107473 * sum(t.genTopHad_pt)))
        if not (t.njets >= 7 and t.nBCSVM >= 2 and tthcut): return 0
        mytree.variables['BDT_CWoLa'][0] = t.CWoLa_BDT
        mytree.variables['BDT_Comb'][0] = t.perm_BDT
        return 1
    else:
        return 0
Пример #18
0
import lhapdf

## Getting a PDF member object
p = lhapdf.mkPDF("CT10", 0)
p = lhapdf.mkPDF("CT10/0")

## Gluon PDF querying at x=0.001, Q2=10000
print(p.xfxQ2(21, 1e-3, 1e4))

## Basic all-flavour PDF querying at x=0.01, Q=M_Z
for pid in p.flavors():
    print(p.xfxQ(pid, 0.01, 91.2))

# TODO: demonstrate looping over PDF set members
pset = lhapdf.getPDFSet("CT10nlo")
print(pset.description)
pcentral = pset.mkPDF(0)
pdfs1 = pset.mkPDFs()
pdfs2 = lhapdf.mkPDFs("CT10nlo")  # a direct way to get all the set's PDFs

## Filling a numpy 2D array with xf(x,Q) samples
import numpy as np
xs = [x for x in np.logspace(-7, 0, 5)]
qs = [q for q in np.logspace(1, 4, 4)]
gluon_xfs = np.empty([len(xs), len(qs)])
for ix, x in enumerate(xs):
    for iq, q in enumerate(qs):
        gluon_xfs[ix, iq] = p.xfxQ(21, x, q)
print(gluon_xfs)