-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathFunctions.py
2319 lines (2155 loc) · 129 KB
/
Functions.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
### Assigning script names to variables
fileNameSaveToPkl = 'saveToPkl.py'
fileNameBuildDataSet = 'buildDataset.py'
fileNameComputeSignificance = 'computeSignificance.py'#'computeSignificanceScores.py' #'computeSignificance.py'#New.py' ##2
fileNameSplitDataSet = 'splitDataset.py'
fileNameBuildDNN = 'buildDNN.py'
#fileNameBuildPDNN = 'buildPDNNtuningHyp.py'
fileNameBuildPDNN = 'buildPDNN.py'#'buildPDNNscores.py'#'buildPDNN.py'
fileName6 = 'tuningHyperparameters.py'
fileNamePlots = 'tests/drawPlots.py'
fileNameCreateScoresBranch = 'addScoreBranch.py'#'createScoresBranch.py'
### Reading the command line
from argparse import ArgumentParser
import sys
from colorama import init, Fore
init(autoreset = True)
def ReadArgParser():
parser = ArgumentParser(add_help = False)
parser.add_argument('-a', '--Analysis', help = 'Type of analysis: \'merged\' or \'resolved\'', type = str)
parser.add_argument('-c', '--Channel', help = 'Channel: \'ggF\' or \'VBF\'', type = str)
parser.add_argument('-s', '--Signal', help = 'Signal: \'VBFHVTWZ\', \'Radion\', \'RSG\', \'VBFRSG\', \'HVTWZ\' or \'VBFRadion\'', type = str)
#parser.add_argument('-j', '--JetCollection', help = 'Jet collection: \'TCC\', \'UFO_PFLOW\'', type = str, default = 'UFO_PFLOW')
parser.add_argument('-b', '--Background', help = 'Background: \'Zjets\', \'Wjets\', \'stop\', \'Diboson\', \'ttbar\' or \'all\' (in quotation mark separated by a space)', type = str, default = 'all')
parser.add_argument('-t', '--TrainingFraction', help = 'Relative size of the training sample, between 0 and 1', default = 0.8)
parser.add_argument('-p', '--PreselectionCuts', help = 'Preselection cut', type = str)
parser.add_argument('-h', '--hpOptimization', help = 'If 1 hyperparameters optimization will be performed', default = 0)
parser.add_argument('-n', '--Nodes', help = 'Number of nodes of the (p)DNN, should always be >= nColumns and strictly positive', default = 48)#128) #32
parser.add_argument('-l', '--Layers', help = 'Number of hidden layers of the (p)DNN', default = 2)#4) #2
parser.add_argument('-e', '--Epochs', help = 'Number of maximum epochs for the training', default = 200) #150
parser.add_argument('-v', '--Validation', help = 'Fraction of the training data that will actually be used for validation', default = 0.2)
parser.add_argument('-d', '--Dropout', help = 'Fraction of the neurons to drop during the training', default = 0.2)
parser.add_argument('-m', '--Mass', help = 'Masses for the (P)DNN train/test (GeV, in quotation mark separated by a space)', default = 'all')
parser.add_argument('--doTrain', help = 'If 1 the training will be performed, if 0 it won\'t', default = 1)
parser.add_argument('--doTest', help = 'If 1 the test will be performed, if 0 it won\'t', default = 1)
parser.add_argument('--loop', help = 'How many times the code will be executed', default = 1) #20
parser.add_argument('--tag', help = 'CxAOD tag', default = 'r33-24')
parser.add_argument('--drawPlots', help = 'If 1 all plots will be saved', default = 0)
parser.add_argument('-r', '--regime', help = '')
parser.add_argument('-f', '--FeatureToPlot', help = 'Feature to plot to compute significance', default = 'score')
parser.add_argument('--trainSet', help = 'trainSet')
parser.add_argument('--doStudyLRpatience', default = 0)
args = parser.parse_args()
analysis = args.Analysis
if args.Analysis is None and fileNameSaveToPkl not in sys.argv[0] and fileNameComputeSignificance not in sys.argv[0]:
parser.error(Fore.RED + 'Requested type of analysis (either \'merged\' or \'resolved\')')
elif args.Analysis and analysis != 'resolved' and analysis != 'merged':
parser.error(Fore.RED + 'Analysis can be either \'merged\' or \'resolved\'')
channel = args.Channel
if args.Channel is None and fileNameSaveToPkl not in sys.argv[0] and fileNameComputeSignificance not in sys.argv[0]:
parser.error(Fore.RED + 'Requested channel (either \'ggF\' or \'VBF\')')
elif args.Channel and channel != 'ggF' and channel != 'VBF':
parser.error(Fore.RED + 'Channel can be either \'ggF\' or \'VBF\'')
signal = args.Signal
if args.Signal is None and fileNameSaveToPkl not in sys.argv[0]:
parser.error(Fore.RED + 'Requested type of signal (\'Radion\', \'RSG\', \'HVTWZ\')')
if args.Signal and signal != 'Radion' and signal != 'RSG' and signal != 'HVTWZ':
parser.error(Fore.RED + 'Signal can be only \'Radion\', \'RSG\' or \'HVTWZ\'')
if args.Channel and channel == 'VBF':
signal = channel + signal
'''
jetCollection = args.JetCollection
if args.JetCollection is None:
parser.error(Fore.RED + 'Requested jet collection (\'TCC\' or \'UFO_PFLOW\')')
elif args.JetCollection != 'TCC' and args.JetCollection != 'UFO_PFLOW':
parser.error(Fore.RED + 'Jet collection can be \'TCC\', \'UFO_PFLOW\'')
'''
background = args.Background.split()
for bkg in background:
if (bkg != 'Zjets' and bkg != 'Wjets' and bkg != 'stop' and bkg != 'Diboson' and bkg != 'ttbar' and bkg != 'all'):
parser.error(Fore.RED + 'Background can be \'Zjets\', \'Wjets\', \'stop\', \'Diboson\', \'ttbar\' or \'all\'')
backgroundString = 'all'
if args.Background != 'all':
backgroundString = '_'.join([str(item) for item in background])
trainingFraction = float(args.TrainingFraction)
if args.TrainingFraction and (trainingFraction < 0. or trainingFraction > 1.):
parser.error(Fore.RED + 'Training fraction must be between 0 and 1')
preselectionCuts = args.PreselectionCuts
if args.PreselectionCuts is None:
preselectionCuts = 'none'
hpOptimization = bool(int(args.hpOptimization))
numberOfNodes = int(args.Nodes)
if args.Nodes and numberOfNodes < 1:
parser.error(Fore.RED + 'Number of nodes must be integer and strictly positive')
numberOfLayers = int(args.Layers)
if args.Layers and numberOfLayers < 1:
parser.error(Fore.RED + 'Number of layers must be integer and strictly positive')
numberOfEpochs = int(args.Epochs)
if args.Epochs and numberOfEpochs < 1:
parser.error(Fore.RED + 'Number of maximum epochs must be integer and strictly positive')
validationFraction = float(args.Validation)
if args.Validation and (validationFraction < 0. or validationFraction > 1.):
parser.error(Fore.RED + 'Validation fraction must be between 0 and 1')
dropout = float(args.Dropout)
if args.Dropout and (dropout < 0. or dropout > 1.):
parser.error(Fore.RED + 'Dropout must be between 0 and 1')
mass = args.Mass.split()
doTrain = bool(int(args.doTrain))
if args.doTrain and (doTrain != 0 and doTrain != 1):
parser.error(Fore.RED + 'doTrain can only be 1 (to perform the training) or 0')
doTest = bool(int(args.doTest))
if args.doTest and (doTest != 0 and doTest != 1):
parser.error(Fore.RED + 'doTest can only be 1 (to perform the test) or 0')
loop = int(args.loop)
trainSet = args.trainSet
tag = args.tag
drawPlots = args.drawPlots
regime = args.regime#.split()
if args.regime:
regime = regime.split()
feature = args.FeatureToPlot
doStudyLRpatience = bool(int(args.doStudyLRpatience))
if fileNameSaveToPkl in sys.argv[0]:
print(Fore.BLUE + ' tag = ' + tag)
#print(Fore.BLUE + 'jet collection = ' + jetCollection)
return tag
if fileNameBuildDataSet in sys.argv[0]:
print(Fore.BLUE + ' tag = ' + tag)
#print(Fore.BLUE + ' jet collection = ' + jetCollection)
print(Fore.BLUE + ' background(s) = ' + str(backgroundString))
print(Fore.BLUE + ' drawPlots = ' + str(drawPlots))
return tag, analysis, channel, preselectionCuts, signal, backgroundString, drawPlots
if fileNameSplitDataSet in sys.argv[0] or fileNamePlots in sys.argv[0]:
print(Fore.BLUE + ' tag = ' + tag)
#print(Fore.BLUE + ' jet collection = ' + jetCollection)
print(Fore.BLUE + ' background = ' + str(backgroundString))
print(Fore.BLUE + 'training fraction = ' + str(trainingFraction))
print(Fore.BLUE + ' drawPlots = ' + str(drawPlots))
return tag, analysis, channel, preselectionCuts, backgroundString, signal, trainingFraction, drawPlots
if fileNameBuildDNN in sys.argv[0] or fileNameBuildPDNN in sys.argv[0]:# or sys.argv[0] == fileName6):
print(Fore.BLUE + ' background(s) = ' + str(backgroundString))
print(Fore.BLUE + ' test mass(es) = ' + str(mass))
print(Fore.BLUE + ' training fraction = ' + str(trainingFraction))
print(Fore.BLUE + 'hyperparameters optimization = ' + str(hpOptimization))
print(Fore.BLUE + ' doTrain = ' + str(doTrain))
print(Fore.BLUE + ' doTest = ' + str(doTest))
print(Fore.BLUE + ' validation fraction = ' + str(validationFraction))
print(Fore.BLUE + ' number of maximum epochs = ' + str(numberOfEpochs))
print(Fore.BLUE + ' trainSet = ' + str(trainSet))
if not hpOptimization:
print(Fore.BLUE + ' number of nodes = ' + str(numberOfNodes))
print(Fore.BLUE + ' number of hidden layers = ' + str(numberOfLayers))
print(Fore.BLUE + ' dropout = ' + str(dropout))
return tag, analysis, channel, preselectionCuts, backgroundString, trainingFraction, signal, numberOfNodes, numberOfLayers, numberOfEpochs, validationFraction, dropout, mass, doTrain, doTest, loop, hpOptimization, drawPlots, trainSet, doStudyLRpatience
if fileNameComputeSignificance in sys.argv[0]:
return tag, regime, preselectionCuts, signal, backgroundString
if fileNameCreateScoresBranch in sys.argv[0]:
print(Fore.BLUE + ' background(s) = ' + str(backgroundString))
print(Fore.BLUE + ' signal = ' + str(signal))
return tag, analysis, channel, preselectionCuts, signal, backgroundString
### Reading from the configuration file
import configparser, ast
import shutil
def ReadConfigSaveToPkl(tag):#, jetCollection):
#configurationFile = 'Configuration_' + jetCollection + '_' + tag + '.ini'
configurationFile = 'Configuration_' + '_' + tag + '.ini'
print(Fore.GREEN + 'Reading configuration file: ' + configurationFile)
config = configparser.ConfigParser()
config.read(configurationFile)
ntuplePath = config.get('config', 'ntuplePath')
inputFiles = ast.literal_eval(config.get('config', 'inputFiles'))
dfPath = config.get('config', 'dfPath')
dfPath += tag + '/'# + jetCollection + '/'
rootBranchSubSample = ast.literal_eval(config.get('config', 'rootBranchSubSample'))
#print (format('Output directory: ' + Fore.GREEN + dfPath), checkCreateDir(dfPath))
#shutil.copyfile(configurationFile, dfPath + configurationFile)
return ntuplePath, inputFiles, dfPath, rootBranchSubSample
#def ReadConfig(tag, analysis, jetCollection, signal):
def ReadConfig(tag, analysis, signal):
configurationFile = 'Configuration_' + tag + '.ini'
print(Fore.GREEN + 'Reading configuration file: ' + configurationFile)
config = configparser.ConfigParser()
config.read(configurationFile)
inputFiles = ast.literal_eval(config.get('config', 'inputFiles'))
ntuplePath = config.get('config', 'ntuplePath')
rootBranchSubSample = ast.literal_eval(config.get('config', 'rootBranchSubSample'))
signalsList = ast.literal_eval(config.get('config', 'signals'))
backgroundsList = ast.literal_eval(config.get('config', 'backgrounds'))
dfPath = config.get('config', 'dfPath')
#dfPath += tag + '/' + jetCollection + '/'
dfPath += tag + '/'
if analysis == 'merged':
InputFeatures = ast.literal_eval(config.get('config', 'inputFeaturesMerged'))
variablesToDerive = ast.literal_eval(config.get('config', 'variablesToDeriveMerged'))
variablesToSave = ast.literal_eval(config.get('config', 'variablesToSaveMerged'))
elif analysis == 'resolved':
#if signal == 'Radion' or signal == 'RSG':
if 'Radion' in signal or 'RSG' in signal:
InputFeatures = ast.literal_eval(config.get('config', 'inputFeaturesResolvedRadionRSG'))
variablesToDerive = ast.literal_eval(config.get('config', 'variablesToDeriveResolvedRadionRSG'))
variablesToSave = ast.literal_eval(config.get('config', 'variablesToSaveResolvedRadionRSG'))
else:
InputFeatures = ast.literal_eval(config.get('config', 'inputFeaturesResolvedHVT'))
variablesToSave = ast.literal_eval(config.get('config', 'variablesToSaveResolvedHVT'))
if fileNameBuildDataSet in sys.argv[0]:
return ntuplePath, InputFeatures, dfPath, variablesToSave, variablesToDerive, backgroundsList
if fileNameComputeSignificance in sys.argv[0] or fileNameCreateScoresBranch in sys.argv[0]:
return inputFiles, rootBranchSubSample, InputFeatures, dfPath, variablesToSave, backgroundsList
if fileNamePlots in sys.argv[0]:
return dfPath, InputFeatures
if fileNameSplitDataSet in sys.argv[0]:
return dfPath, signalsList, backgroundsList
if fileNameBuildDNN in sys.argv[0] or fileNameBuildPDNN in sys.argv[0] or fileName6 in sys.argv[0]:
return ntuplePath, dfPath, InputFeatures
### Checking if the output directory exists. If not, creating it
import os
#os.environ["CUDA_VISIBLE_DEVICES"] = "-1"
os.environ['TF_CPP_MIN_LOG_LEVEL'] = '3' # or any {'0', '1', '2'} ---> '3' to suppress INFO, WARNING, and ERROR messages in Tensorflow
def checkCreateDir(dir):
if not os.path.isdir(dir):
os.makedirs(dir)
return Fore.RED + ' (created)'
else:
return Fore.RED + ' (already there)'
### Functions to enable or disable 'print' calls
def blockPrint():
sys.stdout = open(os.devnull, 'w')
def enablePrint():
sys.stdout = sys.__stdout__
### Loading input data
import pandas as pd
import numpy as np
#def LoadData(dfPath, tag, jetCollection, signal, analysis, channel, background, trainingFraction, preselectionCuts, InputFeatures, iLoop):
def LoadData(dfPath, tag, signal, analysis, channel, background, trainingFraction, preselectionCuts, InputFeatures, iLoop):
fileCommonName = tag + '_' + analysis + '_' + channel + '_' + preselectionCuts + '_' + str(signal) + '_' + background + '_' + str(trainingFraction) + 't'
print(Fore.GREEN + 'Loading ' + dfPath + 'data_train_' + fileCommonName + '.pkl')
dataTrain = pd.read_pickle(dfPath + '/data_train_' + fileCommonName + '.pkl')
#dataTrain = dataTrain.query('Pass_MergHP_GGF_WZ_SR == True or Pass_MergLP_GGF_WZ_SR == True or Pass_MergHP_VBF_WZ_SR == True or Pass_MergLP_VBF_WZ_SR == True')
#print('# of events in dataTrain: ' + str(len(dataTrain)))
'''
passCols = ['Pass_MergHP_GGF_ZZ_Tag_ZCR', 'Pass_MergHP_GGF_ZZ_Untag_ZCR', 'Pass_MergLP_GGF_ZZ_Tag_ZCR', 'Pass_MergLP_GGF_ZZ_Untag_ZCR', 'Pass_MergHP_GGF_WZ_ZCR', 'Pass_MergLP_GGF_WZ_ZCR', 'Pass_MergHP_VBF_WZ_ZCR', 'Pass_MergHP_VBF_ZZ_ZCR', 'Pass_MergLP_VBF_WZ_ZCR', 'Pass_MergLP_VBF_ZZ_ZCR']
for col in passCols:
dataTrain[col].replace(to_replace = [False, True], value = [0, 1], inplace = True)
sumCol = dataTrain[col].sum()
print(col + ' -> ' + str(sumCol))
exit()
'''
#X_train = np.array(dataTrain[InputFeatures].values).astype(np.float32)
#y_train = np.array(dataTrain['isSignal'].values).astype(np.float32)
#w_train = dataTrain['train_weight'].values
print(Fore.GREEN + 'Loading ' + dfPath + 'data_test_' + fileCommonName + '.pkl')
dataTest = pd.read_pickle(dfPath + '/data_test_' + fileCommonName + '.pkl')
#X_test = np.array(dataTest[InputFeatures].values).astype(np.float32)
#y_test = np.array(dataTest['isSignal'].values).astype(np.float32)
#w_test = dataTest['train_weight'].values
return dataTrain, dataTest#, X_train, X_test, y_train, y_test, w_train, w_test
### Writing in the log file
def WriteLogFile(tag, ntuplePath, InputFeatures, dfPath, hpOptimization, doTrain, doTest, validationFraction, batchSize, patienceValue):
logString = 'CxAOD tag: ' + tag + '\nntuple path: ' + ntuplePath + '\nInputFeatures: ' + str(InputFeatures) + '\ndfPath: ' + dfPath + '\nHyperparameters optimization: ' + str(hpOptimization) + '\ndoTrain: ' + str(doTrain) + '\ndoTest: ' + str(doTest) + '\nValidation fraction: ' + str(validationFraction) + '\nBatch size: ' + str(batchSize)# + '\nPatience value: ' + str(patienceValue)# + '\nNumber of train events: ' + str(len(data_train)) + ' (' + str(len(data_train_signal)) + ' signal and ' + str(len(data_train_bkg)) + ' background)' + '\nNumber of test events: ' + str(len(data_test)) + ' (' + str(len(data_test_signal)) + ' signal and ' + str(len(data_test_bkg)) + ' background)'
return logString
def SelectEvents(dataFrame, channel, analysis, preselectionCuts, signal):
### Selecting events according to type of analysis and channel
selectionMergedGGF = 'Pass_MergHP_GGF_ZZ_2btag_SR == True or Pass_MergHP_GGF_ZZ_01btag_SR == True or Pass_MergHP_GGF_WZ_SR == True or Pass_MergLP_GGF_ZZ_2btag_SR == True or Pass_MergLP_GGF_ZZ_01btag_SR == True or Pass_MergLP_GGF_WZ_SR == True or Pass_MergHP_GGF_ZZ_2btag_ZCR == True or Pass_MergHP_GGF_ZZ_01btag_ZCR == True or Pass_MergHP_GGF_WZ_ZCR == True or Pass_MergLP_GGF_ZZ_2btag_ZCR == True or Pass_MergLP_GGF_ZZ_01btag_ZCR == True or Pass_MergLP_GGF_WZ_ZCR == True'# or Pass_MergHP_GGF_ZZ_01btag_TCR == True or Pass_MergHP_GGF_ZZ_2btag_TCR == True or Pass_MergHP_GGF_WZ_TCR == True or Pass_MergLP_GGF_ZZ_01btag_TCR == True or Pass_MergLP_GGF_ZZ_2btag_TCR == True or Pass_MergLP_GGF_WZ_TCR == True'
selectionMergedGGFZZLPuntagSR = 'Pass_MergLP_GGF_ZZ_01btag_SR == True and Pass_MergHP_GGF_ZZ_2btag_SR == False and Pass_MergHP_GGF_ZZ_01btag_SR == False and Pass_MergHP_GGF_WZ_SR == False and Pass_MergLP_GGF_ZZ_2btag_SR == False and Pass_MergHP_GGF_ZZ_2btag_ZCR == False and Pass_MergHP_GGF_WZ_ZCR == False and Pass_MergHP_GGF_ZZ_01btag_ZCR == False and Pass_MergLP_GGF_ZZ_2btag_ZCR == False and Pass_MergLP_GGF_ZZ_01btag_ZCR == False and Pass_MergLP_GGF_WZ_SR == False and Pass_MergLP_GGF_WZ_ZCR == False'
selectionMergedVBF = 'Pass_MergHP_VBF_WZ_SR == True or Pass_MergHP_VBF_ZZ_SR == True or Pass_MergLP_VBF_WZ_SR == True or Pass_MergLP_VBF_ZZ_SR == True or Pass_MergHP_VBF_WZ_ZCR == True or Pass_MergHP_VBF_ZZ_ZCR == True or Pass_MergLP_VBF_WZ_ZCR == True or Pass_MergLP_VBF_ZZ_ZCR == True'# or Pass_MergHP_VBF_WZ_TCR == True or Pass_MergHP_VBF_ZZ_TCR == True or Pass_MergLP_VBF_WZ_TCR == True or Pass_MergLP_VBF_ZZ_TCR == True'
#selectionMergedVBF = 'Pass_MergHP_VBF_ZZ_SR == True or Pass_MergLP_VBF_ZZ_SR == True or Pass_MergHP_VBF_ZZ_ZCR == True or Pass_MergLP_VBF_ZZ_ZCR == True'# or Pass_MergHP_VBF_WZ_TCR == True or Pass_MergHP_VBF_ZZ_TCR == True or Pass_MergLP_VBF_WZ_TCR == True or Pass_MergLP_VBF_ZZ_TCR == True'
selectionResolvedGGF = 'Pass_Res_GGF_WZ_SR == True or Pass_Res_GGF_ZZ_2btag_SR == True or Pass_Res_GGF_ZZ_01btag_SR == True or Pass_Res_GGF_WZ_ZCR == True or Pass_Res_GGF_ZZ_2btag_ZCR == True or Pass_Res_GGF_ZZ_01btag_ZCR == True'# or Pass_Res_GGF_WZ_TCR == True or Pass_Res_GGF_ZZ_2btag_TCR == True or Pass_Res_GGF_ZZ_01btag_TCR == True'
selectionResolvedVBF = 'Pass_Res_VBF_WZ_SR == True or Pass_Res_VBF_ZZ_SR == True or Pass_Res_VBF_WZ_ZCR == True or Pass_Res_VBF_ZZ_ZCR == True'# or Pass_Res_VBF_WZ_TCR == True or Pass_Res_VBF_ZZ_TCR == True'
selectionResolved = 'Pass_Res_GGF_WZ_SR == True or Pass_Res_GGF_ZZ_2btag_SR == True or Pass_Res_GGF_ZZ_01btag_SR == True or Pass_Res_GGF_WZ_ZCR == True or Pass_Res_GGF_ZZ_2btag_ZCR == True or Pass_Res_GGF_ZZ_01btag_ZCR == True or Pass_Res_VBF_WZ_SR == True or Pass_Res_VBF_ZZ_SR == True or Pass_Res_VBF_WZ_ZCR == True or Pass_Res_VBF_ZZ_ZCR == True'
if channel == 'ggF':
dataFrame = dataFrame.query('Pass_isVBF == False')
if analysis == 'merged':
selection = selectionMergedGGF
#selection = selectionMergedGGFZZLPuntagSR
elif analysis == 'resolved':
selection = selectionResolvedGGF
#selection = selectionResolved
elif channel == 'VBF':
dataFrame = dataFrame.query('Pass_isVBF == True')
if analysis == 'merged':
selection = selectionMergedVBF
elif analysis == 'resolved':
selection = selectionResolvedVBF
dataFrame = dataFrame.query(selection)
### Applying preselection cuts (if any)
if preselectionCuts != 'none':
#dataFrame = dataFrame.query(preselectionCuts)
if preselectionCuts == 'looseEventsSelection':
if 'HVT' in signal:
print('Loose events selection for HVT')
dataFrame = dataFrame.query('Pass_SFLeptons == True and Pass_Trigger == True and Pass_FatJet == True and fatjet_pt > 200 and lep1_pt > 30 and lep2_pt > 30 and Pass_WTaggerSubStructCutLP == True')
else:
print('Loose events selection for Radion and RSG')
dataFrame = dataFrame.query('Pass_SFLeptons == True and Pass_Trigger == True and Pass_FatJet == True and fatjet_pt > 200 and lep1_pt > 30 and lep2_pt > 30 and Pass_ZTaggerSubStructCutLP == True')
return dataFrame
def SelectRegime(dataFrame, preselectionCuts, regime, channel):
### Selecting events according to the regime
if channel == 'ggF':
isVBF = 'False'
elif channel == 'VBF':
isVBF = 'True'
if regime == 'allMerged':
dataFrame = dataFrame.query('Pass_isVBF == ' + isVBF)
dataFrame = dataFrame.query('Pass_MergHP_GGF_ZZ_2btag_SR == True or Pass_MergLP_GGF_ZZ_2btag_SR == True or Pass_MergHP_GGF_ZZ_01btag_SR == True or Pass_MergLP_GGF_ZZ_01btag_SR == True')
if regime == 'allMergedZCRs':
dataFrame = dataFrame.query('Pass_isVBF == ' + isVBF)
selectionMergedGGF = 'Pass_MergHP_GGF_ZZ_2btag_SR == True or Pass_MergHP_GGF_ZZ_01btag_SR == True or Pass_MergHP_GGF_WZ_SR == True or Pass_MergLP_GGF_ZZ_2btag_SR == True or Pass_MergLP_GGF_ZZ_01btag_SR == True or Pass_MergLP_GGF_WZ_SR == True or Pass_MergHP_GGF_ZZ_2btag_ZCR == True or Pass_MergHP_GGF_ZZ_01btag_ZCR == True or Pass_MergHP_GGF_WZ_ZCR == True or Pass_MergLP_GGF_ZZ_2btag_ZCR == True or Pass_MergLP_GGF_ZZ_01btag_ZCR == True or Pass_MergLP_GGF_WZ_ZCR == True'# or Pass_MergHP_GGF_ZZ_01btag_TCR == True or Pass_MergHP_GGF_ZZ_2btag_TCR == True or Pass_MergHP_GGF_WZ_TCR == True or Pass_MergLP_GGF_ZZ_01btag_TCR == True or Pass_MergLP_GGF_ZZ_2btag_TCR == True or Pass_MergLP_GGF_WZ_TCR == True'
dataFrame = dataFrame.query(selectionMergedGGF)
#else:
if 'allMerged' not in regime:
dataFrame = dataFrame.query('Pass_isVBF == ' + isVBF + ' and ' + regime + ' == True')
'''
### Applying preselection cuts (if any)
if preselectionCuts != 'none':
dataFrame = dataFrame.query(preselectionCuts)
'''
return dataFrame
### Selecting signal events according to their mass and type of analysis
def CutMasses(dataFrame, analysis):
if analysis == 'merged':
dataFrame = dataFrame.query('mass >= 500')
elif analysis == 'resolved':
dataFrame = dataFrame.query('mass <= 1500')
return dataFrame
### Shuffling dataframe
import sklearn.utils
def ShufflingData(dataFrame):
dataFrame = sklearn.utils.shuffle(dataFrame, random_state = 123)
#dataFrame = dataFrame.reset_index(drop = True)
return dataFrame
### Drawing histograms of each variables in the dataframe divided by class
import seaborn
import matplotlib
import matplotlib.pyplot as plt
plt.ioff()
plt.rcParams["figure.figsize"] = [7,7]
plt.rcParams.update({'font.size': 16})
def integral(y,x,bins):
x_min=x
s=0
for i in np.where(bins>x)[0][:-1]:
s=s+y[i]*(bins[i+1]-bins[i])
return s
#def DrawVariablesHisto(dataFrame, InputFeatures, outputDir, outputFileCommonName, jetCollection, analysis, channel, signal, background, preselectionCuts, scaled = False):
#def DrawVariablesHisto(dataFrame, InputFeatures, outputDir, outputFileCommonName, analysis, channel, signal, background, preselectionCuts, scaled = False):
def DrawVariablesHisto(dataFrame, outputDir, outputFileCommonName, analysis, channel, signal, background, preselectionCuts, scaled = False):
'''
### Replacing '0' with 'Background' and '1' with 'Signal' in the 'isSignal' column
dataFrame['isSignal'].replace(to_replace = [0, 1], value = ['Background', 'Signal'], inplace = True)
dataFrameSignal = dataFrame[dataFrame['isSignal'] == 'Signal']
dataFrameBkg = dataFrame[dataFrame['isSignal'] == 'Background']
'''
dataFrameSignal = dataFrame[dataFrame['origin'] == signal]
dataFrameBkg = dataFrame[dataFrame['origin'] != signal]
#print(list(set(list(dataFrameBkg['origin']))))
if 'VBF' in signal:
signalLabel = signal.replace('VBF', '')
dataFrame['origin'].replace(to_replace = [signal], value = [signalLabel], inplace = True)
else:
signalLabel = signal
featureLogX = ['fatjet_D2', 'fatjet_m', 'fatjet_pt', 'lep1_pt', 'lep2_pt', 'Zcand_pt']
legendText = 'analysis: ' + analysis + '\nchannel: ' + channel + '\nsignal: ' + signal + '\nbackground: ' + ', '.join(background)
if (preselectionCuts != 'none'):
legendText += '\npreselection cuts: ' + preselectionCuts
for feature in dataFrame.columns:
'''
if feature not in InputFeatures and feature != 'origin' and feature != 'weight' and feature != 'DNNScore_t':
continue
'''
if 'Pass' in feature or feature == 'train_weight':
continue
print(feature)
statType = 'density'#'probability'
#hueType = dataFrame['isSignal']
hueType = dataFrameBkg['origin']#dataFrame['isSignal']
legendBool = True
if feature == 'origin' or feature == 'weight':
statType = 'count'
hueType = dataFrame['origin']
legendBool = False
#binsDict = {'lep1_m': np.linspace(0, 0.12, 4), 'lep1_pt': np.linspace(0, 2000, 51), 'lep1_eta': np.linspace(-3, 3, 21), 'lep1_phi': np.linspace(-3.5, 3.5, 21), 'lep2_m': np.linspace(0, 0.12, 4), 'lep2_pt': np.linspace(0, 2000, 51), 'lep2_eta': np.linspace(-3, 3, 21), 'lep2_phi': np.linspace(-3.5, 3.5, 21), 'fatjet_m': np.linspace(0, 500, 51), 'fatjet_pt': np.linspace(0, 3000, 51), 'fatjet_eta': np.linspace(-3, 3, 21), 'fatjet_phi': np.linspace(-3.5, 3.5, 21), 'fatjet_D2': np.linspace(0, 15, 51), 'Zcand_m': np.linspace(60, 140, 21), 'Zcand_pt': np.linspace(0, 7000, 31), 'mass': 'auto', 'origin': 'auto', 'Zdijet_m': np.linspace(60, 140, 21), 'Zdijet_pt': 'auto', 'Zdijet_eta': np.linspace(-4, 4, 11), 'Zdijet_phi': np.linspace(-3.5, 3.5, 11), 'sigZJ1_m': np.linspace(0, 120, 21), 'sigZJ1_pt': np.linspace(0, 1000, 11), 'sigZJ1_eta': np.linspace(-3, 3, 21), 'sigZJ1_phi': np.linspace(-3.5, 3.5, 21), 'sigZJ2_m': np.linspace(0, 40, 16), 'sigZJ2_pt': np.linspace(0, 300, 11), 'sigZJ2_eta': np.linspace(-3, 3, 21), 'sigZJ2_phi': np.linspace(-3.5, 3.5, 21), 'DNNScore_W': np.linspace(0, 1, 21), 'DNNScore_Z': np.linspace(0, 1, 21), 'DNNScore_h': np.linspace(0, 1, 21), 'DNNScore_t': np.linspace(0, 1, 21), 'DNNScore_qg': np.linspace(0, 1, 21)} ## for Radion merged ggF
binsDict = {}
minBin = min(min(dataFrameBkg[feature]), min(dataFrameSignal[feature]))
maxBin = max(max(dataFrameBkg[feature]), max(dataFrameSignal[feature]))
Bins = np.linspace(minBin, maxBin, 16)
if feature not in binsDict:
binsDict[feature] = 'auto'
if feature == 'weight':
#ax = seaborn.histplot(data = dataFrame['weight'], x = dataFrame['weight'], hue = dataFrame['isSignal'], common_norm = False, stat = statType, legend = True)
ax = seaborn.histplot(data = dataFrame['weight'], x = dataFrame['weight'], hue = dataFrame['isSignal'], bins = np.linspace(min(dataFrame['weight']), max(dataFrame['weight']), 21), common_norm = False, stat = statType, legend = True)
if feature == 'origin':
ax = seaborn.histplot(data = dataFrame[feature], x = dataFrame[feature], hue = dataFrame['origin'], common_norm = False, stat = statType, legend = True)
else:
'''
if scaled == False and feature in binsDict:
ax = seaborn.histplot(data = dataFrameBkg[feature], x = dataFrameBkg[feature], weights = dataFrameBkg['weight'], bins = np.array(binsDict[feature]), hue = hueType, legend = legendBool, multiple = 'stack', stat = 'probability', common_norm = True) #stat = statType
if scaled == False and feature not in binsDict:
ax = seaborn.histplot(data = dataFrame[feature], x = dataFrame[feature], weights = dataFrame['weight'], hue = hueType, common_norm = False, stat = statType, legend = legendBool)#, multiple = 'stack')
elif scaled == True:
ax = seaborn.histplot(data = dataFrame[feature], x = dataFrame[feature], weights = dataFrame['weight'], hue = hueType, common_norm = False, stat = statType, legend = legendBool)#, multiple = 'stack')
'''
ax = seaborn.histplot(data = dataFrame[feature], x = dataFrame[feature], weights = dataFrame['weight'], hue = hueType, bins = Bins, common_norm = False, stat = statType, legend = legendBool)#, multiple = 'stack')
#seaborn.histplot(data = dataFrameSignal[feature], x = dataFrameSignal[feature], weights = dataFrameSignal['weight'], bins = np.array(binsDict[feature]), element = 'step', fill = False, stat = 'probability', color = 'red')#, lw = 2, color = 'blue', label = signalLabel)#, density = True)
seaborn.histplot(data = dataFrameSignal[feature], x = dataFrameSignal[feature], weights = dataFrameSignal['weight'], bins = Bins, element = 'step', fill = False, stat = 'probability', color = 'red')#, lw = 2, color = 'blue', label = signalLabel)#, density = True)
#elif fileNameSplitDataSet in sys.argv[0]:
''' histogram of train_weight without bins is slow
if feature == 'train_weight':
ax = seaborn.histplot(data = dataFrame['weight'], x = dataFrame['weight'], hue = dataFrame['isSignal'], common_norm = False, stat = 'count', legend = True)
'''
# contents, bins, _ = plt.hist(dataFrame[feature], weights = dataFrame['train_weight'], bins = 100, label = legendText)
labelDict = {'lep1_e': r'lep$_1$ e [GeV]', 'lep1_m': r'lep$_1$ m [GeV]', 'lep1_pt': r'lep$_1$ p$_T$ [GeV]', 'lep1_eta': r'lep$_1$ $\eta$', 'lep1_phi': r'lep$_1$ $\phi$', 'lep2_e': r'lep$_2$ e [GeV]', 'lep2_m': r'lep$_2$ m [GeV]', 'lep2_pt': r'lep$_2$ p$_t$ [GeV]', 'lep2_eta': r'lep$_2$ $\eta$', 'lep2_phi': r'lep$_2$ $\phi$', 'fatjet_m': 'fat jet m [GeV]', 'fatjet_pt': r'fat jet p$_t$ [GeV]', 'fatjet_eta': r'fat jet $\eta$', 'fatjet_phi': r'fat jet $\phi$', 'fatjet_D2': r'fat jet D$_2$', 'Zcand_m': 'Z$_{cand}$ m [GeV]', 'Zcand_pt': r'Z$_{cand}$ p$_t$ [GeV]', 'X_boosted_m': 'X_boosted m [GeV]', 'X_resolved_ZZ_m': 'X_resolved_ZZ m [GeV]', 'X_resolved_WZ_m': 'X_resolved_WZ m [GeV]', 'mass': 'mass [GeV]', 'weight': 'weight', 'isSignal': 'isSignal', 'origin': 'origin', 'Wdijet_m': 'Wdijet m [GeV]', 'Wdijet_pt': 'Wdijet p$_T$ [GeV]', 'Wdijet_eta': 'Wdijet $\eta$', 'Wdijet_phi': 'Wdijet $\phi$', 'Zdijet_m': 'Z$_{dijet}$ m [GeV]', 'Zdijet_pt': 'Z$_{dijet}$ p$_T$ [GeV]', 'Zdijet_eta': 'Z$_{dijet}$ $\eta$', 'Zdijet_phi': 'Z$_{dijet}$ $\phi$', 'sigWJ1_m': 'sigWJ1 m', 'sigWJ1_pt': 'sigWJ1 p$_T$', 'sigWJ1_eta': 'sigWJ1 $\eta$', 'sigWJ1_phi': 'sigWJ1 $\phi$', 'sigWJ2_m': 'sigWJ2 m', 'sigWJ2_pt': 'sigWJ2 p$_T$', 'sigWJ2_eta': 'sigWJ2 $\eta$', 'sigWJ2_phi': 'sigWJ2 $\phi$', 'sigZJ1_m': 'sigZJ1 m', 'sigZJ1_pt': 'sigZJ1 p$_T$', 'sigZJ1_eta': 'sigZJ1 $\eta$', 'sigZJ1_phi': 'sigZJ1 $\phi$', 'sigZJ2_m': 'sigZJ2 m', 'sigZJ2_pt': 'sigZJ2 p$_T$', 'sigZJ2_eta': 'sigZJ2 $\eta$', 'sigZJ2_phi': 'sigZJ2 $\phi$', 'lep1_px': r'lep$_1$ p$_x$ [GeV]', 'lep1_py': r'lep$_1$ p$_y$ [GeV]', 'lep1_pz': r'lep$_1$ p$_z$ [GeV]', 'lep2_px': r'lep$_2$ p$_x$ [GeV]', 'lep2_py': r'lep$_2$ p$_y$ [GeV]', 'lep2_pz': r'lep$_2$ p$_z$ [GeV]', 'fatjet_e': 'fat jet e [GeV]', 'fatjet_px': r'fat jet p$_x$ [GeV]', 'fatjet_py': r'fat jet p$_y$', 'fatjet_pz': r'fat jet p$_z$'}
'''
if feature in featureLogX:
ax.set_xscale('log')
'''
#plt.figtext(0.35, 0.7, legendText, wrap = True, horizontalalignment = 'left')
#plt.figtext(0.77, 0.45, legendText, wrap = True, horizontalalignment = 'left')
#plt.subplots_adjust(left = 0.1, right = 0.75)
if feature in labelDict:
if scaled == True:
plt.xlabel('Scaled ' + labelDict[feature])
else:
plt.xlabel(labelDict[feature])
else:
if scaled == True and feature != 'origin':
plt.xlabel('Scaled ' + feature)
if scaled == False or feature == 'origin':
plt.xlabel(feature)
'''
if fileNameSplitDataSet in sys.argv[0]:
plt.ylabel('Weighted counts')
plt.legend(handlelength = 0, handletextpad = 0, prop={'size': 15})
if fileNameBuildDataSet in sys.argv[0]:
plt.ylabel('Weighted probability (MC weights)')
if feature == 'weight':
plt.ylabel('Counts')
'''
plt.ylabel('Weighted probability (MC weights)')
if feature == 'weight' or feature == 'origin':
plt.ylabel('Counts')
#plt.legend(handlelength = 0, handletextpad = 0, prop={'size': 15})
if feature == 'origin':
plt.yscale('log')
plt.title('SRs + ZCRs, ' + signalLabel + ', ' + analysis + ', ' + channel)
pltName = '/Histo_' + feature + '_' + outputFileCommonName + '.png'
plt.tight_layout()
plt.savefig(outputDir + pltName)
print(Fore.GREEN + 'Saved ' + outputDir + pltName)
plt.clf()
dataFrame['isSignal'].replace(to_replace = ['Background', 'Signal'], value = [0, 1], inplace = True)
if 'VBF' in signal:
dataFrame['origin'].replace(to_replace = [signalLabel], value = [signal], inplace = True)
plt.close()
#plt.subplots_adjust(left = 0.15, right = 0.95)
return
### Computing train weight
#def ComputeTrainWeights(dataSetSignal, dataSetBackground, massesSignalList, outputDir, fileCommonName, jetCollection, analysis, channel, signal, background, preselectionCuts, drawPlots):
def ComputeTrainWeights(dataSetSignal, dataSetBackground, massesSignalList, outputDir, fileCommonName, analysis, channel, signal, background, preselectionCuts, drawPlots):
numbersDict = {}
logString = ''
for signalMass in massesSignalList:
### Number of signals with each mass value
numbersDict[signalMass] = dataSetSignal[dataSetSignal['mass'] == signalMass].shape[0]
### Minimum number of signals with the same mass
#minNumber = min(numbersDict.values())
minNumber = sum(numbersDict.values()) / len(numbersDict)
### New column in the signal dataframe for train_weight
dataSetSignal = dataSetSignal.assign(train_weight = 0)
for signalMass in massesSignalList:
dataSetSignalMass = dataSetSignal[dataSetSignal['mass'] == signalMass]
### Sum of MC weights for signal with the same mass
signalSampleWeight = dataSetSignalMass['weight'].sum()
### Scale factor to equalize signal samples with different mass
scaleFactorDict = minNumber / signalSampleWeight
### Train weight = MC weight * scale factor
dataSetSignal['train_weight'] = np.where(dataSetSignal['mass'] == signalMass, dataSetSignal['weight'] * scaleFactorDict, dataSetSignal['train_weight'])
if drawPlots:
### Filling the bar plot
plt.bar(signal + ' ' + str(signalMass) + ' GeV', dataSetSignal[dataSetSignal['mass'] == signalMass]['train_weight'].sum(), color = 'blue')
if drawPlots:
plt.bar('all ' + signal, dataSetSignal['train_weight'].sum(), color = 'orange')
'''
### All signal weight
signalWeight = dataSetSignal['train_weight'].sum()
'''
### Background MC weight
bkgWeight = dataSetBackground['weight'].sum()
### Scale factor to equalize signal/background
scaleFactor = minNumber * len(massesSignalList)/ bkgWeight
### Creating new column in the background dataframe with the train weight
dataSetBackground = dataSetBackground.assign(train_weight = dataSetBackground['weight'] * scaleFactor)
if drawPlots:
plt.bar('background', dataSetBackground['train_weight'].sum(), color = 'green')
plt.ylabel('Weighted counts')
plt.xticks(rotation = 'vertical')
legendText = 'analysis: ' + analysis + '\nchannel: ' + channel + '\nsignal: ' + signal + '\nbackground: ' + ', '.join(background)
if (preselectionCuts != 'none'):
legendText += '\npreselection cuts: ' + preselectionCuts
plt.figtext(0.25, 0.7, legendText, wrap = True, horizontalalignment = 'left')
plt.tight_layout()
pltName = outputDir + '/WeightedEvents_' + fileCommonName + '.png'
plt.savefig(pltName)
print(Fore.GREEN + 'Saved ' + pltName)
logString = '\nSaved ' + pltName
plt.clf()
plt.close()
return dataSetSignal, dataSetBackground, logString
### Computing weighted median and IQR range
def ScalingFeatures(dataTrain, dataTest, InputFeatures, outputDir):
dataTrainCopy = dataTrain.copy()
sumTrainWeights = np.array(dataTrainCopy['train_weight']).sum()
halfTrainWeights = sumTrainWeights / 2
perc1 = sumTrainWeights * 0.25
perc2 = sumTrainWeights * 0.75
variablesFileName = outputDir + '/variables.json'
variablesFile = open(variablesFileName, 'w')
variablesFile.write("{\n")
variablesFile.write(" \"inputs\": [\n")
for feature in InputFeatures:
if 'DNN' in feature:
continue
cumulativeSum = 0
print('Scaling ' + feature)
dataTrainCopy = dataTrainCopy.sort_values(by = [feature])
for index in range(len(dataTrainCopy)):
cumulativeSum += dataTrainCopy['train_weight'].iloc[index]
if cumulativeSum <= perc1:
perc1index = index
else:
break
for index in range(perc1index, len(dataTrainCopy)):
cumulativeSum += dataTrainCopy['train_weight'].iloc[index]
if cumulativeSum <= halfTrainWeights:
medianIndex = index
else:
break
for index in range(medianIndex, len(dataTrainCopy)):
cumulativeSum += dataTrainCopy['train_weight'].iloc[index]
if cumulativeSum <= perc2:
perc2index = index
else:
break
quartileLeft = dataTrainCopy[feature].iloc[perc1index]
median = dataTrainCopy[feature].iloc[medianIndex]
quartileRight = dataTrainCopy[feature].iloc[perc2index]
iqr = quartileRight - quartileLeft ### InterQuartile Range
dataTrain[feature] = (dataTrain[feature] - median) / iqr
dataTest[feature] = (dataTest[feature] - median) / iqr
variablesFile.write(" {\n")
variablesFile.write(" \"name\": \"%s\",\n" % feature)
variablesFile.write(" \"offset\": %lf,\n" % median) # EJS 2021-05-27: I have compelling reasons to believe this should be -mu
variablesFile.write(" \"scale\": %lf\n" % iqr) # EJS 2021-05-27: I have compelling reasons to believe this should be 1/sigma
variablesFile.write(" }")
if feature != InputFeatures[len(InputFeatures) - 1]:
variablesFile.write(",\n")
else:
variablesFile.write("\n")
variablesFile.write(" ],\n")
variablesFile.write(" \"class_labels\": [\"BinaryClassificationOutputName\"]\n")
variablesFile.write("}\n")
print(Fore.GREEN + 'Saved variables offsets and scales in ' + variablesFileName)
logString = '\nSaved variables offset and scales in ' + variablesFileName
return dataTrain, dataTest, logString
### Computing weighted median and IQR range
def ComputeScaleFactors(dataTrain, outputDir):
dataTrainCopy = dataTrain.copy()
variablesNotToScale = ['Pass', 'DNN', 'origin', 'isSignal', 'weight', 'train_weight', 'unscaledMass']
variablesToScale = []
for variable in dataTrain.columns:
addVariable = True
for variableNotToScale in variablesNotToScale:
if variableNotToScale in variable:
addVariable = False
print('Not scaling ' + variable)
break
if addVariable == True:
variablesToScale.append(variable)
sumTrainWeights = np.array(dataTrainCopy['train_weight']).sum()
halfTrainWeights = sumTrainWeights / 2
perc1 = sumTrainWeights * 0.25
perc2 = sumTrainWeights * 0.75
variablesFileName = outputDir + '/variables.json'
variablesFile = open(variablesFileName, 'w')
variablesFile.write("{\n")
variablesFile.write(" \"inputs\": [\n")
for feature in variablesToScale:
cumulativeSum = 0
print('Computing scale factors (median and IQR) for ' + feature)
dataTrainCopy = dataTrainCopy.sort_values(by = [feature])
for index in range(len(dataTrainCopy)):
cumulativeSum += dataTrainCopy['train_weight'].iloc[index]
if cumulativeSum <= perc1:
perc1index = index
else:
break
for index in range(perc1index, len(dataTrainCopy)):
cumulativeSum += dataTrainCopy['train_weight'].iloc[index]
if cumulativeSum <= halfTrainWeights:
medianIndex = index
else:
break
for index in range(medianIndex, len(dataTrainCopy)):
cumulativeSum += dataTrainCopy['train_weight'].iloc[index]
if cumulativeSum <= perc2:
perc2index = index
else:
break
quartileLeft = dataTrainCopy[feature].iloc[perc1index]
median = dataTrainCopy[feature].iloc[medianIndex]
quartileRight = dataTrainCopy[feature].iloc[perc2index]
iqr = quartileRight - quartileLeft ### InterQuartile Range (IQR)
variablesFile.write(" {\n")
variablesFile.write(" \"name\": \"%s\",\n" % feature)
variablesFile.write(" \"offset\": %lf,\n" % median) # EJS 2021-05-27: I have compelling reasons to believe this should be -mu
variablesFile.write(" \"scale\": %lf\n" % iqr) # EJS 2021-05-27: I have compelling reasons to believe this should be 1/sigma
variablesFile.write(" }")
if feature != variablesToScale[len(variablesToScale) - 1]:
variablesFile.write(",\n")
else:
variablesFile.write("\n")
variablesFile.write(" ],\n")
variablesFile.write(" \"class_labels\": [\"BinaryClassificationOutputName\"]\n")
variablesFile.write("}\n")
print(Fore.GREEN + 'Saved variables offsets (median) and scales (interquartile range, IQR) in ' + variablesFileName)
logString = '\nSaved variables offset (median) and scales (interquartile range, IQR) in ' + variablesFileName
return logString
### Building the (P)DNN
from keras.models import Model, Sequential
from keras.layers import Dense, Dropout, Input, BatchNormalization
from keras.callbacks import EarlyStopping
from keras.layers.core import Dense, Activation
from sklearn.metrics import log_loss
import tensorflow as tf
from keras.optimizers import SGD
def BuildNN(N_input, nodesNumber, layersNumber, dropout, studyLearningRate):
activationFunction = 'swish'
model = Sequential()
model.add(Dense(units = nodesNumber, input_dim = N_input, activation = activationFunction))
#model.add(Dense(units = 88, input_dim = N_input, activation = 'relu'))
#model.add(Activation('relu'))
if dropout > 0:
model.add(Dropout(dropout))
for i in range(0, layersNumber):
model.add(Dense(nodesNumber, activation = activationFunction)) ##swish
# model.add(Activation('relu'))
model.add(Dropout(dropout))
model.add(Dense(1, activation = 'sigmoid'))
#model.compile(loss = 'binary_crossentropy', optimizer = 'rmsprop', metrics = ['accuracy'])
Loss = 'binary_crossentropy'
Metrics = ['accuracy']
learningRate = 0.01#0.001#0.0003 #0.001
'''
if studyLearningRate:
Optimizer = SGD(lr = 0.1)
else:
#Optimizer = SGD(lr = 0.1)
#Optimizer = tf.keras.optimizers.Adam(learning_rate = learningRate) #Adam
'''
Optimizer = tf.keras.optimizers.Nadam(learning_rate = learningRate) #Adam
return model, Loss, Metrics, learningRate, Optimizer, activationFunction
def scheduler(epoch, lr):
if epoch <= 5:
return 0.003
elif epoch < 30:
return 0.001
else:
return 0.0001
def SaveArchAndWeights(model, outputDir):
arch = model.to_json()
outputArch = outputDir + '/architecture.json'
with open(outputArch, 'w') as arch_file:
arch_file.write(arch)
print(Fore.GREEN + 'Saved NN architecture in ' + outputArch)
outputWeights = outputDir + '/weights.h5'
model.save_weights(outputWeights)
print(Fore.GREEN + 'Saved NN weights in ' + outputWeights)
def SaveVariables(outputDir, X_input):
outputVar = outputDir + '/variables.json'
with open(outputVar, 'w') as var_file:
var_file.write("{\n")
var_file.write(" \"inputs\": [\n")
for col in X_input.columns:
offset = -1. * float(X_input.mean(axis = 0)[col])
scale = 1. / float(X_input.std(axis = 0)[col])
var_file.write(" {\n")
var_file.write(" \"name\": \"%s\",\n" % col)
var_file.write(" \"offset\": %lf,\n" % offset) # EJS 2021-05-27: I have compelling reasons to believe this should be -mu
var_file.write(" \"scale\": %lf\n" % scale) # EJS 2021-05-27: I have compelling reasons to believe this should be 1/sigma
var_file.write(" }")
'''
if (col < X_input.shape[1]-1):
var_file.write(",\n")
else:
var_file.write("\n")
'''
if col != X_input.columns[len(X_input.columns) - 1]:
var_file.write(",\n")
else:
var_file.write("\n")
var_file.write(" ],\n")
var_file.write(" \"class_labels\": [\"BinaryClassificationOutputName\"]\n")
var_file.write("}\n")
print(Fore.GREEN + 'Saved variables in ' + outputVar)
def SaveFeatureScaling(outputDir, X_input):
outputFeatureScaling = outputDir + '/FeatureScaling.dat'
with open(outputFeatureScaling, 'w') as scaling_file: # EJS 2021-05-27: check which file name is hardcoded in the CxAODReader
scaling_file.write("[")
scaling_file.write(', '.join(str(i) for i in X_input.columns))
scaling_file.write("]\n")
scaling_file.write("Mean\n")
scaling_file.write("[")
scaling_file.write(' '.join(str(float(i)) for i in X_input.mean(axis=0)))
scaling_file.write("]\n")
scaling_file.write("minusMean\n")
scaling_file.write("[")
scaling_file.write(' '.join(str(-float(i)) for i in X_input.mean(axis=0)))
scaling_file.write("]\n")
scaling_file.write("Var\n")
scaling_file.write("[")
scaling_file.write(' '.join(str(float(i)) for i in X_input.var(axis=0)))
scaling_file.write("]\n")
scaling_file.write("sqrtVar\n")
scaling_file.write("[")
scaling_file.write(' '.join(str(float(i)) for i in X_input.std(axis=0)))
scaling_file.write("]\n")
scaling_file.write("OneOverStd\n")
scaling_file.write("[")
scaling_file.write(' '.join(str(1./float(i)) for i in X_input.std(axis=0)))
scaling_file.write("]\n")
print(Fore.GREEN + 'Saved features scaling in ' + outputFeatureScaling)
def SaveModel(model, outputDir, NN):
SaveArchAndWeights(model, outputDir)
variablesFileName = '/variables.json'
#previousDir = outputDir.replace('loose' + NN, '') ###########aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
#previousDir = outputDir.replace(NN, '') ###########aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
variablesDir = outputDir.rsplit('/', 1)[0]
#variablesDir += variablesFileName
#print('AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA ' + variablesDir + variablesFileName)
#shutil.copyfile(variablesDir + variablesFileName, outputDir + variablesFileName)
def extractFeatures(dataFrame, inputFeatures):
X = dataFrame[inputFeatures]
y = dataFrame['isSignal']
w = dataFrame['train_weight']
return X, y, w
'''
import matplotlib
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7,7]
plt.rcParams.update({'font.size': 16})
'''
### Evaluating the (P)DNN performance
def EvaluatePerformance(model, X_test, y_test, w_test, batchSize):
perf = model.evaluate(X_test, y_test, sample_weight = w_test, batch_size = batchSize)
testLoss = perf[0]
testAccuracy = perf[1]
return testLoss, testAccuracy
### Prediction on train and test sample (for DNN)
def PredictionTrainTest(model, X_test, X_train, batchSize):
yhat_test = model.predict(X_test, batch_size = batchSize)
yhat_train = model.predict(X_train, batch_size = batchSize)
return yhat_test, yhat_train
### Prediction on signal and background separately (for PDNN)
def PredictionSigBkg(model, X_train_signal, X_train_bkg, X_test_signal, X_test_bkg, batchSize):
yhat_train_signal = model.predict(X_train_signal, batch_size = batchSize)
yhat_train_bkg = model.predict(X_train_bkg, batch_size = batchSize)
yhat_test_signal = model.predict(X_test_signal, batch_size = batchSize)
yhat_test_bkg = model.predict(X_test_bkg, batch_size = batchSize)
return yhat_train_signal, yhat_train_bkg, yhat_test_signal, yhat_test_bkg
### Drawing correlation matrix
def DrawCorrelationMatrix(dataFrame, InputFeatures, outputDir, outputFileCommonName, analysis, channel, signal, bkg):
fig, ax1 = plt.subplots(figsize = (10, 10))
plt.set_cmap('bwr')
im = ax1.matshow((dataFrame[InputFeatures].astype(float)).corr(), vmin = -1, vmax = 1)
plt.colorbar(im, ax = ax1)
plt.xticks(range(len(InputFeatures)), InputFeatures, rotation = 'vertical')
plt.yticks(range(len(InputFeatures)), InputFeatures)
'''
for feature1 in range(len(InputFeatures)): ### This is really slow, perform only if needed
for feature2 in range(len(InputFeatures)):
ax1.text(feature2, feature1, "%.2f" % (dataFrame[InputFeatures].astype(float)).corr().at[InputFeatures[feature2], InputFeatures[feature1]], ha = 'center', va = 'center', color = 'r', fontsize = 6)
'''
plt.title('Correlation matrix')# (' + analysis + ' ' + channel + ' ' + signal + ' ' + bkg + ')')
#legendText = 'jet collection: ' + jetCollection + '\nanalysis: ' + analysis + '\nchannel: ' + channel + '\nsignal: ' + signal + '\nbackground: ' + ', '.join(bkg)
legendText = '\nanalysis: ' + analysis + '\nchannel: ' + channel + '\nsignal: ' + signal + '\nbackground: ' + ', '.join(bkg)
#if (preselectionCuts != 'none'):
# legendText += '\npreselection cuts: ' + preselectionCuts
plt.figtext(0.77, 0.45, legendText, wrap = True, horizontalalignment = 'left')
plt.tight_layout()
plt.subplots_adjust(left = 0.1, right = 0.75)
CorrelationMatrixName = outputDir + '/CorrelationMatrix_' + outputFileCommonName + '.png'
plt.savefig(CorrelationMatrixName)
print(Fore.GREEN + 'Saved ' + CorrelationMatrixName)
plt.clf()
plt.close()
### Drawing Accuracy
#def DrawAccuracy(modelMetricsHistory, testAccuracy, patienceValue, outputDir, NN, jetCollection, analysis, channel, PreselectionCuts, signal, bkg, outputFileCommonName, mass = 0):
def DrawAccuracy(modelMetricsHistory, testAccuracy, patienceValue, outputDir, NN, analysis, channel, PreselectionCuts, signal, bkg, outputFileCommonName, mass = 0):
plt.plot(modelMetricsHistory.history['accuracy'], label = 'Training')
lines = plt.plot(modelMetricsHistory.history['val_accuracy'], label = 'Validation')
xvalues = lines[0].get_xdata()
if testAccuracy != None:
plt.scatter([xvalues[len(xvalues) - 1 - patienceValue]], [testAccuracy], label = 'Test', color = 'green')
emptyPlot, = plt.plot([0, 0], [1, 1], color = 'white')
titleAccuracy = NN + ' model accuracy'
if NN == 'DNN':
outputFileCommonName += '_' + str(int(mass))
if mass >= 1000:
titleAccuracy += ' (mass: ' + str(float(mass / 1000)) + ' TeV)'
else:
titleAccuracy += ' (mass: ' + str(int(mass)) + ' GeV)'
plt.title(titleAccuracy)
plt.ylabel('Accuracy')
plt.xlabel('Epoch')
#plt.legend()
#legend1 = plt.legend(['Training', 'Validation'], loc = 'lower right')
legend1 = plt.legend(loc = 'center right')
#legendText = 'jet collection: ' + jetCollection + '\nanalysis: ' + analysis + '\nchannel: ' + channel + '\nsignal: ' + signal + '\nbackground: ' + str(bkg)
legendText = 'analysis: ' + analysis + '\nchannel: ' + channel + '\nsignal: ' + signal + '\nbackground: ' + str(bkg)
if (PreselectionCuts != 'none'):
legendText += '\npreselection cuts: ' + PreselectionCuts
#legendText += '\nTest accuracy: ' + str(round(testAccuracy, 2))
#plt.figtext(0.5, 0.3, legendText, wrap = True, horizontalalignment = 'left')
#plt.legend(legendText)
legend2 = plt.legend([emptyPlot], [legendText], frameon = False)
plt.gca().add_artist(legend1)
#plt.figtext(0.69, 0.28, 'Test accuracy: ' + str(round(testAccuracy, 2)), wrap = True, horizontalalignment = 'left')#, fontsize = 10)
AccuracyPltName = outputDir + '/Accuracy_' + outputFileCommonName + '.png'
plt.tight_layout()
plt.savefig(AccuracyPltName)
print(Fore.GREEN + 'Saved ' + AccuracyPltName)
plt.clf()
plt.close()
### Drawing Loss
#def DrawLoss(modelMetricsHistory, testLoss, patienceValue, outputDir, NN, jetCollection, analysis, channel, PreselectionCuts, signal, bkg, outputFileCommonName, mass = 0):
def DrawLoss(modelMetricsHistory, testLoss, patienceValue, outputDir, NN, analysis, channel, PreselectionCuts, signal, bkg, outputFileCommonName, mass = 0):
plt.plot(modelMetricsHistory.history['loss'], label = 'Training')
lines = plt.plot(modelMetricsHistory.history['val_loss'], label = 'Validation')
xvalues = lines[0].get_xdata()
#print(yvalues[len(yvalues) - 1])
if testLoss != None:
plt.scatter([xvalues[len(xvalues) - 1 - patienceValue]], [testLoss], label = 'Test', color = 'green')
#emptyPlot, = plt.plot([0, 0], [1, 1], color = 'white')
titleLoss = NN + ' model loss'
if NN == 'DNN':
outputFileCommonName += '_' + str(int(mass))
if mass >= 1000:
titleLoss += ' (mass: ' + str(float(mass / 1000)) + ' TeV)'
else:
titleLoss += ' (mass: ' + str(int(mass)) + ' GeV)'
plt.title(titleLoss)
plt.ylabel('Loss')
plt.xlabel('Epoch')
#plt.legend(['Training', 'Validation'], loc = 'upper right')
legend1 = plt.legend(loc = 'upper center')
#legendText = 'jet collection: ' + jetCollection + '\nanalysis: ' + analysis + '\nchannel: ' + channel + '\npreselection cuts: ' + PreselectionCuts + '\nsignal: ' + signal + '\nbackground: ' + str(bkg)
legendText = 'analysis: ' + analysis + '\nchannel: ' + channel + '\npreselection cuts: ' + PreselectionCuts + '\nsignal: ' + signal + '\nbackground: ' + str(bkg)
if (PreselectionCuts != 'none'):
legendText += '\npreselection cuts: ' + PreselectionCuts
#legendText += '\nTest loss: ' + str(round(testLoss, 2))
plt.figtext(0.4, 0.4, legendText, wrap = True, horizontalalignment = 'left')
#plt.figtext(0.7, 0.7, 'Test loss: ' + str(round(testLoss, 2)), wrap = True, horizontalalignment = 'center')#, fontsize = 10)
#legend2 = plt.legend([emptyPlot], [legendText], frameon = False, loc = 'center right')
#plt.gca().add_artist(legend1)
LossPltName = outputDir + '/Loss_' + outputFileCommonName + '.png'
plt.tight_layout()
plt.savefig(LossPltName)
print(Fore.GREEN + 'Saved ' + LossPltName)
plt.clf()
plt.close()
from sklearn.metrics import roc_curve, auc, roc_auc_score, classification_report
'''
def DrawROC(fpr, tpr, AUC, outputDir, NN, unscaledMass, jetCollection, analysis, channel, preselectionCuts, signal, background):
plt.plot(fpr, tpr, color = 'darkorange', lw = 2)
plt.xlim([-0.05, 1.0])
plt.ylim([0.0, 1.05])
plt.ylabel('True Positive Rate')
plt.xlabel('False Positive Rate')
titleROC = 'ROC curves (mass: ' + str(int(unscaledMass)) + ' GeV)'
plt.title(titleROC)
plt.figtext(0.7, 0.25, 'AUC: ' + str(round(AUC, 2)), wrap = True, horizontalalignment = 'center')
ROCPltName = outputDir + '/oldROC.png'
plt.savefig(ROCPltName)
print('Saved ' + ROCPltName)
plt.clf()
'''
### Drawing ROC and background rejection vs efficiency
#def DrawROCbkgRejectionScores(fpr, tpr, AUC, outputDir, NN, unscaledMass, jetCollection, analysis, channel, preselectionCuts, signal, background, outputFileCommonName, yhat_train_signal, yhat_test_signal, yhat_train_bkg, yhat_test_bkg, wMC_train_signal_mass, wMC_test_signal_mass, wMC_train_bkg, wMC_test_bkg, drawPlots):
def DrawROCbkgRejectionScores(fpr, tpr, AUC, outputDir, NN, unscaledMass, analysis, channel, preselectionCuts, signal, background, outputFileCommonName, yhat_train_signal, yhat_test_signal, yhat_train_bkg, yhat_test_bkg, wMC_train_signal_mass, wMC_test_signal_mass, wMC_train_bkg, wMC_test_bkg, drawPlots):
### ROC
if drawPlots:
emptyPlot, = plt.plot(fpr[0], tpr[0], color = 'white')
plt.plot(fpr, tpr, color = 'darkorange', label = 'AUC: ' + str(round(AUC, 2)), lw = 2)
#plt.plot(fakeFPR, fakeTPR, color = 'blue', label = 'reweighted AUC: ' + str(round(fakeAUC, 2)), lw = 2)
legend1 = plt.legend(handlelength = 0, handletextpad = 0, loc = 'center right')
plt.xlim([-0.05, 1.0])
plt.ylim([0.0, 1.05])
plt.ylabel('True Positive Rate')
plt.xlabel('False Positive Rate')
if unscaledMass >= 1000:
titleScores = NN + ' scores (mass: ' + str(float(unscaledMass / 1000)) + ' TeV)'#, bkg: ' + background + ')'
titleROC = NN + ' ROC curve (mass: ' + str(float(unscaledMass / 1000)) + ' TeV)'#, bkg: ' + background + ')'
BkgRejTitle = NN + ' rejection curve (mass: ' + str(float(unscaledMass / 1000)) + ' TeV)'#, bkg: ' + background + ')'
else:
titleScores = NN + ' scores (mass: ' + str(int(unscaledMass)) + ' GeV)'#, bkg: ' + background + ')'
titleROC = NN + ' ROC curve (mass: ' + str(int(unscaledMass)) + ' GeV)'#, bkg: ' + background + ')'
BkgRejTitle = NN + ' rejection curve (mass: ' + str(int(unscaledMass)) + ' GeV)'#, bkg: ' + background + ')'
plt.title(titleROC)
#legendText = 'jet collection: ' + jetCollection + '\nanalysis: ' + analysis + '\nchannel: ' + channel + '\nsignal: ' + signal + '\nbackground: ' + str(background)
legendText = 'analysis: ' + analysis + '\nchannel: ' + channel + '\nsignal: ' + signal + '\nbackground: ' + str(background)
if (preselectionCuts != 'none'):
legendText += '\npreselection cuts: ' + preselectionCuts
legend2 = plt.legend([emptyPlot], [legendText], loc = 'lower right', handlelength = 0, handletextpad = 0)
for item in legend2.legendHandles:
item.set_visible(False)
plt.gca().add_artist(legend1)
ROCPltName = outputDir + '/ROC_' + outputFileCommonName + '_' + str(unscaledMass) + '.png'
plt.savefig(ROCPltName)#, bbox_inches = 'tight')
print(Fore.GREEN + 'Saved ' + ROCPltName)
plt.clf()
plt.close()
### Scores
Nbins = 1000
plt.hist(yhat_train_signal, weights = wMC_train_signal_mass, bins = Nbins, histtype = 'step', lw = 2, color = 'blue', label = [r'Signal train'], density = True)
y_signal, bins_1, _ = plt.hist(yhat_test_signal, weights = wMC_test_signal_mass, bins = Nbins, histtype = 'stepfilled', lw = 2, color = 'cyan', alpha = 0.5, label = [r'Signal test'], density = True)
plt.hist(yhat_train_bkg, weights = wMC_train_bkg, bins = Nbins, histtype = 'step', lw = 2, color = 'red', label = [r'Background train'], density = True)
y_bkg, bins_0, _ = plt.hist(yhat_test_bkg, weights = wMC_test_bkg, bins = Nbins, histtype = 'stepfilled', lw = 2, color = 'orange', alpha = 0.5, label = [r'Background test'], density = True)
plt.ylabel('Norm. entries')
plt.xlabel('Score')
plt.yscale('log')
plt.title(titleScores)
plt.legend(loc = 'upper center')
ScoresPltName = outputDir + '/Scores_' + outputFileCommonName + '_' + str(unscaledMass) + '.png'
plt.savefig(ScoresPltName)
print(Fore.GREEN + 'Saved ' + ScoresPltName)
plt.clf()
plt.close()
### Background rejection vs efficiency
tprCut = tpr[tpr > 0.85]
fprCut = fpr[tpr > 0.85]
fprCutInverse = 1 / fprCut
if drawPlots:
plt.plot(tprCut, fprCutInverse)
emptyPlot, = plt.plot(tprCut[0], fprCutInverse[0] + 30, color = 'white')
WP = [0.90, 0.94, 0.97, 0.99]
bkgRejections = np.array([])
#print(Fore.BLUE + 'Mass: ' + str(unscaledMass), ', background rejection at WP = 0.90: ' + str(bkgRej90))
for i in range(0, len(WP)):
bkgRejections = np.append(bkgRejections, np.interp(WP[i], tprCut, fprCutInverse))