2 from PhysicsTools.Heppy.analyzers.core.Analyzer
import Analyzer
3 from PhysicsTools.Heppy.analyzers.core.AutoHandle
import AutoHandle
4 from PhysicsTools.Heppy.physicsobjects.PhysicsObjects
import Jet
6 from PhysicsTools.Heppy.physicsutils.JetReCalibrator
import JetReCalibrator
7 import PhysicsTools.HeppyCore.framework.config
as cfg
9 from PhysicsTools.Heppy.physicsutils.QGLikelihoodCalculator
import QGLikelihoodCalculator
15 good = [
True for j
in jets ]
18 for i,j
in enumerate(jets):
19 d2i =
deltaR2(l.eta(),l.phi(), j.eta(),j.phi())
22 if ibest != -1: good[ibest] =
False 23 return [ j
for (i,j)
in enumerate(jets)
if good[i] ==
True ]
27 goodjet = [
True for j
in jets ]
28 goodlep = [
True for l
in leptons ]
29 for il, l
in enumerate(leptons):
31 for i,j
in enumerate(jets):
32 d2i =
deltaR2(l.eta(),l.phi(), j.eta(),j.phi())
34 choice = arbitration(j,l)
39 elif choice == (j,l)
or choice == (l,j):
45 if not goodlep[il]:
continue 46 if ibest != -1: goodjet[ibest] =
False 47 return ( [ j
for (i ,j)
in enumerate(jets)
if goodjet[i ] ==
True ],
48 [ l
for (il,l)
in enumerate(leptons)
if goodlep[il] ==
True ] )
53 factor = 1.079 + JERShift*0.026
54 if aeta > 3.2: factor = 1.056 + JERShift * 0.191
55 elif aeta > 2.8: factor = 1.395 + JERShift * 0.063
56 elif aeta > 2.3: factor = 1.254 + JERShift * 0.062
57 elif aeta > 1.7: factor = 1.208 + JERShift * 0.046
58 elif aeta > 1.1: factor = 1.121 + JERShift * 0.029
59 elif aeta > 0.5: factor = 1.099 + JERShift * 0.028
67 """Taken from RootTools.JetAnalyzer, simplified, modified, added corrections """ 68 def __init__(self, cfg_ana, cfg_comp, looperName):
69 super(JetAnalyzer,self).
__init__(cfg_ana, cfg_comp, looperName)
70 mcGT = cfg_ana.mcGT
if hasattr(cfg_ana,
'mcGT')
else "PHYS14_25_V2" 71 dataGT = cfg_ana.dataGT
if hasattr(cfg_ana,
'dataGT')
else "GR_70_V2_AN1" 72 self.
shiftJEC = self.cfg_ana.shiftJEC
if hasattr(self.cfg_ana,
'shiftJEC')
else 0
74 self.
addJECShifts = self.cfg_ana.addJECShifts
if hasattr(self.cfg_ana,
'addJECShifts')
else 0
77 elif self.
recalibrateJets not in [
True,
False]:
raise RuntimeError(
"recalibrateJets must be any of { True, False, 'MC', 'Data' }, while it is %r " % self.
recalibrateJets)
79 calculateSeparateCorrections = getattr(cfg_ana,
"calculateSeparateCorrections",
False);
80 calculateType1METCorrection = getattr(cfg_ana,
"calculateType1METCorrection",
False);
83 doResidual = getattr(cfg_ana,
'applyL2L3Residual',
'Data')
84 if doResidual ==
"MC": doResidual = self.cfg_comp.isMC
85 elif doResidual ==
"Data": doResidual =
not self.cfg_comp.isMC
86 elif doResidual
not in [
True,
False]:
raise RuntimeError(
"If specified, applyL2L3Residual must be any of { True, False, 'MC', 'Data'(default)}")
87 GT = getattr(cfg_comp,
'jecGT', mcGT
if self.cfg_comp.isMC
else dataGT)
89 kwargs = {
'calculateSeparateCorrections':calculateSeparateCorrections,
90 'calculateType1METCorrection' :calculateType1METCorrection, }
91 if kwargs[
'calculateType1METCorrection']: kwargs[
'type1METParams'] = cfg_ana.type1METParams
94 self.
doPuId = getattr(self.cfg_ana,
'doPuId',
True)
95 self.
jetLepDR = getattr(self.cfg_ana,
'jetLepDR', 0.4)
96 self.
jetLepArbitration = getattr(self.cfg_ana,
'jetLepArbitration',
lambda jet,lepton: lepton)
97 self.
lepPtMin = getattr(self.cfg_ana,
'minLepPt', -1)
98 self.
lepSelCut = getattr(self.cfg_ana,
'lepSelCut',
lambda lep :
True)
99 self.
jetGammaDR = getattr(self.cfg_ana,
'jetGammaDR', 0.4)
100 self.
jetGammaLepDR = getattr(self.cfg_ana,
'jetGammaLepDR', 0.4)
103 if hasattr(self.cfg_ana,
'jetGammaLepDR'):
108 raise RuntimeError(
"DR for simultaneous cleaning of jets from leptons and photons is not defined, and dR(gamma, jet)!=dR(lep, jet)")
109 if(self.cfg_ana.doQG):
110 qgdefname=
"{CMSSW_BASE}/src/PhysicsTools/Heppy/data/pdfQG_AK4chs_13TeV_v2b.root" 112 if not hasattr(self.cfg_ana ,
"collectionPostFix"):self.cfg_ana.collectionPostFix=
"" 116 self.handles[
'jets'] = AutoHandle( self.cfg_ana.jetCol,
'std::vector<pat::Jet>' )
117 self.handles[
'genJet'] = AutoHandle( self.cfg_ana.genJetCol,
'vector<reco::GenJet>' )
118 self.
shiftJER = self.cfg_ana.shiftJER
if hasattr(self.cfg_ana,
'shiftJER')
else 0
119 self.
addJERShifts = self.cfg_ana.addJERShifts
if hasattr(self.cfg_ana,
'addJERShifts')
else 0
120 self.handles[
'rho'] = AutoHandle( self.cfg_ana.rho,
'double' )
126 self.readCollections( event.input )
127 rho =
float(self.handles[
'rho'].product()[0])
131 if self.cfg_ana.copyJetsByValue:
134 allJets =
map(
lambda j:
Jet(ROOT.heppy.JetUtils.copyJet(j)), self.handles[
'jets'].product())
136 allJets =
map(Jet, self.handles[
'jets'].product())
147 jetsBefore = [ (j.pt(),j.eta(),j.phi(),j.rawFactor())
for j
in allJets ]
148 self.jetReCalibrator.correctAll(allJets, rho, delta=self.
shiftJEC,
152 jetsAfter = [ (j.pt(),j.eta(),j.phi(),j.rawFactor())
for j
in allJets ]
153 if len(jetsBefore) != len(jetsAfter):
154 print "ERROR: I had to recompute jet corrections, and they rejected some of the jets:\nold = %s\n new = %s\n" % (jetsBefore,jetsAfter)
156 for (told, tnew)
in zip(jetsBefore,jetsAfter):
157 if (
deltaR2(told[1],told[2],tnew[1],tnew[2])) > 0.0001:
158 print "ERROR: I had to recompute jet corrections, and one jet direction moved: old = %s, new = %s\n" % (told, tnew)
159 elif abs(told[0]-tnew[0])/(told[0]+tnew[0]) > 0.5e-3
or abs(told[3]-tnew[3]) > 0.5e-3:
160 print "ERROR: I had to recompute jet corrections, and one jet pt or corr changed: old = %s, new = %s\n" % (told, tnew)
164 if self.cfg_comp.isMC:
165 self.
genJets = [ x
for x
in self.handles[
'genJet'].product() ]
166 if self.cfg_ana.do_mc_match:
167 for igj, gj
in enumerate(self.
genJets):
170 self.
matchJets(event, [ j
for j
in allJets
if j.pt()>self.cfg_ana.jetPt ])
171 if getattr(self.cfg_ana,
'smearJets',
False):
178 allJets.sort(key =
lambda j : j.pt(), reverse =
True)
181 if hasattr(event,
'selectedLeptons'):
182 leptons = [ l
for l
in event.selectedLeptons
if l.pt() > self.
lepPtMin and self.
lepSelCut(l) ]
183 if self.cfg_ana.cleanJetsFromTaus
and hasattr(event,
'selectedTaus'):
184 leptons = leptons[:] + event.selectedTaus
185 if self.cfg_ana.cleanJetsFromIsoTracks
and hasattr(event,
'selectedIsoCleanTrack'):
186 leptons = leptons[:] + event.selectedIsoCleanTrack
195 leps_with_overlaps = []
196 if getattr(self.cfg_ana,
'checkLeptonPFOverlap',
True):
197 for i
in range(jet.numberOfSourceCandidatePtrs()):
198 p1 = jet.sourceCandidatePtr(i)
200 for j
in range(lep.numberOfSourceCandidatePtrs()):
201 p2 = lep.sourceCandidatePtr(j)
202 has_overlaps = p1.key() == p2.key()
and p1.refCore().
id().productIndex() == p2.refCore().
id().productIndex()
and p1.refCore().
id().processIndex() == p2.refCore().
id().processIndex()
204 leps_with_overlaps += [lep]
205 if len(leps_with_overlaps)>0:
206 for lep
in leps_with_overlaps:
209 self.jetsAllNoID.append(jet)
210 if(self.cfg_ana.doQG):
211 jet.qgl_calc = self.qglcalc.computeQGLikelihood
214 self.jets.append(jet)
215 self.jetsIdOnly.append(jet)
217 self.jetsFailId.append(jet)
219 self.jetsIdOnly.append(jet)
221 jetsEtaCut = [j
for j
in self.
jets if abs(j.eta()) < self.cfg_ana.jetEta ]
227 if hasattr(event,
'selectedLeptons')
and self.cfg_ana.cleanSelectedLeptons:
228 event.discardedLeptons = [ l
for l
in leptons
if l
not in cleanLeptons ]
229 event.selectedLeptons = [ l
for l
in event.selectedLeptons
if l
not in event.discardedLeptons ]
231 if hasattr(lep,
"jetOverlap"):
234 lep.jetOverlapIdx = self.cleanJetsAll.index(lep.jetOverlap)
237 lep.jetOverlapIdx = 1000 + self.discardedJets.index(lep.jetOverlap)
247 if hasattr(event,
'selectedPhotons'):
248 if self.cfg_ana.cleanJetsFromFirstPhoton:
249 photons = event.selectedPhotons[:1]
251 photons = [ g
for g
in event.selectedPhotons ]
270 if self.cfg_ana.alwaysCleanPhotons:
283 self.cleanJetsFailIdAll.append(jet)
291 self.gamma_cleanJetsFailIdAll.append(jet)
296 incleptons = event.inclusiveLeptons
if hasattr(event,
'inclusiveLeptons')
else event.selectedLeptons
300 jet.leptons = [l
for l
in jlpairs
if jlpairs[l] == jet ]
301 for lep
in incleptons:
304 setattr(lep,
"jet"+self.cfg_ana.collectionPostFix,lep)
306 setattr(lep,
"jet"+self.cfg_ana.collectionPostFix,jet)
308 taus = getattr(event,
'selectedTaus',[])
312 jet.taus = [l
for l
in jtaupairs
if jtaupairs[l] == jet ]
314 setattr(tau,
"jet"+self.cfg_ana.collectionPostFix,jtaupairs[tau])
317 if self.cfg_comp.isMC:
320 if hasattr(j,
'deltaMetFromJetSmearing'):
326 if self.cfg_ana.cleanGenJetsFromPhoton:
329 if getattr(self.cfg_ana,
'attachNeutrinos',
True)
and hasattr(self.cfg_ana,
"genNuSelection") :
330 jetNus=[x
for x
in event.genParticles
if abs(x.pdgId())
in [12,14,16]
and self.cfg_ana.genNuSelection(x) ]
331 pairs= matchObjectCollection (jetNus, self.
genJets, 0.4**2)
333 for (nu,genJet)
in six.iteritems(pairs) :
334 if genJet
is not None :
335 if not hasattr(genJet,
"nu") :
341 if self.cfg_ana.do_mc_match:
344 if hasattr(event,
"jets"+self.cfg_ana.collectionPostFix):
raise RuntimeError(
"Event already contains a jet collection with the following postfix: "+self.cfg_ana.collectionPostFix)
345 setattr(event,
"rho" +self.cfg_ana.collectionPostFix, self.
rho )
346 setattr(event,
"deltaMetFromJEC" +self.cfg_ana.collectionPostFix, self.
deltaMetFromJEC )
347 setattr(event,
"type1METCorr" +self.cfg_ana.collectionPostFix, self.
type1METCorr )
348 setattr(event,
"allJetsUsedForMET" +self.cfg_ana.collectionPostFix, self.
allJetsUsedForMET )
349 setattr(event,
"jets" +self.cfg_ana.collectionPostFix, self.
jets )
350 setattr(event,
"jetsFailId" +self.cfg_ana.collectionPostFix, self.
jetsFailId )
351 setattr(event,
"jetsAllNoID" +self.cfg_ana.collectionPostFix, self.
jetsAllNoID )
352 setattr(event,
"jetsIdOnly" +self.cfg_ana.collectionPostFix, self.
jetsIdOnly )
353 setattr(event,
"cleanJetsAll" +self.cfg_ana.collectionPostFix, self.
cleanJetsAll )
354 setattr(event,
"cleanJets" +self.cfg_ana.collectionPostFix, self.
cleanJets )
355 setattr(event,
"cleanJetsFwd" +self.cfg_ana.collectionPostFix, self.
cleanJetsFwd )
356 setattr(event,
"cleanJetsFailIdAll" +self.cfg_ana.collectionPostFix, self.
cleanJetsFailIdAll )
357 setattr(event,
"cleanJetsFailId" +self.cfg_ana.collectionPostFix, self.
cleanJetsFailId )
358 setattr(event,
"discardedJets" +self.cfg_ana.collectionPostFix, self.
discardedJets )
359 setattr(event,
"gamma_cleanJetsAll" +self.cfg_ana.collectionPostFix, self.
gamma_cleanJetsAll )
360 setattr(event,
"gamma_cleanJets" +self.cfg_ana.collectionPostFix, self.
gamma_cleanJets )
361 setattr(event,
"gamma_cleanJetsFwd" +self.cfg_ana.collectionPostFix, self.
gamma_cleanJetsFwd )
366 if self.cfg_comp.isMC:
368 setattr(event,
"cleanGenJets" +self.cfg_ana.collectionPostFix, self.
cleanGenJets )
369 setattr(event,
"genJets" +self.cfg_ana.collectionPostFix, self.
genJets )
370 if self.cfg_ana.do_mc_match:
371 setattr(event,
"bqObjects" +self.cfg_ana.collectionPostFix, self.
bqObjects )
372 setattr(event,
"cqObjects" +self.cfg_ana.collectionPostFix, self.
cqObjects )
373 setattr(event,
"partons" +self.cfg_ana.collectionPostFix, self.
partons )
374 setattr(event,
"heaviestQCDFlavour" +self.cfg_ana.collectionPostFix, self.
heaviestQCDFlavour )
382 jet.puJetIdPassed = jet.puJetId()
383 jet.pfJetIdPassed = jet.jetID(
'POG_PFID_Loose')
384 if self.cfg_ana.relaxJetId:
387 return jet.pfJetIdPassed
and (jet.puJetIdPassed
or not(self.
doPuId))
391 return jet.pt() > self.cfg_ana.jetPt
and \
392 abs( jet.eta() ) < self.cfg_ana.jetEta;
397 if id > 999:
return (id/1000)%10 == f
398 if id > 99:
return (id/100)%10 == f
403 self.
bqObjects = [ p
for p
in event.genParticles
if (p.status() == 2
and isFlavour(p,5)) ]
404 self.
cqObjects = [ p
for p
in event.genParticles
if (p.status() == 2
and isFlavour(p,4)) ]
406 self.
partons = [ p
for p
in event.genParticles
if ((p.status() == 23
or p.status() == 3)
and abs(p.pdgId())>0
and (
abs(p.pdgId())
in [1,2,3,4,5,21]) ) ]
413 jet.partonId = (parton.pdgId()
if parton !=
None else 0)
414 jet.partonMotherId = (parton.mother(0).
pdgId()
if parton !=
None and parton.numberOfMothers()>0
else 0)
416 for jet
in self.
jets:
431 event.genbquarks + event.genwzquarks,
436 jet.mcMatchId = (gen.sourceId
if gen !=
None else 0)
437 jet.mcMatchFlav = (
abs(gen.pdgId())
if gen !=
None else 0)
443 jet.mcJet = match[jet]
452 genpt, jetpt, aeta = gen.pt(), jet.pt(),
abs(jet.eta())
456 ptscale =
max(0.0, (jetpt + (factor-1)*(jetpt-genpt))/jetpt)
458 jet.deltaMetFromJetSmearing = [ -(ptscale-1)*jet.rawFactor()*jet.px(), -(ptscale-1)*jet.rawFactor()*jet.py() ]
460 jet.setP4(jet.p4()*ptscale)
462 jet.setRawFactor(jet.rawFactor()/ptscale)
464 if (self.shiftJER==0)
and (self.addJERShifts):
465 setattr(jet,
"corrJER", ptscale )
467 ptscaleJERUp =
max(0.0, (jetpt + (factorJERUp-1)*(jetpt-genpt))/jetpt)
468 setattr(jet,
"corrJERUp", ptscaleJERUp)
470 ptscaleJERDown =
max(0.0, (jetpt + (factorJERDown-1)*(jetpt-genpt))/jetpt)
471 setattr(jet,
"corrJERDown", ptscaleJERDown)
477 setattr(JetAnalyzer,
"defaultConfig", cfg.Analyzer(
478 class_object = JetAnalyzer,
479 jetCol =
'slimmedJets',
480 copyJetsByValue =
False,
481 genJetCol =
'slimmedGenJets',
482 rho = (
'fixedGridRhoFastjetAll',
'',
''),
487 jetLepArbitration = (
lambda jet,lepton : lepton),
488 cleanSelectedLeptons =
True,
490 lepSelCut =
lambda lep :
True,
494 checkLeptonPFOverlap =
True,
495 recalibrateJets =
False,
496 applyL2L3Residual =
'Data',
497 recalibrationType =
"AK4PFchs",
499 addJECShifts =
False,
503 calculateSeparateCorrections =
False,
504 calculateType1METCorrection =
False,
505 type1METParams = {
'jetPtThreshold':15.,
'skipEMfractionThreshold':0.9,
'skipMuons':
True },
507 cleanJetsFromFirstPhoton =
False,
508 cleanJetsFromTaus =
False,
509 cleanJetsFromIsoTracks =
False,
510 alwaysCleanPhotons =
False,
512 cleanGenJetsFromPhoton =
False,
514 cleanFromLepAndGammaSimultaneously =
False,
516 attachNeutrinos =
True,
517 genNuSelection =
lambda nu :
True,
518 collectionPostFix =
""
deltaMetFromJEC
Read jets, if necessary recalibrate and shift MET.
def testJetNoID(self, jet)
cleanJetsFailIdAll
Jet Id, after jet/lepton cleaning.
def beginLoop(self, setup)
cleanFromLepAndGammaSimultaneously
def matchObjectCollection
def matchJets(self, event, jets)
OutputIterator zip(InputIterator1 first1, InputIterator1 last1, InputIterator2 first2, InputIterator2 last2, OutputIterator result, Compare comp)
noIdCleanJetsAll
First cleaning, then Jet Id.
Abs< T >::type abs(const T &t)
constexpr auto deltaR2(const T1 &t1, const T2 &t2) -> decltype(t1.eta())
def jetFlavour(self, event)
def cleanNearestJetOnly(jets, leptons, deltaR)
def bestMatch(object, matchCollection)
def cleanJetsAndLeptons(jets, leptons, deltaR, arbitration)
def shiftJERfactor(JERShift, aeta)
def __init__(self, cfg_ana, cfg_comp, looperName)
def matchObjectCollection2(objects, matchCollection, deltaRMax=0.3)
gamma_cleanJetsFailIdAll
Jet Id, after jet/photon cleaning.