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
14 good = [
True for j
in jets ]
17 for i,j
in enumerate(jets):
18 d2i =
deltaR2(l.eta(),l.phi(), j.eta(),j.phi())
21 if ibest != -1: good[ibest] =
False
22 return [ j
for (i,j)
in enumerate(jets)
if good[i] ==
True ]
26 goodjet = [
True for j
in jets ]
27 goodlep = [
True for l
in leptons ]
28 for il, l
in enumerate(leptons):
30 for i,j
in enumerate(jets):
31 d2i =
deltaR2(l.eta(),l.phi(), j.eta(),j.phi())
33 choice = arbitration(j,l)
38 elif choice == (j,l)
or choice == (l,j):
44 if not goodlep[il]:
continue
45 if ibest != -1: goodjet[ibest] =
False
46 return ( [ j
for (i ,j)
in enumerate(jets)
if goodjet[i ] ==
True ],
47 [ l
for (il,l)
in enumerate(leptons)
if goodlep[il] ==
True ] )
52 factor = 1.079 + JERShift*0.026
53 if aeta > 3.2: factor = 1.056 + JERShift * 0.191
54 elif aeta > 2.8: factor = 1.395 + JERShift * 0.063
55 elif aeta > 2.3: factor = 1.254 + JERShift * 0.062
56 elif aeta > 1.7: factor = 1.208 + JERShift * 0.046
57 elif aeta > 1.1: factor = 1.121 + JERShift * 0.029
58 elif aeta > 0.5: factor = 1.099 + JERShift * 0.028
66 """Taken from RootTools.JetAnalyzer, simplified, modified, added corrections """
67 def __init__(self, cfg_ana, cfg_comp, looperName):
68 super(JetAnalyzer,self).
__init__(cfg_ana, cfg_comp, looperName)
69 mcGT = cfg_ana.mcGT
if hasattr(cfg_ana,
'mcGT')
else "PHYS14_25_V2"
70 dataGT = cfg_ana.dataGT
if hasattr(cfg_ana,
'dataGT')
else "GR_70_V2_AN1"
71 self.
shiftJEC = self.cfg_ana.shiftJEC
if hasattr(self.cfg_ana,
'shiftJEC')
else 0
73 self.
addJECShifts = self.cfg_ana.addJECShifts
if hasattr(self.cfg_ana,
'addJECShifts')
else 0
76 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 doResidual = getattr(cfg_ana,
'applyL2L3Residual',
'Data')
80 if doResidual ==
"MC": doResidual = self.cfg_comp.isMC
81 elif doResidual ==
"Data": doResidual =
not self.cfg_comp.isMC
82 elif doResidual
not in [
True,
False]:
raise RuntimeError(
"If specified, applyL2L3Residual must be any of { True, False, 'MC', 'Data'(default)}")
83 GT = mcGT
if self.cfg_comp.isMC
else dataGT
85 kwargs = {
'calculateSeparateCorrections':calculateSeparateCorrections,
86 'calculateType1METCorrection' :calculateType1METCorrection, }
87 if kwargs[
'calculateType1METCorrection']: kwargs[
'type1METParams'] = cfg_ana.type1METParams
90 self.
doPuId = getattr(self.cfg_ana,
'doPuId',
True)
91 self.
jetLepDR = getattr(self.cfg_ana,
'jetLepDR', 0.4)
92 self.
jetLepArbitration = getattr(self.cfg_ana,
'jetLepArbitration',
lambda jet,lepton: lepton)
93 self.
lepPtMin = getattr(self.cfg_ana,
'minLepPt', -1)
94 self.
lepSelCut = getattr(self.cfg_ana,
'lepSelCut',
lambda lep :
True)
95 self.
jetGammaDR = getattr(self.cfg_ana,
'jetGammaDR', 0.4)
96 if(self.cfg_ana.doQG):
97 qgdefname=
"{CMSSW_BASE}/src/PhysicsTools/Heppy/data/pdfQG_AK4chs_13TeV_v2b.root"
99 if not hasattr(self.cfg_ana ,
"collectionPostFix"):self.cfg_ana.collectionPostFix=
""
103 self.handles[
'jets'] = AutoHandle( self.cfg_ana.jetCol,
'std::vector<pat::Jet>' )
104 self.handles[
'genJet'] = AutoHandle( self.cfg_ana.genJetCol,
'vector<reco::GenJet>' )
105 self.
shiftJER = self.cfg_ana.shiftJER
if hasattr(self.cfg_ana,
'shiftJER')
else 0
106 self.
addJERShifts = self.cfg_ana.addJERShifts
if hasattr(self.cfg_ana,
'addJERShifts')
else 0
107 self.handles[
'rho'] = AutoHandle( self.cfg_ana.rho,
'double' )
113 self.readCollections( event.input )
114 rho = float(self.handles[
'rho'].product()[0])
118 if self.cfg_ana.copyJetsByValue:
120 allJets = map(
lambda j:
Jet(ROOT.pat.Jet(ROOT.edm.Ptr(ROOT.pat.Jet)(ROOT.edm.ProductID(),j,0))), self.handles[
'jets'].product())
122 allJets = map(Jet, self.handles[
'jets'].product())
133 jetsBefore = [ (j.pt(),j.eta(),j.phi(),j.rawFactor())
for j
in allJets ]
134 self.jetReCalibrator.correctAll(allJets, rho, delta=self.
shiftJEC,
138 jetsAfter = [ (j.pt(),j.eta(),j.phi(),j.rawFactor())
for j
in allJets ]
139 if len(jetsBefore) != len(jetsAfter):
140 print "ERROR: I had to recompute jet corrections, and they rejected some of the jets:\nold = %s\n new = %s\n" % (jetsBefore,jetsAfter)
142 for (told, tnew)
in zip(jetsBefore,jetsAfter):
143 if (
deltaR2(told[1],told[2],tnew[1],tnew[2])) > 0.0001:
144 print "ERROR: I had to recompute jet corrections, and one jet direction moved: old = %s, new = %s\n" % (told, tnew)
145 elif abs(told[0]-tnew[0])/(told[0]+tnew[0]) > 0.5e-3
or abs(told[3]-tnew[3]) > 0.5e-3:
146 print "ERROR: I had to recompute jet corrections, and one jet pt or corr changed: old = %s, new = %s\n" % (told, tnew)
150 if self.cfg_comp.isMC:
151 self.
genJets = [ x
for x
in self.handles[
'genJet'].product() ]
152 if self.cfg_ana.do_mc_match:
153 for igj, gj
in enumerate(self.
genJets):
156 if getattr(self.cfg_ana,
'smearJets',
False):
163 allJets.sort(key =
lambda j : j.pt(), reverse =
True)
166 if hasattr(event,
'selectedLeptons'):
167 leptons = [ l
for l
in event.selectedLeptons
if l.pt() > self.
lepPtMin and self.
lepSelCut(l) ]
168 if self.cfg_ana.cleanJetsFromTaus
and hasattr(event,
'selectedTaus'):
169 leptons = leptons[:] + event.selectedTaus
170 if self.cfg_ana.cleanJetsFromIsoTracks
and hasattr(event,
'selectedIsoCleanTrack'):
171 leptons = leptons[:] + event.selectedIsoCleanTrack
176 self.jetsAllNoID = []
180 leps_with_overlaps = []
181 if getattr(self.cfg_ana,
'checkLeptonPFOverlap',
True):
182 for i
in range(jet.numberOfSourceCandidatePtrs()):
183 p1 = jet.sourceCandidatePtr(i)
185 for j
in range(lep.numberOfSourceCandidatePtrs()):
186 p2 = lep.sourceCandidatePtr(j)
187 has_overlaps = p1.key() == p2.key()
and p1.refCore().id().productIndex() == p2.refCore().id().productIndex()
and p1.refCore().id().processIndex() == p2.refCore().id().processIndex()
189 leps_with_overlaps += [lep]
190 if len(leps_with_overlaps)>0:
191 for lep
in leps_with_overlaps:
194 self.jetsAllNoID.append(jet)
195 if(self.cfg_ana.doQG):
196 jet.qgl_calc = self.qglcalc.computeQGLikelihood
199 self.jets.append(jet)
200 self.jetsIdOnly.append(jet)
202 self.jetsFailId.append(jet)
204 self.jetsIdOnly.append(jet)
206 jetsEtaCut = [j
for j
in self.jets
if abs(j.eta()) < self.cfg_ana.jetEta ]
209 self.cleanJets = [j
for j
in self.cleanJetsAll
if abs(j.eta()) < self.cfg_ana.jetEtaCentral ]
210 self.cleanJetsFwd = [j
for j
in self.cleanJetsAll
if abs(j.eta()) >= self.cfg_ana.jetEtaCentral ]
211 self.discardedJets = [j
for j
in self.jets
if j
not in self.cleanJetsAll]
212 if hasattr(event,
'selectedLeptons')
and self.cfg_ana.cleanSelectedLeptons:
213 event.discardedLeptons = [ l
for l
in leptons
if l
not in cleanLeptons ]
214 event.selectedLeptons = [ l
for l
in event.selectedLeptons
if l
not in event.discardedLeptons ]
216 if hasattr(lep,
"jetOverlap"):
217 if lep.jetOverlap
in self.cleanJetsAll:
219 lep.jetOverlapIdx = self.cleanJetsAll.index(lep.jetOverlap)
220 elif lep.jetOverlap
in self.discardedJets:
222 lep.jetOverlapIdx = 1000 + self.discardedJets.index(lep.jetOverlap)
226 self.noIdCleanJets = [j
for j
in self.noIdCleanJetsAll
if abs(j.eta()) < self.cfg_ana.jetEtaCentral ]
227 self.noIdCleanJetsFwd = [j
for j
in self.noIdCleanJetsAll
if abs(j.eta()) >= self.cfg_ana.jetEtaCentral ]
228 self.noIdDiscardedJets = [j
for j
in self.jetsAllNoID
if j
not in self.noIdCleanJetsAll]
232 if hasattr(event,
'selectedPhotons'):
233 if self.cfg_ana.cleanJetsFromFirstPhoton:
234 photons = event.selectedPhotons[:1]
236 photons = [ g
for g
in event.selectedPhotons ]
239 self.gamma_cleanJets = [j
for j
in self.gamma_cleanJetsAll
if abs(j.eta()) < self.cfg_ana.jetEtaCentral ]
240 self.gamma_cleanJetsFwd = [j
for j
in self.gamma_cleanJetsAll
if abs(j.eta()) >= self.cfg_ana.jetEtaCentral ]
242 self.gamma_noIdCleanJets = [j
for j
in self.gamma_noIdCleanJetsAll
if abs(j.eta()) < self.cfg_ana.jetEtaCentral ]
243 self.gamma_noIdCleanJetsFwd = [j
for j
in self.gamma_noIdCleanJetsAll
if abs(j.eta()) >= self.cfg_ana.jetEtaCentral ]
246 if self.cfg_ana.alwaysCleanPhotons:
247 self.cleanJets = self.gamma_cleanJets
248 self.cleanJetsAll = self.gamma_cleanJetsAll
249 self.cleanJetsFwd = self.gamma_cleanJetsFwd
251 self.noIdCleanJets = self.gamma_noIdCleanJets
252 self.noIdCleanJetsAll = self.gamma_noIdCleanJetsAll
253 self.noIdCleanJetsFwd = self.gamma_noIdCleanJetsFwd
256 self.cleanJetsFailIdAll = []
257 for jet
in self.noIdCleanJetsAll:
259 self.cleanJetsFailIdAll.append(jet)
261 self.cleanJetsFailId = [j
for j
in self.cleanJetsFailIdAll
if abs(j.eta()) < self.cfg_ana.jetEtaCentral ]
264 self.gamma_cleanJetsFailIdAll = []
265 for jet
in self.gamma_noIdCleanJetsAll:
267 self.gamma_cleanJetsFailIdAll.append(jet)
269 self.gamma_cleanJetsFailId = [j
for j
in self.gamma_cleanJetsFailIdAll
if abs(j.eta()) < self.cfg_ana.jetEtaCentral ]
272 incleptons = event.inclusiveLeptons
if hasattr(event,
'inclusiveLeptons')
else event.selectedLeptons
276 jet.leptons = [l
for l
in jlpairs
if jlpairs[l] == jet ]
277 for lep
in incleptons:
280 setattr(lep,
"jet"+self.cfg_ana.collectionPostFix,lep)
282 setattr(lep,
"jet"+self.cfg_ana.collectionPostFix,jet)
284 taus = getattr(event,
'selectedTaus',[])
288 jet.taus = [l
for l
in jtaupairs
if jtaupairs[l] == jet ]
290 setattr(tau,
"jet"+self.cfg_ana.collectionPostFix,jtaupairs[tau])
293 if self.cfg_comp.isMC:
294 self.deltaMetFromJetSmearing = [0, 0]
295 for j
in self.cleanJetsAll:
296 if hasattr(j,
'deltaMetFromJetSmearing'):
297 self.deltaMetFromJetSmearing[0] += j.deltaMetFromJetSmearing[0]
298 self.deltaMetFromJetSmearing[1] += j.deltaMetFromJetSmearing[1]
302 if self.cfg_ana.cleanGenJetsFromPhoton:
305 if getattr(self.cfg_ana,
'attachNeutrinos',
True)
and hasattr(self.cfg_ana,
"genNuSelection") :
306 jetNus=[x
for x
in event.genParticles
if abs(x.pdgId())
in [12,14,16]
and self.cfg_ana.genNuSelection(x) ]
307 pairs= matchObjectCollection (jetNus, self.
genJets, 0.4**2)
309 for (nu,genJet)
in pairs.iteritems() :
310 if genJet
is not None :
311 if not hasattr(genJet,
"nu") :
317 if self.cfg_ana.do_mc_match:
320 if hasattr(event,
"jets"+self.cfg_ana.collectionPostFix):
raise RuntimeError(
"Event already contains a jet collection with the following postfix: "+self.cfg_ana.collectionPostFix)
321 setattr(event,
"rho" +self.cfg_ana.collectionPostFix, self.
rho )
322 setattr(event,
"deltaMetFromJEC" +self.cfg_ana.collectionPostFix, self.
deltaMetFromJEC )
323 setattr(event,
"type1METCorr" +self.cfg_ana.collectionPostFix, self.
type1METCorr )
324 setattr(event,
"allJetsUsedForMET" +self.cfg_ana.collectionPostFix, self.
allJetsUsedForMET )
325 setattr(event,
"jets" +self.cfg_ana.collectionPostFix, self.jets )
326 setattr(event,
"jetsFailId" +self.cfg_ana.collectionPostFix, self.jetsFailId )
327 setattr(event,
"jetsAllNoID" +self.cfg_ana.collectionPostFix, self.jetsAllNoID )
328 setattr(event,
"jetsIdOnly" +self.cfg_ana.collectionPostFix, self.jetsIdOnly )
329 setattr(event,
"cleanJetsAll" +self.cfg_ana.collectionPostFix, self.cleanJetsAll )
330 setattr(event,
"cleanJets" +self.cfg_ana.collectionPostFix, self.cleanJets )
331 setattr(event,
"cleanJetsFwd" +self.cfg_ana.collectionPostFix, self.cleanJetsFwd )
332 setattr(event,
"cleanJetsFailIdAll" +self.cfg_ana.collectionPostFix, self.cleanJetsFailIdAll )
333 setattr(event,
"cleanJetsFailId" +self.cfg_ana.collectionPostFix, self.cleanJetsFailId )
334 setattr(event,
"discardedJets" +self.cfg_ana.collectionPostFix, self.discardedJets )
335 setattr(event,
"gamma_cleanJetsAll" +self.cfg_ana.collectionPostFix, self.gamma_cleanJetsAll )
336 setattr(event,
"gamma_cleanJets" +self.cfg_ana.collectionPostFix, self.gamma_cleanJets )
337 setattr(event,
"gamma_cleanJetsFwd" +self.cfg_ana.collectionPostFix, self.gamma_cleanJetsFwd )
338 setattr(event,
"gamma_cleanJetsFailIdAll" +self.cfg_ana.collectionPostFix, self.gamma_cleanJetsFailIdAll )
339 setattr(event,
"gamma_cleanJetsFailId" +self.cfg_ana.collectionPostFix, self.gamma_cleanJetsFailId )
342 if self.cfg_comp.isMC:
343 setattr(event,
"deltaMetFromJetSmearing"+self.cfg_ana.collectionPostFix, self.deltaMetFromJetSmearing)
344 setattr(event,
"cleanGenJets" +self.cfg_ana.collectionPostFix, self.cleanGenJets )
345 setattr(event,
"genJets" +self.cfg_ana.collectionPostFix, self.
genJets )
346 if self.cfg_ana.do_mc_match:
347 setattr(event,
"bqObjects" +self.cfg_ana.collectionPostFix, self.
bqObjects )
348 setattr(event,
"cqObjects" +self.cfg_ana.collectionPostFix, self.
cqObjects )
349 setattr(event,
"partons" +self.cfg_ana.collectionPostFix, self.
partons )
350 setattr(event,
"heaviestQCDFlavour" +self.cfg_ana.collectionPostFix, self.
heaviestQCDFlavour )
358 jet.puJetIdPassed = jet.puJetId()
359 jet.pfJetIdPassed = jet.jetID(
'POG_PFID_Loose')
360 if self.cfg_ana.relaxJetId:
363 return jet.pfJetIdPassed
and (jet.puJetIdPassed
or not(self.
doPuId))
367 return jet.pt() > self.cfg_ana.jetPt
and \
368 abs( jet.eta() ) < self.cfg_ana.jetEta;
373 if id > 999:
return (id/1000)%10 == f
374 if id > 99:
return (id/100)%10 == f
379 self.
bqObjects = [ p
for p
in event.genParticles
if (p.status() == 2
and isFlavour(p,5)) ]
380 self.
cqObjects = [ p
for p
in event.genParticles
if (p.status() == 2
and isFlavour(p,4)) ]
382 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]) ) ]
387 for jet
in self.cleanJetsAll:
389 jet.partonId = (parton.pdgId()
if parton !=
None else 0)
390 jet.partonMotherId = (parton.mother(0).
pdgId()
if parton !=
None and parton.numberOfMothers()>0
else 0)
392 for jet
in self.jets:
407 event.genbquarks + event.genwzquarks,
412 jet.mcMatchId = (gen.sourceId
if gen !=
None else 0)
413 jet.mcMatchFlav = (
abs(gen.pdgId())
if gen !=
None else 0)
419 jet.mcJet = match[jet]
428 genpt, jetpt, aeta = gen.pt(), jet.pt(),
abs(jet.eta())
432 ptscale =
max(0.0, (jetpt + (factor-1)*(jetpt-genpt))/jetpt)
434 jet.deltaMetFromJetSmearing = [ -(ptscale-1)*jet.rawFactor()*jet.px(), -(ptscale-1)*jet.rawFactor()*jet.py() ]
436 jet.setP4(jet.p4()*ptscale)
438 jet.setRawFactor(jet.rawFactor()/ptscale)
440 if (self.shiftJER==0)
and (self.addJERShifts):
441 setattr(jet,
"corrJER", ptscale )
443 ptscaleJERUp =
max(0.0, (jetpt + (factorJERUp-1)*(jetpt-genpt))/jetpt)
444 setattr(jet,
"corrJERUp", ptscaleJERUp)
446 ptscaleJERDown =
max(0.0, (jetpt + (factorJERDown-1)*(jetpt-genpt))/jetpt)
447 setattr(jet,
"corrJERDown", ptscaleJERDown)
453 setattr(JetAnalyzer,
"defaultConfig", cfg.Analyzer(
454 class_object = JetAnalyzer,
455 jetCol =
'slimmedJets',
456 copyJetsByValue =
False,
457 genJetCol =
'slimmedGenJets',
458 rho = (
'fixedGridRhoFastjetAll',
'',
''),
463 jetLepArbitration = (
lambda jet,lepton : lepton),
464 cleanSelectedLeptons =
True,
466 lepSelCut =
lambda lep :
True,
470 checkLeptonPFOverlap =
True,
471 recalibrateJets =
False,
472 applyL2L3Residual =
'Data',
473 recalibrationType =
"AK4PFchs",
475 addJECShifts =
False,
479 calculateSeparateCorrections =
False,
480 calculateType1METCorrection =
False,
481 type1METParams = {
'jetPtThreshold':15.,
'skipEMfractionThreshold':0.9,
'skipMuons':
True },
483 cleanJetsFromFirstPhoton =
False,
484 cleanJetsFromTaus =
False,
485 cleanJetsFromIsoTracks =
False,
486 alwaysCleanPhotons =
False,
488 cleanGenJetsFromPhoton =
False,
489 attachNeutrinos =
True,
490 genNuSelection =
lambda nu :
True,
491 collectionPostFix =
""
deltaMetFromJEC
Read jets, if necessary recalibrate and shift MET.
def matchObjectCollection
def matchObjectCollection2
Abs< T >::type abs(const T &t)
T1 deltaR2(T1 eta1, T2 phi1, T3 eta2, T4 phi2)