示例#1
0
def filler( event ):
    # shortcut
    r = reader.event

    event.isData = isData
    event.year   = options.year
    event.lumi   = lumi

    if isMC:

        # weight
        event.weight = lumiScaleFactor*r.genWeight if lumiScaleFactor is not None else 0
        #print event.weight, lumiScaleFactor*r.genWeight, sample.xSection, sample.normalization

        # PU reweighting
        event.reweightPU      = nTrueInt_puRW     ( r.Pileup_nTrueInt )
        event.reweightPUDown  = nTrueInt_puRWDown ( r.Pileup_nTrueInt )
        event.reweightPUUp    = nTrueInt_puRWUp   ( r.Pileup_nTrueInt )

        # GEN Particles
        gPart = getParticles( r, collVars=readGenVarList,    coll="GenPart" )
        gJets = getParticles( r, collVars=readGenJetVarList, coll="GenJet" )

        gPart.sort( key = lambda p: -p['pt'] )
        gJets.sort( key = lambda p: -p['pt'] )

        # Overlap removal flags for ttgamma/ttbar and Zgamma/DY
        GenPhoton                  = filterGenPhotons( gPart, status='all' )

        # OR ttgamma/tt
        GenIsoPhotonTTG            = filter( lambda g: isIsolatedPhoton( g, gPart, coneSize=0.1,  ptCut=5, excludedPdgIds=[12,-12,14,-14,16,-16] ), GenPhoton    )
        GenIsoPhotonNoMesonTTG     = filter( lambda g: not hasMesonMother( getParentIds( g, gPart ) ), GenIsoPhotonTTG )

        # OR DY/ZG, WG/WJets
        GenIsoPhoton               = filter( lambda g: isIsolatedPhoton( g, gPart, coneSize=0.05,  ptCut=5, excludedPdgIds=[12,-12,14,-14,16,-16] ), GenPhoton    )
        GenIsoPhotonNoMeson        = filter( lambda g: not hasMesonMother( getParentIds( g, gPart ) ), GenIsoPhoton )

        # OR singleT/tG
        GenIsoPhotonNoMesonTG      = filter( lambda g: not photonFromTopDecay( getParentIds( g, gPart ) ), GenIsoPhotonNoMeson )

        # OR GJets/QCD
        GenIsoPhotonGJets          = filter( lambda g: isIsolatedPhoton( g, gPart, coneSize=0.4,  ptCut=5, excludedPdgIds=[12,-12,14,-14,16,-16] ), GenPhoton    )
        GenIsoPhotonNoMesonGJets   = filter( lambda g: not hasMesonMother( getParentIds( g, gPart ) ), GenIsoPhotonGJets )

        event.isTTGamma = len( filter( lambda g: genPhotonSel_TTG_OR(g), GenIsoPhotonNoMesonTTG     ) ) > 0
        event.isZWGamma = len( filter( lambda g: genPhotonSel_ZG_OR(g),  GenIsoPhotonNoMeson        ) ) > 0
        event.isTGamma  = len( filter( lambda g: genPhotonSel_T_OR(g),   GenIsoPhotonNoMesonTG      ) ) > 0
        event.isGJets   = len( filter( lambda g: genPhotonSel_GJ_OR(g),  GenIsoPhotonNoMesonGJets   ) ) > 0

        # new OR flag: Apply overlap removal directly in pp to better handle the plots
        if options.flagTTGamma:
            event.overlapRemoval = event.isTTGamma     #good TTgamma event
        elif options.flagTTBar:
            event.overlapRemoval = not event.isTTGamma #good TTbar event
        elif options.flagZWGamma:
            event.overlapRemoval = event.isZWGamma     #good Zgamma, Wgamma event
        elif options.flagDYWJets:
            event.overlapRemoval = not event.isZWGamma #good DY, WJets event
        elif options.flagTGamma:
            event.overlapRemoval = event.isTGamma      #good TGamma event
        elif options.flagSingleTopTch:
            event.overlapRemoval = not event.isTGamma  #good singleTop t-channel event
        elif options.flagGJets:
            event.overlapRemoval = event.isGJets       #good gamma+jets event
        elif options.flagQCD:
            event.overlapRemoval = not event.isGJets   #good QCD event
        else:
            event.overlapRemoval = 1 # all other events

        event.jsonPassed  = 1

    elif isData:
        event.isTTGamma = 1
        event.isZWGamma = 1
        event.isTGamma  = 1
        event.isGJets   = 1
        event.overlapRemoval = 1 # all other events
        event.weight     = 1.
        event.reweightPU = 1
        # lumi lists and vetos
        event.jsonPassed  = lumiList.contains( r.run, r.luminosityBlock )
        # make data weight zero if JSON was not passed
        if not event.jsonPassed: event.weight = 0
        # store decision to use after filler has been executed
        event.jsonPassed_ = event.jsonPassed
    else:
        raise NotImplementedError( "isMC %r isData %r " % (isMC, isData) )

    # Photons
    allPhotons = getParticles( r, readPhotonVarList, coll="Photon" )
    allPhotons.sort( key = lambda g: -g['pt'] )
    convertUnits( allPhotons )

    for g in allPhotons:
        g['photonCat']      = -1
        g['photonCatMagic'] = -1
        g['leptonMother']   = -1
        g['mother']         = -1

    # Photons
    loosePhotons = list( filter( lambda g: g["pt"]>=10 and abs(g["eta"])<=2.5 and g["cutBased" if options.year == 2016 else "cutBasedBitmap"]>=1, allPhotons ) )
    event.nPhotonLoose            = len( loosePhotons )

    mediumPhotons = list( filter( lambda g: g["pt"]>=10 and abs(g["eta"])<=2.5 and g["cutBased" if options.year == 2016 else "cutBasedBitmap"]>=2, allPhotons ) )
    event.nPhotonMedium            = len( mediumPhotons )

    tightPhotons = list( filter( lambda g: g["pt"]>=10 and abs(g["eta"])<=2.5 and g["cutBased" if options.year == 2016 else "cutBasedBitmap"]>=3, allPhotons ) )
    event.nPhotonTight            = len( tightPhotons )

    MVAPhotons = list( filter( lambda g: g["pt"]>=10 and abs(g["eta"])<=2.5 and g["mvaID_WP80"], allPhotons ) )
    event.nPhotonMVA            = len( MVAPhotons )

    # Store analysis photons + default photons for a faster plot script
    p0, p1 = ( loosePhotons + [None,None] )[:2]
    fill_vector( event, "PhotonLoose0",  writePhotonVarList, p0 )

    p0, p1 = ( mediumPhotons + [None,None] )[:2]
    fill_vector( event, "PhotonMedium0",  writePhotonVarList, p0 )

    p0, p1 = ( tightPhotons + [None,None] )[:2]
    fill_vector( event, "PhotonTight0",  writePhotonVarList, p0 )

    p0, p1 = ( MVAPhotons + [None,None] )[:2]
    fill_vector( event, "PhotonMVA0",  writePhotonVarList, p0 )

    # Leptons
    allMuons = getParticles( r, readMuonVarList, coll="Muon" )
    allMuons.sort( key = lambda l: -l['pt'] )
    convertUnits( allMuons )

    tightMuons = list( filter( lambda l: l["pt"]>=10 and abs(l["eta"])<=2.4 and l["tightId"], allMuons ) )
    leadtightMuons = list( filter( lambda l: l["pt"]>=20, tightMuons ) )

    event.nMuonTight     = len(tightMuons)
    event.nLeadMuonTight = len(leadtightMuons)

    # Store analysis Muons + 2 default Muons for a faster plotscript
    lt0, lt1       = ( tightMuons       + [None,None] )[:2]
    # Semi-leptonic analysis
    fill_vector( event, "MuonTight0", writeMuonVarList, lt0 )
    fill_vector( event, "MuonTight1", writeMuonVarList, lt1 )

    # Jets
    allJets  = getParticles( r, collVars=readJetVarList, coll="Jet" )

    for j in allJets:
        j["isBJet"] = isBJet( j, tagger=tagger, year=options.year )
        j["isGood"] = 0 #not used
        j["clean"] = 0 #not used

    # Loose jets w/o pt/eta requirement
    goodJets = list( filter( lambda j: recoJetSel(j), allJets ) )
    goodJets = deltaRCleaning( goodJets, tightMuons, dRCut=0.4 )
    goodJets = deltaRCleaning( goodJets, mediumPhotons, dRCut=0.4 )

    event.nJetGood                = len(goodJets)

    # Store analysis jets + 2 default jets for a faster plotscript
    j0, j1       = ( goodJets + [None,None] )[:2]
    fill_vector( event, "JetGood0",  writeJetVarList, j0 )
    fill_vector( event, "JetGood1",  writeJetVarList, j1 )

    # bJets
    bJets    = list( filter( lambda x: x["isBJet"], goodJets ) )

    event.nBTagGood = len( bJets )

    # Store bJets + 2 default bjets for a faster plot script
    bj0, bj1 = ( list(bJets) + [None,None] )[:2]
    fill_vector( event, "Bj0", writeBJetVarList, bj0 )
    fill_vector( event, "Bj1", writeBJetVarList, bj1 )

    event.ht = sum( [ j['pt'] for j in goodJets ] )

    # variables w/ photons
    if len(loosePhotons) > 0:
        if goodJets:
            event.minGLJetdR = min( deltaR( loosePhotons[0], j ) for j in goodJets )
        if tightMuons:
            event.minGLLepdR = min( deltaR( loosePhotons[0], l ) for l in tightMuons )
        if len(tightMuons)>0:
            event.l0gLDR = deltaR( loosePhotons[0], tightMuons[0] )
        if len(tightMuons)>1:
            event.l1gLDR = deltaR( loosePhotons[0], tightMuons[1] )
            event.mllgL = ( get4DVec(tightMuons[0]) + get4DVec(tightMuons[1]) + get4DVec(loosePhotons[0]) ).M()

    if len(mediumPhotons) > 0:
        if goodJets:
            event.minGMJetdR = min( deltaR( mediumPhotons[0], j ) for j in goodJets )
        if tightMuons:
            event.minGMLepdR = min( deltaR( mediumPhotons[0], l ) for l in tightMuons )
        if len(tightMuons)>0:
            event.l0gMDR = deltaR( mediumPhotons[0], tightMuons[0] )
        if len(tightMuons)>1:
            event.l1gMDR = deltaR( mediumPhotons[0], tightMuons[1] )
            event.mllgM = ( get4DVec(tightMuons[0]) + get4DVec(tightMuons[1]) + get4DVec(mediumPhotons[0]) ).M()

    if len(tightPhotons) > 0:
        if goodJets:
            event.minGTJetdR = min( deltaR( tightPhotons[0], j ) for j in goodJets )
        if tightMuons:
            event.minGTLepdR = min( deltaR( tightPhotons[0], l ) for l in tightMuons )
        if len(tightMuons)>0:
            event.l0gTDR = deltaR( tightPhotons[0], tightMuons[0] )
        if len(tightMuons)>1:
            event.l1gTDR = deltaR( tightPhotons[0], tightMuons[1] )
            event.mllgT = ( get4DVec(tightMuons[0]) + get4DVec(tightMuons[1]) + get4DVec(tightPhotons[0]) ).M()

    if len(MVAPhotons) > 0:
        if goodJets:
            event.minGMVAJetdR = min( deltaR( MVAPhotons[0], j ) for j in goodJets )
        if tightMuons:
            event.minGMVALepdR = min( deltaR( MVAPhotons[0], l ) for l in tightMuons )
        if len(tightMuons)>0:
            event.l0gMVADR = deltaR( MVAPhotons[0], tightMuons[0] )
        if len(tightMuons)>1:
            event.l1gMVADR = deltaR( MVAPhotons[0], tightMuons[1] )
            event.mllgMVA = ( get4DVec(tightMuons[0]) + get4DVec(tightMuons[1]) + get4DVec(MVAPhotons[0]) ).M()


    if len(tightMuons) > 1:
        event.lldR   = deltaR( tightMuons[0], tightMuons[1] )
        event.lldPhi = deltaPhi( tightMuons[0]['phi'], tightMuons[1]['phi'] )
        event.mll    = ( get4DVec(tightMuons[0]) + get4DVec(tightMuons[1]) ).M()

    if len(goodJets) > 0 and len(tightMuons) > 0:
        event.leptonJetdR = min( deltaR( l, j ) for j in goodJets for l in tightMuons )
