-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathValidation.py
More file actions
1743 lines (1343 loc) · 96.6 KB
/
Validation.py
File metadata and controls
1743 lines (1343 loc) · 96.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
from DataLoader import DataLoader
from Correlation import Correlation as cor
import gc
import json
import logging
import numpy as np
logging.getLogger('matplotlib').setLevel(logging.ERROR)
import warnings
warnings.filterwarnings('ignore', r'invalid value encountered in true_divide')
# Little incantation to display trying to X display
import matplotlib as mpl
mpl.use('Agg')
import matplotlib.pyplot as plt
import matplotlib.lines as ml
import matplotlib.cm as CM
import seaborn as sns
import pickle
import mplhep as hep
plt.style.use([hep.style.ROOT,hep.style.CMS]) # For now ROOT defaults to CMS
plt.style.use({'legend.frameon':False,'legend.fontsize':16,'legend.edgecolor':'black'})
from sklearn.metrics import roc_curve, auc, precision_recall_curve, average_precision_score, roc_auc_score
from sklearn.model_selection import KFold
import tracemalloc
import datetime
import math
#plt.rcParams['png.fonttype'] = 42
def timeStamp():
return datetime.datetime.now().strftime("%Y/%m/%d %H:%M:%S")
class Validation:
def __init__(self, model, config, loader, valLoader, evalLoader, testLoader, result_log=None, do_LRP = False, kfold=False):
self.model = model
self.config = config
self.result_log = result_log
self.metric = {}
self.doLog = False
self.loader = loader
self.valLoader = valLoader
self.evalLoader = evalLoader
self.testLoader = testLoader
self.kfold = kfold
self.sample = {"RPV" : 100, "SYY" : 101, "SHH" : 102}
self.do_LRP = do_LRP
def __del__(self):
del self.model
del self.config
del self.result_log
del self.metric
def samplesLoaded(self, trainList, xvalList):
trainListClean = []
for train in trainList:
trainListClean.append(train.replace("*","").replace("-",""))
for xval in xvalList:
xvalClean = xval.replace("*","").replace("-","")
if xvalClean in trainListClean:
return True
return False
def getAUC(self, fpr, tpr):
try:
return auc(fpr, tpr)
except:
print("Roc curve didn't work?????")
print(fpr)
print(tpr)
return -1
def getOutput(self, model, data, Sig, Bkg):
return model.predict(data), model.predict(Sig), model.predict(Bkg)
def getResults(self, output, output_sg, output_bg, outputNum=0, columnNum=0, sum=True):
if sum:
return output[outputNum][:,columnNum].ravel(), output_sg[outputNum][:,columnNum].ravel(), output_bg[outputNum][:,columnNum].ravel()
#return output[outputNum][:,columnNum].ravel() + output[outputNum][:,columnNum+1].ravel() + output[outputNum][:,columnNum+2].ravel(), output_sg[outputNum][:,columnNum].ravel() + output_sg[outputNum][:,columnNum+1].ravel() + output_sg[outputNum][:,columnNum+2].ravel(), output_bg[outputNum][:,columnNum].ravel() + output_bg[outputNum][:,columnNum+1].ravel() + output_bg[outputNum][:,columnNum+2].ravel()
else:
return output[outputNum][:,columnNum].ravel(), output_sg[outputNum][:,columnNum].ravel(), output_bg[outputNum][:,columnNum].ravel()
# Plot a set of 1D hists together, where the hists, colors, labels, weights
# are provided as a list argument.
def plotDisc(self, hists, colors, labels, weights, name, xlab, ylab, bins=100, arange=(0,1), doLog=False):
# Plot predicted mass
fig, ax = plt.subplots(figsize=(12, 12))
hep.cms.label(llabel="Simulation", data=False, paper=False, year="Run 2", ax=ax)
ax.set_ylabel(xlab); ax.set_xlabel(ylab)
for i in range(0, len(hists)):
try:
mean = round(np.average(hists[i], weights=weights[i]), 2)
plt.hist(hists[i], bins=bins, range=arange, color="xkcd:"+colors[i], alpha=0.9, histtype='step', lw=2, label=labels[i]+" mean="+str(mean), density=True, log=doLog, weights=weights[i])
except Exception as e:
print("\nplotDisc: Could not plot %s hist for figure %s ::"%(labels[i],name), e, "\n")
continue
ax.legend(loc=1, frameon=False)
fig.savefig(self.config["outputDir"]+"/%s.png"%(name), dpi=fig.dpi)
with open(self.config["outputDir"]+"/%s.pkl"%(name), 'wb') as f:
pickle.dump(fig, f)
plt.close(fig)
# Member function to plot the discriminant variable while making a selection on another discriminant
# The result for signal and background are shown together
def plotDiscWithCut(self, c, b1, b2, bw, s1, s2, sw, tag1, tag2, mass, Njets=-1, bins=100, arange=(0,1)):
maskBGT = np.ma.masked_where(b2>c, b2).mask
maskSGT = np.ma.masked_where(s2>c, s2).mask
bnew = b1[maskBGT]; snew = s1[maskSGT]
bwnew = bw[maskBGT]; swnew = sw[maskSGT]
bw2new = np.square(bwnew); sw2new = np.square(swnew)
bwnewBinned, binEdges = np.histogram(bnew, bins=bins, range=arange, weights=bwnew)
swnewBinned, binEdges = np.histogram(snew, bins=bins, range=arange, weights=swnew)
bw2newBinned, binEdges = np.histogram(bnew, bins=bins, range=arange, weights=bw2new)
sw2newBinned, binEdges = np.histogram(snew, bins=bins, range=arange, weights=sw2new)
if len(bw2newBinned) == 0: bw2newBinned = np.zeros(bins)
if len(bwnewBinned) == 0: bwnewBinned = np.zeros(bins)
if len(sw2newBinned) == 0: sw2newBinned = np.zeros(bins)
if len(swnewBinned) == 0: swnewBinned = np.zeros(bins)
if not np.any(bw2newBinned): bw2newBinned += 10e-2
if not np.any(bwnewBinned): bwnewBinned += 10e-2
if not np.any(sw2newBinned): sw2newBinned += 10e-2
if not np.any(swnewBinned): swnewBinned += 10e-2
fig = plt.figure(figsize=(12,12))
ax = hep.histplot(h=bwnewBinned, bins=binEdges, w2=bw2newBinned, density=True, histtype="step", label="Background", alpha=0.9, lw=2)
ax = hep.histplot(h=swnewBinned, bins=binEdges, w2=sw2newBinned, density=True, histtype="step", label="Signal (mass = %s GeV)"%(mass), alpha=0.9, lw=2, ax=ax)
hep.cms.label(llabel="Simulation", data=False, paper=False, year="Run 2", ax=ax)
ax.set_ylabel('A.U.'); ax.set_xlabel('Disc. %s'%(tag1))
plt.text(0.05, 0.85, r"$\bf{Disc. %s}$ > %.3f"%(tag2,c), transform=ax.transAxes, fontfamily='sans-serif', fontsize=16, bbox=dict(facecolor='white', alpha=1.0))
# Stupid nonsense to remove duplicate entries in legend
handles, labels = ax.get_legend_handles_labels()
ax.legend(handles[-2:], labels[-2:], loc=2, frameon=False)
if Njets == -1:
fig.savefig(self.config["outputDir"]+"/Disc%s_BvsS_m%s.png"%(tag1,mass))
with open(self.config["outputDir"]+"/Disc%s_BvsS_m%s.pkl"%(tag1,mass), 'wb') as f:
pickle.dump(fig, f)
else:
fig.savefig(self.config["outputDir"]+"/Disc%s_BvsS_m%s_Njets%d.png"%(tag1,mass,Njets))
with open(self.config["outputDir"]+"/Disc%s_BvsS_m%s_Njets%d.pkl"%(tag1,mass,Njets), 'wb') as f:
pickle.dump(fig, f)
plt.close(fig)
# Member function to plot the discriminant variable while making a selection on another discriminant
# Compare the discriminant shape on either "side" of the selection on the other disc.
def plotDiscWithCutCompare(self, c, d1, d2, dw, tag1, tag2, tag3, mass = "", Njets=-1, bins=100, arange=(0,1)):
maskGT = np.ma.masked_where(d2>c, d2).mask; maskLT = ~maskGT
dgt = d1[maskGT]; dlt = d1[maskLT]
dwgt = dw[maskGT]; dwlt = dw[maskLT]
dw2gt = np.square(dwgt); dw2lt = np.square(dwlt)
dwgtBinned, binEdges = np.histogram(dgt, bins=bins, range=arange, weights=dwgt)
dw2gtBinned, binEdges = np.histogram(dgt, bins=bins, range=arange, weights=dw2gt)
dwltBinned, binEdges = np.histogram(dlt, bins=bins, range=arange, weights=dwlt)
dw2ltBinned, binEdges = np.histogram(dlt, bins=bins, range=arange, weights=dw2lt)
if len(dw2gtBinned) == 0: dw2gtBinned = np.zeros(bins)
if len(dwgtBinned) == 0: dwgtBinned = np.zeros(bins)
if len(dw2ltBinned) == 0: dw2ltBinned = np.zeros(bins)
if len(dwltBinned) == 0: dwltBinned = np.zeros(bins)
if not np.any(dw2gtBinned): dw2gtBinned += 10e-2
if not np.any(dwgtBinned): dwgtBinned += 10e-2
if not np.any(dw2ltBinned): dw2ltBinned += 10e-2
if not np.any(dwltBinned): dwltBinned += 10e-2
fig = plt.figure(figsize=(12,12))
ax = hep.histplot(h=dwgtBinned, bins=binEdges, w2=dw2gtBinned, density=True, histtype="step", label="Disc. %s > %.2f"%(tag2,c), alpha=0.9, lw=2)
ax = hep.histplot(h=dwltBinned, bins=binEdges, w2=dw2ltBinned, density=True, histtype="step", label="Disc. %s < %.2f"%(tag2,c), alpha=0.9, lw=2, ax=ax)
hep.cms.label(llabel="Simulation", data=False, paper=False, year="Run 2", ax=ax)
ax.set_ylabel('A.U.'); ax.set_xlabel('Disc. %s'%(tag1))
# Stupid nonsense to remove duplicate entries in legend
handles, labels = ax.get_legend_handles_labels()
ax.legend(handles[-2:], labels[-2:], loc=2, frameon=False)
if Njets == -1:
fig.savefig(self.config["outputDir"]+"/%s%s_Disc%s_Compare_Shapes.png"%(tag3, mass, tag1))
with open(self.config["outputDir"]+"/%s%s_Disc%s_Compare_Shapes.pkl"%(tag3, mass, tag1), 'wb') as f:
pickle.dump(fig, f)
else:
fig.savefig(self.config["outputDir"]+"/%s%s_Njets%d_Disc%s_Compare_Shapes.png"%(tag3, mass, Njets, tag1))
with open(self.config["outputDir"]+"/%s%s_Njets%d_Disc%s_Compare_Shapes.pkl"%(tag3, mass, Njets, tag1), 'wb') as f:
pickle.dump(fig, f)
plt.close(fig)
# Plot loss of training vs test
def plotAccVsEpoch(self, h1, h2, title, name):
lambda_names = {'disc': 'disc_lambda', 'disco': 'bkg_disco_lambda', 'closure': 'abcd_close_lambda', 'mass_reg': 'mass_reg_lambda'}
fig = plt.figure(figsize=(12,12))
if not title.split(" ")[0]:
#fig.axes[0].ticklabel_format(useOffset=False)
plt.ticklabel_format(useOffset=False)
hep.cms.label(llabel="Simulation", data=False, paper=False, year="Run 2")
plt.plot(self.result_log.history[h1])
plt.plot(self.result_log.history[h2])
if title.split(" ")[0] == "mass_reg":
plt.yscale("log")
#plt.title(title, pad=45.0)
plt.ylabel(title)
plt.xlabel('Epoch')
plt.legend(['train', 'test'], loc='best')
fig.savefig(self.config["outputDir"]+"/%s.pdf"%(name), dpi=fig.dpi)
with open(self.config["outputDir"]+"/%s.pkl"%(name), 'wb') as f:
pickle.dump(fig, f)
plt.close(fig)
def plotAccVsEpochAll(self, h, n, val, title, name):
fig = plt.figure(figsize=(12,12))
hep.cms.label(llabel="Simulation", data=False, paper=False, year="Run 2")
#plt.title(title, pad=45.0)
plt.ylabel('training loss')
plt.xlabel('epoch')
l = []
for H in h:
plt.plot(self.result_log.history["%s%s_loss"%(val,H)])
l.append(n[h.index(H)])
plt.yscale("log")
plt.legend(l, loc='best')
fig.savefig(self.config["outputDir"]+"/%s.pdf"%(name), dpi=fig.dpi)
with open(self.config["outputDir"]+"/%s.pkl"%(name), 'wb') as f:
pickle.dump(fig, f)
plt.close(fig)
def plotDiscPerNjet(self, tag, samples, sigMask, nBins=100):
for sample in samples:
trainSample = samples[sample][0]
y_train_Sp = samples[sample][1]
weights = samples[sample][2]
bins = np.linspace(0, 1, nBins)
fig, ax = plt.subplots(figsize=(12, 12))
hep.cms.label(llabel="Simulation", data=False, paper=False, year="Run 2")
ax.set_ylabel('Norm Events')
ax.set_xlabel('Discriminator')
for key in sorted(trainSample.keys()):
if key.find("mask_nJet") != -1:
mask = True
if sample == "Sig": mask = sigMask
yt = y_train_Sp[trainSample[key]&mask]
wt = weights[trainSample[key]&mask]
if yt.size != 0 and wt.size != 0:
plt.hist(yt, bins, alpha=0.9, histtype='step', lw=2, label=sample+" Train "+key, density=True, log=self.doLog, weights=wt)
plt.legend(loc='best')
fig.savefig(self.config["outputDir"]+"/nJet_"+sample+tag+".png", dpi=fig.dpi)
with open(self.config["outputDir"]+"/nJet_"+sample+tag+".pkl", 'wb') as f:
pickle.dump(fig, f)
plt.close(fig)
def plotROC(self, dataMaskEval=None, dataMaskVal=None, tag="", y_eval=None, y_val=None, evalData=None, valData=None, xEval=None, xVal=None, yEval=None, yVal=None, evalLab=None, valLab=None, doMass=False, minMass=300, maxMass=1400, y_val_err=None):
extra = None
if "disc1" in tag or "Disc1" in tag: extra = "disc1"
else: extra = "disc2"
if extra not in self.config: self.config[extra] = {"eval_auc" : {}, "val_auc" : {}}
fig = plt.figure(figsize=(12,12))
hep.cms.label(llabel="Simulation", data=False, paper=False, year="Run 2")
plt.plot([0, 1], [0, 1], 'k--')
plt.xlabel('False positive rate')
plt.ylabel('True positive rate')
plt.title('', pad=45.0)
if y_eval is None:
plt.plot(xVal, yVal, color='xkcd:red', linestyle=":", label='Val (area = {:.3f})'.format(valLab))
plt.plot(xEval, yEval, color='xkcd:red', label='Train (area = {:.3f})'.format(evalLab))
self.config[extra]["eval_auc"]["total"] = evalLab
self.config[extra]["val_auc"]["total"] = valLab
# Adding a kfold cross-validation to add error bars to roc plots
# if you want to run this, use --kfold when training
elif self.kfold and doMass:
i_mass = [m for m in range(minMass, maxMass, 200)]
kf = KFold(n_splits=8, shuffle=True)
for mass in i_mass:
#try:
massMask = evalData["mass"] == float(mass)
massMask |= evalData["mass"] == float(173.0)
labels = evalData["label"][dataMaskEval&massMask]
weights = evalData["weight"][dataMaskEval&massMask]
y = y_eval[dataMaskEval&massMask]
if len(y)==0:
continue
res = []
val_res = []
auc_list = []
val_auc_list = []
first = None
for i, (train_idx, test_idx) in enumerate(kf.split(labels)):
res.append(roc_curve(labels[train_idx], y[train_idx], sample_weight=weights[train_idx]))
auc_list.append(roc_auc_score(labels[train_idx], y[train_idx]))
val_res.append(roc_curve(labels[test_idx], y[test_idx], sample_weight=weights[test_idx]))
val_auc_list.append(roc_auc_score(labels[test_idx], y[test_idx]))
if first is None:
first = res[0][0]
fpr_eval = first #np.mean([res[i][0] for i in range(len(res))], axis=0)
tpr_eval = np.mean([np.interp(first, res[i][0], res[i][1]) for i in range(len(res))], axis=0)
auc_eval = np.mean(auc_list)
fpr_val = first #np.mean([val_res[i][0] for i in range(len(val_res))], axis=0)
tpr_val = np.mean([np.interp(first, val_res[i][0], val_res[i][1]) for i in range(len(val_res))], axis=0)
auc_val = np.mean(val_auc_list)
tpr_val_std = np.std([np.interp(first, val_res[i][0], val_res[i][1]) for i in range(len(val_res))], axis=0)
color = next(plt.gca()._get_lines.prop_cycler)['color']
plt.plot(fpr_eval, tpr_eval, label="$M_{\mathregular{\\tilde{t}}}$ = %d (Train)"%(int(mass)) + " (area = {:.3f})".format(auc_eval), color=color)
plt.plot(fpr_val, tpr_val, linestyle=":", label="$M_{\mathregular{\\tilde{t}}}$ = %d (Val)"%(int(mass)) + " (area = {:.3f})".format(auc_val), color=color)
plt.fill_between(fpr_val, tpr_val-tpr_val_std, tpr_val+tpr_val_std, alpha=0.3, color=color)
self.config[extra]["eval_auc"]["Mass%d"%(int(mass))] = auc_eval
#except Exception as e:
# print("\nplotROC: Could not plot ROC for Mass = %d ::"%(int(mass)), e, "\n")
# continue
elif doMass:
i_mass = [m for m in range(minMass, maxMass, 200)]
for mass in i_mass:
try:
massMask = evalData["mass"] == float(mass)
massMask |= evalData["mass"] == float(173.0)
labels = evalData["label"][dataMaskEval&massMask]
weights = evalData["weight"][dataMaskEval&massMask]
y = y_eval[dataMaskEval&massMask]
if len(y)==0:
continue
fpr_eval, tpr_eval, thresholds_eval = roc_curve(labels, y, sample_weight=weights)
auc_eval = roc_auc_score(labels, y)
plt.plot(fpr_eval, tpr_eval, label="$M_{\mathregular{\\tilde{t}}}$ = %d (Train)"%(int(mass)) + " (area = {:.3f})".format(auc_eval))
self.config[extra]["eval_auc"]["Mass%d"%(int(mass))] = auc_eval
except Exception as e:
print("\nplotROC: Could not plot ROC for Mass = %d ::"%(int(mass)), e, "\n")
continue
plt.gca().set_prop_cycle(None)
for mass in i_mass:
try:
massMask = valData["mass"] == float(mass)
massMask |= valData["mass"] == float(173.0)
labels = valData["label"][dataMaskVal&massMask]
weights = valData["weight"][dataMaskVal&massMask]
y = y_val[dataMaskVal&massMask]
if len(y)==0:
continue
fpr_val, tpr_val, thresholds_val = roc_curve(labels, y, sample_weight=weights)
auc_val = roc_auc_score(labels, y)
plt.plot(fpr_val, tpr_val, linestyle=":", label="$M_{\mathregular{\\tilde{t}}}$ = %d (Val)"%(int(mass)) + " (area = {:.3f})".format(auc_val))
self.config[extra]["val_auc"]["Mass%d"%(int(mass))] = auc_val
except Exception as e:
print("\nplotROC: Could not plot ROC for Mass = %d ::"%(int(mass)), e, "\n")
continue
else:
NJetsRange = range(self.config["minNJetBin"], self.config["maxNJetBin"]+1)
for NJets in NJetsRange:
try:
njets = float(NJets)
if self.config["Mask"] and (int(NJets) in self.config["Mask_nJet"]): continue
dataNjetsMaskEval = evalData["njets"]==njets
labels = evalData["label"][dataMaskEval&dataNjetsMaskEval]
weights = evalData["weight"][dataMaskEval&dataNjetsMaskEval]
y = y_eval[dataMaskEval&dataNjetsMaskEval]
if len(y)==0:
continue
fpr_eval, tpr_eval, thresholds_eval = roc_curve(labels, y, sample_weight=weights)
auc_eval = roc_auc_score(labels, y)
plt.plot(fpr_eval, tpr_eval, label="$N_{\mathregular{jets}}$ = %d (Train)"%(int(NJets)) + " (area = {:.3f})".format(auc_eval))
self.config[extra]["eval_auc"]["Njets%d"%(int(NJets))] = auc_eval
except Exception as e:
print("\nplotROC: Could not plot ROC for Njets = %d ::"%(int(NJets)), e, "\n")
continue
plt.gca().set_prop_cycle(None)
for NJets in NJetsRange:
try:
njets = float(NJets)
if self.config["Mask"] and (int(NJets) in self.config["Mask_nJet"]): continue
dataNjetsMaskVal = valData["njets"] == njets
valLabels = valData["label"][dataMaskVal&dataNjetsMaskVal]
valWeights = valData["weight"][dataMaskVal&dataNjetsMaskVal]
yVal = y_val[dataMaskVal&dataNjetsMaskVal]
if len(yVal)==0:
continue
fpr_val, tpr_val, thresholds_val = roc_curve(valLabels, yVal, sample_weight=valWeights)
auc_val = roc_auc_score(valLabels, yVal)
plt.plot(fpr_val, tpr_val, linestyle=":", label="$N_{\mathregular{jets}}$ = %d (Val)"%(int(NJets)) + " (area = {:.3f})".format(auc_val))
self.config[extra]["val_auc"]["Njets%d"%(int(NJets))] = auc_val
except Exception as e:
print("\nplotROC: Could not plot ROC for Njets = %d ::"%(int(NJets)), e, "\n")
continue
newtag = tag.replace(" ", "_")
plt.grid()
plt.legend(loc='best')
fig.savefig(self.config["outputDir"]+"/roc_plot"+newtag+".png", dpi=fig.dpi)
with open(self.config["outputDir"]+"/roc_plot"+newtag+".pkl", 'wb') as f:
pickle.dump(fig, f)
plt.close(fig)
# Plot disc1 vs disc2 for both background and signal
def plotD1VsD2SigVsBkgd(self, b1, b2, s1, s2, mass, Njets=-1):
fig = plt.figure(figsize=(12,12))
ax1 = fig.add_subplot(111)
hep.cms.label(llabel="Simulation", data=False, paper=False, year="Run 2", ax=ax1)
ax1.scatter(b1, b2, s=10, c='b', marker="s", label='background')
ax1.scatter(s1, s2, s=10, c='r', marker="o", label='signal (mass = %s GeV)'%(mass))
ax1.set_xlim([0, 1])
ax1.set_ylim([0, 1])
ax1.set_xlabel("Disc. 1")
ax1.set_ylabel("Disc. 2")
plt.legend(loc='best');
if Njets == -1:
fig.savefig(self.config["outputDir"]+"/2D_SigVsBkgd_Disc1VsDisc2_m%s.png"%(mass), dpi=fig.dpi)
with open(self.config["outputDir"]+"/2D_SigVsBkgd_Disc1VsDisc2_m%s.pkl"%(mass), 'wb') as f:
pickle.dump(fig, f)
else:
fig.savefig(self.config["outputDir"]+"/2D_SigVsBkgd_Disc1VsDisc2_m%s_Njets%d.png"%(mass,Njets), dpi=fig.dpi)
with open(self.config["outputDir"]+"/2D_SigVsBkgd_Disc1VsDisc2_m%s_Njets%d.pkl"%(mass,Njets), 'wb') as f:
pickle.dump(fig, f)
plt.close(fig)
def plotPandR(self, pval, rval, ptrain, rtrain, valLab, trainLab, name):
fig = plt.figure(figsize=(12,12))
hep.cms.label(llabel="Simulation", data=False, paper=False, year="Run 2")
plt.ylim(0,1)
plt.xlim(0,1)
plt.plot(pval, rval, color='xkcd:black', label='Val (AP = {:.3f})'.format(valLab))
plt.plot(ptrain, rtrain, color='xkcd:red', label='Train (AP = {:.3f})'.format(trainLab))
plt.xlabel('Recall')
plt.ylabel('Precision')
plt.title('Precision and Recall curve', pad=45.0)
plt.legend(loc='best')
fig.savefig(self.config["outputDir"]+"/PandR_plot_{}.png".format(name), dpi=fig.dpi)
with open(self.config["outputDir"]+"/PandR_plot_{}.pkl".format(name), 'wb') as f:
pickle.dump(fig, f)
plt.close(fig)
def plotPandR2D(self, labels, d1_val, d2_val, sample_weight=None, name=None):
bins = []
ncuts = 5
cut = 1./float(ncuts)
for i in range(0,ncuts):
cond = d1_val > cut * i
cond &= d2_val > cut * i
try:
precision_val, recall_val, thresholds = precision_recall_curve(labels[cond], d2_val[cond], sample_weight=sample_weight[cond])
ap_val = average_precision_score(labels[cond], d2_val[cond], sample_weight=sample_weight[cond])
except Exception as e:
print(e)
print("Probably not enough events in the last bin, possibly try rebinning for P and R 2D plot")
continue
bins.append({})
bins[i]["cut"] = cut * i
bins[i]["pval"] = precision_val
bins[i]["rval"] = recall_val
bins[i]["apVal"] = ap_val
fig = plt.figure(figsize=(12,12))
hep.cms.label(llabel="Simulation", data=False, paper=False, year="Run 2")
plt.ylim(0,1)
plt.xlim(0,1)
for x in bins:
plt.plot(x["pval"], x["rval"], label='Val d1,d2 > {:.2f} (AP = {:.3f})'.format(x["cut"], x["apVal"]))
#plt.plot(ptrain, rtrain, color='xkcd:red', label='Train (AP = {:.3f})'.format(trainLab))
plt.xlabel('Recall')
plt.ylabel('Precision')
plt.title('Precision and Recall curve', pad=45.0)
plt.legend(loc='best')
fig.savefig(self.config["outputDir"]+"/PandR2D_plot_{}.png".format(name), dpi=fig.dpi)
with open(self.config["outputDir"]+"/PandR2D_plot_{}.pkl".format(name), 'wb') as f:
pickle.dump(fig, f)
plt.close(fig)
def cutAndCount(self, c1s, c2s, b1, b2, bw, s1, s2, sw):
# First get the total counts in region "D" for all possible c1, c2
bcounts = {"a" : {}, "b" : {}, "c" : {}, "d" : {}, "A" : {}, "B" : {}, "C" : {}, "D" : {}, "A2" : {}, "B2" : {}, "C2" : {}, "D2" : {}}
scounts = {"a" : {}, "b" : {}, "c" : {}, "d" : {}, "A" : {}, "B" : {}, "C" : {}, "D" : {}, "A2" : {}, "B2" : {}, "C2" : {}, "D2" : {}}
for c1 in c1s:
c1k = "%.2f"%c1
if c1k not in bcounts["A"]:
bcounts["A"][c1k] = {}; bcounts["A2"][c1k] = {}; bcounts["a"][c1k] = {};
bcounts["B"][c1k] = {}; bcounts["B2"][c1k] = {}; bcounts["b"][c1k] = {};
bcounts["C"][c1k] = {}; bcounts["C2"][c1k] = {}; bcounts["c"][c1k] = {};
bcounts["D"][c1k] = {}; bcounts["D2"][c1k] = {}; bcounts["d"][c1k] = {};
if c1k not in scounts["A"]:
scounts["A"][c1k] = {}; scounts["A2"][c1k] = {}; scounts["a"][c1k] = {};
scounts["B"][c1k] = {}; scounts["B2"][c1k] = {}; scounts["b"][c1k] = {};
scounts["C"][c1k] = {}; scounts["C2"][c1k] = {}; scounts["c"][c1k] = {};
scounts["D"][c1k] = {}; scounts["D2"][c1k] = {}; scounts["d"][c1k] = {};
for c2 in c2s:
c2k = "%.2f"%c2
if c2k not in bcounts["A"][c1k]:
bcounts["A"][c1k][c2k] = 0.0; bcounts["A2"][c1k][c2k] = 0.0; bcounts["a"][c1k][c2k] = 0.0
bcounts["B"][c1k][c2k] = 0.0; bcounts["B2"][c1k][c2k] = 0.0; bcounts["b"][c1k][c2k] = 0.0
bcounts["C"][c1k][c2k] = 0.0; bcounts["C2"][c1k][c2k] = 0.0; bcounts["c"][c1k][c2k] = 0.0
bcounts["D"][c1k][c2k] = 0.0; bcounts["D2"][c1k][c2k] = 0.0; bcounts["d"][c1k][c2k] = 0.0
if c2k not in scounts["A"][c1k]:
scounts["A"][c1k][c2k] = 0.0; scounts["A2"][c1k][c2k] = 0.0; scounts["a"][c1k][c2k] = 0.0
scounts["B"][c1k][c2k] = 0.0; scounts["B2"][c1k][c2k] = 0.0; scounts["b"][c1k][c2k] = 0.0
scounts["C"][c1k][c2k] = 0.0; scounts["C2"][c1k][c2k] = 0.0; scounts["c"][c1k][c2k] = 0.0
scounts["D"][c1k][c2k] = 0.0; scounts["D2"][c1k][c2k] = 0.0; scounts["d"][c1k][c2k] = 0.0
mask1BGT = np.ma.masked_where(b1>c1, b1).mask; mask1BLT = ~mask1BGT
mask1SGT = np.ma.masked_where(s1>c1, s1).mask; mask1SLT = ~mask1SGT
mask2BGT = np.ma.masked_where(b2>c2, b2).mask; mask2BLT = ~mask2BGT
mask2SGT = np.ma.masked_where(s2>c2, s2).mask; mask2SLT = ~mask2SGT
maskBA = mask1BGT&mask2BGT; maskSA = mask1SGT&mask2SGT
maskBB = mask1BLT&mask2BGT; maskSB = mask1SLT&mask2SGT
maskBC = mask1BGT&mask2BLT; maskSC = mask1SGT&mask2SLT
maskBD = mask1BLT&mask2BLT; maskSD = mask1SLT&mask2SLT
bA = bw[maskBA]
bcounts["A"][c1k][c2k] = np.sum(bA)
bcounts["a"][c1k][c2k] = np.count_nonzero(bA)
bcounts["A2"][c1k][c2k] = np.sum(np.square(bA))
bB = bw[maskBB]
bcounts["B"][c1k][c2k] = np.sum(bB)
bcounts["b"][c1k][c2k] = np.count_nonzero(bB)
bcounts["B2"][c1k][c2k] = np.sum(np.square(bB))
bC = bw[maskBC]
bcounts["C"][c1k][c2k] = np.sum(bC)
bcounts["c"][c1k][c2k] = np.count_nonzero(bC)
bcounts["C2"][c1k][c2k] = np.sum(np.square(bC))
bD = bw[maskBD]
bcounts["D"][c1k][c2k] = np.sum(bD)
bcounts["d"][c1k][c2k] = np.count_nonzero(bD)
bcounts["D2"][c1k][c2k] = np.sum(np.square(bD))
sA = sw[maskSA]
scounts["A"][c1k][c2k] = np.sum(sA)
scounts["a"][c1k][c2k] = np.count_nonzero(sA)
scounts["A2"][c1k][c2k] = np.sum(np.square(sA))
sB = sw[maskSB]
scounts["B"][c1k][c2k] = np.sum(sB)
scounts["b"][c1k][c2k] = np.count_nonzero(sB)
scounts["B2"][c1k][c2k] = np.sum(np.square(sB))
sC = sw[maskSC]
scounts["C"][c1k][c2k] = np.sum(sC)
scounts["c"][c1k][c2k] = np.count_nonzero(sC)
scounts["C2"][c1k][c2k] = np.sum(np.square(sC))
sD = sw[maskSD]
scounts["D"][c1k][c2k] = np.sum(sD)
scounts["d"][c1k][c2k] = np.count_nonzero(sD)
scounts["D2"][c1k][c2k] = np.sum(np.square(sD))
return bcounts, scounts
def findABCDedges(self, bcts, scts, bkgNormUnc = 0.3, minBkgEvts = 5):
# Now calculate signal fraction and significance
# Pick c1 and c2 that give 30% sig fraction and maximizes significance
significance = 0.0; finalc1 = -1.0; finalc2 = -1.0;
closureErr = 0.0; metric = 999.0
signs = []
signsWNC = []
predsigns = []
closeErrs = []
edges = []
wBkgA = []; uwBkgA = []; wSigA = []; uwSigA = []
wBkgB = []; uwBkgB = []; wSigB = []; uwSigB = []
wBkgC = []; uwBkgC = []; wSigC = []; uwSigC = []
wBkgD = []; uwBkgD = []; wSigD = []; uwSigD = []
sFracsA = []; sFracsB = []; sFracsC = []; sFracsD = []
normSigFracs = []
for c1k, c2s in bcts["A"].items():
for c2k, temp in c2s.items():
bA = bcts["A"][c1k][c2k]; bB = bcts["B"][c1k][c2k]; bC = bcts["C"][c1k][c2k]; bD = bcts["D"][c1k][c2k]
ba = bcts["a"][c1k][c2k]; bb = bcts["b"][c1k][c2k]; bc = bcts["c"][c1k][c2k]; bd = bcts["d"][c1k][c2k]
sA = scts["A"][c1k][c2k]; sB = scts["B"][c1k][c2k]; sC = scts["C"][c1k][c2k]; sD = scts["D"][c1k][c2k]
sa = scts["a"][c1k][c2k]; sb = scts["b"][c1k][c2k]; sc = scts["c"][c1k][c2k]; sd = scts["d"][c1k][c2k]
bA2 = bcts["A2"][c1k][c2k]; bB2 = bcts["B2"][c1k][c2k]; bC2 = bcts["C2"][c1k][c2k]; bD2 = bcts["D2"][c1k][c2k]
sA2 = scts["A2"][c1k][c2k]; sB2 = scts["B2"][c1k][c2k]; sC2 = scts["C2"][c1k][c2k]; sD2 = scts["D2"][c1k][c2k]
bTotal = bA + bB + bC + bD
sTotal = sA + sB + sC + sD
tempsbfracA = -1.0; tempsbfracAunc = -1.0; tempsTotfracA = -1.0; tempbTotfracA = -1.0
tempsbfracB = -1.0; tempsbfracBunc = -1.0; tempsTotfracB = -1.0; tempbTotfracB = -1.0
tempsbfracC = -1.0; tempsbfracCunc = -1.0; tempsTotfracC = -1.0; tempbTotfracC = -1.0
tempsbfracD = -1.0; tempsbfracDunc = -1.0; tempsTotfracD = -1.0; tempbTotfracD = -1.0
if bA + sA > 0.0:
tempsbfracA = sA / (sA + bA)
tempsbfracAunc = ((bA * sA2**0.5 / (sA + bA)**2.0)**2.0 + \
(sA * bA2**0.5 / (sA + bA)**2.0)**2.0)**0.5
if bB + sB > 0.0:
tempsbfracB = sB / (sB + bB)
tempsbfracBunc = ((bB * sB2**0.5 / (sB + bB)**2.0)**2.0 + \
(sB * bB2**0.5 / (sB + bB)**2.0)**2.0)**0.5
if bC + sC > 0.0:
tempsbfracC = sC / (sC + bC)
tempsbfracCunc = ((bC * sC2**0.5 / (sC + bC)**2.0)**2.0 + \
(sC * bC2**0.5 / (sC + bC)**2.0)**2.0)**0.5
if bD + sD > 0.0:
tempsbfracD = sD / (sD + bD)
tempsbfracDunc = ((bD * sD2**0.5 / (sD + bD)**2.0)**2.0 + \
(sD * bD2**0.5 / (sD + bD)**2.0)**2.0)**0.5
tempbfracA = bA / bTotal; tempsfracA = sA / sTotal
tempbfracB = bB / bTotal; tempsfracB = sB / sTotal
tempbfracC = bC / bTotal; tempsfracC = sC / sTotal
tempbfracD = bD / bTotal; tempsfracD = sD / sTotal
tempsignificance = 0.0; tempclosureerr = -999.0; tempmetric = 999.0; tempclosureerrunc = -999.0; tempsignunc = 0.0; temppredsign = 0.0
tempsignificanceWNC = 0.0; tempsignuncWNC = 0.0
if bD > 0.0 and bA > 0.0:
tempclosureerr = abs(1.0 - (bB * bC) / (bA * bD))
tempclosureerrunc = (((bB2**0.5 * bC)/(bA * bD))**2.0 + \
((bB * bC2**0.5)/(bA * bD))**2.0 + \
((bB * bC * bA2**0.5)/(bA**2.0 * bD))**2.0 + \
((bB * bC * bD2**0.5)/(bA * bD**2.0))**2.0)**0.5
if bA > 0.0:
tempsignificanceWNC += (sA / (bA + (bkgNormUnc*bA)**2.0 + (tempclosureerr*bA)**2.0)**0.5)
tempsignificance += (sA / (bA)**0.5)
temppredsign += (sA / (bB * bC / bD)**0.5)
tempsignuncWNC += ((sA2**0.5 / (bA + (bkgNormUnc*bA)**2.0 + (tempclosureerr*bA)**2.0)**0.5)**2.0 + \
((sA * bA2**0.5 * (2.0 * bA * tempclosureerr**2.0 + 2.0 * bkgNormUnc**2.0 * bA + 1)) / (bA + (bkgNormUnc*bA)**2.0 + (tempclosureerr*bA)**2.0)**1.5)**2.0 + \
((bA**2.0 * tempclosureerr * sA * tempclosureerrunc) / (bA * (bA * (tempclosureerr**2.0 + bkgNormUnc**2.0) + 1))**1.5)**2.0)**0.5
tempsignunc += tempsignificance * (((sA)**0.5/sA)**2 + (0.5)*(1/(bA**1.5)))**0.5
if tempsignificance > 0.0 and tempclosureerr > 0.0:
signs.append([tempsignificance, tempsignunc])
signsWNC.append([tempsignificanceWNC, tempsignuncWNC])
predsigns.append([temppredsign, tempsignunc])
closeErrs.append([abs(tempclosureerr), tempclosureerrunc])
edges.append([float(c1k),float(c2k)])
wBkgA.append([bA, bA2**0.5]); wBkgB.append([bB, bB2**0.5])
uwBkgA.append([ba, ba**0.5]); uwBkgB.append([bb, bb**0.5])
wSigA.append([sA, sA2**0.5]); wSigB.append([sB, sB2**0.5])
uwSigA.append([sa, sa**0.5]); uwSigB.append([sb, sb**0.5])
wBkgC.append([bC, bC2**0.5]); wBkgD.append([bD, bD2**0.5])
uwBkgC.append([bc, bc**0.5]); uwBkgD.append([bd, bd**0.5])
wSigC.append([sC, sC2**0.5]); wSigD.append([sD, sD2**0.5])
uwSigC.append([sc, sc**0.5]); uwSigD.append([sd, sd**0.5])
sFracsA.append([float(tempsbfracA), float(tempsbfracAunc)])
sFracsB.append([float(tempsbfracB), float(tempsbfracBunc)])
sFracsC.append([float(tempsbfracC), float(tempsbfracCunc)])
sFracsD.append([float(tempsbfracD), float(tempsbfracDunc)])
normSigFracs.append([float(tempsbfracA)**-1 * (tempsbfracB + tempsbfracC - tempsbfracD)])
# Compute metric if...
# signal fraction in B, C, and D regions is < 10%
# total background fraction in A is greater than 5%
if ba > minBkgEvts and \
bb > minBkgEvts and \
bc > minBkgEvts and \
bd > minBkgEvts:
if tempsignificance > 0.0:
tempmetric = tempclosureerr**2.0 + (1.0 / tempsignificance)**2.0
#tempmetric = 1.0 / tempsignificance
#if tempmetric < metric:
if c1k == "0.60" and c2k == "0.60":
finalc1 = c1k; finalc2 = c2k
metric = tempmetric
significance = tempsignificance
closureErr = tempclosureerr
return finalc1, finalc2, significance, closureErr, np.array(edges), np.array(signs), np.array(signsWNC), np.array(predsigns), np.array(closeErrs), {"A" : np.array(sFracsA), "B" : np.array(sFracsB), "C" : np.array(sFracsC), "D" : np.array(sFracsD)}, {"A" : np.array(wBkgA), "B" : np.array(wBkgB), "C" : np.array(wBkgC), "D" : np.array(wBkgD)}, {"A" : np.array(uwBkgA), "B" : np.array(uwBkgB), "C" : np.array(uwBkgC), "D" : np.array(uwBkgD)}, {"A" : np.array(wSigA), "B" : np.array(wSigB), "C" : np.array(wSigC), "D" : np.array(wSigD)}, {"A" : np.array(uwSigA), "B" : np.array(uwSigB), "C" : np.array(uwSigC), "D" : np.array(uwSigD)}, normSigFracs
# Define closure as how far away prediction for region D is compared to actual
def predictABCD(self, bNB, bNC, bND, bNBerr, bNCerr, bNDerr):
# Define A: > c1, > c2 B | A
# Define B: < c1, > c2 __________|__________
# Define C: > c1, < c2 |
# Define D: < c1, < c2 D | C
num = bNC * bNB
bNApred = -1.0; bNApredUnc = 0.0
if bND > 0.0:
bNApred = num / bND
bNApredUnc = ((bNC * bNBerr / bND)**2.0 + (bNCerr * bNB / bND)**2.0 + (bNC * bNB * bNDerr / bND**2.0)**2.0)**0.5
return bNApred, bNApredUnc
def countPeaks(self, disc1, disc2):
def checkAround(hist, i, j, min=0, max=4):
arr = hist[0]
current = arr[i][j]
left = current > arr[i-1][j] if i is not min else True
right = current > arr[i+1][j] if i is not max else True
up = current > arr[i][j-1] if j is not min else True
down = current > arr[i][j+1] if j is not max else True
return left and right and up and down
hist = np.histogram2d(disc1, disc2, bins=5, range=[[0,1],[0,1]], normed=None, weights=None, density=None)
req = np.sum(hist[0]) * 0.1
print(hist)
nPeaks = 0
i = 0
for x in hist[0]:
j = 0
for y in x:
if y > req and checkAround(hist, i, j):
nPeaks += 1
j += 1
i += 1
print("I found {} peaks".format(nPeaks))
def plotDisc1vsDisc2(self, disc1, disc2, bw, c1, c2, significance, tag, mass = "", Njets = -1, nBins = 100):
#self.countPeaks(disc1, disc2)
fig = plt.figure(figsize=(12,12))
corr = 999.0
try: corr = cor.pearson_corr(disc1, disc2)
except: print("Correlation coefficient could not be calculated!")
plt.hist2d(disc1, disc2, bins=[nBins, nBins], range=[[0, 1], [0, 1]], cmap=plt.cm.viridis, weights=bw, cmin = bw.min())#, norm=mpl.colors.LogNorm())
plt.colorbar(label="Num. Events")
ax = plt.gca()
l1 = ml.Line2D([c1, c1], [0.0, 1.0], color="red", linewidth=2); l2 = ml.Line2D([0.0, 1.0], [c2, c2], color="red", linewidth=2)
ax.add_line(l1); ax.add_line(l2)
ax.set_ylabel("Disc. 2"); ax.set_xlabel("Disc. 1")
hep.cms.label(llabel="Simulation", data=False, paper=False, year="Run 2")
fig.tight_layout()
if Njets == -1:
fig.savefig(self.config["outputDir"]+"/2D_%s%s_Disc1VsDisc2.png"%(tag,mass), dpi=fig.dpi)
with open(self.config["outputDir"]+"/2D_%s%s_Disc1VsDisc2.pkl"%(tag,mass), 'wb') as f:
pickle.dump(fig, f)
else:
fig.savefig(self.config["outputDir"]+"/2D_%s%s_Disc1VsDisc2_Njets%d.png"%(tag,mass,Njets), dpi=fig.dpi)
with open(self.config["outputDir"]+"/2D_%s%s_Disc1VsDisc2_Njets%d.pkl"%(tag,mass,Njets), 'wb') as f:
pickle.dump(fig, f)
plt.close(fig)
return corr
def plotVarVsBinEdges(self, var, edges, c1, c2, minEdge, maxEdge, edgeWidth, cmax, vmax, tag, Njets = -1):
nBins = int((1.0 + edgeWidth)/edgeWidth)
if tag == "NonClosure":
lab_tag = "Non-Closure"
elif tag == "Sign":
lab_tag = "Significance"
else:
lab_tag = tag
fig = plt.figure(figsize=(12,12))
plt.hist2d(edges[:,0], edges[:,1], bins=[nBins, nBins], range=[[-edgeWidth/2.0, 1+edgeWidth/2.0], [-edgeWidth/2.0, 1+edgeWidth/2.0]], cmap=plt.cm.viridis, weights=var, cmin=10e-10, cmax=cmax, vmin = 0.0, vmax = vmax)
cb = plt.colorbar(label=lab_tag)
cb.set_label(label="{}".format(lab_tag), loc='center')
ax = plt.gca()
ax.set_ylabel("Disc. 2 Bin Edge"); ax.set_xlabel("Disc. 1 Bin Edge");
hep.cms.label(llabel="Simulation", data=False, paper=False, year="Run 2")
l1 = ml.Line2D([c1, c1], [0.0, 1.0], color="black", linewidth=2, linestyle="dashed"); l2 = ml.Line2D([0.0, 1.0], [c2, c2], color="black", linewidth=2, linestyle="dashed")
ax.add_line(l1); ax.add_line(l2)
fig.tight_layout()
if Njets == -1:
fig.savefig(self.config["outputDir"]+"/%s_vs_Disc1Disc2.png"%(tag), dpi=fig.dpi)
with open(self.config["outputDir"]+"/%s_vs_Disc1Disc2.pkl"%(tag), 'wb') as f:
pickle.dump(fig, f)
else:
fig.savefig(self.config["outputDir"]+"/%s_vs_Disc1Disc2_Njets%s.png"%(tag,Njets), dpi=fig.dpi)
with open(self.config["outputDir"]+"/%s_vs_Disc1Disc2_Njets%s.pkl"%(tag,Njets), 'wb') as f:
pickle.dump(fig, f)
plt.close(fig)
def plotVarVsDisc(self, vars, edges, ylim = -1.0, ylog = False, ylabel = "", tag = "", Njets = -1):
print("Plotting var vs disc for {}".format(ylabel))
x1 = []; x2 = []
var = []
varUnc = []
for i in range(0, int(len(vars)/10)):
x1.append(edges[0][i][0])
x2.append(edges[0][i][1])
var.append(vars[i])
fig, ax = plt.subplots(figsize=(12,12))
#Z1, xedges, yedges = np.histogram2d(var, x1, bins=100)
#Z2, xedges, yedges = np.histogram2d(var, x2, bins=(xedges, yedges))
#Z /= np.max(Z) if abs(np.max(Z)) >= abs(np.min(Z)) else np.min(Z)
#normalize = mpl.colors.Normalize(vmin=-1, vmax=1)
#hist = ax.pcolormesh(xedges, yedges, Z, cmap = CM.RdBu_r, norm=normalize)
#c1 = ax.contour(var, x1, Z1)
#cbar1 = plt.colorbar(c1, ax=ax)
#cbar1.ax.set_ylabel("Normalized Events Disc. 1")
data1 = {"var": var, "x": x1}
data2 = {"var": var, "x": x2}
sns.kdeplot(data=data1, x="var", y="x", ax=ax, label="Disc. 1")
#c2 = ax.contour(var, x2, Z2)
#cbar2 = plt.colorbar(c2, ax=ax)
#cbar2.ax.set_ylabel("Normalized Events Disc. 2")
sns.kdeplot(data=data2, x="var", y="x", ax=ax, label="Disc. 2")
#ax.hist2d(var, x, label="Disc. 1 - Disc. 2", weights = w)
#ax[1].hist2d(x2, var, label="Disc. 2")
if ylim != -1.0:
ax.set_ylim((0.0, ylim))
#ax[1].set_ylim((0.0, ylim))
ax.set_ylabel("Disc. Output"); ax.set_xlabel(ylabel)
#ax[1].set_ylabel(ylabel); ax[1].set_xlabel("Disc. 2")
if ylog:
ax.set_yscale("log")
#ax[1].set_yscale("log")
plt.legend(loc='best')
hep.cms.label(llabel="Simulation", data=False, paper=False, year="Run 2")
fig.tight_layout()
if Njets == -1:
fig.savefig(self.config["outputDir"]+"/%sbyDisc.png"%(tag), dpi=fig.dpi)
with open(self.config["outputDir"]+"/%sbyDisc.pkl"%(tag), 'wb') as f:
pickle.dump(fig, f)
else:
fig.savefig(self.config["outputDir"]+"/%sbyDisc_Njets%s.png"%(tag,Njets), dpi=fig.dpi)
with open(self.config["outputDir"]+"/%sbyDisc_Njets%s.pkl"%(tag,Njets), 'wb') as f:
pickle.dump(fig, f)
plt.close(fig)
def plotBinEdgeMetricComps(self, finalSign, finalClosureErr, sign, closeErr, edges, d1edge, d2edge, Njets = -1):
fig = plt.figure(figsize=(12,12))
hep.cms.label(llabel="Simulation", data=False, paper=False, year="Run 2")
ax = plt.gca()
plt.scatter(np.reciprocal(sign[0]), closeErr[0], color='xkcd:silver', marker="o", label="1 - Pred./Obs. vs 1 / Significance")
if finalSign != 0.0:
plt.scatter([1.0/finalSign], [finalClosureErr], s=100, color='xkcd:red', marker="o", label="Chosen Solution")
plt.xlabel('1 / Significance')
plt.ylabel('|1 - Pred./Obs.|')
plt.legend(loc='best')
plt.ylim(bottom=0)
plt.xlim(left=0)
plt.gca().invert_yaxis()
plt.text(0.50, 0.85, r"$%.2f < \bf{Disc.\;1\;Edge}$ = %s < %.2f"%(edges[0],d1edge,edges[-1]), transform=ax.transAxes, fontfamily='sans-serif', fontsize=16)
plt.text(0.50, 0.80, r"$%.2f < \bf{Disc.\;2\;Edge}$ = %s < %.2f"%(edges[0],d2edge,edges[-1]), transform=ax.transAxes, fontfamily='sans-serif', fontsize=16)
fig.tight_layout()
if Njets == -1:
fig.savefig(self.config["outputDir"]+"/InvSign_vs_NonClosure.png", dpi=fig.dpi)
with open(self.config["outputDir"]+"/InvSign_vs_NonClosure.pkl", 'wb') as f:
pickle.dump(fig, f)
else:
fig.savefig(self.config["outputDir"]+"/InvSign_vs_NonClosure_Njets%d.png"%(Njets), dpi=fig.dpi)
with open(self.config["outputDir"]+"/InvSign_vs_NonClosure_Njets%d.pkl"%(Njets), 'wb') as f:
pickle.dump(fig, f)
plt.close(fig)
return np.average(closeErr), np.std(closeErr)
def plotNjets(self, bkgd, sig, label):
binCenters = [i for i in range(self.config["minNJetBin"], self.config["maxNJetBin"]+1)]
xErr = [0.5 for i in range(0, len(bkgd))]
sign = 0.0
for i in range(0, len(bkgd)):
if bkgd[i][0] > 0.0: sign += (sig[i][0] / (bkgd[i][0] + (0.3*bkgd[i][0])**2.0)**0.5)**2.0
sign = sign**0.5
fig = plt.figure(figsize=(12,12))
ax = plt.gca()
ax.set_yscale("log")
ax.set_ylim([1,10e4])
ax.errorbar(binCenters, bkgd[:,0], yerr=bkgd[:,1], label="Background", xerr=xErr, fmt='', color="black", lw=0, elinewidth=2, marker="o", markerfacecolor="black")
ax.errorbar(binCenters, sig[:,0], yerr=sig[:,1], label="Signal", xerr=xErr, fmt='', color="red", lw=0, elinewidth=2, marker="o", markerfacecolor="red")
hep.cms.label(llabel="Simulation", data=False, paper=False, year="Run 2", ax=ax)
plt.xlabel('$N_{jets}$')
plt.ylabel('Events')
plt.legend(loc='best')
plt.text(0.05, 0.94, r"Significance = %.2f"%(sign), transform=ax.transAxes, fontfamily='sans-serif', fontsize=16, bbox=dict(facecolor='white', alpha=1.0))
fig.savefig(self.config["outputDir"]+"/Njets_Region_%s.png"%(label))
with open(self.config["outputDir"]+"/Njets_Region_%s.pkl"%(label), 'wb') as f:
pickle.dump(fig, f)
plt.close(fig)
return sign
def plotNjetsClosure(self, bkgd, bkgdPred, bkgdSign, tag = ""):
binCenters = []
xErr = []
abcdPull = []
abcdError = []