-
Notifications
You must be signed in to change notification settings - Fork 4.3k
/
runMETCorrectionsAndUncertainties.py
2086 lines (1778 loc) · 117 KB
/
runMETCorrectionsAndUncertainties.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from __future__ import print_function
import FWCore.ParameterSet.Config as cms
from PhysicsTools.PatAlgos.tools.ConfigToolBase import *
import PhysicsTools.PatAlgos.tools.helpers as configtools
from PhysicsTools.PatAlgos.tools.helpers import getPatAlgosToolsTask, addToProcessAndTask, addTaskToProcess
from PhysicsTools.PatAlgos.tools.jetTools import switchJetCollection
import CommonTools.CandAlgos.candPtrProjector_cfi as _mod
from PhysicsTools.PatUtils.tools.pfforTrkMET_cff import *
import JetMETCorrections.Type1MET.BadPFCandidateJetsEEnoiseProducer_cfi as _modbad
import JetMETCorrections.Type1MET.UnclusteredBlobProducer_cfi as _modunc
# function to determine whether a valid input tag was given
def isValidInputTag(input):
input_str = input
if isinstance(input, cms.InputTag):
input_str = input.value()
if input is None or input_str == '""':
return False
else:
return True
# class to manage the (re-)calculation of MET, its corrections, and its uncertainties
class RunMETCorrectionsAndUncertainties(ConfigToolBase):
_label='RunMETCorrectionsAndUncertainties'
_defaultParameters=dicttypes.SortedKeysDict()
def __init__(self):
ConfigToolBase.__init__(self)
# MET type, correctionlevel, and uncertainties
self.addParameter(self._defaultParameters, 'metType', "PF",
"Type of considered MET (only PF and Puppi supported so far)", Type=str, allowedValues = ["PF","Puppi"])
self.addParameter(self._defaultParameters, 'correctionLevel', [""],
"level of correction : available corrections for pfMet are T0, T1, T2, Txy and Smear)",
allowedValues=["T0","T1","T2","Txy","Smear",""])
self.addParameter(self._defaultParameters, 'computeUncertainties', True,
"enable/disable the uncertainty computation", Type=bool)
self.addParameter(self._defaultParameters, 'produceIntermediateCorrections', False,
"enable/disable the production of all correction schemes (only for the most common)", Type=bool)
# high-level object collections used e.g. for MET uncertainties or jet cleaning
self.addParameter(self._defaultParameters, 'electronCollection', cms.InputTag('selectedPatElectrons'),
"Input electron collection", Type=cms.InputTag, acceptNoneValue=True)
self.addParameter(self._defaultParameters, 'photonCollection', cms.InputTag('selectedPatPhotons'),
"Input photon collection", Type=cms.InputTag, acceptNoneValue=True)
self.addParameter(self._defaultParameters, 'muonCollection', cms.InputTag('selectedPatMuons'),
"Input muon collection", Type=cms.InputTag, acceptNoneValue=True)
self.addParameter(self._defaultParameters, 'tauCollection', cms.InputTag('selectedPatTaus'),
"Input tau collection", Type=cms.InputTag, acceptNoneValue=True)
self.addParameter(self._defaultParameters, 'jetCollectionUnskimmed', cms.InputTag('patJets'),
"Input unskimmed jet collection for T1 MET computation", Type=cms.InputTag, acceptNoneValue=True)
# pf candidate collection used for recalculation of MET from pf candidates
self.addParameter(self._defaultParameters, 'pfCandCollection', cms.InputTag('particleFlow'),
"pf Candidate collection", Type=cms.InputTag, acceptNoneValue=True)
# some options influencing MET corrections and uncertainties calculation
self.addParameter(self._defaultParameters, 'autoJetCleaning', 'LepClean',
"Enable the jet cleaning for the uncertainty computation: Full for tau/photons/jet cleaning, Partial for jet cleaning, LepClean for jet cleaning with muon and electrons only, None or Manual for no cleaning",
allowedValues = ["Full","Partial","LepClean","None"])
self.addParameter(self._defaultParameters, 'jetFlavor', 'AK4PFchs',
"Use AK4PF/AK4PFchs for PFJets,AK4Calo for CaloJets", Type=str, allowedValues = ["AK4PF","AK4PFchs","AK4PFPuppi","CaloJets"])
self.addParameter(self._defaultParameters, 'jetCorrectionType', 'L1L2L3-L1',
"Use L1L2L3-L1 for the standard L1 removal / L1L2L3-RC for the random-cone correction", Type=str, allowedValues = ["L1L2L3-L1","L1L2L3-RC"])
# technical options determining which JES corrections are used
self.addParameter(self._defaultParameters, 'jetCorLabelUpToL3', "ak4PFCHSL1FastL2L3Corrector", "Use ak4PFL1FastL2L3Corrector (ak4PFCHSL1FastL2L3Corrector) for PFJets with (without) charged hadron subtraction, ak4CaloL1FastL2L3Corrector for CaloJets", Type=str)
self.addParameter(self._defaultParameters, 'jetCorLabelL3Res', "ak4PFCHSL1FastL2L3ResidualCorrector", "Use ak4PFL1FastL2L3ResidualCorrector (ak4PFCHSL1FastL2L3ResidualCorrector) for PFJets with (without) charged hadron subtraction, ak4CaloL1FastL2L3ResidualCorrector for CaloJets", Type=str)
# the file is used only for local running
self.addParameter(self._defaultParameters, 'jecUncertaintyFile', '',
"Extra JES uncertainty file", Type=str)
self.addParameter(self._defaultParameters, 'jecUncertaintyTag', None,
"JES uncertainty Tag", acceptNoneValue=True) # Type=str,
# options to apply selections to the considered jets
self.addParameter(self._defaultParameters, 'manualJetConfig', False,
"Enable jet configuration options", Type=bool)
self.addParameter(self._defaultParameters, 'jetSelection', 'pt>15 && abs(eta)<9.9',
"Advanced jet kinematic selection", Type=str)
# flags to influence how the MET is (re-)calculated, e.g. completely from scratch or just propagating new JECs
self.addParameter(self._defaultParameters, 'recoMetFromPFCs', False,
"Recompute the MET from scratch using the pfCandidate collection", Type=bool)
self.addParameter(self._defaultParameters, 'reapplyJEC', True,
"Flag to enable/disable JEC update", Type=bool)
self.addParameter(self._defaultParameters, 'reclusterJets', False,
"Flag to enable/disable the jet reclustering", Type=bool)
self.addParameter(self._defaultParameters, 'computeMETSignificance', True,
"Flag to enable/disable the MET significance computation", Type=bool)
self.addParameter(self._defaultParameters, 'CHS', False,
"Flag to enable/disable the CHS jets", Type=bool)
# information on what dataformat or datatype we are running on
self.addParameter(self._defaultParameters, 'runOnData', False,
"Switch for data/MC processing", Type=bool)
self.addParameter(self._defaultParameters, 'onMiniAOD', False,
"Switch on miniAOD configuration", Type=bool)
# special input parameters when running over 2017 data
self.addParameter(self._defaultParameters,'fixEE2017', False,
"Exclude jets and PF candidates with EE noise characteristics (fix for 2017 run)", Type=bool)
self.addParameter(self._defaultParameters,'fixEE2017Params', {'userawPt': True, 'ptThreshold': 50.0, 'minEtaThreshold': 2.65, 'maxEtaThreshold': 3.139},
"Parameters dict for fixEE2017: userawPt, ptThreshold, minEtaThreshold, maxEtaThreshold", Type=dict)
self.addParameter(self._defaultParameters, 'extractDeepMETs', False,
"Extract DeepMETs from miniAOD, instead of recomputing them.", Type=bool)
# technical parameters
self.addParameter(self._defaultParameters, 'Puppi', False,
"Puppi algorithm (private)", Type=bool)
self.addParameter(self._defaultParameters, 'puppiProducerLabel', 'puppi',
"PuppiProducer module for jet clustering label name", Type=str)
self.addParameter(self._defaultParameters, 'puppiProducerForMETLabel', 'puppiNoLep',
"PuppiProducer module for MET clustering label name", Type=str)
self.addParameter(self._defaultParameters, 'addToPatDefaultSequence', False,
"Flag to enable/disable that metUncertaintySequence is inserted into patDefaultSequence", Type=bool)
self.addParameter(self._defaultParameters, 'postfix', '',
"Technical parameter to identify the resulting sequences/tasks and its corresponding modules (allows multiple calls in a job)", Type=str)
self.addParameter(self._defaultParameters, 'campaign', '', 'Production campaign', Type=str)
self.addParameter(self._defaultParameters, 'era', '', 'Era e.g. 2018, 2017B, ...', Type=str)
# make another parameter collection by copying the default parameters collection
# later adapt the newly created parameter collection to always have a copy of the default parameters
self._parameters = copy.deepcopy(self._defaultParameters)
self._comment = ""
# function to return the saved default parameters of the class
def getDefaultParameters(self):
return self._defaultParameters
#=========================================================================================
# implement __call__ function to be able to use class instances like functions
# reads the given parameters and saves them
# runs the toolCode function in the end
def __call__(self, process,
metType =None,
correctionLevel =None,
computeUncertainties =None,
produceIntermediateCorrections = None,
electronCollection =None,
photonCollection =None,
muonCollection =None,
tauCollection =None,
jetCollectionUnskimmed =None,
pfCandCollection =None,
autoJetCleaning =None,
jetFlavor =None,
jetCorr =None,
jetCorLabelUpToL3 =None,
jetCorLabelL3Res =None,
jecUncertaintyFile =None,
jecUncertaintyTag =None,
addToPatDefaultSequence =None,
manualJetConfig =None,
jetSelection =None,
recoMetFromPFCs =None,
reapplyJEC =None,
reclusterJets =None,
computeMETSignificance =None,
CHS =None,
puppiProducerLabel =None,
puppiProducerForMETLabel = None,
runOnData =None,
onMiniAOD =None,
fixEE2017 =None,
fixEE2017Params =None,
extractDeepMETs =None,
campaign =None,
era =None,
postfix =None):
electronCollection = self.initializeInputTag(electronCollection, 'electronCollection')
photonCollection = self.initializeInputTag(photonCollection, 'photonCollection')
muonCollection = self.initializeInputTag(muonCollection, 'muonCollection')
tauCollection = self.initializeInputTag(tauCollection, 'tauCollection')
jetCollectionUnskimmed = self.initializeInputTag(jetCollectionUnskimmed, 'jetCollectionUnskimmed')
pfCandCollection = self.initializeInputTag(pfCandCollection, 'pfCandCollection')
if metType is None :
metType = self._defaultParameters['metType'].value
if correctionLevel is None :
correctionLevel = self._defaultParameters['correctionLevel'].value
if computeUncertainties is None :
computeUncertainties = self._defaultParameters['computeUncertainties'].value
if produceIntermediateCorrections is None :
produceIntermediateCorrections = self._defaultParameters['produceIntermediateCorrections'].value
if electronCollection is None :
electronCollection = self._defaultParameters['electronCollection'].value
if photonCollection is None :
photonCollection = self._defaultParameters['photonCollection'].value
if muonCollection is None :
muonCollection = self._defaultParameters['muonCollection'].value
if tauCollection is None :
tauCollection = self._defaultParameters['tauCollection'].value
if jetCollectionUnskimmed is None :
jetCollectionUnskimmed = self._defaultParameters['jetCollectionUnskimmed'].value
if pfCandCollection is None :
pfCandCollection = self._defaultParameters['pfCandCollection'].value
if autoJetCleaning is None :
autoJetCleaning = self._defaultParameters['autoJetCleaning'].value
if jetFlavor is None :
jetFlavor = self._defaultParameters['jetFlavor'].value
if jetCorr is None :
jetCorr = self._defaultParameters['jetCorrectionType'].value
if jetCorLabelUpToL3 is None:
jetCorLabelUpToL3 = self._defaultParameters['jetCorLabelUpToL3'].value
if jetCorLabelL3Res is None:
jetCorLabelL3Res = self._defaultParameters['jetCorLabelL3Res'].value
if jecUncertaintyFile is None:
jecUncertaintyFile = self._defaultParameters['jecUncertaintyFile'].value
if jecUncertaintyTag is None:
jecUncertaintyTag = self._defaultParameters['jecUncertaintyTag'].value
if addToPatDefaultSequence is None :
addToPatDefaultSequence = self._defaultParameters['addToPatDefaultSequence'].value
if manualJetConfig is None :
manualJetConfig = self._defaultParameters['manualJetConfig'].value
if jetSelection is None :
jetSelection = self._defaultParameters['jetSelection'].value
recoMetFromPFCsIsNone = (recoMetFromPFCs is None)
if recoMetFromPFCs is None :
recoMetFromPFCs = self._defaultParameters['recoMetFromPFCs'].value
if reapplyJEC is None :
reapplyJEC = self._defaultParameters['reapplyJEC'].value
reclusterJetsIsNone = (reclusterJets is None)
if reclusterJets is None :
reclusterJets = self._defaultParameters['reclusterJets'].value
if computeMETSignificance is None :
computeMETSignificance = self._defaultParameters['computeMETSignificance'].value
if CHS is None :
CHS = self._defaultParameters['CHS'].value
if puppiProducerLabel is None:
puppiProducerLabel = self._defaultParameters['puppiProducerLabel'].value
if puppiProducerForMETLabel is None:
puppiProducerForMETLabel = self._defaultParameters['puppiProducerForMETLabel'].value
if runOnData is None :
runOnData = self._defaultParameters['runOnData'].value
if onMiniAOD is None :
onMiniAOD = self._defaultParameters['onMiniAOD'].value
if postfix is None :
postfix = self._defaultParameters['postfix'].value
if fixEE2017 is None :
fixEE2017 = self._defaultParameters['fixEE2017'].value
if fixEE2017Params is None :
fixEE2017Params = self._defaultParameters['fixEE2017Params'].value
if extractDeepMETs is None :
extractDeepMETs = self._defaultParameters['extractDeepMETs'].value
if campaign is None :
campaign = self._defaultParameters['campaign'].value
if era is None :
era = self._defaultParameters['era'].value
self.setParameter('metType',metType),
self.setParameter('correctionLevel',correctionLevel),
self.setParameter('computeUncertainties',computeUncertainties),
self.setParameter('produceIntermediateCorrections',produceIntermediateCorrections),
self.setParameter('electronCollection',electronCollection),
self.setParameter('photonCollection',photonCollection),
self.setParameter('muonCollection',muonCollection),
self.setParameter('tauCollection',tauCollection),
self.setParameter('jetCollectionUnskimmed',jetCollectionUnskimmed),
self.setParameter('pfCandCollection',pfCandCollection),
self.setParameter('autoJetCleaning',autoJetCleaning),
self.setParameter('jetFlavor',jetFlavor),
#optional
self.setParameter('jecUncertaintyFile',jecUncertaintyFile),
self.setParameter('jecUncertaintyTag',jecUncertaintyTag),
self.setParameter('addToPatDefaultSequence',addToPatDefaultSequence),
self.setParameter('jetSelection',jetSelection),
self.setParameter('recoMetFromPFCs',recoMetFromPFCs),
self.setParameter('reclusterJets',reclusterJets),
self.setParameter('computeMETSignificance',computeMETSignificance),
self.setParameter('reapplyJEC',reapplyJEC),
self.setParameter('CHS',CHS),
self.setParameter('puppiProducerLabel',puppiProducerLabel),
self.setParameter('puppiProducerForMETLabel',puppiProducerForMETLabel),
self.setParameter('runOnData',runOnData),
self.setParameter('onMiniAOD',onMiniAOD),
self.setParameter('postfix',postfix),
self.setParameter('fixEE2017',fixEE2017),
self.setParameter('fixEE2017Params',fixEE2017Params),
self.setParameter('extractDeepMETs',extractDeepMETs),
self.setParameter('campaign',campaign),
self.setParameter('era',era),
# if puppi MET, autoswitch to std jets
if metType == "Puppi":
self.setParameter('CHS',False),
# enabling puppi flag
# metType is set back to PF because the necessary adaptions are handled via a postfix and directly changing parameters when Puppi parameter is true
self.setParameter('Puppi',self._defaultParameters['Puppi'].value)
if metType == "Puppi":
self.setParameter('metType',"PF")
self.setParameter('Puppi',True)
# jet energy scale uncertainty needs
if manualJetConfig:
self.setParameter('CHS',CHS)
self.setParameter('jetCorLabelUpToL3',jetCorLabelUpToL3)
self.setParameter('jetCorLabelL3Res',jetCorLabelL3Res)
self.setParameter('reclusterJets',reclusterJets)
else:
# internal jet configuration
self.jetConfiguration()
# defaults for 2017 fix
# (don't need to recluster, just uses a subset of the input jet coll)
if fixEE2017:
if recoMetFromPFCsIsNone: self.setParameter('recoMetFromPFCs',True)
if reclusterJetsIsNone: self.setParameter('reclusterJets',False)
# met reprocessing and jet reclustering
if recoMetFromPFCs and reclusterJetsIsNone and not fixEE2017:
self.setParameter('reclusterJets',True)
self.apply(process)
def toolCode(self, process):
################################
### 1. read given parameters ###
################################
# MET type, corrections, and uncertainties
metType = self._parameters['metType'].value
correctionLevel = self._parameters['correctionLevel'].value
computeUncertainties = self._parameters['computeUncertainties'].value
produceIntermediateCorrections = self._parameters['produceIntermediateCorrections'].value
# physics object collections to consider when recalculating MET
electronCollection = self._parameters['electronCollection'].value
photonCollection = self._parameters['photonCollection'].value
muonCollection = self._parameters['muonCollection'].value
tauCollection = self._parameters['tauCollection'].value
jetCollectionUnskimmed = self._parameters['jetCollectionUnskimmed'].value
pfCandCollection = self._parameters['pfCandCollection'].value
# jet specific options: jet corrections/uncertainties as well as jet selection/cleaning options
jetSelection = self._parameters['jetSelection'].value
autoJetCleaning = self._parameters['autoJetCleaning'].value
jetFlavor = self._parameters['jetFlavor'].value
jetCorLabelUpToL3 = self._parameters['jetCorLabelUpToL3'].value
jetCorLabelL3Res = self._parameters['jetCorLabelL3Res'].value
jecUncertaintyFile = self._parameters['jecUncertaintyFile'].value
jecUncertaintyTag = self._parameters['jecUncertaintyTag'].value
# additional MET calculation/extraction options
recoMetFromPFCs = self._parameters['recoMetFromPFCs'].value
reapplyJEC = self._parameters['reapplyJEC'].value
reclusterJets = self._parameters['reclusterJets'].value
computeMETSignificance = self._parameters['computeMETSignificance'].value
extractDeepMETs = self._parameters['extractDeepMETs'].value
# specific option for 2017 EE noise mitigation
fixEE2017 = self._parameters['fixEE2017'].value
fixEE2017Params = self._parameters['fixEE2017Params'].value
campaign = self._parameters['campaign'].value
era = self._parameters['era'].value
# additional runtime options
onMiniAOD = self._parameters['onMiniAOD'].value
addToPatDefaultSequence = self._parameters['addToPatDefaultSequence'].value
postfix = self._parameters['postfix'].value
# prepare jet configuration used during MET (re-)calculation
jetUncInfos = {
"jCorrPayload":jetFlavor,
"jCorLabelUpToL3":jetCorLabelUpToL3,
"jCorLabelL3Res":jetCorLabelL3Res,
"jecUncFile":jecUncertaintyFile,
"jecUncTag":"Uncertainty"
}
# get jet uncertainties from file
if (jecUncertaintyFile!="" and jecUncertaintyTag==None):
jetUncInfos[ "jecUncTag" ] = ""
# get jet uncertainties from tag
elif (jecUncertaintyTag!=None):
jetUncInfos[ "jecUncTag" ] = jecUncertaintyTag
#############################
### 2. (re-)construct MET ###
#############################
# task for main MET construction modules
patMetModuleTask = cms.Task()
# 2017 EE fix will modify pf cand and jet collections used downstream
if fixEE2017:
pfCandCollection, jetCollectionUnskimmed = self.runFixEE2017(process,
fixEE2017Params,
jetCollectionUnskimmed,
pfCandCollection,
[electronCollection,muonCollection,tauCollection,photonCollection],
patMetModuleTask,
postfix,
)
# recompute the MET (and thus the jets as well for correction) from scratch i.e. from pfcandidates
if recoMetFromPFCs:
self.recomputeRawMetFromPfcs(process,
pfCandCollection,
onMiniAOD,
patMetModuleTask,
postfix)
# if not using pfcandidates, you also can extract the raw MET from MiniAOD
elif onMiniAOD:
self.extractMET(process, "raw", patMetModuleTask, postfix)
# jet AK4 reclustering if needed for JECs ...
if reclusterJets:
jetCollectionUnskimmed = self.ak4JetReclustering(process, pfCandCollection,
patMetModuleTask, postfix)
# ... or reapplication of JECs to already existing jets in MiniAOD
if onMiniAOD:
if not reclusterJets and reapplyJEC:
jetCollectionUnskimmed = self.updateJECs(process, jetCollectionUnskimmed, patMetModuleTask, postfix)
# getting the jet collection that will be used for corrections and uncertainty computation
# starts with the unskimmed jet collection and applies some selection and cleaning criteria
jetCollection = self.getJetCollectionForCorsAndUncs(process,
jetCollectionUnskimmed,
jetSelection,
autoJetCleaning,
patMetModuleTask,
postfix)
if onMiniAOD:
# obtain specific METs (caloMET, DeepMET, PFCHS MET, TRKMET) from MiniAOD
self.miniAODConfigurationPre(process, patMetModuleTask, pfCandCollection, postfix)
else:
from PhysicsTools.PatUtils.pfeGammaToCandidate_cfi import pfeGammaToCandidate
addToProcessAndTask("pfeGammaToCandidate", pfeGammaToCandidate.clone(
electrons = copy.copy(electronCollection),
photons = copy.copy(photonCollection)),
process, patMetModuleTask)
if hasattr(process,"patElectrons") and process.patElectrons.electronSource == cms.InputTag("reducedEgamma","reducedGedGsfElectrons"):
process.pfeGammaToCandidate.electron2pf = "reducedEgamma:reducedGsfElectronPfCandMap"
if hasattr(process,"patPhotons") and process.patPhotons.photonSource == cms.InputTag("reducedEgamma","reducedGedPhotons"):
process.pfeGammaToCandidate.photon2pf = "reducedEgamma:reducedPhotonPfCandMap"
# default MET production
self.produceMET(process, metType, patMetModuleTask, postfix)
# preparation to run over miniAOD (met reproduction)
if onMiniAOD:
self.miniAODConfiguration(process,
pfCandCollection,
jetCollection,
patMetModuleTask,
postfix
)
###########################
### 3. (re-)correct MET ###
###########################
patMetCorrectionTask = cms.Task()
metModName = self.getCorrectedMET(process, metType, correctionLevel,
produceIntermediateCorrections,
jetCollection,
patMetCorrectionTask, postfix )
# fix the default jets for the type1 computation to those used to compute the uncertainties
# in order to be consistent with what is done in the correction and uncertainty step
# particularly true for miniAODs
if "T1" in metModName:
getattr(process,"patPFMetT1T2Corr"+postfix).src = jetCollection
getattr(process,"patPFMetT2Corr"+postfix).src = jetCollection
#ZD:puppi currently doesn't have the L1 corrections in the GT
if self._parameters["Puppi"].value:
getattr(process,"patPFMetT1T2Corr"+postfix).offsetCorrLabel = cms.InputTag("")
getattr(process,"patPFMetT2Corr"+postfix).offsetCorrLabel = cms.InputTag("")
if "Smear" in metModName:
getattr(process,"patSmearedJets"+postfix).src = jetCollection
if self._parameters["Puppi"].value:
getattr(process,"patPFMetT1T2SmearCorr"+postfix).offsetCorrLabel = cms.InputTag("")
####################################
### 4. compute MET uncertainties ###
####################################
patMetUncertaintyTask = cms.Task()
if not hasattr(process, "patMetUncertaintyTask"+postfix):
if self._parameters["Puppi"].value:
patMetUncertaintyTask.add(cms.Task(getattr(process, "ak4PFPuppiL1FastL2L3CorrectorTask"),getattr(process, "ak4PFPuppiL1FastL2L3ResidualCorrectorTask")))
else:
patMetUncertaintyTask.add(cms.Task(getattr(process, "ak4PFCHSL1FastL2L3CorrectorTask"),getattr(process, "ak4PFCHSL1FastL2L3ResidualCorrectorTask")))
patShiftedModuleTask = cms.Task()
if computeUncertainties:
self.getMETUncertainties(process, metType, metModName,
electronCollection,
photonCollection,
muonCollection,
tauCollection,
pfCandCollection,
jetCollection,
jetUncInfos,
patMetUncertaintyTask,
postfix)
####################################
### 5. Bring everything together ###
####################################
# add main MET tasks to process
addTaskToProcess(process, "patMetCorrectionTask"+postfix, patMetCorrectionTask)
addTaskToProcess(process, "patMetUncertaintyTask"+postfix, patMetUncertaintyTask)
addTaskToProcess(process, "patShiftedModuleTask"+postfix, patShiftedModuleTask)
addTaskToProcess(process, "patMetModuleTask"+postfix, patMetModuleTask)
# prepare and fill the final task containing all the sub-tasks
fullPatMetTask = cms.Task()
fullPatMetTask.add(getattr(process, "patMetModuleTask"+postfix))
fullPatMetTask.add(getattr(process, "patMetCorrectionTask"+postfix))
fullPatMetTask.add(getattr(process, "patMetUncertaintyTask"+postfix))
fullPatMetTask.add(getattr(process, "patShiftedModuleTask"+postfix))
# include calo MET in final MET task
if hasattr(process, "patCaloMet"):
fullPatMetTask.add(getattr(process, "patCaloMet"))
# include deepMETsResolutionTune and deepMETsResponseTune into final MET task
if hasattr(process, "deepMETsResolutionTune"):
fullPatMetTask.add(getattr(process, "deepMETsResolutionTune"))
if hasattr(process, "deepMETsResponseTune"):
fullPatMetTask.add(getattr(process, "deepMETsResponseTune"))
# adding the slimmed MET module to final MET task
if hasattr(process, "slimmedMETs"+postfix):
fullPatMetTask.add(getattr(process, "slimmedMETs"+postfix))
# add final MET task to the process
addTaskToProcess(process, "fullPatMetTask"+postfix, fullPatMetTask)
# add final MET task to the complete PatAlgosTools task
task = getPatAlgosToolsTask(process)
task.add(getattr(process,"fullPatMetTask"+postfix))
#removing the non used jet selectors
#configtools.removeIfInSequence(process, "selectedPatJetsForMetT1T2Corr", "patPFMetT1T2CorrSequence", postfix )
#last modification for miniAODs
self.miniAODConfigurationPost(process, postfix)
# insert the fullPatMetSequence into patDefaultSequence if needed
if addToPatDefaultSequence:
if not hasattr(process, "patDefaultSequence"):
raise ValueError("PAT default sequence is not defined !!")
process.patDefaultSequence += getattr(process, "fullPatMetSequence"+postfix)
#====================================================================================================
def produceMET(self, process, metType, patMetModuleTask, postfix):
# create a local task and a corresponding label to collect all the modules added in this function
produceMET_task, produceMET_label = cms.Task(), "produceMET_task{}".format(postfix)
# if PF MET is requested and not already part of the process object, then load the necessary configs and add them to the subtask
if metType == "PF" and not hasattr(process, 'pat'+metType+'Met'):
process.load("PhysicsTools.PatUtils.patPFMETCorrections_cff")
produceMET_task.add(process.producePatPFMETCorrectionsTask)
produceMET_task.add(process.patPFMetT2SmearCorrTask)
produceMET_task.add(process.patPFMetTxyCorrTask)
produceMET_task.add(process.jetCorrectorsTask)
# account for a possible postfix
_myPatMet = 'pat'+metType+'Met'+postfix
# if a postfix is requested, the MET type is PF MET, and there is not already an associated object in the process object, then add the needed modules
if postfix != "" and metType == "PF" and not hasattr(process, _myPatMet):
noClonesTmp = [ "particleFlowDisplacedVertex", "pfCandidateToVertexAssociation" ]
# clone the PF MET correction task, add it to the process with a postfix, and add it to the patAlgosToolsTask but exclude the modules above
# QUESTION: is it possible to add this directly to the subtask?
configtools.cloneProcessingSnippetTask(process, getattr(process,"producePatPFMETCorrectionsTask"), postfix, noClones = noClonesTmp)
produceMET_task.add(getattr(process,"producePatPFMETCorrectionsTask"+postfix))
# add a clone of the patPFMet producer to the process and the subtask
addToProcessAndTask(_myPatMet, getattr(process,'patPFMet').clone(), process, produceMET_task)
# adapt some inputs of the patPFMet producer to account e.g. for the postfix
getattr(process, _myPatMet).metSource = cms.InputTag("pfMet"+postfix)
getattr(process, _myPatMet).srcPFCands = copy.copy(self.getvalue("pfCandCollection"))
# account for possibility of Puppi
if self.getvalue("Puppi"):
getattr(process, _myPatMet).srcWeights = self._parameters['puppiProducerForMETLabel'].value
# set considered electrons, muons, and photons depending on data tier
if metType == "PF":
getattr(process, _myPatMet).srcLeptons = \
cms.VInputTag(copy.copy(self.getvalue("electronCollection")) if self.getvalue("onMiniAOD") else
cms.InputTag("pfeGammaToCandidate","electrons"),
copy.copy(self.getvalue("muonCollection")),
copy.copy(self.getvalue("photonCollection")) if self.getvalue("onMiniAOD") else
cms.InputTag("pfeGammaToCandidate","photons"))
# if running on data, remove generator quantities
if self.getvalue("runOnData"):
getattr(process, _myPatMet).addGenMET = False
# add PAT MET producer to subtask
produceMET_task.add(getattr(process, _myPatMet ))
# add the local task to the process
addTaskToProcess(process, produceMET_label, produceMET_task)
# add the task to the patMetModuleTask of the toolCode function
patMetModuleTask.add(getattr(process, produceMET_label))
#====================================================================================================
def getCorrectedMET(self, process, metType, correctionLevel, produceIntermediateCorrections,
jetCollection, metModuleTask, postfix):
# default outputs
getCorrectedMET_task, getCorrectedMET_label = cms.Task(), "getCorrectedMET_task{}".format(postfix)
# metModName -> metModuleName
metModName = "pat"+metType+"Met"+postfix
# names of correction types
# not really needed but in case we have changes in the future ...
corTypeNames = {
"T0":"T0pc",
"T1":"T1",
"T2":"T2",
"Txy":"Txy",
"Smear":"Smear",
}
# if empty correction level, no need to try something or stop if an unknown correction type is used
for corType in correctionLevel:
if corType not in corTypeNames.keys():
if corType != "":
raise ValueError(corType+" is not a proper MET correction name! Aborting the MET correction production")
else:
return metModName
# names of the tasks implementing a specific corretion type, see PatUtils/python/patPFMETCorrections_cff.py
corTypeTaskNames = {
"T0": "patPFMetT0CorrTask"+postfix,
"T1": "patPFMetT1T2CorrTask"+postfix,
"T2": "patPFMetT2CorrTask"+postfix,
"Txy": "patPFMetTxyCorrTask"+postfix,
"Smear": "patPFMetSmearCorrTask"+postfix,
"T2Smear": "patPFMetT2SmearCorrTask"+postfix
}
# if a postfix is requested, clone the needed correction task to the configs and a add a postfix
# this adds all the correction tasks for all the other METs e.g. PuppiMET due to the postfix
if postfix != "":
noClonesTmp = [ "particleFlowDisplacedVertex", "pfCandidateToVertexAssociation" ]
if not hasattr(process, "patPFMetT0CorrTask"+postfix):
configtools.cloneProcessingSnippetTask(process, getattr(process,"patPFMetT0CorrTask"), postfix, noClones = noClonesTmp)
getCorrectedMET_task.add(getattr(process,"patPFMetT0CorrTask"+postfix))
if not hasattr(process, "patPFMetT1T2CorrTask"+postfix):
configtools.cloneProcessingSnippetTask(process, getattr(process,"patPFMetT1T2CorrTask"), postfix)
getCorrectedMET_task.add(getattr(process,"patPFMetT1T2CorrTask"+postfix))
if not hasattr(process, "patPFMetT2CorrTask"+postfix):
configtools.cloneProcessingSnippetTask(process, getattr(process,"patPFMetT2CorrTask"), postfix)
getCorrectedMET_task.add(getattr(process,"patPFMetT2CorrTask"+postfix))
if not hasattr(process, "patPFMetTxyCorrTask"+postfix):
configtools.cloneProcessingSnippetTask(process, getattr(process,"patPFMetTxyCorrTask"), postfix)
getCorrectedMET_task.add(getattr(process,"patPFMetTxyCorrTask"+postfix))
if not hasattr(process, "patPFMetSmearCorrTask"+postfix):
configtools.cloneProcessingSnippetTask(process, getattr(process,"patPFMetSmearCorrTask"), postfix)
getCorrectedMET_task.add(getattr(process,"patPFMetSmearCorrTask"+postfix))
if not hasattr(process, "patPFMetT2SmearCorrTask"+postfix):
configtools.cloneProcessingSnippetTask(process, getattr(process,"patPFMetT2SmearCorrTask"), postfix)
getCorrectedMET_task.add(getattr(process,"patPFMetT2SmearCorrTask"+postfix))
# collect the MET correction tasks, which have been added to the process, in a dict
corTypeTasks = {}
for corType in corTypeTaskNames.keys():
corTypeTasks[corType] = getattr(process, corTypeTaskNames[corType] )
# the names of the products which are created by the MET correction tasks and added to the event
corTypeTags = {
"T0":['patPFMetT0Corr'+postfix,''],
"T1":['patPFMetT1T2Corr'+postfix, 'type1'],
"T2":['patPFMetT2Corr'+postfix, 'type2'],
"Txy": ['patPFMetTxyCorr'+postfix,''],
"Smear":['patPFMetT1T2SmearCorr'+postfix, 'type1'],
"T2Smear":['patPFMetT2SmearCorr'+postfix, 'type2']
}
# build the correction string (== correction level), collect the corresponding corrections, and collect the needed tasks
correctionScheme=""
correctionProducts = []
correctionTasks = []
for corType in correctionLevel:
correctionScheme += corTypeNames[corType]
correctionProducts.append(cms.InputTag(corTypeTags[corType][0],corTypeTags[corType][1]))
correctionTasks.append(corTypeTasks[corType])
# T2 and smearing corModuleTag switch, specific case
if "T2" in correctionLevel and "Smear" in correctionLevel:
correctionProducts.append(cms.InputTag(corTypeTags["T2Smear"][0],corTypeTags["T2Smear"][1]))
correctionTasks.append(corTypeTasks["T2Smear"])
# if both are here, consider smeared corJets for the full T1+Smear correction
if "T1" in correctionLevel and "Smear" in correctionLevel:
correctionProducts.remove(cms.InputTag(corTypeTags["T1"][0],corTypeTags["T1"][1]))
# Txy parameter tuning
if "Txy" in correctionLevel:
datamc = "DATA" if self.getvalue("runOnData") else "MC"
self.tuneTxyParameters(process, correctionScheme, postfix, datamc, self.getvalue("campaign"), self.getvalue("era"))
getattr(process, "patPFMetTxyCorr"+postfix).srcPFlow = self._parameters["pfCandCollection"].value
if self.getvalue("Puppi"):
getattr(process, "patPFMetTxyCorr"+postfix).srcWeights = self._parameters['puppiProducerForMETLabel'].value
# Enable MET significance if the type1 MET is computed
if "T1" in correctionLevel:
_myPatMet = "pat"+metType+"Met"+postfix
getattr(process, _myPatMet).computeMETSignificance = cms.bool(self.getvalue("computeMETSignificance"))
getattr(process, _myPatMet).srcPFCands = copy.copy(self.getvalue("pfCandCollection"))
getattr(process, _myPatMet).srcLeptons = \
cms.VInputTag(copy.copy(self.getvalue("electronCollection")) if self.getvalue("onMiniAOD") else
cms.InputTag("pfeGammaToCandidate","electrons"),
copy.copy(self.getvalue("muonCollection")),
copy.copy(self.getvalue("photonCollection")) if self.getvalue("onMiniAOD") else
cms.InputTag("pfeGammaToCandidate","photons"))
if postfix=="NoHF":
getattr(process, _myPatMet).computeMETSignificance = cms.bool(False)
if self.getvalue("runOnData"):
from RecoMET.METProducers.METSignificanceParams_cfi import METSignificanceParams_Data
getattr(process, _myPatMet).parameters = METSignificanceParams_Data
if self.getvalue("Puppi"):
getattr(process, _myPatMet).srcWeights = self._parameters['puppiProducerForMETLabel'].value
getattr(process, _myPatMet).srcJets = cms.InputTag('cleanedPatJets'+postfix)
getattr(process, _myPatMet).srcJetSF = 'AK4PFPuppi'
getattr(process, _myPatMet).srcJetResPt = 'AK4PFPuppi_pt'
getattr(process, _myPatMet).srcJetResPhi = 'AK4PFPuppi_phi'
# MET significance bypass for the patMETs from AOD
if not self._parameters["onMiniAOD"].value and not postfix=="NoHF":
_myPatMet = "patMETs"+postfix
getattr(process, _myPatMet).computeMETSignificance = cms.bool(self.getvalue("computeMETSignificance"))
getattr(process, _myPatMet).srcPFCands=copy.copy(self.getvalue("pfCandCollection"))
getattr(process, _myPatMet).srcLeptons = \
cms.VInputTag(copy.copy(self.getvalue("electronCollection")) if self.getvalue("onMiniAOD") else
cms.InputTag("pfeGammaToCandidate","electrons"),
copy.copy(self.getvalue("muonCollection")),
copy.copy(self.getvalue("photonCollection")) if self.getvalue("onMiniAOD") else
cms.InputTag("pfeGammaToCandidate","photons"))
if self.getvalue("Puppi"):
getattr(process, _myPatMet).srcWeights = self._parameters['puppiProducerForMETLabel'].value
if hasattr(process, "patCaloMet"):
getattr(process, "patCaloMet").computeMETSignificance = cms.bool(False)
# T1 parameter tuning when CHS jets are not used
if "T1" in correctionLevel and not self._parameters["CHS"].value and not self._parameters["Puppi"].value:
addToProcessAndTask("corrPfMetType1"+postfix, getattr(process, "corrPfMetType1" ).clone(), process, getCorrectedMET_task)
getattr(process, "corrPfMetType1"+postfix).src = cms.InputTag("ak4PFJets"+postfix)
getattr(process, "corrPfMetType1"+postfix).jetCorrLabel = cms.InputTag("ak4PFL1FastL2L3Corrector")
getattr(process, "corrPfMetType1"+postfix).jetCorrLabelRes = cms.InputTag("ak4PFL1FastL2L3ResidualCorrector")
getattr(process, "corrPfMetType1"+postfix).offsetCorrLabel = cms.InputTag("ak4PFL1FastjetCorrector")
getattr(process, "basicJetsForMet"+postfix).offsetCorrLabel = cms.InputTag("ak4PFL1FastjetCorrector")
if "T1" in correctionLevel and self._parameters["Puppi"].value:
addToProcessAndTask("corrPfMetType1"+postfix, getattr(process, "corrPfMetType1" ).clone(), process, getCorrectedMET_task)
getattr(process, "corrPfMetType1"+postfix).src = cms.InputTag("ak4PFJets"+postfix)
getattr(process, "corrPfMetType1"+postfix).jetCorrLabel = cms.InputTag("ak4PFPuppiL1FastL2L3Corrector")
getattr(process, "corrPfMetType1"+postfix).jetCorrLabelRes = cms.InputTag("ak4PFPuppiL1FastL2L3ResidualCorrector")
getattr(process, "corrPfMetType1"+postfix).offsetCorrLabel = cms.InputTag("ak4PFPuppiL1FastjetCorrector")
getattr(process, "basicJetsForMet"+postfix).offsetCorrLabel = cms.InputTag("L1FastJet")
if "T1" in correctionLevel and self._parameters["CHS"].value and self._parameters["reclusterJets"].value:
getattr(process, "corrPfMetType1"+postfix).src = cms.InputTag("ak4PFJetsCHS"+postfix)
# create the main MET producer with the applied correction scheme
metModName = "pat"+metType+"Met"+correctionScheme+postfix
taskName=""
corMetProducer=None
# this should always be true due to the way e.g. PuppiMET is handled (metType is set back to PF and the puppi flag is set to true instead)
if metType == "PF":
corMetProducer = cms.EDProducer("CorrectedPATMETProducer",
src = cms.InputTag('pat'+metType+'Met' + postfix),
srcCorrections = cms.VInputTag(correctionProducts)
)
taskName="getCorrectedMET_task"
addToProcessAndTask(metModName, corMetProducer, process, getCorrectedMET_task)
# adding the full sequence only if it does not exist
if not hasattr(process, getCorrectedMET_label):
for corTask in correctionTasks:
getCorrectedMET_task.add(corTask)
# if it exists, only add the missing correction modules, no need to redo everything
else:
for corType in corTypeTaskNames.keys():
if not configtools.contains(getCorrectedMET_task, corTypeTags[corType][0]) and corType in correctionLevel:
getCorrectedMET_task.add(corTypeTasks[corType])
# plug the main patMetproducer
getCorrectedMET_task.add(getattr(process, metModName))
addTaskToProcess(process, getCorrectedMET_label, getCorrectedMET_task)
metModuleTask.add(getattr(process, getCorrectedMET_label))
# create the intermediate MET steps
# and finally add the met producers in the sequence for scheduled mode
if produceIntermediateCorrections:
interMets = self.addIntermediateMETs(process, metType, correctionLevel, correctionScheme, corTypeTags,corTypeNames, postfix)
for met in interMets.keys():
addToProcessAndTask(met, interMets[met], process, getCorrectedMET_task)
return metModName
#====================================================================================================
def addIntermediateMETs(self, process, metType, correctionLevel, corScheme, corTags, corNames, postfix):
interMets = {}
# we don't want to duplicate an exisiting module if we ask for a simple 1-corr scheme
if len(correctionLevel) == 1:
return interMets
#ugly, but it works
nCor=len(correctionLevel)+1
ids = [0]*nCor
for i in range(nCor**nCor):
tmp=i
exists=False
corName=""
corrections = []
for j in range(nCor):
ids[j] = tmp%nCor
tmp = tmp//nCor
if j != 0 and ids[j-1] < ids[j]:
exists=True
for k in range(0,j):
if ids[k] == ids[j] and ids[k]!=0:
exists=True
if exists or sum(ids[j] for j in range(nCor))==0:
continue
for cor in range(nCor):
cid = ids[nCor-cor-1]
cKey = correctionLevel[cid-1]
if cid ==0:#empty correction
continue
else :
corName += corNames[cKey]
corrections.append( cms.InputTag(corTags[ cKey ][0], corTags[ cKey ][1]) )
if corName == corScheme:
continue
corName='pat'+metType+'Met' + corName + postfix
if configtools.contains(getattr(process,"getCorrectedMET_task"+postfix), corName ) and hasattr(process, corName):
continue
interMets[corName] = cms.EDProducer("CorrectedPATMETProducer",
src = cms.InputTag('pat'+metType+'Met' + postfix),
srcCorrections = cms.VInputTag(corrections)
)
return interMets
#====================================================================================================
def getMETUncertainties(self, process, metType, metModName, electronCollection,
photonCollection, muonCollection, tauCollection,
pfCandCollection, jetCollection, jetUncInfos,
patMetUncertaintyTask,
postfix):
# create a local task and a corresponding label to collect all the modules added in this function
getMETUncertainties_task, getMETUncertainties_label = cms.Task(), "getMETUncertainties_task{}".format(postfix)
#===================================================================================
# jet energy resolution shifts
#===================================================================================
if not isValidInputTag(jetCollection): #or jetCollection=="":
print("INFO : jet collection %s does not exists, no energy resolution shifting will be performed in MET uncertainty tools" % jetCollection)
else:
preId=""
if "Smear" in metModName:
preId="Smeared"
metJERUncModules = self.getVariations(process, metModName, "Jet",preId, jetCollection, "Res", patMetUncertaintyTask, postfix=postfix )
for mod in metJERUncModules.keys():
addToProcessAndTask(mod, metJERUncModules[mod], process, getMETUncertainties_task)
#===================================================================================
# Unclustered energy candidates
#===================================================================================
if not hasattr(process, "pfCandsForUnclusteredUnc"+postfix):
#Jet projection ==
pfCandsNoJets = _mod.candPtrProjector.clone(
src = pfCandCollection,
veto = jetCollection,
)
addToProcessAndTask("pfCandsNoJets"+postfix, pfCandsNoJets, process, getMETUncertainties_task)
#electron projection ==
pfCandsNoJetsNoEle = _mod.candPtrProjector.clone(
src = "pfCandsNoJets"+postfix,
veto = electronCollection,
)
if not self.getvalue("onMiniAOD"):
pfCandsNoJetsNoEle.veto = "pfeGammaToCandidate:electrons"
addToProcessAndTask("pfCandsNoJetsNoEle"+postfix, pfCandsNoJetsNoEle, process, getMETUncertainties_task)
#muon projection ==
pfCandsNoJetsNoEleNoMu = _mod.candPtrProjector.clone(
src = "pfCandsNoJetsNoEle"+postfix,
veto = muonCollection,
)
addToProcessAndTask("pfCandsNoJetsNoEleNoMu"+postfix, pfCandsNoJetsNoEleNoMu, process, getMETUncertainties_task)
#tau projection ==
pfCandsNoJetsNoEleNoMuNoTau = _mod.candPtrProjector.clone(
src = "pfCandsNoJetsNoEleNoMu"+postfix,
veto = tauCollection,
)
addToProcessAndTask("pfCandsNoJetsNoEleNoMuNoTau"+postfix, pfCandsNoJetsNoEleNoMuNoTau, process, getMETUncertainties_task)
#photon projection ==
pfCandsForUnclusteredUnc = _mod.candPtrProjector.clone(
src = "pfCandsNoJetsNoEleNoMuNoTau"+postfix,
veto = photonCollection,
)
if not self.getvalue("onMiniAOD"):
pfCandsForUnclusteredUnc.veto = "pfeGammaToCandidate:photons"
addToProcessAndTask("pfCandsForUnclusteredUnc"+postfix, pfCandsForUnclusteredUnc, process, getMETUncertainties_task)
#===================================================================================
# energy shifts
#===================================================================================
# PFMuons, PFElectrons, PFPhotons, and PFTaus will be used
# to calculate MET Uncertainties.
#===================================================================================
#--------------
# PFElectrons :
#--------------
pfElectrons = cms.EDFilter("CandPtrSelector",
src = electronCollection,
cut = cms.string("pt > 5 && isPF && gsfTrack.isAvailable() && gsfTrack.hitPattern().numberOfLostHits(\'MISSING_INNER_HITS\') < 2")
)
addToProcessAndTask("pfElectrons"+postfix, pfElectrons, process, getMETUncertainties_task)
#--------------------------------------------------------------------
# PFTaus :
#---------
pfTaus = cms.EDFilter("PATTauRefSelector",
src = tauCollection,
cut = cms.string('pt > 18.0 & abs(eta) < 2.6 & tauID("decayModeFinding") > 0.5 & isPFTau')
)
addToProcessAndTask("pfTaus"+postfix, pfTaus, process, getMETUncertainties_task)
#---------------------------------------------------------------------
# PFMuons :
#----------
pfMuons = cms.EDFilter("CandPtrSelector",
src = muonCollection,
cut = cms.string("pt > 5.0 && isPFMuon && abs(eta) < 2.4")
)
addToProcessAndTask("pfMuons"+postfix, pfMuons, process, getMETUncertainties_task)
#---------------------------------------------------------------------
# PFPhotons :
#------------
if self._parameters["Puppi"].value or not self._parameters["onMiniAOD"].value:
cutforpfNoPileUp = cms.string("")
else:
cutforpfNoPileUp = cms.string("fromPV > 1")
pfNoPileUp = cms.EDFilter("CandPtrSelector",
src = pfCandCollection,
cut = cutforpfNoPileUp
)
addToProcessAndTask("pfNoPileUp"+postfix, pfNoPileUp, process, getMETUncertainties_task)
pfPhotons = cms.EDFilter("CandPtrSelector",
src = pfCandCollection if self._parameters["Puppi"].value or not self._parameters["onMiniAOD"].value else cms.InputTag("pfCHS"),
cut = cms.string("abs(pdgId) = 22")
)
addToProcessAndTask("pfPhotons"+postfix, pfPhotons, process, getMETUncertainties_task)
#-------------------------------------------------------------------------
# Collections which have only PF Objects for calculating MET uncertainties
#-------------------------------------------------------------------------
electronCollection = cms.InputTag("pfElectrons"+postfix)
muonCollection = cms.InputTag("pfMuons"+postfix)
tauCollection = cms.InputTag("pfTaus"+postfix)
photonCollection = cms.InputTag("pfPhotons"+postfix)
objectCollections = { "Jet":jetCollection,
"Electron":electronCollection,
"Photon":photonCollection,
"Muon":muonCollection,
"Unclustered":cms.InputTag("pfCandsForUnclusteredUnc"+postfix),
"Tau":tauCollection,
}
for obj in objectCollections.keys():
if not isValidInputTag(objectCollections[obj]): # or objectCollections[obj]=="":
print("INFO : %s collection %s does not exists, no energy scale shifting will be performed in MET uncertainty tools" %(obj, objectCollections[obj]))
else:
metObjUncModules = self.getVariations(process, metModName, obj,"", objectCollections[obj], "En", patMetUncertaintyTask, jetUncInfos, postfix )
#adding the shifted MET produced to the proper patMetModuleSequence