-
Notifications
You must be signed in to change notification settings - Fork 10
/
make_good_plots.py
2032 lines (1659 loc) · 111 KB
/
make_good_plots.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import sys
import os
import numpy as np
import pandas as pd
#import torch
#import torch.nn as nn
#from torch.autograd.variable import *
#import torch.optim as optim
import matplotlib
matplotlib.use('agg')
import matplotlib.pyplot as plt
from matplotlib import rcParams
from matplotlib import rc
from sklearn.metrics import roc_curve, auc, accuracy_score
import scipy
import h5py
import argparse
import glob
import matplotlib.lines as mlines
from sklearn.ensemble import GradientBoostingRegressor
import itertools
#from histo_utilities import create_TH1D, make_ratio_plot
rc('font',**{'family':'sans-serif','sans-serif':['Helvetica']})
rcParams['font.size'] = 22
rcParams['text.latex.preamble'] = [
# r'\usepackage{siunitx}', # i need upright \micro symbols, but you need...
# r'\sisetup{detect-all}', # ...this to force siunitx to actually use your fonts
r'\usepackage{helvet}', # set the normal font here
r'\usepackage{sansmath}', # load up the sansmath so that math -> helvet
r'\sansmath' # <- tricky! -- gotta actually tell tex to use!
]
rc('text', usetex=True)
def make_dirs(dirname):
import os, errno
"""
Ensure that a named directory exists; if it does not, attempt to create it.
"""
try:
os.makedirs(dirname)
except:
print("pass")
def make_plots(outputDir, dataframes, tdf_train, savedirs=["Plots"], taggerNames=["IN"], eraText=r'2016 (13 TeV)'):
print("Making standard plots")
def cut(tdf, ptlow=300, pthigh=2000):
mlow, mhigh = 40, 200
cdf = tdf[(tdf.fj_pt < pthigh) & (tdf.fj_pt>ptlow) &(tdf.fj_sdmass < mhigh) & (tdf.fj_sdmass>mlow)]
masses = cdf['fj_sdmass'].values
bins_sdmass = np.digitize(masses, bins = np.linspace(mlow,mhigh,9))-1
cdf.insert(4, 'bins_sdmass', bins_sdmass, True)
return cdf
def cutrho(tdf, rholow=-8, rhohigh=-1):
tdf = tdf[(tdf.fj_pt>0) & (tdf.fj_sdmass>0)]
masses = tdf['fj_sdmass'].values
pTs = tdf['fj_pt'].values
rho = np.log(np.divide(np.square(masses), np.square(pTs)))
tdf.insert(2, 'fj_rho', rho, True)
bins_rho = np.digitize(rho, bins = np.linspace(rholow,rhohigh,21))-1
tdf.insert(3, 'bins_rho', bins_rho, True)
cdf = tdf[(tdf.fj_rho>rholow) & (tdf.fj_rho<rhohigh)]
return cdf
def cuteta(tdf, etalow=-2.5, etahigh=2.5):
#mlow, mhigh = 90, 140
mlow, mhigh = 40, 200
cdf = tdf[(tdf.fj_eta < etahigh) & (tdf.fj_eta>etalow) &(tdf.fj_sdmass < mhigh) & (tdf.fj_sdmass>mlow)]
return cdf
def roc_input(frame, signal=["HCC"], include = ["HCC", "Light", "gBB", "gCC", "HBB"], norm=False):
# Bkg def - filter unwanted
bkg = np.zeros(frame.shape[0])
for label in include:
bkg = np.add(bkg, frame['truth'+label].values )
bkg = [bool(x) for x in bkg]
tdf = frame[bkg] #tdf for temporary df
# Signal
truth = np.zeros(tdf.shape[0])
predict = np.zeros(tdf.shape[0])
prednorm = np.zeros(tdf.shape[0])
predict_IN = np.zeros(tdf.shape[0])
prednorm_IN = np.zeros(tdf.shape[0])
for label in signal:
truth += tdf['truth'+label].values
predict += tdf['predict'+label].values
#predict_IN += tdf['predict_IN'+label].values
for label in include:
prednorm += tdf['predict'+label].values
#prednorm_IN += tdf['predict_IN'+label].values
db = tdf['fj_doubleb'].values
if norm == False:
return truth, predict, db
else:
return truth, np.divide(predict, prednorm), db
def plot_rocs(dfs=[], savedir="", names=[], sigs=[["Hcc"]], bkgs=[["Hbb"]], norm=False, plotname=""):
def find_nearest(array,value):
idx = (np.abs(array-value)).argmin()
return idx, array[idx]
f, ax = plt.subplots(figsize=(10, 10))
for frame, name, sig, bkg in zip(dfs, names, sigs, bkgs):
truth, predict, db = roc_input(frame, signal=sig, include = sig+bkg, norm=norm)
fpr, tpr, threshold = roc_curve(truth, predict)
ax.plot(tpr, fpr, lw=2.5, label="{}, AUC = {:.1f}\%".format(name,auc(fpr,tpr)*100))
ROCtext=open(os.path.join(savedir, "ROCComparison_"+"+".join(sig)+"_vs_"+"+".join(bkg)+".txt"),'w')
for ind in range(len(tpr)):
ROCtext.write(str(tpr[ind])+'\t'+str(fpr[ind])+'\n')
ROCtext.close()
print("{}, AUC={}%".format(name, auc(fpr,tpr)*100), "Sig:", sig, "Bkg:", bkg)
print("{}, Acc={}%".format(name, accuracy_score(truth,predict>0.5)*100), "Sig:", sig, "Bkg:", bkg)
#print(1/fpr[find_nearest(tpr, 0.3)[0]])
#print(1/fpr[find_nearest(tpr, 0.5)[0]])
#print(tpr[find_nearest(fpr, 0.01)[0]])
ax.set_xlim(0,1)
ax.set_ylim(0.001,1)
if len(sig) == 1 and len(sig[0]) == 3 and sig[0][0] in ["H", "Z", "g"]:
xlab = '{} \\rightarrow {}'.format(sig[0][0], sig[0][-2]+'\\bar{'+sig[0][-1]+'}')
ax.set_xlabel(r'Tagging efficiency ($\mathrm{}$)'.format('{'+xlab+'}'), ha='right', x=1.0)
else:
xlab = ['{} \\rightarrow {}'.format(l[0], l[-2]+'\\bar{'+l[-1]+'}') if l[0][0] in ["H", "Z", "g"] else l for l in sig ]
ax.set_xlabel(r'Tagging efficiency ($\mathrm{}$)'.format("{"+", ".join(xlab)+"}"), ha='right', x=1.0)
if len(bkg) == 1 and len(bkg[0]) == 3 and bkg[0][0] in ["H", "Z", "g"]:
ylab = '{} \\rightarrow {}'.format(bkg[0][0], bkg[0][-2]+'\\bar{'+bkg[0][-1]+'}')
ax.set_ylabel(r'Mistagging rate ($\mathrm{}$)'.format('{'+ylab+'}'), ha='right', y=1.0)
else:
ylab = ['{} \\rightarrow {}'.format(l[0], l[-2]+'\\bar{'+l[-1]+'}') if l[0][0] in ["H", "Z", "g"] else l for l in bkg ]
ax.set_ylabel(r'Mistagging rate ($\mathrm{}$)'.format("{"+", ".join(ylab)+"}"), ha='right', y=1.0)
import matplotlib.ticker as plticker
ax.xaxis.set_major_locator(plticker.MultipleLocator(base=0.1))
ax.xaxis.set_minor_locator(plticker.MultipleLocator(base=0.02))
ax.tick_params(direction='in', axis='both', which='major', labelsize=15, length=12 )
ax.tick_params(direction='in', axis='both', which='minor' , length=6)
ax.xaxis.set_ticks_position('both')
ax.yaxis.set_ticks_position('both')
ax.semilogy()
ax.grid(which='minor', alpha=0.5, axis='y', linestyle='dotted')
ax.grid(which='major', alpha=0.9, linestyle='dotted')
leg = ax.legend(borderpad=1, frameon=False, loc=2, fontsize=16,
title = ""+str(int(round((min(frame.fj_pt)))))+" $\mathrm{<\ jet\ p_T\ <}$ "+str(int(round((max(frame.fj_pt)))))+" GeV" \
+ "\n "+str(int(round((min(frame.fj_sdmass)))))+" $\mathrm{<\ jet\ m_{SD}\ <}$ "+str(int(round((max(frame.fj_sdmass)))))+" GeV"
)
leg._legend_box.align = "left"
ax.annotate(eraText, xy=(0.75, 1.1), fontname='Helvetica', ha='left',
bbox={'facecolor':'white', 'edgecolor':'white', 'alpha':0, 'pad':13}, annotation_clip=False)
ax.annotate('$\mathbf{CMS}$', xy=(0.01, 1.1), fontname='Helvetica', fontsize=24, fontweight='bold', ha='left',
bbox={'facecolor':'white', 'edgecolor':'white', 'alpha':0, 'pad':13}, annotation_clip=False)
ax.annotate('$Simulation\ Open\ Data$', xy=(0.115, 1.1), fontsize=18, fontstyle='italic', ha='left',
annotation_clip=False)
if norm:
f.savefig(os.path.join(savedir, "ROCNormComparison_"+"+".join(sig)+"_vs_"+"+".join(bkg)+".pdf"), dpi=400)
f.savefig(os.path.join(savedir, "ROCNormComparison_"+"+".join(sig)+"_vs_"+"+".join(bkg)+".png"), dpi=400)
else:
f.savefig(os.path.join(savedir, "ROCComparison_"+"+".join(sig)+"_vs_"+"+".join(bkg)+".pdf"), dpi=400)
f.savefig(os.path.join(savedir, "ROCComparison_"+"+".join(sig)+"_vs_"+"+".join(bkg)+".png"), dpi=400)
plt.close(f)
def plot_rocs_with_DDT(dfs=[], savedir="", names=[], sigs=[["Hcc"]], bkgs=[["Hbb"]], norm=False, plotname="", DDT_results = [[],[]]):
f, ax = plt.subplots(figsize=(10, 10))
colors = ['C0', 'C6', 'C1', 'C2', ]
line_styles = ['-', '--', '-.' , ':', '--']
line_widths = [2.5, 2.5, 2.5, 3, 2.5]
for frame, name, sig, bkg, color, style, width in zip(dfs, names, sigs, bkgs, colors, line_styles, line_widths):
truth, predict, db = roc_input(frame, signal=sig, include = sig+bkg, norm=norm)
fpr, tpr, threshold = roc_curve(truth, predict)
if color not in ['C6', 'C1', 'C2']:
ax.plot(tpr, fpr, lw=width, color=color, linestyle = style, label="{}, AUC = {:.1f}\%".format(name,auc(fpr,tpr)*100))
ROCtext=open(os.path.join(savedir, "ROCComparison_"+"+".join(sig)+"_vs_"+"+".join(bkg)+".txt"),'w')
for ind in range(len(tpr)):
ROCtext.write(str(tpr[ind])+'\t'+str(fpr[ind])+'\n')
ROCtext.close()
print("{}, AUC={}%".format(name, auc(fpr,tpr)*100), "Sig:", sig, "Bkg:", bkg)
ax.plot(DDT_results[0][0], DDT_results[1], lw=2.5, color='C3', linestyle = '-', label="{}, AUC = {:.1f}\%".format('Interaction network, DDT',auc(DDT_results[1],DDT_results[0][0])*100))
for frame, name, sig, bkg, color, style, width in zip(dfs, names, sigs, bkgs, colors, line_styles, line_widths):
truth, predict, db = roc_input(frame, signal=sig, include = sig+bkg, norm=norm)
fpr, tpr, threshold = roc_curve(truth, predict)
if color in ['C2']:
ax.plot(tpr, fpr, lw=width, color=color, linestyle=style, label="{}, AUC = {:.1f}\%".format(name,auc(fpr,tpr)*100))
ROCtext=open(os.path.join(savedir, "ROCComparison_"+"+".join(sig)+"_vs_"+"+".join(bkg)+".txt"),'w')
for ind in range(len(tpr)):
ROCtext.write(str(tpr[ind])+'\t'+str(fpr[ind])+'\n')
ROCtext.close()
print("{}, AUC={}%".format(name, auc(fpr,tpr)*100), "Sig:", sig, "Bkg:", bkg)
ax.plot(DDT_results[0][3], DDT_results[1], lw=2.5, color='C5', linestyle = ':', label="{}, AUC = {:.1f}\%".format('Deep double-b+, DDT',auc(DDT_results[1],DDT_results[0][3])*100))
if color in ['C6']:
ax.plot(tpr, fpr, lw=width, color=color, linestyle=style, label="{}, AUC = {:.1f}\%".format(name,auc(fpr,tpr)*100))
ROCtext=open(os.path.join(savedir, "ROCComparison_"+"+".join(sig)+"_vs_"+"+".join(bkg)+".txt"),'w')
for ind in range(len(tpr)):
ROCtext.write(str(tpr[ind])+'\t'+str(fpr[ind])+'\n')
ROCtext.close()
print("{}, AUC={}%".format(name, auc(fpr,tpr)*100), "Sig:", sig, "Bkg:", bkg)
ax.plot(DDT_results[0][1], DDT_results[1], lw=2.5, color='C7', linestyle = '--', label="{}, AUC = {:.1f}\%".format('All-particle interaction network, DDT',auc(DDT_results[1],DDT_results[0][1])*100))
if color in ['C1']:
ax.plot(tpr, fpr, lw=width, color=color, linestyle=style, label="{}, AUC = {:.1f}\%".format(name,auc(fpr,tpr)*100))
ROCtext=open(os.path.join(savedir, "ROCComparison_"+"+".join(sig)+"_vs_"+"+".join(bkg)+".txt"),'w')
for ind in range(len(tpr)):
ROCtext.write(str(tpr[ind])+'\t'+str(fpr[ind])+'\n')
ROCtext.close()
print("{}, AUC={}%".format(name, auc(fpr,tpr)*100), "Sig:", sig, "Bkg:", bkg)
ax.plot(DDT_results[0][2], DDT_results[1], lw=2.5, color='C4', linestyle = '-.', label="{}, AUC = {:.1f}\%".format('Deep double-b, DDT',auc(DDT_results[1],DDT_results[0][2])*100))
ax.set_xlim(0,1)
ax.set_ylim(0.001,1)
if len(sig) == 1 and len(sig[0]) == 3 and sig[0][0] in ["H", "Z", "g"]:
xlab = '{} \\rightarrow {}'.format(sig[0][0], sig[0][-2]+'\\bar{'+sig[0][-1]+'}')
ax.set_xlabel(r'Tagging efficiency ($\mathrm{}$)'.format('{'+xlab+'}'), ha='right', x=1.0)
else:
xlab = ['{} \\rightarrow {}'.format(l[0], l[-2]+'\\bar{'+l[-1]+'}') if l[0][0] in ["H", "Z", "g"] else l for l in sig ]
ax.set_xlabel(r'Tagging efficiency ($\mathrm{}$)'.format("{"+", ".join(xlab)+"}"), ha='right', x=1.0)
if len(bkg) == 1 and len(bkg[0]) == 3 and bkg[0][0] in ["H", "Z", "g"]:
ylab = '{} \\rightarrow {}'.format(bkg[0][0], bkg[0][-2]+'\\bar{'+bkg[0][-1]+'}')
ax.set_ylabel(r'Mistagging rate ($\mathrm{}$)'.format('{'+ylab+'}'), ha='right', y=1.0)
else:
ylab = ['{} \\rightarrow {}'.format(l[0], l[-2]+'\\bar{'+l[-1]+'}') if l[0][0] in ["H", "Z", "g"] else l for l in bkg ]
ax.set_ylabel(r'Mistagging rate ($\mathrm{}$)'.format("{"+", ".join(ylab)+"}"), ha='right', y=1.0)
import matplotlib.ticker as plticker
ax.xaxis.set_major_locator(plticker.MultipleLocator(base=0.1))
ax.xaxis.set_minor_locator(plticker.MultipleLocator(base=0.02))
ax.tick_params(direction='in', axis='both', which='major', labelsize=15, length=12 )
ax.tick_params(direction='in', axis='both', which='minor' , length=6)
ax.xaxis.set_ticks_position('both')
ax.yaxis.set_ticks_position('both')
ax.semilogy()
ax.grid(which='minor', alpha=0.5, axis='y', linestyle='dotted')
ax.grid(which='major', alpha=0.9, linestyle='dotted')
leg = ax.legend(borderpad=1, frameon=False, loc=2, fontsize=16,
title = ""+str(int(round((min(frame.fj_pt)))))+" $\mathrm{<\ jet\ p_T\ <}$ "+str(int(round((max(frame.fj_pt)))))+" GeV" \
+ "\n "+str(int(round((min(frame.fj_sdmass)))))+" $\mathrm{<\ jet\ m_{SD}\ <}$ "+str(int(round((max(frame.fj_sdmass)))))+" GeV"
)
leg._legend_box.align = "left"
ax.annotate(eraText, xy=(0.75, 1.1), fontname='Helvetica', ha='left',
bbox={'facecolor':'white', 'edgecolor':'white', 'alpha':0, 'pad':13}, annotation_clip=False)
ax.annotate('$\mathbf{CMS}$', xy=(0.01, 1.1), fontname='Helvetica', fontsize=24, fontweight='bold', ha='left',
bbox={'facecolor':'white', 'edgecolor':'white', 'alpha':0, 'pad':13}, annotation_clip=False)
ax.annotate('$Simulation\ Open\ Data$', xy=(0.115, 1.1), fontsize=18, fontstyle='italic', ha='left',
annotation_clip=False)
if norm:
f.savefig(os.path.join(savedir, "ROCNormComparison_withDDT_"+"+".join(sig)+"_vs_"+"+".join(bkg)+".pdf"), dpi=400)
f.savefig(os.path.join(savedir, "ROCNormComparison_withDDT_"+"+".join(sig)+"_vs_"+"+".join(bkg)+".png"), dpi=400)
else:
f.savefig(os.path.join(savedir, "ROCComparison_withDDT_"+"+".join(sig)+"_vs_"+"+".join(bkg)+".pdf"), dpi=400)
f.savefig(os.path.join(savedir, "ROCComparison_withDDT_"+"+".join(sig)+"_vs_"+"+".join(bkg)+".png"), dpi=400)
plt.close(f)
def quantile_regression_DDT_FPR(dfs, dfs_train, FPR_cut):
print('Fitting Quantile Reg. of FPR = ' + str(FPR_cut))
data_train = [[mass] for mass, pT in zip(dfs.loc[dfs['truth'+'QCD'] == 1]['fj_sdmass'].values , dfs.loc[dfs['truth'+'QCD'] == 1]['fj_pt'].values)]
data = [[mass] for mass, pT in zip(dfs['fj_sdmass'].values , dfs['fj_pt'].values)]
if FPR_cut > 10:
aux_scale = 0.1*float(FPR_cut)/3000.
else:
aux_scale = 0.1*float(FPR_cut)/100.
model = GradientBoostingRegressor(loss='quantile', alpha=1-float(FPR_cut)/100,
n_estimators=500,
min_samples_leaf=50,
min_samples_split=2500,
max_depth = 5,
validation_fraction=0.2,
n_iter_no_change=10, tol=1e-3,
verbose=1, random_state=42)
model.fit(data_train, dfs.loc[dfs['truth'+'QCD'] == 1]['predict'+'Hbb'].values/aux_scale)
cuts = aux_scale*model.predict(data)
return cuts
def quantile_regression_DDT_TPR(dfs, dfs_train, TPR_cut):
print('Fitting Quantile Reg. of TPR = ' + str(TPR_cut))
data_train = [[mass] for mass, pT in zip(dfs.loc[dfs['truth'+'Hbb'] == 1]['fj_sdmass'].values , dfs.loc[dfs['truth'+'Hbb'] == 1]['fj_pt'].values)]
data = [[mass] for mass, pT in zip(dfs['fj_sdmass'].values , dfs['fj_pt'].values)]
if TPR_cut > 10:
aux_scale = 0.1*float(TPR_cut)/3000.
else:
aux_scale = 0.1*float(TPR_cut)/100.
model = GradientBoostingRegressor(loss='quantile', alpha=float(TPR_cut)/100,
n_estimators=500,
min_samples_leaf=50,
min_samples_split=2500,
max_depth=5,
validation_fraction=0.2,
n_iter_no_change=10, tol=1e-3,
verbose=1, random_state=42)
model.fit(data_train, dfs.loc[dfs['truth'+'Hbb'] == 1]['predict'+'Hbb'].values/aux_scale)
cuts = aux_scale*model.predict(data)
return cuts
def fit_quantile_reg(tdf, FPR_cut=[], savename=""):
from sklearn.ensemble import GradientBoostingRegressor
print('Setting DDT cut to {}%'.format(FPR_cut))
big_cuts = []
for FPR in range(len(FPR_cut)):
cuts = quantile_regression_DDT(tdf, tdf_train, FPR_cut[FPR])
big_cuts.append(cuts)
return(big_cuts)
def JSD(A,B):
S = A/2. + B/2.
eA = scipy.stats.entropy( A, S, base=2)
eB = scipy.stats.entropy( B, S, base=2)
jsd = eA/2. + eB/2.
return 1./jsd
def plot_jsd(dfs=[], savedir="", names=[], sigs=[["Hcc"]], bkgs=[["Hbb"]], norm=False, plotname=""):
prop_cycle = plt.rcParams['axes.prop_cycle']
colors = prop_cycle.by_key()['color']
def find_nearest(array,value):
idx = (np.abs(array-value)).argmin()
return idx, array[idx]
rhomin = -8
rhomax = -1
bins = 20
# Specifically ordered in this method for paper
dfs.insert(1, dfs[0])
dfs.insert(3, dfs[2])
dfs.insert(5, dfs[4])
temp_names = np.copy(names)
temp_names = np.insert(temp_names, 1, 'Interaction network, DDT')
temp_names = np.insert(temp_names, 3, 'Deep double-b, DDT')
temp_names = np.insert(temp_names, 5, 'Deep double-b+, DDT')
temp_names = ['Interaction network','Interaction network, DDT', 'Deep double-b', 'Deep double-b, DDT','Deep double-b+','Deep double-b+, DDT']
for i in range(3):
sigs.append('Hbb')
bkgs.append('QCD')
min_jsd_eff = 2e-4
mmin = 40
mmax = 200
nbins = 8
f, ax = plt.subplots(figsize=(10, 10))
ax.loglog()
line_styles = ['-', '-', '-.', '-.', ':', ':']
colors = ['C0', 'C3', 'C1', 'C4', 'C2', 'C5']
counter = -1
for frame, name, sig, bkg, col, style in zip(dfs, temp_names, sigs, bkgs, colors, line_styles):
if name in ['Interaction network', 'Deep double-b', 'Deep double-b+']:
truth, predict, db = roc_input(frame, signal=sig, include = sig+bkg, norm=norm)
fpr, tpr, threshold = roc_curve(truth, predict)
print("{}, AUC={}%".format(name, auc(fpr,tpr)*100), "Sig:", sig, "Bkg:", bkg)
print("{}, Acc={}%".format(name, accuracy_score(truth,predict>0.5)*100), "Sig:", sig, "Bkg:", bkg)
cuts = {}
jsd_plot = []
eb_plot = []
for wp,marker in zip([0.5,0.9,0.95],['^','s','o','v']): # % signal eff
idx, val = find_nearest(tpr, wp)
cuts[str(wp)] = threshold[idx] # threshold for deep double-b corresponding to ~1% mistag rate
mask_pass = (frame['predict'+sig[0]] > cuts[str(wp)]) & frame['truth'+bkg[0]]
mask_fail = (frame['predict'+sig[0]] < cuts[str(wp)]) & frame['truth'+bkg[0]]
mass = frame['fj_sdmass'].values
mass_pass = mass[mask_pass]
mass_fail = mass[mask_fail]
# digitze into bins
spec_pass = np.digitize(mass_pass, bins=np.linspace(mmin,mmax,nbins+1), right=False)-1
spec_fail = np.digitize(mass_fail, bins=np.linspace(mmin,mmax,nbins+1), right=False)-1
# one hot encoding
spec_ohe_pass = np.zeros((spec_pass.shape[0],nbins))
spec_ohe_pass[np.arange(spec_pass.shape[0]),spec_pass] = 1
spec_ohe_pass_sum = np.sum(spec_ohe_pass,axis=0)/spec_ohe_pass.shape[0]
spec_ohe_fail = np.zeros((spec_fail.shape[0],nbins))
spec_ohe_fail[np.arange(spec_fail.shape[0]),spec_fail] = 1
spec_ohe_fail_sum = np.sum(spec_ohe_fail,axis=0)/spec_ohe_fail.shape[0]
M = 0.5*spec_ohe_pass_sum+0.5*spec_ohe_fail_sum
kld_pass = scipy.stats.entropy(spec_ohe_pass_sum,M,base=2)
kld_fail = scipy.stats.entropy(spec_ohe_fail_sum,M,base=2)
jsd = 0.5*kld_pass+0.5*kld_fail
print('eS = %.2f%%, eB = %.2f%%, 1/eB=%.2f, jsd = %.2f, 1/jsd = %.2f'%(tpr[idx]*100,fpr[idx]*100,1/fpr[idx],jsd,1/jsd))
eb_plot.append(1/fpr[idx])
jsd_plot.append(1/jsd)
ax.plot([1/fpr[idx]],[1/jsd],marker=marker,markersize=12,color=col)
elif name in ['Interaction network, DDT', 'Deep double-b, DDT', 'Deep double-b+, DDT']:
counter += 1
truth, predict, db = roc_input(frame, signal=sig, include = sig+bkg, norm=norm)
fpr, tpr, threshold = roc_curve(truth, predict)
print("{}, AUC={}%".format(name, auc(fpr,tpr)*100), "Sig:", sig, "Bkg:", bkg)
print("{}, Acc={}%".format(name, accuracy_score(truth,predict>0.5)*100), "Sig:", sig, "Bkg:", bkg)
jsd_plot = []
eb_plot = []
for wp,marker in zip([50.,90.,95.],['^','s','o', 'v']): # % signal eff.
idx, val = find_nearest(tpr, wp/100)
cuts = quantile_regression_DDT_FPR(cut(frame), cut(frame), wp)
mask_pass = (frame['predict'+sig[0]] > cuts) & frame['truth'+bkg[0]]
mask_fail = (frame['predict'+sig[0]] < cuts) & frame['truth'+bkg[0]]
mass = frame['fj_sdmass'].values
mass_pass = mass[mask_pass]
mass_fail = mass[mask_fail]
# digitze into bins
spec_pass = np.digitize(mass_pass, bins=np.linspace(mmin,mmax,nbins+1), right=False)-1
spec_fail = np.digitize(mass_fail, bins=np.linspace(mmin,mmax,nbins+1), right=False)-1
# one hot encoding
spec_ohe_pass = np.zeros((spec_pass.shape[0],nbins))
spec_ohe_pass[np.arange(spec_pass.shape[0]),spec_pass] = 1
spec_ohe_pass_sum = np.sum(spec_ohe_pass,axis=0)/spec_ohe_pass.shape[0]
spec_ohe_fail = np.zeros((spec_fail.shape[0],nbins))
spec_ohe_fail[np.arange(spec_fail.shape[0]),spec_fail] = 1
spec_ohe_fail_sum = np.sum(spec_ohe_fail,axis=0)/spec_ohe_fail.shape[0]
M = 0.5*spec_ohe_pass_sum+0.5*spec_ohe_fail_sum
kld_pass = scipy.stats.entropy(spec_ohe_pass_sum,M,base=2)
kld_fail = scipy.stats.entropy(spec_ohe_fail_sum,M,base=2)
jsd = 0.5*kld_pass+0.5*kld_fail
#FPR_wp = 1./(model.predict([[wp/100.]])[0]*aux_scale)
FPR_wp = 1./make_FPR_DDT(cut(frame), 1+wp, siglab='QCD', sculp_label='fj_sdmass', savedir=savedir, taggerName=name)
print('eS = %.2f%%, eB = %.2f%%, 1/eB=%.2f, jsd = %.2f, 1/jsd = %.2f'%(tpr[idx]*100,fpr[idx]*100,1/fpr[idx],jsd,1/jsd))
eb_plot.append(FPR_wp)
jsd_plot.append(1/jsd)
ax.plot([FPR_wp],[1/jsd],marker=marker,markersize=12,color=col)
ax.plot(eb_plot,jsd_plot,linestyle=style,label=name,color=col)
ax.set_xlim(1,2e3)
ax.set_ylim(1,1e9)
ax.set_xlabel(r'Background rejection (QCD) 1 / $\varepsilon_\mathrm{bkg}$',ha='right', x=1.0)
ax.set_ylabel(r'Mass decorrelation 1 / $D_\mathrm{JS}$',ha='right', y=1.0)
import matplotlib.ticker as plticker
ax.tick_params(direction='in', axis='both', which='major', labelsize=15, length=12 )
ax.tick_params(direction='in', axis='both', which='minor' , length=6)
ax.xaxis.set_ticks_position('both')
ax.yaxis.set_ticks_position('both')
ax.loglog()
ax.grid(which='minor', alpha=0.5, linestyle='dotted')
ax.grid(which='major', alpha=0.9, linestyle='dotted')
leg = ax.legend(borderpad=1, frameon=False, loc='upper left', fontsize=16,
title = ""+str(int(round((min(frame.fj_pt)))))+" $\mathrm{<\ jet\ p_T\ <}$ "+str(int(round((max(frame.fj_pt)))))+" GeV" \
+ "\n "+str(int(round((min(frame.fj_sdmass)))))+" $\mathrm{<\ jet\ m_{SD}\ <}$ "+str(int(round((max(frame.fj_sdmass)))))+" GeV"
)
leg._legend_box.align = "right"
circle = mlines.Line2D([], [], color='gray', marker='o', linestyle='None',
markersize=12, label=r'$\varepsilon_\mathrm{sig}$ = 95\%%')
square = mlines.Line2D([], [], color='gray', marker='s', linestyle='None',
markersize=12, label=r'$\varepsilon_\mathrm{sig}$ = 90\%%')
utriangle = mlines.Line2D([], [], color='gray', marker='^', linestyle='None',
markersize=12, label=r'$\varepsilon_\mathrm{sig}$ = 50\%%')
#dtriangle = mlines.Line2D([], [], color='gray', marker='v', linestyle='None',
# markersize=12, label=r'$\varepsilon_\mathrm{sig}$ = 30\%%')
plt.gca().add_artist(leg)
#leg2 = ax.legend(handles=[circle, square, utriangle, dtriangle],fontsize=16,frameon=False,borderpad=1,loc='upper right')
leg2 = ax.legend(handles=[circle, square, utriangle],fontsize=16,frameon=False,borderpad=1,loc='upper right')
leg2._legend_box.align = "right"
plt.gca().add_artist(leg2)
ax.annotate(eraText, xy=(2.5e2, 1.1e9), fontname='Helvetica', ha='left',
bbox={'facecolor':'white', 'edgecolor':'white', 'alpha':0, 'pad':13}, annotation_clip=False)
ax.annotate('$\mathbf{CMS}$', xy=(1.1, 1.1e9), fontname='Helvetica', fontsize=24, fontweight='bold', ha='left',
bbox={'facecolor':'white', 'edgecolor':'white', 'alpha':0, 'pad':13}, annotation_clip=False)
ax.annotate('$Simulation\ Open\ Data$', xy=(2.3, 1.1e9), fontsize=18, fontstyle='italic', ha='left',
annotation_clip=False)
f.savefig(os.path.join(savedir, "JSD_"+"+".join(sig)+"_vs_"+"+".join(bkg)+".pdf"), dpi=400)
f.savefig(os.path.join(savedir, "JSD_"+"+".join(sig)+"_vs_"+"+".join(bkg)+".png"), dpi=400)
plt.close(f)
def plot_jsd_sig(dfs=[], savedir="", names=[], sigs=[["Hcc"]], bkgs=[["Hbb"]], norm=False, plotname=""):
prop_cycle = plt.rcParams['axes.prop_cycle']
colors = prop_cycle.by_key()['color']
def find_nearest(array,value):
idx = (np.abs(array-value)).argmin()
return idx, array[idx]
rhomin = -8
rhomax = -1
bins = 20
dfs.append(dfs[2])
temp_names = np.copy(names)
temp_names = np.append(temp_names, 'Interaction network, DDT')
sigs.append('Hbb')
bkgs.append('QCD')
mmin = 40
mmax = 200
nbins = 8
min_jsd_eff = 0.01
f, ax = plt.subplots(figsize=(10, 10))
ax.semilogy()
for frame, name, sig, bkg, color in zip(dfs, temp_names, sigs, bkgs, colors):
if name not in ['Interaction network, DDT']:
#frame = frame[:int(len(frame)*min_jsd_eff)]\
truth, predict, db = roc_input(frame, signal=sig, include = sig+bkg, norm=norm)
fpr, tpr, threshold = roc_curve(truth, predict)
print("{}, AUC={}%".format(name, auc(fpr,tpr)*100), "Sig:", sig, "Bkg:", bkg)
print("{}, Acc={}%".format(name, accuracy_score(truth,predict>0.5)*100), "Sig:", sig, "Bkg:", bkg)
cuts = {}
jsd_plot = []
es_plot = []
#for wp,marker in zip([0.005,0.01,0.05,0.1],['v','^','s','o']): # % bkg rej.
for wp,marker in zip([0.01,0.05,0.1],['^','s','o']): # % bkg rej.
idx, val = find_nearest(fpr, wp)
cuts[str(wp)] = threshold[idx] # threshold
jsds = []
for i in range(100):
index = np.random.randint(0, len(frame), int(min_jsd_eff*len(frame)))
mask_pass = (frame.iloc[index]['predict'+sig[0]] > cuts[str(wp)]) & frame.iloc[index]['truth'+bkg[0]]
mask_fail = (frame.iloc[index]['predict'+sig[0]] < cuts[str(wp)]) & frame.iloc[index]['truth'+bkg[0]]
mass = frame.iloc[index]['fj_sdmass'].values
mass_pass = mass[mask_pass]
mass_fail = mass[mask_fail]
#mass_pass_temp = mass_pass[np.random.randint(0, len(mass_pass), int(min_jsd_eff*len(mass_pass)))]
#mass_fail_temp = mass_fail[np.random.randint(0, len(mass_fail), int(min_jsd_eff*len(mass_fail)))]
#mass_pass = mass_pass[:int(min_jsd_eff*len(mass_pass)) + 1]
#mass_fail = mass_fail[:int(min_jsd_eff*len(mass_fail))]
# digitze into bins
spec_pass = np.digitize(mass_pass, bins=np.linspace(mmin,mmax,nbins+1), right=False)-1
spec_fail = np.digitize(mass_fail, bins=np.linspace(mmin,mmax,nbins+1), right=False)-1
# one hot encoding
spec_ohe_pass = np.zeros((spec_pass.shape[0],nbins))
spec_ohe_pass[np.arange(spec_pass.shape[0]),spec_pass] = 1
spec_ohe_pass_sum = np.sum(spec_ohe_pass,axis=0)/spec_ohe_pass.shape[0]
spec_ohe_fail = np.zeros((spec_fail.shape[0],nbins))
spec_ohe_fail[np.arange(spec_fail.shape[0]),spec_fail] = 1
spec_ohe_fail_sum = np.sum(spec_ohe_fail,axis=0)/spec_ohe_fail.shape[0]
M = 0.5*spec_ohe_pass_sum+0.5*spec_ohe_fail_sum
kld_pass = scipy.stats.entropy(spec_ohe_pass_sum,M,base=2)
kld_fail = scipy.stats.entropy(spec_ohe_fail_sum,M,base=2)
jsd = 0.5*kld_pass+0.5*kld_fail
jsds.append(jsd)
jsd = np.mean(jsds)
print('eS = %.2f%%, eB = %.2f%%, 1/eB=%.2f, jsd = %.2f, 1/jsd = %.2f'%(tpr[idx]*100,fpr[idx]*100,1/fpr[idx],jsd,1/jsd))
es_plot.append(tpr[idx])
jsd_plot.append(1/jsd)
ax.plot([tpr[idx]],[1/jsd],marker=marker,markersize=12,color=color)
ax.plot(es_plot,jsd_plot,linestyle='-',label=name,color=color)
else:
#frame_size = int(len(frame)*min_jsd_eff)
#frame = frame[:frame_size]
truth, predict, db = roc_input(frame, signal=sig, include = sig+bkg, norm=norm)
fpr, tpr, threshold = roc_curve(truth, predict)
print("{}, AUC={}%".format(name, auc(fpr,tpr)*100), "Sig:", sig, "Bkg:", bkg)
print("{}, Acc={}%".format(name, accuracy_score(truth,predict>0.5)*100), "Sig:", sig, "Bkg:", bkg)
cuts = {}
jsd_plot = []
es_plot = []
#for wp,marker in zip([0.5,1.,5.,10.],['v','^','s','o']): # % bkg rej.
for wp,marker in zip([1.,5.,10.],['^','s','o']): # % bkg rej.
idx, val = find_nearest(fpr, wp/100)
cuts = quantile_regression_DDT_FPR(cut(frame), cut(frame), wp)
mask_pass = (frame['predict'+sig[0]] > cuts) & frame['truth'+bkg[0]]
mask_fail = (frame['predict'+sig[0]] < cuts) & frame['truth'+bkg[0]]
mass = frame['fj_sdmass'].values
mass_pass = mass[mask_pass]
mass_fail = mass[mask_fail]
#mass_pass_temp = mass_pass[np.random.randint(0, len(mass_pass), int(min_jsd_eff*len(mass_pass)))]
#mass_fail_temp = mass_fail[np.random.randint(0, len(mass_fail), int(min_jsd_eff*len(mass_fail)))]
#mass_pass = mass_pass[:int(min_jsd_eff*len(mass_pass))]
#mass_fail = mass_fail[:int(min_jsd_eff*len(mass_fail))]
# digitze into bins
spec_pass = np.digitize(mass_pass, bins=np.linspace(mmin,mmax,nbins+1), right=False)-1
spec_fail = np.digitize(mass_fail, bins=np.linspace(mmin,mmax,nbins+1), right=False)-1
# one hot encoding
spec_ohe_pass = np.zeros((spec_pass.shape[0],nbins))
spec_ohe_pass[np.arange(spec_pass.shape[0]),spec_pass] = 1
spec_ohe_pass_sum = np.sum(spec_ohe_pass,axis=0)/spec_ohe_pass.shape[0]
spec_ohe_fail = np.zeros((spec_fail.shape[0],nbins))
spec_ohe_fail[np.arange(spec_fail.shape[0]),spec_fail] = 1
spec_ohe_fail_sum = np.sum(spec_ohe_fail,axis=0)/spec_ohe_fail.shape[0]
M = 0.5*spec_ohe_pass_sum+0.5*spec_ohe_fail_sum
kld_pass = scipy.stats.entropy(spec_ohe_pass_sum,M,base=2)
kld_fail = scipy.stats.entropy(spec_ohe_fail_sum,M,base=2)
jsd = 0.5*kld_pass+0.5*kld_fail
print('eS = %.2f%%, eB = %.2f%%, 1/eB=%.2f, jsd = %.2f, 1/jsd = %.2f'%(tpr[idx]*100,fpr[idx]*100,1/fpr[idx],jsd,1/jsd))
es_plot.append(make_TPR_DDT(frame, wp, siglab='QCD', sculp_label='fj_sdmass', taggerName=name))
jsd_plot.append(1/jsd)
ax.plot([make_TPR_DDT(frame, wp, siglab='QCD', sculp_label='fj_sdmass', taggerName=name)],[1/jsd],marker=marker,markersize=12,color=color)
ax.plot(es_plot,jsd_plot,linestyle='-',label=name,color=color)
ax.set_xlim(0,1)
ax.set_ylim(1,5e4)
ax.set_xlabel(r'Tagging efficiency ($\mathrm{H \rightarrow b\bar{b}}$) $\varepsilon_\mathrm{sig}$',ha='right', x=1.0)
ax.set_ylabel(r'Mass decorrelation 1 / $D_\mathrm{JS}$',ha='right', y=1.0)
import matplotlib.ticker as plticker
ax.tick_params(direction='in', axis='both', which='major', labelsize=15, length=12 )
ax.tick_params(direction='in', axis='both', which='minor' , length=6)
ax.xaxis.set_ticks_position('both')
ax.yaxis.set_ticks_position('both')
ax.semilogy()
ax.grid(which='minor', alpha=0.5, linestyle='dotted')
ax.grid(which='major', alpha=0.9, linestyle='dotted')
leg = ax.legend(borderpad=1, frameon=False, loc='upper left', fontsize=16,
title = ""+str(int(round((min(frame.fj_pt)))))+" $\mathrm{<\ jet\ p_T\ <}$ "+str(int(round((max(frame.fj_pt)))))+" GeV" \
+ "\n "+str(int(round((min(frame.fj_sdmass)))))+" $\mathrm{<\ jet\ m_{SD}\ <}$ "+str(int(round((max(frame.fj_sdmass)))))+" GeV"
)
leg._legend_box.align = "left"
circle = mlines.Line2D([], [], color='gray', marker='o', linestyle='None',
markersize=12, label=r'$\varepsilon_\mathrm{bkg}$ = 10\%%')
square = mlines.Line2D([], [], color='gray', marker='s', linestyle='None',
markersize=12, label=r'$\varepsilon_\mathrm{bkg}$ = 5\%%')
utriangle = mlines.Line2D([], [], color='gray', marker='^', linestyle='None',
markersize=12, label=r'$\varepsilon_\mathrm{bkg}$ = 1\%%')
#dtriangle = mlines.Line2D([], [], color='gray', marker='v', linestyle='None',
# markersize=12, label=r'$\varepsilon_\mathrm{bkg}$ = 0.5\%%')
plt.gca().add_artist(leg)
#leg2 = ax.legend(handles=[circle, square, utriangle, dtriangle],fontsize=16,frameon=False,borderpad=1,loc='center left')
leg2 = ax.legend(handles=[circle, square, utriangle],fontsize=16,frameon=False,borderpad=1,loc='upper right')
leg2._legend_box.align = "left"
plt.gca().add_artist(leg2)
ax.annotate(eraText, xy=(0.75, 5.1e4),fontname='Helvetica', ha='left',
bbox={'facecolor':'white', 'edgecolor':'white', 'alpha':0, 'pad':13}, annotation_clip=False)
ax.annotate('$\mathbf{CMS}$', xy=(0, 5.1e4), fontname='Helvetica', fontsize=24, fontweight='bold', ha='left',
bbox={'facecolor':'white', 'edgecolor':'white', 'alpha':0, 'pad':13}, annotation_clip=False)
ax.annotate('$Simulation\ Open\ Data$', xy=(0.105, 5.1e4), fontsize=18, fontstyle='italic', ha='left',
annotation_clip=False)
f.savefig(os.path.join(savedir, "JSD_sig_"+"+".join(sig)+"_vs_"+"+".join(bkg)+".pdf"), dpi=400)
f.savefig(os.path.join(savedir, "JSD_sig_"+"+".join(sig)+"_vs_"+"+".join(bkg)+".png"), dpi=400)
plt.close(f)
def make_TPR_DDT(tdf, FPR_cut=5, siglab="Hcc", sculp_label='Light', savedir="", taggerName=""):
NBINS= 8 # number of bins for loss function
MMAX = 200. # max value
MMIN = 40. # min value
weight = tdf['truth'+'Hbb'].values
bins = np.linspace(40,200,NBINS+1)
correct = sum(weight)
if siglab == sculp_label: return
def find_nearest(array,value):
idx = (np.abs(array-value)).argmin()
return idx, array[idx]
# Placing events in bins to detemine threshold for each individual bin
ctdf = tdf.copy()
ctdf = ctdf.head(0)
cuts = quantile_regression_DDT_FPR(tdf, tdf_train, FPR_cut)
#big_cuts = np.load('DDT_FPRcuts_sdmass.npy')
#cuts = big_cuts.item().get(str(round(FPR_cut, 5)))
ctdf = ctdf.append(tdf.loc[tdf['predict'+'Hbb'].values > cuts[:len(tdf)]])
weight = ctdf['truth'+'Hbb'].values
selected = sum(weight)
return(float(selected)/correct)
def make_FPR_DDT(tdf, TPR_cut=5, siglab="Hcc", sculp_label='Light', savedir="", taggerName=""):
NBINS= 8 # number of bins for loss function
MMAX = 200. # max value
MMIN = 40. # min value
weight = tdf['truth'+'QCD'].values
bins = np.linspace(40,200,NBINS+1)
correct = sum(weight)
def find_nearest(array,value):
idx = (np.abs(array-value)).argmin()
return idx, array[idx]
# Placing events in bins to detemine threshold for each individual bin
ctdf = tdf.copy()
ctdf = ctdf.head(0)
cuts = quantile_regression_DDT_TPR(tdf, tdf_train, TPR_cut)
ctdf = ctdf.append(tdf.loc[tdf['predict'+'Hbb'].values > cuts])
weight = ctdf['truth'+'QCD'].values
selected = sum(weight)
return(float(selected)/(correct))
def DDT_Accuracy(tdf, TPR_cut=50, siglab="Hbb", sculp_label='Light', sig = ['Hbb'], bkg = ["QCD"], savedir="", taggerName=""):
NBINS= 8 # number of bins for loss function
MMAX = 200. # max value
MMIN = 40. # min value
weight_Hbb = tdf['truth'+'Hbb'].values
weight_QCD = tdf['truth'+'Hbb'].values
bins = np.linspace(40,200,NBINS+1)
#correct = sum(weight)
if siglab == sculp_label: return
def find_nearest(array,value):
idx = (np.abs(array-value)).argmin()
return idx, array[idx]
if siglab[0] in ["H", "Z", "g"] and len(siglab) == 3:
legend_siglab = '{} \\rightarrow {}'.format(siglab[0], siglab[-2]+'\\bar{'+siglab[-1]+'}')
legend_siglab = '$\mathrm{}$'.format('{'+legend_siglab+'}')
else:
legend_siglab = siglab
if sculp_label[0] in ["H", "Z", "g"] and len(sculp_label) == 3:
legend_bkglab = '{} \\rightarrow {}'.format(sculp_label[0], sculp_label[-2]+'\\bar{'+sculp_label[-1]+'}')
legend_bkglab = '$\mathrm{}$'.format('{'+legend_bkglab+'}')
else: legend_bkglab = sculp_label
# Placing events in bins to detemine threshold for each individual bin
ctdf = tdf.copy()
ctdf = ctdf.head(0)
cuts = quantile_regression_DDT_FPR(tdf, tdf_train, TPR_cut)
#big_cuts = np.load('DDT_FPRcuts_sdmass.npy')
#cuts = big_cuts.item().get(str(round(FPR_cut, 5)))
ctdf = ctdf.append(tdf.loc[tdf['predict'+'Hbb'].values > cuts])
truth, predict, db = roc_input(ctdf, signal=sig, include = sig+bkg, norm=False)
accuracy = accuracy_score(truth, predict>0.5)
weight = ctdf['truth'+'Hbb'].values
selected = sum(weight)
return(accuracy)
def make_DDT(tdf, FPR_cut=[], siglab="Hcc", sculp_label='Light', savedir="", taggerName=""):
#############################################################
### This method is depricated in favor of GBR DDT Methods ###
#############################################################
NBINS= 8 # number of bins for loss function
MMAX = 200. # max value
MMIN = 40. # min value
bins = np.linspace(MMIN,MMAX,NBINS+1)
'''
weight = tdf['truth'+'Hbb'].values
bins = np.linspace(40,200,NBINS+1)
values, bins, _ = plt.hist(tdf['fj_sdmass'].values, bins=bins, weights = weight, lw=2, normed=False,
histtype='step',label='{}\% FPR Cut QCD'.format(FPR_cut))
correct = sum(values)
'''
print('Setting DDT cut to {}%'.format(FPR_cut))
if siglab == sculp_label: return
def find_nearest(array,value):
idx = (np.abs(array-value)).argmin()
return idx, array[idx]
if siglab[0] in ["H", "Z", "g"] and len(siglab) == 3:
legend_siglab = '{} \\rightarrow {}'.format(siglab[0], siglab[-2]+'\\bar{'+siglab[-1]+'}')
legend_siglab = '$\mathrm{}$'.format('{'+legend_siglab+'}')
else:
legend_siglab = siglab
if sculp_label[0] in ["H", "Z", "g"] and len(sculp_label) == 3:
legend_bkglab = '{} \\rightarrow {}'.format(sculp_label[0], sculp_label[-2]+'\\bar{'+sculp_label[-1]+'}')
legend_bkglab = '$\mathrm{}$'.format('{'+legend_bkglab+'}')
else: legend_bkglab = sculp_label
f, ax = plt.subplots(figsize=(10,10))
big_cuts = np.load('DDT_FPRcuts_sdmass.npy') #premade DDT cuts
#big_cuts = {}
ctdf = tdf.copy()
ctdf = ctdf.head(0)
dataframes_cut = [ctdf for i in range(len(FPR_cut))]
for FPR in range(len(FPR_cut)):
cuts = big_cuts.item().get(str(round(FPR_cut[FPR], 5)))
cuts = quantile_regression_DDT(tdf, tdf_train, FPR_cut[FPR])
#big_cuts[str(round(FPR_cut[FPR], 5))] = cuts
dataframes_cut[FPR] = dataframes_cut[FPR].append(tdf.loc[tdf['predict'+'Hbb'].values > cuts])
f, ax = plt.subplots(figsize=(10,10))
h_list = []
weight_uncut = tdf['truth'+'QCD'].values.astype(float)
n, binEdges = np.histogram(tdf.loc[tdf['truth'+'QCD'] == 1]['fj_sdmass'].values, bins=bins)
#h_list.append(create_TH1D(tdf['fj_sdmass'].values, name='No tagging applied', title=None, binning=bins, weights=weight_uncut/np.sum(weight_uncut), h2clone=None, axis_title = ['Soft-Drop Mass', 'Normalized Scale (QCD)'], opt='', color = 1))
#h_list[-1].SetMarkerStyle(20)
#h_list[-1].SetMarkerColor(1)
#h_list[-1].SetStats(0)
#h_list[-1].SetLineWidth(2)
colorcode = [2, 5, 6, 8, 9]
for FPR in range(len(FPR_cut)):
weight = dataframes_cut[FPR]['truth'+'QCD'].values.astype(float)
ax.hist(dataframes_cut[FPR]['fj_sdmass'].values, bins=bins,
weights=weight/np.sum(weight),
lw=2,
normed=False,
histtype='step',
label='{}\% mistagging rate'.format(FPR_cut[FPR]),
color='C'+str(FPR)
)
n, binEdges = np.histogram(dataframes_cut[FPR].loc[dataframes_cut[FPR]['truth'+'QCD'] == 1]['fj_sdmass'].values, bins=bins)
#h_list.append(create_TH1D(dataframes_cut[FPR]['fj_sdmass'].values, name='{}% mistagging rate'.format(FPR_cut[FPR]), title=None, binning=bins, weights=weight/np.sum(weight), h2clone=None, axis_title = ['Soft-Drop Mass', 'Normalized Scale (QCD)'], opt='', color = colorcode[FPR]))
#h_list[-1].SetStats(0)
#h_list[-1].SetLineWidth(2)
err = np.sqrt(n)
bincenters = 0.5*(binEdges[1:]+binEdges[:-1])
#plt.errorbar(bincenters, n/np.sum(n), yerr=err/np.sum(n), fmt='none', ecolor='C'+str(FPR))
#plot = make_ratio_plot(h_list, title = "", label = "", in_tags = None, ratio_bounds = [0.6, 1.4], draw_opt = 'E1')
#plot.SaveAs(os.path.join(savedir,'Ratio_Plot_SDmass_QCD.pdf'))
ax.hist(tdf['fj_sdmass'].values, bins=bins, weights = weight_uncut/np.sum(weight_uncut), lw=2, normed=False,
histtype='step',label='No tagging applied')
#values, bins, _ = plt.hist(ctdf['fj_sdmass'].values, bins=bins, weights = weight, lw=2, normed=False,
# histtype='step',label='{}\% FPR Cut QCD'.format(FPR_cut))
#selected = sum(values)
#print('TPR IS: ' + str(selected/correct))
ax.set_xlabel(r'$\mathrm{m_{SD}\ [GeV]}$', ha='right', x=1.0)
ax.set_ylabel(r'Normalized scale ({})'.format('QCD'), ha='right', y=1.0)
import matplotlib.ticker as plticker
ax.xaxis.set_major_locator(plticker.MultipleLocator(base=20))
ax.xaxis.set_minor_locator(plticker.MultipleLocator(base=10))
ax.yaxis.set_minor_locator(plticker.AutoMinorLocator(5))
ax.set_xlim(40, 200)
ax.set_ylim(0, 0.45)
ax.tick_params(direction='in', axis='both', which='major', labelsize=15, length=12)#, labelleft=False )
ax.tick_params(direction='in', axis='both', which='minor' , length=6)
ax.xaxis.set_ticks_position('both')
ax.yaxis.set_ticks_position('both')
#ax.grid(which='minor', alpha=0.5, axis='y', linestyle='dotted')
ax.grid(which='major', alpha=0.9, linestyle='dotted')
leg = ax.legend(borderpad=1, frameon=False, loc='best', fontsize=16,
title = ""+str(int(round((min(frame.fj_pt)))))+" $\mathrm{<\ jet\ p_T\ <}$ "+str(int(round((max(frame.fj_pt)))))+" GeV" \
+ "\n "+str(int(round((min(frame.fj_sdmass)))))+" $\mathrm{<\ jet\ m_{SD}\ <}$ "+str(int(round((max(frame.fj_sdmass)))))+" GeV"
+ "\n {} tagging {}".format(taggerName, legend_siglab) )
leg._legend_box.align = "right"
ax.annotate(eraText, xy=(0.75, 1.015), xycoords='axes fraction', fontname='Helvetica', ha='left',
bbox={'facecolor':'white', 'edgecolor':'white', 'alpha':0, 'pad':13}, annotation_clip=False)
ax.annotate('$\mathbf{CMS}$', xy=(0, 1.015), xycoords='axes fraction', fontname='Helvetica', fontsize=24, fontweight='bold', ha='left',
bbox={'facecolor':'white', 'edgecolor':'white', 'alpha':0, 'pad':13}, annotation_clip=False)
ax.annotate('$Simulation\ Open\ Data$', xy=(0.105, 1.015), xycoords='axes fraction', fontsize=18, fontstyle='italic', ha='left',
annotation_clip=False)
f.savefig(os.path.join(savedir,'DDT_QCD_tag'+'QCD_cut' + '.png'), dpi=400)
f.savefig(os.path.join(savedir,'DDT_QCD_tag'+'QCD_cut' + '.pdf'), dpi=400)
# Plot Hbb distribution with the same 5% QCD cut
f, ax = plt.subplots(figsize=(10,10))
ctdf = tdf.copy()
ctdf = ctdf.head(0)
f, ax = plt.subplots(figsize=(10,10))
weight_uncut = tdf['truth'+'Hbb'].values.astype(float)
for FPR in range(len(FPR_cut)):
weight = dataframes_cut[FPR]['truth'+'Hbb'].values.astype(float)
ax.hist(dataframes_cut[FPR]['fj_sdmass'].values, bins=bins,
weights=weight/np.sum(weight),
lw=2,
normed=False,
histtype='step',
label='{}\% mistagging rate'.format(FPR_cut[FPR]),
color='C'+str(FPR)
)
#n, binEdges = np.histogram(dataframes_cut[FPR].loc[dataframes_cut[FPR]['truth'+'Hbb'] == 1]['fj_sdmass'].values, bins=bins)
#h_list.append(n)
#h_list.append(create_TH1D(dataframes_cut[FPR]['fj_sdmass'].values, name='{}% mistagging rate'.format(FPR_cut[FPR]), title=None, binning=bins, weights=weight/np.sum(weight), h2clone=None, axis_title = ['Soft-Drop Mass', 'Normalized Scale (Hbb)'], opt='', color = colorcode[FPR]))
#h_list[-1].SetStats(0)
#err = np.sqrt(n)
#bincenters = 0.5*(binEdges[1:]+binEdges[:-1])
#plt.errorbar(bincenters, n/np.sum(n), yerr=err/np.sum(n), fmt='none', ecolor='C'+str(FPR))
#plot = make_ratio_plot(h_list, title = "", label = "", in_tags = None, ratio_bounds = [0.8, 1.2], draw_opt = 'E1')
#plot.SaveAs(os.path.join(savedir,'Ratio_Plot_SDmass_Hbb.pdf'))
ax.hist(tdf['fj_sdmass'].values, bins=bins, weights = weight_uncut/np.sum(weight_uncut), lw=2, normed=False,
histtype='step',label='No tagging applied')
ax.set_xlabel(r'$\mathrm{m_{SD}\ [GeV]}$', ha='right', x=1.0)
ax.set_ylabel(r'Normalized scale ({})'.format('Hbb'), ha='right', y=1.0)
import matplotlib.ticker as plticker
ax.xaxis.set_major_locator(plticker.MultipleLocator(base=20))
ax.xaxis.set_minor_locator(plticker.MultipleLocator(base=10))
ax.yaxis.set_minor_locator(plticker.AutoMinorLocator(5))
ax.set_xlim(40, 200)
ax.set_ylim(0, 0.6)
ax.tick_params(direction='in', axis='both', which='major', labelsize=15, length=12)#, labelleft=False )
ax.tick_params(direction='in', axis='both', which='minor' , length=6)
ax.xaxis.set_ticks_position('both')
ax.yaxis.set_ticks_position('both')
#ax.grid(which='minor', alpha=0.5, axis='y', linestyle='dotted')
ax.grid(which='major', alpha=0.9, linestyle='dotted')
leg = ax.legend(borderpad=1, frameon=False, loc='best', fontsize=16,
title = ""+str(int(round((min(frame.fj_pt)))))+" $\mathrm{<\ jet\ p_T\ <}$ "+str(int(round((max(frame.fj_pt)))))+" GeV" \
+ "\n "+str(int(round((min(frame.fj_sdmass)))))+" $\mathrm{<\ jet\ m_{SD}\ <}$ "+str(int(round((max(frame.fj_sdmass)))))+" GeV"
+ "\n {} tagging {}".format(taggerName, legend_siglab) )
leg._legend_box.align = "right"
ax.annotate(eraText, xy=(0.75, 1.015), xycoords='axes fraction', fontname='Helvetica', ha='left',
bbox={'facecolor':'white', 'edgecolor':'white', 'alpha':0, 'pad':13}, annotation_clip=False)
ax.annotate('$\mathbf{CMS}$', xy=(0, 1.015), xycoords='axes fraction', fontname='Helvetica', fontsize=24, fontweight='bold', ha='left',
bbox={'facecolor':'white', 'edgecolor':'white', 'alpha':0, 'pad':13}, annotation_clip=False)
ax.annotate('$Simulation\ Open\ Data$', xy=(0.105, 1.015), xycoords='axes fraction', fontsize=18, fontstyle='italic', ha='left',