示例#2
0
def filler(event):

    event.run, event.lumi, event.evt = reader.evt
    event.lumiweight1fb = lumiweight1fb

    if reader.position % 100 == 0:
        logger.info("At event %i/%i", reader.position, reader.nEvents)

    if args.addReweights:
        event.nrw = weightInfo.nid
        lhe_weights = reader.products['lhe'].weights()
        weights = []
        param_points = []

        for weight in lhe_weights:
            # Store nominal weight (First position!)
            if weight.id == 'rwgt_1': event.rw_nominal = weight.wgt
            if not weight.id in weightInfo.id: continue
            pos = weightInfo.data[weight.id]
            event.rw_w[pos] = weight.wgt
            weights.append(weight.wgt)
            interpreted_weight = interpret_weight(weight.id)
            for var in weightInfo.variables:
                getattr(event, "rw_" + var)[pos] = interpreted_weight[var]
            # weight data for interpolation
            if not hyperPoly.initialized:
                param_points.append(
                    tuple(interpreted_weight[var]
                          for var in weightInfo.variables))

        # get list of values of ref point in specific order
        ref_point_coordinates = [
            weightInfo.ref_point_coordinates[var]
            for var in weightInfo.variables
        ]

        # Initialize with Reference Point
        if not hyperPoly.initialized:
            hyperPoly.initialize(param_points, ref_point_coordinates)
        coeff = hyperPoly.get_parametrization(weights)

        # = HyperPoly(weight_data, args.interpolationOrder)
        event.np = hyperPoly.ndof
        event.chi2_ndof = hyperPoly.chi2_ndof(coeff, weights)
        #logger.debug( "chi2_ndof %f coeff %r", event.chi2_ndof, coeff )
        if event.chi2_ndof > 10**-6:
            logger.warning("chi2_ndof is large: %f", event.chi2_ndof)
        for n in xrange(hyperPoly.ndof):
            event.p_C[n] = coeff[n]

        # lumi weight / w0
        event.ref_lumiweight1fb = event.lumiweight1fb / coeff[0]

    # All gen particles
    gp = reader.products['gp']

    # for searching
    search = GenSearch(gp)

    # find heavy objects before they decay
    genTops = map(
        lambda t: {var: getattr(t, var)()
                   for var in top_varnames},
        filter(lambda p: abs(p.pdgId()) == 6 and search.isLast(p), gp))

    genTops.sort(key=lambda p: -p['pt'])
    fill_vector_collection(event, "genTop", top_varnames, genTops)

    # generated Z's
    genZs = filter(
        lambda p: abs(p.pdgId()) == 23 and search.isLast(p) and abs(
            p.daughter(0).pdgId()) in [11, 13], gp)
    genZs.sort(key=lambda p: -p.pt())
    if len(genZs) > 0:
        genZ = genZs[0]
        for var in boson_read_varnames:
            setattr(event, "genZ_" + var, getattr(genZ, var)())
    else:
        genZ = None

    event.signalZ = 0  #ttZ with Z from gluon or top
    if genZ is not None:

        if abs(search.ascend(genZ).mother(0).pdgId()) in [6, 21]:
            event.signalZ = 1  #ttZ with Z from gluon or top

        d1, d2 = genZ.daughter(0), genZ.daughter(1)
        if d1.pdgId() > 0:
            lm, lp = d1, d2
        else:
            lm, lp = d2, d1
        event.genZ_daughterPdg = lm.pdgId()
        event.genZ_cosThetaStar = cosThetaStar(genZ.mass(), genZ.pt(),
                                               genZ.eta(), genZ.phi(), lm.pt(),
                                               lm.eta(), lm.phi())

    # generated W's
    genWs = filter(lambda p: abs(p.pdgId()) == 24 and search.isLast(p), gp)
    genWs.sort(key=lambda p: -p.pt())
    # W can't have a top-mother - We're looking for the extra boson (there is always an extra boson)
    genWs = filter(lambda p: abs(search.ascend(p).mother(0).pdgId()) != 6,
                   genWs)
    if len(genWs) > 0:
        genW = genWs[0]
        for var in boson_read_varnames:
            setattr(event, "genW_" + var, getattr(genW, var)())
    else:
        genW = None

    if genW is not None:
        d1, d2 = genW.daughter(0), genW.daughter(1)
        if abs(d1.pdgId()) in [11, 13, 15]:
            lep, neu = d1, d2
        else:
            lep, neu = d2, d1

        event.genW_daughterPdg = lep.pdgId()

    def printTopMothers():
        genTopCheck = [(search.ascend(l), l, search.ancestry(search.ascend(l)))
                       for l in filter(lambda p: abs(p.pdgId()) == 6, gp)]

        print genTopCheck
        genTopCheck.sort(key=lambda p: -p[1].pt())
        if len(genTopCheck) > 0:
            topPdg_ids = filter(
                lambda p: p != 2212,
                [abs(particle.pdgId()) for particle in genTopCheck[0][2]])
            print 'TOP 1'
            print topPdg_ids
            previous = genTopCheck[0][0].mother(1)
            print 'first', genTopCheck[0][0].pdgId()
            for i, pdg in enumerate(topPdg_ids):
                try:
                    print 'mother', i, previous.pdgId()
                    print 'mothers', i, [
                        p.pdgId() for p in search.ancestry(previous)
                    ]
                    previous = previous.mother(0)
                except Exception as val:
                    print val
                    break
        if len(genTopCheck) > 1:
            topPdg_ids = filter(
                lambda p: p != 2212,
                [abs(particle.pdgId()) for particle in genTopCheck[1][2]])
            print 'TOP 2'
            print topPdg_ids
            previous = genTopCheck[1][0].mother(1)
            print 'first', genTopCheck[1][0].pdgId()
            for i, pdg in enumerate(topPdg_ids):
                try:
                    print 'mother', i, previous.pdgId()
                    print 'mothers', i, [
                        p.pdgId() for p in search.ancestry(previous)
                    ]
                    previous = previous.mother(0)
                except Exception as val:
                    print val
                    break

    # MET
    genMet = {
        'pt': reader.products['genMET'][0].pt(),
        'phi': reader.products['genMET'][0].phi()
    }
    event.genMet_pt = genMet['pt']
    event.genMet_phi = genMet['phi']

    #    for ttgamma and tt events, categorize events:
    #        a1) ttgamma vertex, gamma from t/g, isolated, must be in ttgamma sample   = ttgamma signal (photonSignal == 1)
    #            -> gamma isolated
    #            -> gamma with only tops/gluons in ancestry
    #        a2) ttgamma, gamma from ISR, must be in ttgamma sample                    = tt ISR bg (photonISR == 1)
    #            -> gamma isolated
    #            -> gamma with no top in ancestry
    #            -> gamma with only gluons and light quarks in ancestry
    #            -> direct gamma mother != gluon!!! (this is a1)
    #        b) tt + isolated gamma from W, l, tau, must be in tt sample               = ttgamma (W,l,tau) bg (photonLep == 1)
    #            -> gamma isolated
    #            -> gamma with direct abs mother being 11, 13, 15 or 24
    #        c1) tt + non isolated gamma from anything including mesons                = tt bg (ttBg == 1)
    #            -> gamma non isolated or meson in ancestry
    #        c2) tt + isolated gamma from bottom quark (from t decay) or jets (from W) = tt bottom bg (ttBg == 1)
    #            -> gamma isolated from b or j (from t/W decay)
    #            ATTENTION: gammas from bottoms with off-shell tops where the
    #                       top decay is done by pythia are currently labeled as ISR!
    #                       However this case is currently not simulated in any sample
    #        d) tt + gamma fake                                                        = ttgamma fake (photonFake == 1)
    #            -> everything else does not contain a photon
    #            -> if it still passes selection: it is a photon fake

    genPhotonsSignalCheck = [
        (search.ascend(l), l, search.ancestry(search.ascend(l)))
        for l in filter(
            lambda p: abs(p.pdgId()) == 22 and p.pt() > 10 and abs(p.eta()) <
            2.5 and search.isLast(p) and p.status() == 1, gp)
    ]
    genPhotonsSignalCheck.sort(key=lambda p: -p[1].pt())

    photonSignal = 0  #a1
    photonISR = 0  #a2
    photonLep = 0  #b
    ttBg = 0  #c1
    photonJets = 0  #c2
    photonFake = 0  #d

    if len(genPhotonsSignalCheck) > 0:
        # check hardest photon with pT>13 and abs(eta)<2.5
        first, last, ancestry = genPhotonsSignalCheck[0]
        # get abs pdgIDs of ancestry
        pdg_ids = filter(lambda p: p != 2212,
                         [abs(particle.pdgId()) for particle in ancestry])
        # check if particles are close by
        close_particles = filter(
            lambda p: p != last and p.pt() > 5 and deltaR2(
                {
                    'phi': last.phi(),
                    'eta': last.eta()
                }, {
                    'phi': p.phi(),
                    'eta': p.eta()
                }) < 0.2**2, search.final_state_particles_no_neutrinos)

        #        print 'mothers pdg', pdg_ids
        #        print 'close', [p.pdgId() for p in close_particles]
        #        print 'first mother pdg', first.mother(0).pdgId()

        #        if len(pdg_ids) < 999:
        #            previous = first.mother(0)
        #            for i, pdg in enumerate(pdg_ids):
        #                try:
        #                    print 'mother', i, previous.pdgId()
        #                    previous = previous.mother(0)
        #                except Exception as val:
        #                    print val
        #                    break

        # deside the categories
        if max(pdg_ids) > 100 or len(close_particles) != 0:
            #photon with meson in ancestry or non isolated -> cat c1)
            ttBg = 1
        elif abs(first.mother(0).pdgId()) in [11, 13, 15, 24]:
            #isolated photon with W, l or tau direct mother -> cat b)
            photonLep = 1
