ViewVC Help
View File | Revision Log | Show Annotations | Root Listing
root/cvsroot/UserCode/Betchart/TopRefTuple/python/pf2pat.py
Revision: 1.2
Committed: Wed Nov 7 18:54:00 2012 UTC (12 years, 6 months ago) by bbetchar
Content type: text/x-python
Branch: MAIN
Changes since 1.1: +74 -43 lines
Log Message:
reorganize

File Contents

# User Rev Content
1 bbetchar 1.1 import operator,sys,os
2     from FWCore.ParameterSet import Config as cms
3     from PhysicsTools.PatAlgos.tools import coreTools,pfTools
4    
5     def tags(stuff) :
6     return ( cms.InputTag(stuff) if type(stuff)!=list else
7     cms.VInputTag([tags(item) for item in stuff]) )
8    
9     class TopRefPF2PAT(object) :
10     '''Implement the Top Reference configuration of PF2PAT.
11    
12     https://twiki.cern.ch/twiki/bin/viewauth/CMS/TWikiTopRefEventSel
13 bbetchar 1.2 Modify the PF selections to match the PAT selections, for consistent TopProjection cross-cleaning.
14 bbetchar 1.1 '''
15    
16     def __init__(self, process, options) :
17     self.stdout = sys.stdout
18     sys.stdout = open(os.devnull, 'w')
19 bbetchar 1.2 print >>self.stdout, "usePF2PAT() output suppressed. (%s)"%__file__
20 bbetchar 1.1
21     self.before = set(dir(process))
22     process.load( "PhysicsTools.PatAlgos.patSequences_cff" )
23     pfTools.usePF2PAT( process,
24     runPF2PAT = True,
25     postfix = options.postfix,
26     runOnMC = not options.isData,
27     pvCollection = tags( 'goodOfflinePrimaryVertices' ),
28     typeIMetCorrections = True,
29     jetAlgo = 'AK5',
30     jetCorrections = ('AK5PFchs', ['L1FastJet','L2Relative','L3Absolute','L2L3Residual'][:None if options.isData else -1] )
31     )
32     getattr( process, 'pfPileUpIso'+options.postfix).checkClosestZVertex = True
33     if options.isData: coreTools.runOnData( process, names = [ 'PFAll' ], postfix = options.postfix )
34     coreTools.removeSpecificPATObjects( process, names = [ 'Photons', 'Taus' ], postfix = options.postfix )
35    
36 bbetchar 1.2 self.isoValues = {'el':0.15,'mu':0.20}
37     self.eleID = 'mvaTrigV0'
38     self.minEleID = 0.
39     self.dBFactor = -0.5
40     self.cuts = {'el': ['pt>20.',
41     'abs(eta)<2.5',
42     'gsfTrackRef.isNonnull',
43     'gsfTrackRef.trackerExpectedHitsInner.numberOfLostHits<2',
44     '(chargedHadronIso+max(0.,neutralHadronIso)+photonIso+%f*puChargedHadronIso)/et < %f'%(self.dBFactor, self.isoValues['el']),
45     'electronID("%s") > %f'%(self.eleID,self.minEleID),
46     ],
47     'mu' :[#'(isGlobalMuon || isTrackerMuon)',
48     'pt>10.',
49     'abs(eta)<2.5',
50     '(chargedHadronIso+neutralHadronIso+photonIso%+f*puChargedHadronIso)/pt < %f'%(self.dBFactor, self.isoValues['mu']),
51     'isPFMuon',
52     ],
53     'jet' : ['abs(eta) < 2.5', # Careful! these jet cuts affect the typeI met corrections
54     'pt > 15.',
55     # PF jet ID:
56     'numberOfDaughters > 1',
57     'neutralHadronEnergyFraction < 0.99',
58     'neutralEmEnergyFraction < 0.99',
59     '(chargedEmEnergyFraction < 0.99 || abs(eta) >= 2.4)',
60     '(chargedHadronEnergyFraction > 0. || abs(eta) >= 2.4)',
61     '(chargedMultiplicity > 0 || abs(eta) >= 2.4)']
62     }
63    
64 bbetchar 1.1 self.process = process
65     self.options = options
66     self.fix = options.postfix
67     self.patSeq = getattr(process, 'patPF2PATSequence' + self.fix)
68     self.btags = ['combinedSecondaryVertex','jetProbability']
69     self.taginfos = ["impactParameter","secondaryVertex"]
70    
71     self.configTopProjections()
72     self.configPfLepton('el', iso3 = True)
73     self.configPfLepton('mu', iso3 = False)
74     self.configPatMuons()
75     self.configPatElectrons()
76     self.configPatJets()
77 bbetchar 1.2 self.configLeptonFilter()
78 bbetchar 1.1 self.removeCruft()
79     sys.stdout = self.stdout
80    
81     def attr(self, item) : return getattr(self.process, item)
82 bbetchar 1.2 def show(self, item) : print >> (sys.stdout if self.options.quiet else self.stdout), item, '=', self.attr(item).dumpPython() if hasattr(self.process, item) else 'Not Found.'
83 bbetchar 1.1
84     def configTopProjections(self) :
85     '''Enable TopProjections except for Taus (do not remove tau cands from jet collection).'''
86    
87     for key,val in {'PileUp':1,'Muon':1,'Electron':1,'Jet':1,'Tau':0}.items() :
88     self.attr('pfNo'+key+self.fix).enable = bool(val)
89 bbetchar 1.2 self.attr('pfNoElectron').verbose = True
90 bbetchar 1.1 return
91    
92     def configPfLepton(self, lep, iso3) :
93     full = {'el':'Electrons','mu':'Muons'}[lep] + self.fix
94     iso = self.attr('pfIsolated'+full)
95 bbetchar 1.2 iso.isolationCut = self.isoValues[lep]
96 bbetchar 1.1 iso.doDeltaBetaCorrection = True
97 bbetchar 1.2 iso.deltaBetaFactor = self.dBFactor
98     sel = self.attr('pfSelected'+full)
99     sel.cut = ' && '.join(self.cuts[lep][:-2])
100     #sel.filter = cms.bool(True)
101     #iso.filter = cms.bool(True)
102     print >>self.stdout, ""
103     if lep == 'el' :
104     idName = 'pfIdentifiedElectrons'+self.fix
105     id = cms.EDFilter("ElectronIDPFCandidateSelector",
106     src = cms.InputTag('pfElectronsFromVertex'+self.fix),
107     recoGsfElectrons = cms.InputTag("gsfElectrons"),
108     electronIdMap = cms.InputTag(self.eleID),
109     electronIdCut = cms.double(self.minEleID))
110     setattr(self.process, idName, id )
111     self.patSeq.replace( sel, id*sel)
112     sel.src = idName
113     self.show(idName)
114    
115 bbetchar 1.1 if iso3:
116     pf = {'el':'PFId','mu':''}[lep] + self.fix
117     for item in ['pf','pfIsolated'] :
118     col = self.attr( item+full )
119     col.deltaBetaIsolationValueMap = tags( lep+'PFIsoValuePU03'+pf )
120     col.isolationValueMapsCharged = tags( [lep+'PFIsoValueCharged03'+pf] )
121     col.isolationValueMapsNeutral = tags( [ lep+'PFIsoValueNeutral03'+pf, lep+'PFIsoValueGamma03'+pf] )
122     val = self.attr( 'pat'+full ).isolationValues
123     val.pfNeutralHadrons = tags( lep+'PFIsoValueNeutral03' + pf )
124     val.pfChargedAll = tags( lep+'PFIsoValueChargedAll03' + pf )
125     val.pfPUChargedHadrons = tags( lep+'PFIsoValuePU03' + pf )
126     val.pfPhotons = tags( lep+'PFIsoValueGamma03' + pf )
127     val.pfChargedHadrons = tags( lep+'PFIsoValueCharged03' + pf )
128 bbetchar 1.2
129     self.show('pfSelected'+full)
130     self.show('pfIsolated'+full)
131 bbetchar 1.1 return
132    
133     def configPatMuons(self) :
134     for mod,attr,val in [('patMuons','usePV',False), # use beam spot rather than PV, which is necessary for 'dB' cut
135     ('patMuons','embedTrack',True), # embedded track needed for muon ID cuts
136 bbetchar 1.2 ('selectedPatMuons','cut', ' && '.join(self.cuts['mu'])),
137 bbetchar 1.1 ] : setattr( self.attr(mod+self.fix), attr, val )
138     self.show('selectedPatMuons'+self.fix)
139     return
140    
141     def configPatElectrons(self) :
142 bbetchar 1.2 electronIDSources = cms.PSet(**dict([(i,tags(i)) for i in [self.eleID]]))
143     for mod,attr,val in [('patElectrons','electronIDSources', electronIDSources),
144     ('selectedPatElectrons','cut', ' && '.join(c for c in self.cuts['el'] if 'gsfTrackRef' not in c)),
145 bbetchar 1.1 ] : setattr( self.attr( mod+self.fix), attr, val )
146     self.show('selectedPatElectrons'+self.fix)
147     return
148    
149     def configPatJets(self) :
150     for mod,attr,val in [('patJets','discriminatorSources',[tags(tag+'BJetTagsAOD'+self.fix) for tag in self.btags]),
151     ('patJets','tagInfoSources',[tags(tag+'TagInfosAOD'+self.fix) for tag in self.taginfos]),
152     ('patJets','addTagInfos',True),
153 bbetchar 1.2 ('selectedPatJets','cut', ' && '.join(self.cuts['jet'])),
154 bbetchar 1.1 ] : setattr( self.attr(mod+self.fix), attr, val )
155     self.show('selectedPatJets'+self.fix)
156     return
157    
158 bbetchar 1.2 def configLeptonFilter(self) :
159     if not self.options.requireLepton : return
160     leptonsName = 'pfLeptons'+self.fix
161     requireLeptonName = 'requireLepton'+self.fix
162     leptons = cms.EDProducer("CandViewMerger", src = tags(['pfIsolated%s%s'%(lep,self.fix) for lep in ['Electrons','Muons']]))
163     requireLepton = cms.EDFilter("CandViewCountFilter", src = tags(leptonsName), minNumber = cms.uint32(1) )
164     setattr(self.process, leptonsName, leptons)
165     setattr(self.process, requireLeptonName, requireLepton)
166    
167     jets = self.attr('pfJets'+self.fix)
168     self.patSeq.replace(jets, leptons*requireLepton*jets)
169     self.show(leptonsName)
170     self.show(requireLeptonName)
171     return
172 bbetchar 1.1
173     def removeCruft(self) :
174     nothanks = [mod for mod in set(str(self.patSeq).split('+'))
175     if ( any( keyword in mod for keyword in ['count','Legacy','pfJetsPiZeros','ak7','soft','iterativeCone',
176     'tauIsoDeposit','tauGenJet','hpsPFTau','tauMatch','pfTau','hpsSelection',
177     'photonMatch','phPFIso','pfIsolatedPhotons','pfCandsNotInJet','pfCandMETcorr',
178     'Negative','ToVertex','particleFlowDisplacedVertex',
179     'ype2Corr','ype0','patType1p2CorrectedPFMet','atCandidateSummaryTR','atPFParticles'] ) or
180     ( 'JetTagsAOD' in mod and not any( (btag+'B') in mod for btag in self.btags ) ) or
181     ( 'TagInfosAOD' in mod and not any( (info+'TagInfosAOD') in mod for info in self.taginfos ) ) or
182     ( 'elPFIsoValue' in mod and ('04' in mod or 'NoPFId' in mod ) ) or
183     ( 'muPFIsoValue' in mod and ('03' in mod))) ]
184     for mod in nothanks : self.patSeq.remove( self.attr(mod) )
185    
186     nothanks = ['ic5','kt4','kt6','JPT','ak7','ak5Calo']
187     now = set(dir(self.process))
188     for item in now - self.before - set(str(self.patSeq).split('+')) :
189     if any(part in item for part in nothanks) :
190     delattr(self.process,item)
191     return