-
Notifications
You must be signed in to change notification settings - Fork 9
/
BaseHHtobbWW.py
2214 lines (1992 loc) · 154 KB
/
BaseHHtobbWW.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
import os
import re
import sys
import json
import yaml
import copy
from itertools import chain
from functools import partial
import bamboo
from bamboo import treefunctions as op
from bamboo.analysismodules import NanoAODModule, NanoAODHistoModule, NanoAODSkimmerModule
from bamboo.analysisutils import makeMultiPrimaryDatasetTriggerSelection
from bamboo.scalefactors import binningVariables_nano, BtagSF, get_scalefactor
from bamboo.plots import Plot, EquidistantBinning, Selection, SelectionWithDataDriven, CutFlowReport
from bamboo.analysisutils import forceDefine
from bamboo.root import loadLibrary, loadHeader
from METScripts import METFilter, METcorrection
from scalefactorsbbWW import ScaleFactorsbbWW
from btagHelper import makeBtagRatioReweighting
from triggers import returnTriggerRanges
from highlevelLambdas import highlevelLambdas
from DDHelper import DataDrivenPseudoData, DataDrivenLOReweighting
from selectionDef import SelectionObject
import logging
logger = logging.getLogger(__name__)
#===============================================================================================#
# BaseHHtobbWW #
#===============================================================================================#
class BaseNanoHHtobbWW(NanoAODModule):
""" Base module: HH->bbW(->e/µ nu)W(->e/µ nu) histograms from NanoAOD """
def __init__(self, args):
super(BaseNanoHHtobbWW, self).__init__(args)
# Set plots options #
self.plotDefaults = {"show-ratio": True,
"y-axis-show-zero" : True,
#"normalized": True,
"y-axis": "Events",
"log-y" : "both",
"ratio-y-axis-range" : [0.8,1.2],
"ratio-y-axis" : '#frac{Data}{MC}',
"sort-by-yields" : True}
#-------------------------------------------------------------------------------------------#
# addArgs #
#-------------------------------------------------------------------------------------------#
def addArgs(self,parser):
super(BaseNanoHHtobbWW, self).addArgs(parser)
parser.title = """
Arguments for the HH->bbWW analysis on bamboo framework
----- Argument groups -----
* Lepton arguments *
--NoZVeto
--ZPeak
--NoTauVeto
* Jet arguments *
--Ak4
--Ak8
--Resolved0Btag
--Resolved1Btag
--Resolved2Btag
--TightResolved0b4j
--TightResolved1b3j
--TightResolved2b2j
--SemiBoostedHbb
--SemiBoostedWjj
--TTBarCR
--BtagReweightingOn
--BtagReweightingOff
* Skimmer arguments *
--Synchronization
--Channel
* Plotter arguments *
--OnlyYield
* Technical *
--backend
--NoSystematics
----- Plotter mode -----
Every combination of lepton and jet arguments can be used, if none specified they will all be plotted
----- Skimmer mode -----
One lepton and and one jet argument must be specified in addition to the required channel
(this is because only one selection at a time can produce a ntuple)
----- Detailed explanation -----
"""
#----- Technical arguments -----#
parser.add_argument("--backend",
type=str,
default="dataframe",
help="Backend to use, 'dataframe' (default) or 'lazy'")
parser.add_argument("-s",
"--subset",
type = str,
required = False,
help="Subset of samples to be run over, keys defined in the 'samples' entry of the yaml analysis config")
parser.add_argument("--NoSystematics",
action = "store_true",
default = False,
help="Disable all systematic variations (default=False)")
parser.add_argument("--analysis",
type = str,
default = 'res',
help="Analysis type : res (default) | nonres ")
parser.add_argument("--Events",
nargs = '+',
type = int,
help="Cut on events (as list)")
parser.add_argument("--HHReweighting",
action = 'append',
type = str,
default = None,
help="GGF LO->NLO reweighting benchmarks to use (can be several)")
parser.add_argument("--mass",
nargs = '+',
action = 'extend',
type = float,
default = None,
help="Mass to use for the parametric DNN (can be several)")
parser.add_argument("--era",
action = 'store',
type = int,
default = None,
help="Era to be fed to the parametric DNN")
parser.add_argument("--PrintYield",
action = "store_true",
default = False,
help="Print yield to screen (for debugging)")
#----- Lepton selection arguments -----#
parser.add_argument("--NoZVeto",
action = "store_true",
default = False,
help = "Remove the cut of preselected leptons |M_ll-M_Z|>10 GeV")
parser.add_argument("--ZPeak",
action = "store_true",
default = False,
help = "Select the Z peak at tight level |M_ll-M_Z|<10 GeV (must be used with --NoZVeto, only effective with --Tight)")
parser.add_argument("--NoTauVeto",
action = "store_true",
default = False,
help = "Select the events do not have any tau overlapped with fakeable leptons")
parser.add_argument("--FakeRateNonClosureMCFakes",
action = "store_true",
default = False,
help = "Use tight non-prompt lepton to estimate MC fakes [Only on TTHardronic events]")
parser.add_argument("--FakeRateNonClosureMCClosure",
action = "store_true",
default = False,
help = "Use tight non-prompt lepton to estimate MC closure [Only on TTHardronic events]")
#----- Jet selection arguments -----#
parser.add_argument("--Ak4",
action = "store_true",
default = False,
help = "Produce the plots/skim for two Ak4 jets passing the selection criteria")
parser.add_argument("--Ak8",
action = "store_true",
default = False,
help = "Produce the plots/skim for one Ak8 jet passing the selection criteria")
parser.add_argument("--Resolved0Btag",
action = "store_true",
default = False,
help = "Produce the plots/skim for the exclusive resolved category with no btagged jet")
parser.add_argument("--Resolved1Btag",
action = "store_true",
default = False,
help = "Produce the plots/skim for the exclusive resolved category with only one btagged jet")
parser.add_argument("--Resolved2Btag",
action = "store_true",
default = False,
help = "Produce the plots/skim for the exclusive resolved category with two btagged jets")
# SL Categories
# Resolved
parser.add_argument("--Res2b2Wj",
action = "store_true",
default = False,
help = "Produce the plots/skim for the exclusive 2b2Wj JPA category")
parser.add_argument("--Res1b3Wj",
action = "store_true",
default = False,
help = "Produce the plots/skim for the exclusive 1b3Wj JPA category") # for basic reco only
parser.add_argument("--Res2b1Wj",
action = "store_true",
default = False,
help = "Produce the plots/skim for the exclusive 2b1Wj JPA category")
parser.add_argument("--Res2b0Wj",
action = "store_true",
default = False,
help = "Produce the plots/skim for the exclusive 2b0Wj JPA category")
parser.add_argument("--Res1b2Wj",
action = "store_true",
default = False,
help = "Produce the plots/skim for the exclusive 1b2Wj JPA category")
parser.add_argument("--Res1b1Wj",
action = "store_true",
default = False,
help = "Produce the plots/skim for the exclusive 1b1Wj JPA category")
parser.add_argument("--Res1b0Wj",
action = "store_true",
default = False,
help = "Produce the plots/skim for the exclusive 1b0Wj JPA category")
parser.add_argument("--Res0b",
action = "store_true",
default = False,
help = "Produce the plots/skim for the exclusive 0b JPA category")
# Semi-Boosted
parser.add_argument("--Hbb2Wj",
action = "store_true",
default = False,
help = "Produce the plots/skim for the exclusive Hbb2Wj JPA category")
parser.add_argument("--Hbb1Wj",
action = "store_true",
default = False,
help = "Produce the plots/skim for the exclusive Hbb1Wj JPA category")
parser.add_argument("--Hbb0Wj",
action = "store_true",
default = False,
help = "Produce the plots/skim for the exclusive Hbb0Wj JPA category")
parser.add_argument("--Resolved",
action = "store_true",
default = False,
help = "Produce the plots/skim for all JPA resolved categories")
parser.add_argument("--Boosted",
action = "store_true",
default = False,
help = "Produce the plots/skim for all JPA boosted categories")
################
parser.add_argument("--Boosted0Btag",
action = "store_true",
default = False,
help = "Produce the plots/skim for the inclusive boosted category")
parser.add_argument("--Boosted1Btag",
action = "store_true",
default = False,
help = "Produce the plots/skim for the inclusive boosted category")
parser.add_argument("--TTBarCR",
action = "store_true",
default = False,
help = "Apply cut on Mbb for ttbar CR (only effective with --Resolved2Btag)")
parser.add_argument("--BtagReweightingOn",
action = "store_true",
default = False,
help = "Btag ratio study : Btag SF applied (without the ratio), will only do the plots for reweighting (jets and leptons args are ignored)")
parser.add_argument("--BtagReweightingOff",
action = "store_true",
default = False,
help = "Btag ratio study : Btag Sf not applied (without the ratio), will only do the plots for reweighting (jets and leptons args are ignored)")
parser.add_argument("--DYStitchingPlots",
action = "store_true",
default = False,
help = "DY stitching studies : only produce LHE jet multiplicities (inclusive analysis, only on DY events, rest of plots ignored)")
parser.add_argument("--WJetsStitchingPlots",
action = "store_true",
default = False,
help = "W+jets stitching studies : only produce LHE jet multiplicities (inclusive analysis, only on W+jets events, rest of plots ignored)")
parser.add_argument("--NoStitching",
action = "store_true",
default = False,
help = "To not apply the stitching weights to DY and WJets samples")
#----- Skimmer arguments -----#
parser.add_argument("--Synchronization",
action = "store_true",
default = False,
help = "Produce the skims for the synchronization (without triggers, corrections of flags) if alone. If sync for specific selection, lepton, jet and channel arguments need to be used")
parser.add_argument("--Channel",
action = "store",
type = str,
help = "Specify the channel for the tuple : ElEl, MuMu, ElMu")
parser.add_argument("--FakeCR",
action = "store_true",
default = False,
help = "Use the Fake CR instead of the SR")
parser.add_argument("--DYCR",
action = "store_true",
default = False,
help = "Use the DY CR instead of the SR")
#----- Plotter arguments -----#
parser.add_argument("--OnlyYield",
action = "store_true",
default = False,
help = "Only produce the yield plots")
parser.add_argument("--Classifier",
action = "store",
type = str,
help = "BDT-SM | BDT-Rad900 | DNN | LBN")
parser.add_argument("--WhadTagger",
action = "store",
type = str,
help = "BDT | simple")
#-------------------------------------------------------------------------------------------#
# initialize #
#-------------------------------------------------------------------------------------------#
def initialize(self,forSkimmer=False):
# Include all the contributions from the subsets in the yaml #
self._customizeAnalysisCfg(self.analysisConfig)
# Add the LO reweighting to the datadriven parts #
if self.args.HHReweighting is not None and 'all' in self.args.HHReweighting:
self.args.HHReweighting = self.analysisConfig['benchmarks']['targets']
if not forSkimmer and self.args.HHReweighting is not None:
self.analysisConfig['datadriven'].update({benchmark:{'replaces': 'all', 'uses': 'all'}
for benchmark in self.analysisConfig['benchmarks']['targets']
if benchmark in self.args.HHReweighting})
newContrib = [benchmark for benchmark in self.analysisConfig['benchmarks']['targets'] if benchmark in self.args.HHReweighting]
if self.args.datadriven is None:
self.args.datadriven = newContrib
else:
self.args.datadriven += newContrib
super(BaseNanoHHtobbWW, self).initialize()
# PseudoData #
if not forSkimmer:
if "PseudoData" in self.datadrivenContributions:
contrib = self.datadrivenContributions["PseudoData"]
self.datadrivenContributions["PseudoData"] = DataDrivenPseudoData(contrib.name, contrib.config)
# Include the datadriven reweighting #
if self.args.HHReweighting is not None:
self.datadrivenContributions.update({benchmark:DataDrivenLOReweighting(benchmark,self.analysisConfig['datadriven'][benchmark],substrs=self.analysisConfig['benchmarks']['uses'])
for benchmark in self.analysisConfig['benchmarks']['targets']
if benchmark in self.args.HHReweighting})
# Check analysis type #
if self.args.analysis not in ['res','nonres']:
raise RuntimeError("Analysis type '{}' not understood".format(self.args.analysis))
#-------------------------------------------------------------------------------------------#
# customizeAnalysisCfg #
#-------------------------------------------------------------------------------------------#
def _customizeAnalysisCfg(self,analysisCfg):
samples = {}
if self.args.subset is None:
return
reqArgs = self.args.subset.split(',')
foundArgs = set()
subsets = []
for item in analysisCfg['samples']:
if not 'keys' in item.keys() or not 'config' in item.keys():
continue
keys = item['keys']
if not isinstance(keys,list):
keys = [keys]
if all([key in reqArgs for key in keys]) or 'all' in reqArgs:
foundArgs.update(keys)
subsets.append(item['config'])
with open(os.path.join(os.path.dirname(os.path.abspath(__file__)),'Yaml',item['config'])) as handle:
subsetDict = yaml.load(handle,yaml.SafeLoader)
for sampleName,sampleCfg in subsetDict.items():
if self.args.analysis == 'res' and 'type' in sampleCfg.keys() and sampleCfg['type'] == 'signal':
if 'mass' not in sampleCfg.keys():
raise RuntimeError(f'Yaml config {item["config"]} sample {sampleName} does not have `mass` entry')
mass = float(re.findall('M-\d+',sampleName)[0].replace('M-',''))
if float(mass) != float(sampleCfg['mass']):
raise RuntimeError(f'Yaml config {item["config"]} sample {sampleName} have `mass` entry {sampleCfg["mass"]} but name tells {mass}')
if self.args.mass is not None and mass not in self.args.mass:
continue
samples[sampleName] = sampleCfg
self.analysisConfig['samples'] = samples
notFoundArgs = [arg for arg in reqArgs if arg not in foundArgs]
if len(notFoundArgs)>0:
raise RuntimeError('The following subsets have not been found in the keys of the analysis yaml file : '+', '.join(notFoundArgs))
if len(subsets) > 0:
print ("Imported following yaml subsets :")
for subset in subsets:
print ('... {}'.format(subset))
#-------------------------------------------------------------------------------------------#
# counters #
#-------------------------------------------------------------------------------------------#
def readCounters(self, resultsFile):
counters = super(BaseNanoHHtobbWW, self).readCounters(resultsFile)
# Corrections to the generated sum "
if resultsFile.GetListOfKeys().FindObject('generated_sum_corrected'):
sample = os.path.basename(resultsFile.GetName())
print (f'Sample {sample} : genEventSumw correction from {counters["genEventSumw"]:.3f} to {resultsFile.Get("generated_sum_corrected").GetBinContent(1):.3f}')
counters["genEventSumw"] = resultsFile.Get('generated_sum_corrected').GetBinContent(1)
return counters
def mergeCounters(self, outF, infileNames, sample=None):
super(BaseNanoHHtobbWW, self).mergeCounters(outF, infileNames, sample)
if outF.GetListOfKeys().FindObject('generated_sum_corrected'): # Main file
self.generated_sum_corrected = copy.deepcopy(outF.Get('generated_sum_corrected'))
else: # All the additional files ("datadriven")
if hasattr(self,'generated_sum_corrected'):
self.generated_sum_corrected.Write()
#-------------------------------------------------------------------------------------------#
# prepareTree #
#-------------------------------------------------------------------------------------------#
def prepareTree(self, tree, sample=None, sampleCfg=None):
from bamboo.treedecorators import NanoAODDescription, nanoRochesterCalc, nanoJetMETCalc, nanoJetMETCalc_METFixEE2017, nanoFatJetCalc
# JEC's Recommendation for Full RunII: https://twiki.cern.ch/twiki/bin/view/CMS/JECDataMC
# JER : -----------------------------: https://twiki.cern.ch/twiki/bin/view/CMS/JetResolution
# Get base aguments #
era = sampleCfg['era']
self.is_MC = self.isMC(sample) # no confusion between boolean is_MC and method isMC()
metName = "METFixEE2017" if era == "2017" else "MET"
tree,noSel,backend,lumiArgs = super(BaseNanoHHtobbWW,self).prepareTree(tree = tree,
sample = sample,
sampleCfg = sampleCfg,
description = NanoAODDescription.get(
tag = "v7",
year = (era if era else "2016"),
isMC = self.is_MC,
systVariations = [ (nanoJetMETCalc_METFixEE2017 if era == "2017" else nanoJetMETCalc), nanoFatJetCalc]),
# will do Jet and MET variations, and not the Rochester correction
backend = ("lazy" if self.args.onlypost else self.args.backend))
# Plots in base that need to be propagated to the Plotters #
self.base_plots = []
#----- Helper classes declaration ----#
if self.args.analysis == "res":
loadLibrary(os.path.join(os.path.dirname(os.path.abspath(__file__)),'HMEStudy','build','libBambooHMEEvaluator'))
loadHeader(os.path.join(os.path.dirname(os.path.abspath(__file__)),'HMEStudy','include','HME.h'))
loadHeader(os.path.join(os.path.dirname(os.path.abspath(__file__)),'HMEStudy','include','Reader.h'))
self.hmeEval = op.define("hme::HMEEvaluator", "hme::HMEEvaluator <<name>>{{}}; // for {sample}".format(sample=sample.replace('-','')), nameHint="bamboo_hmeEval{sample}".format(sample=sample.replace('-','')))
#----- CutFlow report -----#
self.yields = CutFlowReport("yields",printInLog=self.args.PrintYield,recursive=self.args.PrintYield)
#----- Safeguards for signals -----#
if "HH" in sample:
noSel = noSel.refine('HHMCWeight',cut=[op.abs(tree.genWeight)<100])
if self.args.PrintYield:
self.yields.add(noSel)
# Correct the gen event weight sum #
self.base_plots.append(Plot.make1D("generated_sum_corrected",
op.c_float(0.5),
noSel,
EquidistantBinning(1,0.,1.),
weight=tree.genWeight,
autoSyst=False))
#----- Genweight -----#
if self.is_MC:
noSel = noSel.refine("genWeight", weight=tree.genWeight)
if self.args.PrintYield:
self.yields.add(noSel)
# Event cut #
if self.args.Events:
print ("Events to use only :")
for e in self.args.Events:
print ('... %d'%e)
noSel = noSel.refine('eventcut',cut = [op.OR(*[tree.event == e for e in self.args.Events])])
if self.args.PrintYield:
self.yields.add(noSel)
# Save some useful stuff in self #
self.sample = sample
self.sampleCfg = sampleCfg
self.era = era
# Check distributed option #
isNotWorker = (self.args.distributed != "worker")
# Turn off systs #
if self.args.NoSystematics:
noSel = noSel.refine('SystOff',autoSyst=False)
if self.args.PrintYield:
self.yields.add(noSel)
# Check era #
if era != "2016" and era != "2017" and era != "2018":
raise RuntimeError("Unknown era {0}".format(era))
# Rochester and JEC corrections (depends on era) #
# Check if basic synchronization is required (no corrections and triggers) #
self.inclusive_sel = ((self.args.Synchronization
and not any([self.args.__dict__[key] for key in['Ak4', 'Ak8', 'Resolved0Btag', 'Resolved1Btag', 'Resolved2Btag', 'Boosted0Btag','Boosted1Btag',
'Resolved','Boosted','Res2b2Wj','Res2b1Wj','Res2b0Wj','Res1b2Wj','Res1b1Wj','Res1b1Wj','Res0b',
'Hbb2Wj','Hbb1Wj','Hbb0Wj']]) \
and (self.args.Channel is None or self.args.Channel=='None')) \
# No channel selection
# None is local mode, "None" in distributed mode
or self.args.BtagReweightingOn
or self.args.BtagReweightingOff
or self.args.DYStitchingPlots
or self.args.WJetsStitchingPlots)
# Inclusive plots
# If no lepton, jet and channel selection : basic object selection (no trigger nor corrections)
if self.inclusive_sel:
print ("Inclusive analysis, no selections applied")
#----- Theory uncertainties -----#
if self.is_MC:
# PDF scale weights #
# Twiki: https://twiki.cern.ch/twiki/bin/viewauth/CMS/TopSystematics#Factorization_and_renormalizatio
# len(LHEScaleWeight) == 9
# -> nominal = LHEScaleWeight[4]
# -> Fact : up = LHEScaleWeight[5] and down = LHEScaleWeight[3]
# -> Renorm : up = LHEScaleWeight[7] and down = LHEScaleWeight[1]
# -> Mixed : up = LHEScaleWeight[8] and down = LHEScaleWeight[0]
# len(LHEScaleWeight) == 8
# -> nominal = 1.
# -> Fact : up = LHEScaleWeight[4] and down = LHEScaleWeight[3]
# -> Renorm : up = LHEScaleWeight[6] and down = LHEScaleWeight[1]
# -> Mixed : up = LHEScaleWeight[7] and down = LHEScaleWeight[0]
# len(LHEScaleWeight) different (usually 44 ?!)
# -> nominal = up = down = 1.
# Meaning :
# [' LHE scale variation weights (w_var / w_nominal)',
# ' [0] is renscfact=0.5d0 facscfact=0.5d0 ',
# ' [1] is renscfact=0.5d0 facscfact=1d0 ',
# ' [2] is renscfact=0.5d0 facscfact=2d0 ',
# ' [3] is renscfact=1d0 facscfact=0.5d0 ',
# ' [4] is renscfact=1d0 facscfact=1d0 ',
# ' [5] is renscfact=1d0 facscfact=2d0 ',
# ' [6] is renscfact=2d0 facscfact=0.5d0 ',
# ' [7] is renscfact=2d0 facscfact=1d0 ',
# ' [8] is renscfact=2d0 facscfact=2d0 ']
# Clipping is done to avoid malicious files in ST samples
basicScaleWeight = op.systematic(op.c_float(1.),
name = "ScaleWeight",
#Factup = op.c_float(1.),
#Factdown = op.c_float(1.),
#Renormup = op.c_float(1.),
#Renormdown = op.c_float(1.),
#Mixedup = op.c_float(1.),
#Mixeddown = op.c_float(1.),
Envelopeup = op.c_float(1.),
Envelopedown = op.c_float(1.))
if sample.startswith('ST'): # Dropped because bugs in the LHE scale weights
self.scaleWeight = basicScaleWeight
elif hasattr(tree,"LHEScaleWeight"): # If has tree -> find the values
factor = 1.
if sample.startswith('DYToLL_0J') or sample.startswith('DYToLL_1J'):
# Bug of factor 0.5, see https://hypernews.cern.ch/HyperNews/CMS/get/generators/4383.html?inline=-1 (only in the "8" weights case)
factor = 2.
self.scaleWeight = op.multiSwitch((op.AND(op.rng_len(tree.LHEScaleWeight) == 9, tree.LHEScaleWeight[4] != 0.),
op.systematic(op.c_float(1.), #tree.LHEScaleWeight[4],
name = "ScaleWeight",
#Factup = op.min(op.c_float(10.),op.max(op.c_float(0.),tree.LHEScaleWeight[5]/tree.LHEScaleWeight[4])),
#Factdown = op.min(op.c_float(10.),op.max(op.c_float(0.),tree.LHEScaleWeight[3]/tree.LHEScaleWeight[4])),
#Renormup = op.min(op.c_float(10.),op.max(op.c_float(0.),tree.LHEScaleWeight[7]/tree.LHEScaleWeight[4])),
#Renormdown = op.min(op.c_float(10.),op.max(op.c_float(0.),tree.LHEScaleWeight[1]/tree.LHEScaleWeight[4])),
#Mixedup = op.min(op.c_float(10.),op.max(op.c_float(0.),tree.LHEScaleWeight[8]/tree.LHEScaleWeight[4])),
#Mixeddown = op.min(op.c_float(10.),op.max(op.c_float(0.),tree.LHEScaleWeight[0]/tree.LHEScaleWeight[4])),
Envelopeup = op.min(op.c_float(10.),
op.max(op.max(op.max(tree.LHEScaleWeight[5]/tree.LHEScaleWeight[4], # Fact up
tree.LHEScaleWeight[7]/tree.LHEScaleWeight[4]), # Renorm up
tree.LHEScaleWeight[8]/tree.LHEScaleWeight[4]), # Mixed up
op.c_float(0.))),
Envelopedown = op.max(op.c_float(0.),
op.min(op.min(op.min(tree.LHEScaleWeight[3]/tree.LHEScaleWeight[4], # Fact down
tree.LHEScaleWeight[1]/tree.LHEScaleWeight[4]), # Renorm down
tree.LHEScaleWeight[0]/tree.LHEScaleWeight[4]), # Mixed own
op.c_float(10.))))),
(op.rng_len(tree.LHEScaleWeight) == 8,
op.systematic(op.c_float(1.),
name = "ScaleWeight",
#Factup = factor * tree.LHEScaleWeight[4],
#Factdown = factor * tree.LHEScaleWeight[3],
#Renormup = factor * tree.LHEScaleWeight[6],
#Renormdown = factor * tree.LHEScaleWeight[1],
#Mixedup = factor * tree.LHEScaleWeight[7],
#Mixeddown = factor * tree.LHEScaleWeight[0],
Envelopeup = op.max(op.max(factor * tree.LHEScaleWeight[4], # Fact up
factor * tree.LHEScaleWeight[6]), # Renorm up
factor * tree.LHEScaleWeight[7]), # Mixed up
Envelopedown = op.min(op.min(factor * tree.LHEScaleWeight[3], # Fact down
factor * tree.LHEScaleWeight[1]), # Renorm down
factor * tree.LHEScaleWeight[0]))), # Mixed down
basicScaleWeight)
else: # No tree -> use 1
self.scaleWeight = basicScaleWeight
noSel = noSel.refine("PDFScaleWeights", weight = [self.scaleWeight])
if self.args.PrintYield:
self.yields.add(noSel)
# PDF #
#noSel = noSel.refine("PDFWeights", weight = [tree.LHEPdfWeight])
# TODO : add that next time
# https://cms-nanoaod-integration.web.cern.ch/integration/master-102X/mc102X_doca.html#LHEPdfWeight
# https://lhapdf.hepforge.org/pdfsets.html
# -> range of ID
# Branch LHEPdfWeight -> docstring -> get the id -> check the list above
# we want "NNPDF31_nnlo_hessian_pdfas" (ID : 306000) -> if not use 1.
# PS weights #
self.psISRSyst = op.switch(op.rng_len(tree.PSWeight) == 4,
op.systematic(op.c_float(1.), name="psISR", up=tree.PSWeight[2], down=tree.PSWeight[0]),
op.systematic(op.c_float(1.), name="psISR", up=op.c_float(1.), down=op.c_float(1.)))
self.psFSRSyst = op.switch(op.rng_len(tree.PSWeight) == 4,
op.systematic(op.c_float(1.), name="psFSR", up=tree.PSWeight[3], down=tree.PSWeight[1]),
op.systematic(op.c_float(1.), name="psFSR", up=op.c_float(1.), down=op.c_float(1.)))
noSel = noSel.refine("PSweights", weight = [self.psISRSyst, self.psFSRSyst])
if self.args.PrintYield:
self.yields.add(noSel)
#----- Triggers and Corrections -----#
self.triggersPerPrimaryDataset = {}
def addHLTPath(key,HLT):
if key not in self.triggersPerPrimaryDataset.keys():
self.triggersPerPrimaryDataset[key] = []
try:
self.triggersPerPrimaryDataset[key].append(getattr(tree.HLT,HLT))
except AttributeError:
print ("Could not find branch tree.HLT.%s, will omit it"%HLT)
from bamboo.analysisutils import configureJets ,configureRochesterCorrection, configureType1MET
############################################################################################
# ERA 2016 #
############################################################################################
if era == "2016":
# # Rochester corrections #
# configureRochesterCorrection(variProxy = tree._Muon,
# paramsFile = os.path.join(os.path.dirname(__file__), "data", "RoccoR2016.txt"),
# isMC = self.is_MC,
# backend = backend,
# uName = sample)
# SingleMuon #
addHLTPath("SingleMuon","IsoMu22")
addHLTPath("SingleMuon","IsoTkMu22")
addHLTPath("SingleMuon","IsoMu22_eta2p1")
addHLTPath("SingleMuon","IsoTkMu22_eta2p1")
addHLTPath("SingleMuon","IsoMu24")
addHLTPath("SingleMuon","IsoTkMu24")
# SingleElectron #
addHLTPath("SingleElectron","Ele27_WPTight_Gsf")
addHLTPath("SingleElectron","Ele25_eta2p1_WPTight_Gsf")
addHLTPath("SingleElectron","Ele27_eta2p1_WPLoose_Gsf")
# DoubleMuon #
addHLTPath("DoubleMuon","Mu17_TrkIsoVVL_Mu8_TrkIsoVVL")
addHLTPath("DoubleMuon","Mu17_TrkIsoVVL_Mu8_TrkIsoVVL_DZ")
addHLTPath("DoubleMuon","Mu17_TrkIsoVVL_TkMu8_TrkIsoVVL")
addHLTPath("DoubleMuon","Mu17_TrkIsoVVL_TkMu8_TrkIsoVVL_DZ")
# DoubleEGamma #
addHLTPath("DoubleEGamma","Ele23_Ele12_CaloIdL_TrackIdL_IsoVL_DZ")
# MuonEG #
addHLTPath("MuonEG","Mu8_TrkIsoVVL_Ele23_CaloIdL_TrackIdL_IsoVL")
addHLTPath("MuonEG","Mu8_TrkIsoVVL_Ele23_CaloIdL_TrackIdL_IsoVL_DZ")
addHLTPath("MuonEG","Mu23_TrkIsoVVL_Ele8_CaloIdL_TrackIdL_IsoVL")
addHLTPath("MuonEG","Mu23_TrkIsoVVL_Ele8_CaloIdL_TrackIdL_IsoVL_DZ")
# Links :
# JEC : https://twiki.cern.ch/twiki/bin/viewauth/CMS/JECDataMC
# JER (smear) : https://twiki.cern.ch/twiki/bin/view/CMS/JetResolution
# JetMET treatment #
if self.is_MC: # if MC -> needs smearing
configureJets(variProxy = tree._Jet,
jetType = "AK4PFchs",
jec = "Summer16_07Aug2017_V11_MC",
smear = "Summer16_25nsV1_MC",
jesUncertaintySources = "Merged",
regroupTag = "V2",
enableSystematics = lambda v : not "jesTotal" in v,
mayWriteCache = isNotWorker,
isMC = self.is_MC,
backend = backend,
uName = sample)
configureJets(variProxy = tree._FatJet,
jetType = "AK8PFPuppi",
jec = "Summer16_07Aug2017_V11_MC",
smear = "Summer16_25nsV1_MC",
jesUncertaintySources = "Merged",
uncertaintiesFallbackJetType = "AK4PFchs",
mcYearForFatJets = era if self.args.analysis == 'res' else None,
regroupTag = "V2",
enableSystematics = lambda v : not "jesTotal" in v,
mayWriteCache = isNotWorker,
isMC = self.is_MC,
backend = backend,
uName = sample)
configureType1MET(variProxy = getattr(tree, f"_{metName}"),
jec = "Summer16_07Aug2017_V11_MC",
smear = "Summer16_25nsV1_MC",
isT1Smear = True,
jesUncertaintySources = "Merged",
regroupTag = "V2",
enableSystematics = lambda v : not "jesTotal" in v,
mayWriteCache = isNotWorker,
isMC = self.is_MC,
backend = backend,
uName = sample)
else: # If data -> extract info from config
jecTag = None
if "2016B" in sample or "2016C" in sample or "2016D" in sample:
jecTag = "Summer16_07Aug2017BCD_V11_DATA"
elif "2016E" in sample or "2016F" in sample:
jecTag = "Summer16_07Aug2017EF_V11_DATA"
elif "2016G" in sample or "2016H" in sample:
jecTag = "Summer16_07Aug2017GH_V11_DATA"
else:
raise RuntimeError("Could not find appropriate JEC tag for data")
configureJets(variProxy = tree._Jet,
jetType = "AK4PFchs",
jec = jecTag,
mayWriteCache = isNotWorker,
isMC = self.is_MC,
backend = backend,
uName = sample)
configureJets(variProxy = tree._FatJet,
jetType = "AK8PFPuppi",
jec = jecTag,
regroupTag = "V2",
mayWriteCache = isNotWorker,
isMC = self.is_MC,
backend = backend,
uName = sample)
configureType1MET(variProxy = getattr(tree, f"_{metName}"),
jec = jecTag,
mayWriteCache = isNotWorker,
isMC = self.is_MC,
backend = backend,
uName = sample)
############################################################################################
# ERA 2017 #
############################################################################################
elif era == "2017":
#configureRochesterCorrection(variProxy = tree._Muon,
# paramsFile = os.path.join(os.path.dirname(__file__), "data", "RoccoR2017.txt"),
# isMC = self.is_MC,
# backend = backend,
# uName = sample)
# SingleMuon #
addHLTPath("SingleMuon","IsoMu24")
addHLTPath("SingleMuon","IsoMu27")
# SingleElectron #
addHLTPath("SingleElectron","Ele35_WPTight_Gsf")
addHLTPath("SingleElectron","Ele32_WPTight_Gsf")
# DoubleMuon #
addHLTPath("DoubleMuon","Mu17_TrkIsoVVL_Mu8_TrkIsoVVL_DZ_Mass3p8")
addHLTPath("DoubleMuon","Mu17_TrkIsoVVL_Mu8_TrkIsoVVL_DZ_Mass8")
# DoubleEGamma #
addHLTPath("DoubleEGamma","Ele23_Ele12_CaloIdL_TrackIdL_IsoVL")
# MuonEG #
addHLTPath("MuonEG","Mu8_TrkIsoVVL_Ele23_CaloIdL_TrackIdL_IsoVL_DZ")
addHLTPath("MuonEG","Mu12_TrkIsoVVL_Ele23_CaloIdL_TrackIdL_IsoVL_DZ")
addHLTPath("MuonEG","Mu23_TrkIsoVVL_Ele12_CaloIdL_TrackIdL_IsoVL")
addHLTPath("MuonEG","Mu23_TrkIsoVVL_Ele12_CaloIdL_TrackIdL_IsoVL_DZ")
# JetMET treatment #
if self.is_MC: # if MC -> needs smearing
configureJets(variProxy = tree._Jet,
jetType = "AK4PFchs",
jec = "Fall17_17Nov2017_V32_MC",
smear = "Fall17_V3b_MC",
jesUncertaintySources = "Merged",
regroupTag = "V2",
enableSystematics = lambda v : not "jesTotal" in v,
mayWriteCache = isNotWorker,
isMC = self.is_MC,
backend = backend,
uName = sample)
configureJets(variProxy = tree._FatJet,
jetType = "AK8PFPuppi",
jec = "Fall17_17Nov2017_V32_MC",
smear = "Fall17_V3b_MC",
jesUncertaintySources = "Merged",
regroupTag = "V2",
enableSystematics = lambda v : not "jesTotal" in v,
uncertaintiesFallbackJetType = "AK4PFchs",
mcYearForFatJets = era if self.args.analysis == 'res' else None,
mayWriteCache = isNotWorker,
isMC = self.is_MC,
backend = backend,
uName = sample)
configureType1MET(variProxy = getattr(tree, f"_{metName}"),
jec = "Fall17_17Nov2017_V32_MC",
smear = "Fall17_V3b_MC",
isT1Smear = True,
jesUncertaintySources = "Merged",
regroupTag = "V2",
enableSystematics = lambda v : not "jesTotal" in v,
mayWriteCache = isNotWorker,
isMC = self.is_MC,
backend = backend,
uName = sample)
else: # If data -> extract info from config
jecTag = None
if "2017B" in sample:
jecTag = "Fall17_17Nov2017B_V32_DATA"
elif "2017C" in sample:
jecTag = "Fall17_17Nov2017C_V32_DATA"
elif "2017D" in sample or "2017E" in sample:
jecTag = "Fall17_17Nov2017DE_V32_DATA"
elif "2017F" in sample:
jecTag = "Fall17_17Nov2017F_V32_DATA"
else:
raise RuntimeError("Could not find appropriate JEC tag for data")
configureJets(variProxy = tree._Jet,
jetType = "AK4PFchs",
jec = jecTag,
mayWriteCache = isNotWorker,
isMC = self.is_MC,
backend = backend,
uName = sample)
configureJets(variProxy = tree._FatJet,
jetType = "AK8PFPuppi",
jec = jecTag,
mayWriteCache = isNotWorker,
isMC = self.is_MC,
backend = backend,
uName = sample)
configureType1MET(variProxy = getattr(tree, f"_{metName}"),
jec = jecTag,
mayWriteCache = isNotWorker,
isMC = self.is_MC,
backend = backend,
uName = sample)
############################################################################################
# ERA 2018 #
############################################################################################
elif era == "2018":
#configureRochesterCorrection(variProxy = tree._Muon,
# paramsFile = os.path.join(os.path.dirname(__file__), "data", "RoccoR2018.txt"),
# isMC = self.is_MC,
# backend = backend,
# uName = sample)
# SingleMuon #
addHLTPath("SingleMuon","IsoMu24")
addHLTPath("SingleMuon","IsoMu27")
# SingleElectron #
addHLTPath("SingleElectron","Ele32_WPTight_Gsf")
# DoubleMuon #
addHLTPath("DoubleMuon","Mu17_TrkIsoVVL_Mu8_TrkIsoVVL_DZ_Mass3p8")
# DoubleEGamma #
addHLTPath("DoubleEGamma","Ele23_Ele12_CaloIdL_TrackIdL_IsoVL")
# MuonEG #
addHLTPath("MuonEG","Mu8_TrkIsoVVL_Ele23_CaloIdL_TrackIdL_IsoVL_DZ")
addHLTPath("MuonEG","Mu12_TrkIsoVVL_Ele23_CaloIdL_TrackIdL_IsoVL_DZ")
addHLTPath("MuonEG","Mu23_TrkIsoVVL_Ele12_CaloIdL_TrackIdL_IsoVL")
# JetMET treatment #
if self.is_MC: # if MC -> needs smearing
configureJets(variProxy = tree._Jet,
jetType = "AK4PFchs",
jec = "Autumn18_V19_MC",
smear = "Autumn18_V7b_MC",
jesUncertaintySources = "Merged",
regroupTag = "V2",
enableSystematics = lambda v : not "jesTotal" in v,
addHEM2018Issue = True,
mayWriteCache = isNotWorker,
isMC = self.is_MC,
backend = backend,
uName = sample)
configureJets(variProxy = tree._FatJet,
jetType = "AK8PFPuppi",
jec = "Autumn18_V19_MC",
smear = "Autumn18_V7b_MC",
jesUncertaintySources = "Merged",
regroupTag = "V2",
enableSystematics = lambda v : not "jesTotal" in v,
addHEM2018Issue = True,
uncertaintiesFallbackJetType = "AK4PFchs",
mayWriteCache = isNotWorker,
isMC = self.is_MC,
backend = backend,
uName = sample)
configureType1MET(variProxy = getattr(tree, f"_{metName}"),
jec = "Autumn18_V19_MC",
smear = "Autumn18_V7b_MC",
isT1Smear = True,
jesUncertaintySources = "Merged",
regroupTag = "V2",
enableSystematics = lambda v : not "jesTotal" in v,
addHEM2018Issue = True,
mayWriteCache = isNotWorker,
isMC = self.is_MC,
backend = backend,
uName = sample)
else: # If data -> extract info from config
jecTag = None
if "2018A" in sample:
jecTag = "Autumn18_RunA_V19_DATA"
elif "2018B" in sample:
jecTag = "Autumn18_RunB_V19_DATA"
elif "2018C" in sample:
jecTag = "Autumn18_RunC_V19_DATA"
elif "2018D" in sample:
jecTag = "Autumn18_RunD_V19_DATA"
else:
raise RuntimeError("Could not find appropriate JEC tag for data")
configureJets(variProxy = tree._Jet,
jetType = "AK4PFchs",
jec = jecTag,
mayWriteCache = isNotWorker,
isMC = self.is_MC,
backend = backend,
uName = sample)
configureJets(variProxy = tree._FatJet,
jetType = "AK8PFPuppi",
jec = jecTag,
mayWriteCache = isNotWorker,
isMC = self.is_MC,
backend = backend,
uName = sample)
configureType1MET(variProxy = getattr(tree, f"_{metName}"),
jec = jecTag,
mayWriteCache = isNotWorker,
isMC = self.is_MC,
backend = backend,
uName = sample)
return tree,noSel,backend,lumiArgs
#-------------------------------------------------------------------------------------------#
# prepareObjects #
#-------------------------------------------------------------------------------------------#
def prepareObjects(self, t, noSel, sample, sampleCfg, channel, forSkimmer=False):
# Some imports #
if channel not in ["DL","SL"]:
raise RuntimeError('Channel %s not understood'%channel)
era = sampleCfg['era']
self.era = era
self.tree = t
###########################################################################
# Pseudo-data #
###########################################################################
if not forSkimmer and "PseudoData" in self.datadrivenContributions and self.is_MC:
# Skimmer does not know about self.datadrivenContributions
noSel = SelectionWithDataDriven.create(parent = noSel,
name = 'pseudodata',
ddSuffix = 'Pseudodata',
enable = "PseudoData" in self.datadrivenContributions
and self.datadrivenContributions["PseudoData"].usesSample(self.sample, self.sampleCfg))
###########################################################################
# Signal Reweighting #
###########################################################################
self.signalReweightBenchmarks = {}
if 'type' in sampleCfg.keys() and sampleCfg["type"] == "signal" \
and not forSkimmer \
and 'benchmarks' in self.analysisConfig.keys() \
and any(useFile in sample for useFile in self.analysisConfig['benchmarks']['uses']) \
and self.args.HHReweighting is not None:
# Get gen level Higgs #
self.genh = op.select(t.GenPart,lambda g : op.AND(g.pdgId==25, g.statusFlags & ( 0x1 << 13)))
# Get gen level variables mHH and cos(theta*) #
HH_p4 = self.genh[0].p4 + self.genh[1].p4
cm = HH_p4.BoostToCM()
boosted_h = op.extMethod("ROOT::Math::VectorUtil::boost", returnType=self.genh[0].p4._typeName)(self.genh[0].p4,cm)
self.mHH = op.invariant_mass(self.genh[0].p4,self.genh[1].p4)
self.cosHH = op.abs(boosted_h.Pz()/boosted_h.P())
for v in (self.mHH, self.cosHH):
forceDefine(v, noSel)
def funConst(x, v=None):
return v
signalReweightParams = {
'Eta': partial(funConst, v=self.mHH),
'Pt' : partial(funConst, v=self.cosHH)
}
if forSkimmer:
# In the case of the skimmer, we cannot use the create from datadriven.
# At the same time we do not want the many-to-many procedure for the DNN training
# because it would mean repeating events with different weights.