#        elif all( [ p in [ 6, 21 ] for p in pdg_ids ] ) or abs(first.mother(0).pdgId()) == 21: # not working for photons from top, as the gluons can come from light quarks
        elif abs(first.mother(0).pdgId()) in [6, 21]:
            #isolated photon with photon from top or gluon -> cat a1)
            photonSignal = 1


#            printTopMothers()
        elif all([p in [1, 2, 3, 4, 5, 21] for p in pdg_ids]):
            #isolated photon with photon ancestry only containing light quarks or gluons (ISR) -> cat a1)
            photonISR = 1
        else:
            #isolated gammas from bottoms originating from the top decay or jets from W -> cat c2)
            photonJets = 1

    else:
        # if events with photonFake == 1 pass selection: fake gamma -> cat d)
        photonFake = 1

    # if all flags are 0, it is an isolated gamma from a process I havn't thought of!
    # should not be there! - check!
    event.signalPhoton = photonSignal
    event.isrPhoton = photonISR
    event.lepPhoton = photonLep
    event.nonIsoPhoton = ttBg
    event.jetPhoton = photonJets
    event.fakePhoton = photonFake

    # gen photons: particle-level isolated gen photons
    genPhotons = [(search.ascend(l), l) for l in filter(
        lambda p: abs(p.pdgId()) == 22 and p.pt() > 15 and search.isLast(p) and
        p.status() == 1, gp)]
    genPhotons.sort(key=lambda p: -p[1].pt())
    genPhotons_ = []

    for first, last in genPhotons[:100]:
        mother_pdgId = first.mother(
            0).pdgId() if first.numberOfMothers() > 0 else 0
        genPhoton_ = {var: getattr(last, var)() for var in boson_read_varnames}
        # kinematic photon selection
        if not isGoodGenPhoton(genPhoton_): continue
        genPhoton_['motherPdgId'] = mother_pdgId
        genPhoton_['status'] = last.status()

        close_particles = filter(
            lambda p: p != last and deltaR2(
                {
                    'phi': last.phi(),
                    'eta': last.eta()
                }, {
                    'phi': p.phi(),
                    'eta': p.eta()
                }) < 0.4**2, search.final_state_particles_no_neutrinos)
        genPhoton_['relIso04'] = sum([p.pt() for p in close_particles],
                                     0) / last.pt()
        # require isolation
        if genPhoton_['relIso04'] < 0.4:
            genPhotons_.append(genPhoton_)

    # genLeptons: prompt gen-leptons
    genLeptons = [(search.ascend(l), l) for l in filter(
        lambda p: abs(p.pdgId()) in [11, 13] and search.isLast(p) and p.pt() >=
        0 and p.status() == 1, gp)]
    promptGenLeps = []
    allGenLeps = []
    for first, last in genLeptons:
        mother = first.mother(0) if first.numberOfMothers() > 0 else None
        if mother is not None:
            mother_pdgId = mother.pdgId()
            mother_ascend = search.ascend(mother)
            grandmother = mother_ascend.mother(
                0) if mother.numberOfMothers() > 0 else None
            grandmother_pdgId = grandmother.pdgId(
            ) if grandmother is not None else 0
        else:
            mother_pdgId = 0
            grandmother_pdgId = 0
        genLep = {var: getattr(last, var)() for var in lep_varnames}
        genLep['motherPdgId'] = mother_pdgId
        genLep['grandmotherPdgId'] = grandmother_pdgId
        allGenLeps.append(genLep)
        if abs(genLep['motherPdgId']) in [11, 13, 15, 23, 24, 25]:
            promptGenLeps.append(genLep)

    # filter gen leptons
    promptGenLeps = list(filter(lambda l: isGoodGenLepton(l), promptGenLeps))
    promptGenLeps.sort(key=lambda p: -p['pt'])
    addIndex(promptGenLeps)

    ## removing photons in dR cone leptons (radiation photons)
    for genPhoton in genPhotons_:
        genPhoton['minLeptonDR'] = min(
            [999] + [deltaR(genPhoton, l) for l in allGenLeps])
    genPhotons_ = list(filter(lambda g: g['minLeptonDR'] > 0.4, genPhotons_))
    addIndex(genPhotons_)

    # jets
    fwlite_genJets = filter(genJetId, reader.products['genJets'])
    genJets = map(
        lambda t: {var: getattr(t, var)()
                   for var in jet_read_varnames},
        filter(lambda j: j.pt() > 30, fwlite_genJets))
    # filter genJets
    genJets = list(filter(lambda j: isGoodGenJet(j), genJets))
    # cleaning of jets with isolated photons
    genJets = list(
        filter(
            lambda j: min([999] + [deltaR2(j, p)
                                   for p in genPhotons_]) > 0.4**2, genJets))

    # store minimum DR to jets
    for genPhoton in genPhotons_:
        genPhoton['minJetDR'] = min([999] +
                                    [deltaR(genPhoton, j) for j in genJets])

    # find b's from tops:
    b_partons = [
        b for b in filter(
            lambda p: abs(p.pdgId()) == 5 and p.numberOfMothers() == 1 and abs(
                p.mother(0).pdgId()) == 6, gp)
    ]

    # store if gen-jet is DR matched to a B parton
    for genJet in genJets:
        genJet['matchBParton'] = (min([999] + [
            deltaR2(genJet, {
                'eta': b.eta(),
                'phi': b.phi()
            }) for b in b_partons
        ]) < 0.2**2)

    genJets = filter(
        lambda j:
        (min([999] + [deltaR2(j, l) for l in promptGenLeps
                      if l['pt'] > 10]) > 0.3**2), genJets)
    genJets.sort(key=lambda p: -p['pt'])
    addIndex(genJets)

    # gen b jets
    trueBjets = list(filter(lambda j: j['matchBParton'], genJets))
    trueNonBjets = list(filter(lambda j: not j['matchBParton'], genJets))

    # Mimick b reconstruction ( if the trailing b fails acceptance, we supplement with the leading non-b jet )
    genBj0, genBj1 = (trueBjets + trueNonBjets + [None, None])[:2]
    if genBj0: fill_vector(event, "genBj0", jet_write_varnames, genBj0)
    if genBj1: fill_vector(event, "genBj1", jet_write_varnames, genBj1)

    # reco-bjet/leading lepton association
    if len(promptGenLeps) > 0 and genBj0 and genBj1:
        if vecSumPt(genBj0, promptGenLeps[0], genMet) > vecSumPt(
                genBj1, promptGenLeps[0], genMet):
            event.genBjLeadlep_index, event.genBjLeadhad_index = genBj0[
                'index'], genBj1['index']
        else:
            event.genBjLeadlep_index, event.genBjLeadhad_index = genBj1[
                'index'], genBj0['index']

    # find Z in genLep
    (event.genLepZ_mass, genLepZ_l1_index,
     genLepZ_l2_index) = closestOSDLMassToMZ(promptGenLeps)
    genLepNonZ_indices = [
        i for i in range(len(promptGenLeps))
        if i not in [genLepZ_l1_index, genLepZ_l2_index]
    ]
    event.genLepZ_l1_index = promptGenLeps[genLepZ_l1_index][
        'index'] if genLepZ_l1_index >= 0 else -1
    event.genLepZ_l2_index = promptGenLeps[genLepZ_l2_index][
        'index'] if genLepZ_l2_index >= 0 else -1
    event.genLepNonZ_l1_index = promptGenLeps[
        genLepNonZ_indices[0]]['index'] if len(genLepNonZ_indices) > 0 else -1
    event.genLepNonZ_l2_index = promptGenLeps[
        genLepNonZ_indices[1]]['index'] if len(genLepNonZ_indices) > 1 else -1
    # store genLepZ stuff
    if event.genLepZ_mass > 0:
        genLepZ_l1 = ROOT.TLorentzVector()
        genLepZ_l1.SetPtEtaPhiM(promptGenLeps[event.genLepZ_l1_index]['pt'],
                                promptGenLeps[event.genLepZ_l1_index]['eta'],
                                promptGenLeps[event.genLepZ_l1_index]['phi'],
                                0)
        genLepZ_l2 = ROOT.TLorentzVector()
        genLepZ_l2.SetPtEtaPhiM(promptGenLeps[event.genLepZ_l2_index]['pt'],
                                promptGenLeps[event.genLepZ_l2_index]['eta'],
                                promptGenLeps[event.genLepZ_l2_index]['phi'],
                                0)
        genLepZ = genLepZ_l1 + genLepZ_l2
        event.genLepZ_pt = genLepZ.Pt()
        event.genLepZ_eta = genLepZ.Eta()
        event.genLepZ_phi = genLepZ.Phi()
        event.genLepZ_lldPhi = deltaPhi(
            promptGenLeps[event.genLepZ_l1_index]['phi'],
            promptGenLeps[event.genLepZ_l2_index]['phi'])
        event.genLepZ_lldR = deltaR(promptGenLeps[event.genLepZ_l1_index],
                                    promptGenLeps[event.genLepZ_l2_index])
        genLepMinus_index = event.genLepZ_l1_index if promptGenLeps[
            event.genLepZ_l1_index]['pdgId'] > 0 else event.genLepZ_l2_index
        event.genLepZ_cosThetaStar = cosThetaStar(
            event.genLepZ_mass, event.genLepZ_pt, event.genLepZ_eta,
            event.genLepZ_phi, promptGenLeps[genLepMinus_index]['pt'],
            promptGenLeps[genLepMinus_index]['eta'],
            promptGenLeps[genLepMinus_index]['phi'])

    # reco-bjet/nonZ lepton association
    if event.genLepNonZ_l1_index >= 0 and genBj0 and genBj1:
        if vecSumPt(genBj0, promptGenLeps[event.genLepNonZ_l1_index],
                    genMet) > vecSumPt(
                        genBj1, promptGenLeps[event.genLepNonZ_l1_index],
                        genMet):
            event.genBjNonZlep_index, event.genBjNonZhad_index = genBj0[
                'index'], genBj1['index']
        else:
            event.genBjNonZlep_index, event.genBjNonZhad_index = genBj1[
                'index'], genBj0['index']

    #for jet in genJets:
    #    print jet['isMuon'], jet['isElectron'], jet['isPhoton'], min([999]+[deltaR2(jet, l) for l in promptGenLeps if l['pt']>10]), jet

    # jet/lepton disambiguation -> remove jets, because gen-jets cluster all leptons
    #if args.logLevel == 'DEBUG':
    #    for jet in filter( lambda j: not (min([999]+[deltaR2(j, l) for l in promptGenLeps if l['pt']>10]) > 0.3**2 ), genJets ):
    #        logger.debug( "Filtered gen %f jet %r lep %r", sqrt((min([999]+[deltaR2(jet, l) for l in promptGenLeps if l['pt']>10]))), jet, [ (l['eta'], jet['pt']/l['pt']) for l in promptGenLeps] )
    #        assert False, ""

    fill_vector_collection(event, "genPhoton", gen_photon_varnames,
                           genPhotons_)
    fill_vector_collection(event, "genLep", lep_all_varnames, promptGenLeps)
    fill_vector_collection(event, "genJet", jet_write_varnames, genJets)
示例#3
0
plots.append(
    Plot(
        name='eta',
        texX='#eta',
        texY='Number of Events',
        attribute=lambda event, sample: event.lep_eta,
        binning=[30, -3, 3],
        addOverFlowBin='upper',
    ))

plots.append(
    Plot(
        name='dPhi_lep_met',
        texX='#Delta#phi(lep,met)',
        texY='Number of Events',
        attribute=lambda event, sample: deltaPhi(event.lep_phi, event.met_phi),
        binning=[30, -3, 3],
        addOverFlowBin='upper',
    ))

plots.append(
    Plot(
        name='dPhi_j0_met',
        texX='#Delta#phi(jet,met)',
        texY='Number of Events',
        attribute=lambda event, sample: deltaPhi(event.JetGood_phi[0], event.
                                                 met_phi),
        binning=[30, -3, 3],
        addOverFlowBin='upper',
    ))