-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathheader.py
1453 lines (1242 loc) · 58.8 KB
/
header.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 ROOT
from ROOT import *
from contextlib import contextmanager
import os, pickle, subprocess, time,random
import math, collections
from math import sqrt
import array
import json
import CMS_lumi, tdrstyle
import pprint
pp = pprint.PrettyPrinter(indent = 2)
def setSnapshot(d=''):
# header.executeCmd('combine -M MultiDimFit -d '+base_workspace+' --saveWorkspace --freezeParameters r --setParameters r=0,'+mask_string)
# f = TFile.Open('higgsCombineTest.MultiDimFit.mH120.root')
# w = f.Get('w')
# w.loadSnapshot("MultiDimFit")
# w.var("r").setConstant(0)
# w.var("r").setVal(0)
# w.var("r").setMin(-20)
# w.var("r").setMax(20)
# myargs = RooArgSet(w.allVars())
# myargs.add(w.allCats())
# w.saveSnapshot("initialFit",myargs)
# fout = TFile('initialFitWorkspace.root',"recreate")
# fout.WriteTObject(w,'w')
# fout.Close()
w_f = TFile.Open(d+'higgsCombineTest.FitDiagnostics.mH120.root')
w = w_f.Get('w')
fr_f = TFile.Open(d+'fitDiagnostics.root')
fr = fr_f.Get('fit_b')
myargs = RooArgSet(fr.floatParsFinal())
w.saveSnapshot('initialFit',myargs,True)
fout = TFile('initialFitWorkspace.root',"recreate")
fout.WriteTObject(w,'w')
fout.Close()
# Function stolen from https://stackoverflow.com/questions/9590382/forcing-python-json-module-to-work-with-ascii
def openJSON(f,twoDconfig=True):
with open(f) as fInput_config:
input_config = json.load(fInput_config, object_hook=ascii_encode_dict) # Converts most of the unicode to ascii
if twoDconfig:
for process in [proc for proc in input_config['PROCESS'].keys() if proc != 'HELP']:
for index,item in enumerate(input_config['PROCESS'][process]['SYSTEMATICS']): # There's one list that also
input_config['PROCESS'][process]['SYSTEMATICS'][index] = item.encode('ascii')
return input_config
def ascii_encode_dict(data):
ascii_encode = lambda x: x.encode('ascii') if isinstance(x, unicode) else x
return dict(map(ascii_encode, pair) for pair in data.items())
def copyHistWithNewXbins(thisHist,newXbins,copyName):
# Make a copy with the same Y bins but new X bins
ybins = []
for iy in range(1,thisHist.GetNbinsY()+1):
ybins.append(thisHist.GetYaxis().GetBinLowEdge(iy))
ybins.append(thisHist.GetYaxis().GetXmax())
ybins_array = array.array('f',ybins)
ynbins = len(ybins_array)-1
xbins_array = array.array('f',newXbins)
xnbins = len(xbins_array)-1
# Use copyName with _temp to avoid overwriting if thisHist has the same name
# We can do this at the end but not before we're finished with thisHist
hist_copy = TH2F(copyName+'_temp',copyName+'_temp',xnbins,xbins_array,ynbins,ybins_array)
hist_copy.Sumw2()
hist_copy.GetXaxis().SetName(thisHist.GetXaxis().GetName())
hist_copy.GetYaxis().SetName(thisHist.GetYaxis().GetName())
# Loop through the old bins
for ybin in range(1,ynbins+1):
# print 'Bin y: ' + str(binY)
for xbin in range(1,xnbins+1):
new_bin_content = 0
new_bin_errorsq = 0
new_bin_min = hist_copy.GetXaxis().GetBinLowEdge(xbin)
new_bin_max = hist_copy.GetXaxis().GetBinUpEdge(xbin)
# print '\t New bin x: ' + str(newBinX) + ', ' + str(newBinXlow) + ', ' + str(newBinXhigh)
for old_xbin in range(1,thisHist.GetNbinsX()+1):
old_bin_min = thisHist.GetXaxis().GetBinLowEdge(old_xbin)
old_bin_max = thisHist.GetXaxis().GetBinUpEdge(old_xbin)
if old_bin_min >= new_bin_max:
break
elif old_bin_min >= new_bin_min and old_bin_min < new_bin_max:
if old_bin_max <= new_bin_max:
new_bin_content += thisHist.GetBinContent(old_xbin,ybin)
new_bin_errorsq += thisHist.GetBinError(old_xbin,ybin)**2
elif old_bin_max > new_bin_max:
raise ValueError(
'''The requested X rebinning does not align bin edges with the input bin edge.
Cannot split input bin [%s,%s] with output bin [%s,%s]'''%(old_bin_min,old_bin_max,new_bin_min,new_bin_max))
elif old_bin_min <= new_bin_min and old_bin_max > new_bin_min:
raise ValueError(
'''The requested Y rebinning does not align bin edges with the input bin edge.
Cannot split input bin [%s,%s] with output bin [%s,%s]'''%(old_bin_min,old_bin_max,new_bin_min,new_bin_max))
# print '\t Setting content ' + str(newBinContent) + '+/-' + str(sqrt(newBinErrorSq))
if new_bin_content > 0:
hist_copy.SetBinContent(xbin,ybin,new_bin_content)
hist_copy.SetBinError(xbin,ybin,sqrt(new_bin_errorsq))
# Will now set the copyName which will overwrite thisHist if it has the same name
hist_copy.SetName(copyName)
hist_copy.SetTitle(copyName)
return hist_copy
def copyHistWithNewYbins(thisHist,newYbins,copyName):
# Make a copy with the same X bins but new Y bins
xbins = []
for ix in range(1,thisHist.GetNbinsX()+1):
xbins.append(thisHist.GetXaxis().GetBinLowEdge(ix))
xbins.append(thisHist.GetXaxis().GetXmax())
xbins_array = array.array('f',xbins)
xnbins = len(xbins_array)-1
ybins_array = array.array('f',newYbins)
ynbins = len(ybins_array)-1
# Use copyName with _temp to avoid overwriting if thisHist has the same name
# We can do this at the end but not before we're finished with thisHist
hist_copy = TH2F(copyName+'_temp',copyName+'_temp',xnbins,xbins_array,ynbins,ybins_array)
hist_copy.Sumw2()
hist_copy.GetXaxis().SetName(thisHist.GetXaxis().GetName())
hist_copy.GetYaxis().SetName(thisHist.GetYaxis().GetName())
# Loop through the old bins
for xbin in range(1,xnbins+1):
# print 'Bin y: ' + str(binY)
for ybin in range(1,ynbins+1):
new_bin_content = 0
new_bin_errorsq = 0
new_bin_min = hist_copy.GetYaxis().GetBinLowEdge(ybin)
new_bin_max = hist_copy.GetYaxis().GetBinUpEdge(ybin)
# print '\t New bin x: ' + str(newBinX) + ', ' + str(newBinXlow) + ', ' + str(newBinXhigh)
for old_ybin in range(1,thisHist.GetNbinsY()+1):
old_bin_min = thisHist.GetYaxis().GetBinLowEdge(old_ybin)
old_bin_max = thisHist.GetYaxis().GetBinUpEdge(old_ybin)
if old_bin_min >= new_bin_max:
break
elif old_bin_min >= new_bin_min and old_bin_min < new_bin_max:
if old_bin_max <= new_bin_max:
new_bin_content += thisHist.GetBinContent(xbin,old_ybin)
new_bin_errorsq += thisHist.GetBinError(xbin,old_ybin)**2
elif old_bin_max > new_bin_max:
raise ValueError(
'''The requested Y rebinning does not align bin edges with the input bin edge.
Cannot split input bin [%s,%s] with output bin [%s,%s]'''%(old_bin_min,old_bin_max,new_bin_min,new_bin_max))
elif old_bin_min <= new_bin_min and old_bin_max > new_bin_min:
raise ValueError(
'''The requested Y rebinning does not align bin edges with the input bin edge.
Cannot split input bin [%s,%s] with output bin [%s,%s]'''%(old_bin_min,old_bin_max,new_bin_min,new_bin_max))
# print '\t Setting content ' + str(newBinContent) + '+/-' + str(sqrt(newBinErrorSq))
if new_bin_content > 0:
hist_copy.SetBinContent(xbin,ybin,new_bin_content)
hist_copy.SetBinError(xbin,ybin,sqrt(new_bin_errorsq))
# Will now set the copyName which will overwrite thisHist if it has the same name
hist_copy.SetName(copyName)
hist_copy.SetTitle(copyName)
return hist_copy
def ConvertToEvtsPerUnit(hist,width=None):
if width == None:
use_width = GetMinWidth(hist)
else:
use_width = width
converted = hist.Clone()
for ibin in range(1,hist.GetNbinsX()+1):
if hist.GetBinWidth(ibin) == use_width:
continue
else:
factor = use_width/hist.GetBinWidth(ibin)
new_content = factor * converted.GetBinContent(ibin)
new_error = factor * converted.GetBinError(ibin)
converted.SetBinContent(ibin,new_content)
converted.SetBinError(ibin,new_error)
return converted
def GetMinWidth(hist):
use_width = 10**6
for ibin in range(1,hist.GetNbinsX()+1):
if hist.GetBinWidth(ibin) < use_width:
use_width = hist.GetBinWidth(ibin)
return int(use_width)
def smoothHist2D(name,histToSmooth,renormalize=False,iterate=1,skipEdges=False):
print "Smoothing "+name
if renormalize: norm = histToSmooth.Integral()
smoothed_hist = histToSmooth.Clone(name)
smoothed_hist.Reset()
smoothed_hist.Sumw2()
for ix in range(1,histToSmooth.GetNbinsX()+1):
for iy in range(1,histToSmooth.GetNbinsY()+1):
bin_contents = [histToSmooth.GetBinContent(ix,iy)]
if ix == 1:
if iy == 1: # lower left corner
if skipEdges: pass
else:
bin_contents.append(histToSmooth.GetBinContent(ix+1,iy ))
bin_contents.append(histToSmooth.GetBinContent(ix+1,iy+1))
bin_contents.append(histToSmooth.GetBinContent(ix ,iy+1))
elif iy == histToSmooth.GetNbinsY(): # upper left corner
if skipEdges: pass
else:
bin_contents.append(histToSmooth.GetBinContent(ix+1,iy ))
bin_contents.append(histToSmooth.GetBinContent(ix+1,iy-1))
bin_contents.append(histToSmooth.GetBinContent(ix ,iy-1))
else: # left wall
if not skipEdges:
bin_contents.append(histToSmooth.GetBinContent(ix+1,iy+1))
bin_contents.append(histToSmooth.GetBinContent(ix+1,iy ))
bin_contents.append(histToSmooth.GetBinContent(ix+1,iy-1))
bin_contents.append(histToSmooth.GetBinContent(ix ,iy+1))
bin_contents.append(histToSmooth.GetBinContent(ix ,iy-1))
elif ix == histToSmooth.GetNbinsX():
if iy == 1: # lower right corner
if skipEdges: pass
else:
bin_contents.append(histToSmooth.GetBinContent(ix-1,iy ))
bin_contents.append(histToSmooth.GetBinContent(ix-1,iy+1))
bin_contents.append(histToSmooth.GetBinContent(ix ,iy+1))
elif iy == histToSmooth.GetNbinsY(): # upper right corner
if skipEdges: pass
else:
bin_contents.append(histToSmooth.GetBinContent(ix-1,iy ))
bin_contents.append(histToSmooth.GetBinContent(ix-1,iy-1))
bin_contents.append(histToSmooth.GetBinContent(ix ,iy-1))
else: # right wall
if not skipEdges:
bin_contents.append(histToSmooth.GetBinContent(ix-1,iy+1))
bin_contents.append(histToSmooth.GetBinContent(ix-1,iy ))
bin_contents.append(histToSmooth.GetBinContent(ix-1,iy-1))
bin_contents.append(histToSmooth.GetBinContent(ix ,iy+1))
bin_contents.append(histToSmooth.GetBinContent(ix ,iy-1))
else:
if iy == 1: # bottom wall
if not skipEdges:
bin_contents.append(histToSmooth.GetBinContent(ix-1,iy+1))
bin_contents.append(histToSmooth.GetBinContent(ix ,iy+1))
bin_contents.append(histToSmooth.GetBinContent(ix+1,iy+1))
bin_contents.append(histToSmooth.GetBinContent(ix-1,iy ))
bin_contents.append(histToSmooth.GetBinContent(ix+1,iy ))
elif iy == histToSmooth.GetNbinsY(): # top wall
if not skipEdges:
bin_contents.append(histToSmooth.GetBinContent(ix-1,iy-1))
bin_contents.append(histToSmooth.GetBinContent(ix ,iy-1))
bin_contents.append(histToSmooth.GetBinContent(ix+1,iy-1))
bin_contents.append(histToSmooth.GetBinContent(ix-1,iy ))
bin_contents.append(histToSmooth.GetBinContent(ix+1,iy ))
else: # full square
bin_contents.append(histToSmooth.GetBinContent(ix+1,iy+1))
bin_contents.append(histToSmooth.GetBinContent(ix ,iy+1))
bin_contents.append(histToSmooth.GetBinContent(ix-1,iy+1))
bin_contents.append(histToSmooth.GetBinContent(ix+1,iy ))
# bin_contents.append(histToSmooth.GetBinContent(ix ,iy ))
bin_contents.append(histToSmooth.GetBinContent(ix-1,iy ))
bin_contents.append(histToSmooth.GetBinContent(ix+1,iy-1))
bin_contents.append(histToSmooth.GetBinContent(ix ,iy-1))
bin_contents.append(histToSmooth.GetBinContent(ix-1,iy-1))
avg = 0
for b in bin_contents: avg += b
avg = avg/len(bin_contents)
smoothed_hist.SetBinContent(ix,iy,avg)
if renormalize:
smoothed_norm = smoothed_hist.Integral()
smoothed_hist.Scale(norm/smoothed_norm)
if iterate > 1: smoothed_hist = smoothHist2D(name+str(iterate),smoothed_hist,iterate=iterate-1)
return smoothed_hist
def zeroNegativeBins(name,inhist):
outhist = inhist.Clone(name)
outhist.Reset()
for ix in range(1,inhist.GetNbinsX()):
for iy in range(1,inhist.GetNbinsY()):
content = max(0,inhist.GetBinContent(ix,iy))
outhist.SetBinContent(ix,iy,content)
if content == 0: outhist.SetBinError(ix,iy,0)
else: outhist.SetBinError(ix,iy,inhist.GetBinError(ix,iy))
return outhist
def stitchHistsInX(name,xbins,ybins,thisHistList,blinded=[]):
# Required that thisHistList be in order of desired stitching
# `blinded` is a list of the index of regions you wish to skip/blind
axbins = array.array('d',xbins)
aybins = array.array('d',ybins)
stitched_hist = TH2F(name,name,len(xbins)-1,axbins,len(ybins)-1,aybins)
bin_jump = 0
for i,h in enumerate(thisHistList):
if i in blinded:
bin_jump += thisHistList[i].GetNbinsX()
continue
for ybin in range(1,h.GetNbinsY()+1):
for xbin in range(1,h.GetNbinsX()+1):
stitched_xindex = xbin + bin_jump
stitched_hist.SetBinContent(stitched_xindex,ybin,h.GetBinContent(xbin,ybin))
stitched_hist.SetBinError(stitched_xindex,ybin,h.GetBinError(xbin,ybin))
bin_jump += thisHistList[i].GetNbinsX()
return stitched_hist
def rebinY(thisHist,name,tag,new_y_bins_array):
xnbins = thisHist.GetNbinsX()
xmin = thisHist.GetXaxis().GetXmin()
xmax = thisHist.GetXaxis().GetXmax()
rebinned = TH2F(name,name,xnbins,xmin,xmax,len(new_y_bins_array)-1,new_y_bins_array)
# print new_y_bins_array
# print rebinned.GetYaxis().GetBinUpEdge(len(new_y_bins_array)-1)
rebinned.Sumw2()
for xbin in range(1,xnbins+1):
newBinContent = 0
newBinErrorSq = 0
rebinHistYBin = 1
nybins = 0
for ybin in range(1,thisHist.GetNbinsY()+1):
# If upper edge of old Rpf ybin is < upper edge of rebinHistYBin then add the Rpf bin to the count
if thisHist.GetYaxis().GetBinUpEdge(ybin) < rebinned.GetYaxis().GetBinUpEdge(rebinHistYBin):
newBinContent += thisHist.GetBinContent(xbin,ybin)
newBinErrorSq += thisHist.GetBinError(xbin,ybin)**2
nybins+=1
# If ==, add to newBinContent, assign newBinContent to current rebinHistYBin, move to the next rebinHistYBin, and restart newBinContent at 0
elif thisHist.GetYaxis().GetBinUpEdge(ybin) == rebinned.GetYaxis().GetBinUpEdge(rebinHistYBin):
newBinContent += thisHist.GetBinContent(xbin,ybin)
newBinErrorSq += thisHist.GetBinError(xbin,ybin)**2
nybins+=1
rebinned.SetBinContent(xbin, rebinHistYBin, newBinContent/float(nybins))
rebinned.SetBinError(xbin, rebinHistYBin, sqrt(newBinErrorSq)/float(nybins))# NEED TO SET BIN ERRORS
rebinHistYBin += 1
newBinContent = 0
newBinErrorSq = 0
nybins = 0
else:
print 'ERROR when doing psuedo-2D y rebin approximation. Slices do not line up on y bin edges'
print 'Input bin upper edge = '+str(thisHist.GetYaxis().GetBinUpEdge(ybin))
print 'Rebin upper edge = '+str(rebinned.GetYaxis().GetBinUpEdge(rebinHistYBin))
quit()
makeCan(name+'_rebin_compare',tag,[rebinned,thisHist])
return rebinned
def splitBins(binList, sigLow, sigHigh):
return_bins = {'LOW':[],'SIG':[],'HIGH':[]}
for b in binList:
if b <= sigLow:
return_bins['LOW'].append(b)
if b >= sigLow and b <= sigHigh:
return_bins['SIG'].append(b)
if b >= sigHigh:
return_bins['HIGH'].append(b)
return return_bins
def remapToUnity(hist):
# Map to [-1,1]
ybins = array.array('d',[(hist.GetYaxis().GetBinLowEdge(b)-hist.GetYaxis().GetXmin())/(hist.GetYaxis().GetXmax()-hist.GetYaxis().GetXmin()) for b in range(1,hist.GetNbinsY()+1)]+[1])
xbins = array.array('d',[(hist.GetXaxis().GetBinLowEdge(b)-hist.GetXaxis().GetXmin())/(hist.GetXaxis().GetXmax()-hist.GetXaxis().GetXmin()) for b in range(1,hist.GetNbinsX()+1)]+[1])
remap = TH2F(hist.GetName()+'_unit',hist.GetName()+'_unit',hist.GetNbinsX(),xbins,hist.GetNbinsY(),ybins)
remap.Sumw2()
for xbin in range(hist.GetNbinsX()+1):
for ybin in range(hist.GetNbinsY()+1):
remap.SetBinContent(xbin,ybin,hist.GetBinContent(xbin,ybin))
remap.SetBinError(xbin,ybin,hist.GetBinError(xbin,ybin))
return remap
def makeBlindedHist(nomHist,sigregion):
# Grab stuff to make it easier to read
xlow = nomHist.GetXaxis().GetXmin()
xhigh = nomHist.GetXaxis().GetXmax()
xnbins = nomHist.GetNbinsX()
ylow = nomHist.GetYaxis().GetXmin()
yhigh = nomHist.GetYaxis().GetXmax()
ynbins = nomHist.GetNbinsY()
blindName = nomHist.GetName()
# Need to change nominal hist name or we'll get a memory leak
nomHist.SetName(blindName+'_unblinded')
blindedHist = TH2F(blindName,blindName,xnbins,xlow,xhigh,ynbins,ylow,yhigh)
blindedHist.Sumw2()
for binY in range(1,ynbins+1):
# Fill only those bins outside the signal region
for binX in range(1,xnbins+1):
if nomHist.GetXaxis().GetBinUpEdge(binX) <= sigregion[0] or nomHist.GetXaxis().GetBinLowEdge(binX) >= sigregion[1]:
if nomHist.GetBinContent(binX,binY) > 0:
blindedHist.SetBinContent(binX,binY,nomHist.GetBinContent(binX,binY))
blindedHist.SetBinError(binX,binY,nomHist.GetBinError(binX,binY))
return blindedHist
def makeRDH(myTH2,RAL_vars,altname=''):
name = myTH2.GetName()
if altname != '':
name = altname
thisRDH = RooDataHist(name,name,RAL_vars,myTH2)
return thisRDH
def makeRHP(myRDH,RAL_vars):
name = myRDH.GetName()
thisRAS = RooArgSet(RAL_vars)
thisRHP = RooHistPdf(name,name,thisRAS,myRDH)
return thisRHP
def colliMate(myString,width=18):
sub_strings = myString.split(' ')
new_string = ''
for i,sub_string in enumerate(sub_strings):
string_length = len(sub_string)
n_spaces = width - string_length
if i != len(sub_strings)-1:
if n_spaces <= 0:
n_spaces = 2
new_string += sub_string + ' '*n_spaces
else:
new_string += sub_string
return new_string
def dictStructureCopy(inDict):
newDict = {}
for k1,v1 in inDict.items():
if type(v1) == dict:
newDict[k1] = dictStructureCopy(v1)
else:
newDict[k1] = 0
return newDict
def dictCopy(inDict):
newDict = {}
for k1,v1 in inDict.items():
if type(v1) == dict:
newDict[k1] = dictCopy(v1)
else:
newDict[k1] = v1
return newDict
def printWorkspace(myfile,myworkspace):
myf = TFile.Open(myfile)
myw = myf.Get(myworkspace)
myw.Print()
def ftestInfoLookup(projInfoDict):
nrpfparams = 0
nbins = 0
for k in projInfoDict.keys():
this_nrpfparams = len(projInfoDict[k]['rpfVarNames'])
this_nbins = (len(projInfoDict[k]['full_x_bins'])-1) * (len(projInfoDict[k]['newYbins'])-1)
if projInfoDict[k]['blindedFit'] == True:
this_nbins = this_nbins - ( (len(projInfoDict[k]['newXbins']['SIG'])-1) * (len(projInfoDict[k]['newYbins'])-1) )
nrpfparams+=this_nrpfparams
nbins+=this_nbins
return nrpfparams,nbins
def FStatCalc(filename1,filename2,p1,p2,n):
print 'Calculating F statistic'
# Flip flop to make sure p2 is always greater than p1 (more parameters should always fit better)
if p1 > p2:
p1, p2 = p2, p1
filename1, filename2 = filename2, filename1
print 'Files: ',filename1,filename2
print 'Parameters: p1 %f, p2 %f, n %f'%(p1,p2,n)
# Get limit trees from each file
file1 = TFile.Open(filename1)
tree1 = file1.Get("limit")
file2 = TFile.Open(filename2)
tree2 = file2.Get("limit")
diffs=[]
# print 'Entries ',tree1.GetEntries(),tree2.GetEntries()
# Loop over entries and calculate the F statistics
for i in range(0,tree1.GetEntries()):
tree1.GetEntry(i)
tree2.GetEntry(i)
# print 'Limits ',tree1.limit,tree2.limit
if tree1.limit-tree2.limit>0:
F = (tree1.limit-tree2.limit)/(p2-p1)/(tree2.limit/(n-p2))
# print 'Entry ',i, ":", tree2.limit, "-", tree1.limit, "=", tree2.limit-tree1.limit, "F =", F
# if F < 50:
diffs.append(F)
else:
print 'WARNING in calculation of F statistic for entry %i. limit1-limit2 <=0 (%f - %f)' %(i,tree1.limit,tree2.limit)
diffs.append(0)
# print 'Diffs F stat: ',diffs
return diffs
def makeToyCard(channelNames):
# Open a new card
toy_gen_card = open('card_toygen.txt','w')
column_width = 20
nchannels = len(channelNames) # imax
nprocesses = 1 # jmax
nsystematics = 0 # kmax
toy_gen_card.write('imax '+str(nchannels)+'\n')
toy_gen_card.write('jmax '+str(nprocesses)+'\n')
toy_gen_card.write('kmax '+str(nsystematics)+'\n')
toy_gen_card.write('-'*120+'\n')
processes = ['TotalSig','TotalBkg','data_obs']
for proc in processes:
if proc == 'TotalSig' or proc == 'data_obs':
preORpost = '_prefit'
else:
preORpost = '_postfit'
for chan in channelNames:
toy_gen_card.write(colliMate('shapes '+proc+' '+chan+' toy_gen_workspace.root w_toys:'+proc+'_'+chan+'\n'))
toy_gen_card.write('-'*120+'\n')
tempString = 'bin '
for chan in channelNames:
tempString += (chan+' ')
tempString += '\n'
toy_gen_card.write(colliMate(tempString,column_width))
tempString = 'observation '
for ichan in range(int(nchannels)):
tempString += '-1 '
tempString += '\n'
toy_gen_card.write(colliMate(tempString,column_width))
toy_gen_card.write('-'*120+'\n')
bin_line = 'bin '
processName_line = 'process '
processCode_line = 'process '
rate_line = 'rate '
for chan in channelNames:
for proc in ['TotalBkg','TotalSig']:
# Start lines
bin_line += (chan+' ')
processName_line += (proc+' ')
# If signal
if proc == 'TotalSig':
processCode_line += ('0 ')
rate_line += ('-1 ')
# If bkg
elif proc == 'TotalBkg':
processCode_line += ('1 ')
rate_line += '-1 '
toy_gen_card.write(colliMate(bin_line+'\n',column_width))
toy_gen_card.write(colliMate(processName_line+'\n',column_width))
toy_gen_card.write(colliMate(processCode_line+'\n',column_width))
toy_gen_card.write(colliMate(rate_line+'\n',column_width))
toy_gen_card.write('-'*120+'\n')
toy_gen_card.close()
def projInfoLookup(projDir,card_tag):
# Check if there was more than one 2DAlphabet object run over
more_than_one = False
run_card = open(projDir+'/card_'+card_tag+'.txt','r')
firstline = run_card.readline()
if 'Combination of ' in firstline:
more_than_one = True
proj_info = {}
if more_than_one:
# Look up all categories run in the most recent fit
twoD_names = getTwoDAlphaNames(firstline)
for n in twoD_names:
proj_info[n] = pickle.load(open(projDir+'/'+n+'/saveOut.p','r'))
proj_info[n]['rpfVarNames'] = proj_info[n]['rpf'].getFuncVarNames()
elif not more_than_one:
proj_info[card_tag] = pickle.load(open(projDir+'/saveOut.p','r'))
proj_info['rpfVarNames'] = proj_info['rpf'].getFuncVarNames()
return proj_info
def getTwoDAlphaNames(line):
card_locs = [loc for loc in line.split(' ') if (loc != ' ' and loc != '' and 'txt' in loc)]
proj_names = [n.split('/')[0] for n in card_locs]
return proj_names
def executeCmd(cmd,dryrun=False):
print 'Executing: '+cmd
if not dryrun:
subprocess.call([cmd],shell=True)
def dictToLatexTable(dict2convert,outfilename,roworder=[],columnorder=[]):
# First set of keys are row, second are column
if len(roworder) == 0:
rows = sorted(dict2convert.keys())
else:
rows = roworder
if len(columnorder) == 0:
columns = []
for r in rows:
thesecolumns = dict2convert[r].keys()
for c in thesecolumns:
if c not in columns:
columns.append(c)
columns.sort()
else:
columns = columnorder
latexout = open(outfilename,'w')
latexout.write('\\begin{table}[] \n')
latexout.write('\\begin{tabular}{|c|'+len(columns)*'c'+'|} \n')
latexout.write('\\hline \n')
column_string = ' &'
for c in columns:
column_string += str(c)+'\t& '
column_string = column_string[:-2]+'\\\ \n'
latexout.write(column_string)
latexout.write('\\hline \n')
for r in rows:
row_string = '\t'+r+'\t& '
for c in columns:
if c in dict2convert[r].keys():
row_string += str(dict2convert[r][c])+'\t& '
else:
row_string += '- \t& '
row_string = row_string[:-2]+'\\\ \n'
latexout.write(row_string)
latexout.write('\\hline \n')
latexout.write('\\end{tabular} \n')
latexout.write('\\end{table}')
latexout.close()
def reorderHists(histlist):
if len(histlist) != 6:
print Exception('reorderHists() only built to rearrange list of six hists from 2x3 to 3x2')
return histlist
outlist = []
outlist.append(histlist[0])
outlist.append(histlist[3])
outlist.append(histlist[1])
outlist.append(histlist[4])
outlist.append(histlist[2])
outlist.append(histlist[5])
return outlist
def makeCan(name, tag, histlist, bkglist=[],totalBkg=None,signals=[],colors=[],
titles=[],subtitles=[],sliceVar='X',dataName='Data',bkgNames=[],signalNames=[],logy=False,
rootfile=False,xtitle='',ytitle='',ztitle='',dataOff=False,
datastyle='pe',year=1, addSignals=True, extraText=''):
# histlist is just the generic list but if bkglist is specified (non-empty)
# then this function will stack the backgrounds and compare against histlist as if
# it is data. The imporant bit is that bkglist is a list of lists. The first index
# of bkglist corresponds to the index in histlist (the corresponding data).
# For example you could have:
# histlist = [data1, data2]
# bkglist = [[bkg1_1,bkg2_1],[bkg1_2,bkg2_2]]
if len(histlist) == 1:
width = 800
height = 700
padx = 1
pady = 1
elif len(histlist) == 2:
width = 1200
height = 700
padx = 2
pady = 1
elif len(histlist) == 3:
width = 1800
height = 600
padx = 3
pady = 1
elif len(histlist) == 4:
width = 1200
height = 1000
padx = 2
pady = 2
elif len(histlist) == 6 or len(histlist) == 5:
height = 1600
width = 1200
padx = 2
pady = 3
histlist = reorderHists(histlist)
if bkglist != []: bkglist = reorderHists(bkglist)
if signals != []: signals = reorderHists(signals)
if totalBkg != None: totalBkg = reorderHists(totalBkg)
if titles != []: titles = reorderHists(titles)
if subtitles != []: subtitles = reorderHists(subtitles)
else:
print 'histlist of size ' + str(len(histlist)) + ' not currently supported'
print histlist
return 0
tdrstyle.setTDRStyle()
gStyle.SetLegendFont(42)
gStyle.SetTitleBorderSize(0)
gStyle.SetTitleAlign(33)
gStyle.SetTitleX(.77)
myCan = TCanvas(name,name,width,height)
myCan.Divide(padx,pady)
# Just some colors that I think work well together and a bunch of empty lists for storage if needed
default_colors = [kRed,kMagenta,kGreen,kCyan,kBlue]
if len(colors) == 0:
colors = default_colors
color_idx_order = None
stacks = []
tot_hists_err = []
tot_hists = []
legends = []
mains = []
subs = []
pulls = []
logString = ''
tot_sigs = []
# For each hist/data distribution
for hist_index, hist in enumerate(histlist):
# Grab the pad we want to draw in
myCan.cd(hist_index+1)
# if len(histlist) > 1:
thisPad = myCan.GetPrimitive(name+'_'+str(hist_index+1))
thisPad.cd()
thisPad.SetRightMargin(0.0)
thisPad.SetTopMargin(0.0)
thisPad.SetBottomMargin(0.0)
# If this is a TH2, just draw the lego
if hist.ClassName().find('TH2') != -1:
gPad.SetLeftMargin(0.15)
gPad.SetRightMargin(0.2)
gPad.SetBottomMargin(0.12)
gPad.SetTopMargin(0.1)
if logy: gPad.SetLogz()
hist.GetXaxis().SetTitle(xtitle)
hist.GetYaxis().SetTitle(ytitle)
hist.GetZaxis().SetTitle(ztitle)
hist.GetXaxis().SetTitleOffset(1.15)
hist.GetYaxis().SetTitleOffset(1.5)
hist.GetZaxis().SetTitleOffset(1.5)
hist.GetYaxis().SetLabelSize(0.05)
hist.GetYaxis().SetTitleSize(0.05)
hist.GetXaxis().SetLabelSize(0.05)
hist.GetXaxis().SetTitleSize(0.05)
hist.GetZaxis().SetLabelSize(0.05)
hist.GetZaxis().SetTitleSize(0.05)
hist.GetXaxis().SetNdivisions(505)
# hist.GetXaxis().SetLabelOffset(0.02)
if 'lego' in datastyle.lower(): hist.GetZaxis().SetTitleOffset(1.4)
if len(titles) > 0:
hist.SetTitle(titles[hist_index])
if datastyle != 'pe': hist.Draw(datastyle)
else: hist.Draw('colz')
if len(bkglist) > 0:
raise TypeError('ERROR: It seems you are trying to plot backgrounds with data on a 2D plot. This is not supported since there is no good way to view this type of distribution.')
CMS_lumi.extraText = extraText
CMS_lumi.CMS_lumi(thisPad, year, 11, sim=False if 'data' in name.lower() else True)
# Otherwise it's a TH1 hopefully
else:
titleSize = 0.09
alpha = 1
if dataOff:
alpha = 0
hist.SetLineColorAlpha(kBlack,alpha)
if 'pe' in datastyle.lower():
hist.SetMarkerColorAlpha(kBlack,alpha)
hist.SetMarkerStyle(8)
if 'hist' in datastyle.lower():
hist.SetFillColorAlpha(0,0)
hist.GetXaxis().SetTitle(xtitle)
hist.GetYaxis().SetTitle(ytitle)
# If there are no backgrounds, only plot the data (semilog if desired)
if len(bkglist) == 0:
hist.SetMaximum(1.13*hist.GetMaximum())
if len(titles) > 0:
hist.SetTitle(titles[hist_index])
hist.SetTitleOffset(1.1)
hist.Draw(datastyle)
CMS_lumi.CMS_lumi(thisPad, year, 11)
# Otherwise...
else:
# Create some subpads, a legend, a stack, and a total bkg hist that we'll use for the error bars
if not dataOff:
mains.append(TPad(hist.GetName()+'_main',hist.GetName()+'_main',0, 0.35, 1, 1))
subs.append(TPad(hist.GetName()+'_sub',hist.GetName()+'_sub',0, 0, 1, 0.35))
else:
mains.append(TPad(hist.GetName()+'_main',hist.GetName()+'_main',0, 0.1, 1, 1))
subs.append(TPad(hist.GetName()+'_sub',hist.GetName()+'_sub',0, 0, 0, 0))
if len(signals) == 0:
nsignals = 0
elif addSignals:
nsignals = 1
else:
nsignals = len(signals[0])
legend_topY = 0.73-0.03*(min(len(bkglist[0]),6)+nsignals+1)
# legend_bottomY = 0.2+0.02*(len(bkglist[0])+nsignals+1)
legends.append(TLegend(0.65,legend_topY,0.90,0.88))
legend_duplicates = []
if not dataOff: legends[hist_index].AddEntry(hist,dataName,datastyle)
stacks.append(THStack(hist.GetName()+'_stack',hist.GetName()+'_stack'))
if totalBkg == None:
tot_hist = hist.Clone(hist.GetName()+'_tot')
tot_hist.Reset()
else:
tot_hist = totalBkg[hist_index]
tot_hist.SetTitle(hist.GetName()+'_tot')
tot_hist.SetMarkerStyle(0)
tot_hists.append(tot_hist)
tot_hists_err.append(tot_hist.Clone())
tot_hists[hist_index].SetLineColor(kBlack)
tot_hists_err[hist_index].SetLineColor(kBlack)
tot_hists_err[hist_index].SetLineWidth(0)
tot_hists_err[hist_index].SetFillColor(kBlack)
tot_hists_err[hist_index].SetFillStyle(3354)
legends[hist_index].AddEntry(tot_hists_err[hist_index],'Total bkg unc.','F')
# Set margins and make these two pads primitives of the division, thisPad
mains[hist_index].SetBottomMargin(0.04)
mains[hist_index].SetLeftMargin(0.17)
mains[hist_index].SetRightMargin(0.05)
mains[hist_index].SetTopMargin(0.1)
subs[hist_index].SetLeftMargin(0.17)
subs[hist_index].SetRightMargin(0.05)
subs[hist_index].SetTopMargin(0)
subs[hist_index].SetBottomMargin(0.35)
mains[hist_index].Draw()
subs[hist_index].Draw()
# If logy, put QCD on top
# if logy: bkglist[0], bkglist[-1] = bkglist[-1], bkglist[0]
# Order based on colors
if color_idx_order == None:
color_idx_order = ColorCodeSortedIndices(colors)
colors = [colors[i] for i in color_idx_order]
bkglist[hist_index] = [bkglist[hist_index][i] for i in color_idx_order]
if bkgNames != [] and isinstance(bkgNames[0],list):
bkgNames[hist_index] = [bkgNames[hist_index][i] for i in color_idx_order]
# Build the stack
legend_info = collections.OrderedDict()
for bkg_index,bkg in enumerate(bkglist[hist_index]): # Won't loop if bkglist is empty
# bkg.Sumw2()
if totalBkg == None: tot_hists[hist_index].Add(bkg)
if logy:
bkg.SetMinimum(1e-3)
if 'qcd' in bkg.GetName():
bkg.SetFillColor(kYellow)
bkg.SetLineColor(kYellow)
else:
if colors[bkg_index] != None:
bkg.SetFillColor(colors[bkg_index])
bkg.SetLineColor(colors[bkg_index] if colors[bkg_index]!=0 else kBlack)
else:
bkg.SetFillColor(default_colors[bkg_index])
bkg.SetLineColor(default_colors[bkg_index] if colors[bkg_index]!=0 else kBlack)
stacks[hist_index].Add(bkg)
if bkgNames == []: this_bkg_name = bkg.GetName().split('_')[0]
elif type(bkgNames[0]) != list: this_bkg_name = bkgNames[bkg_index]
else: this_bkg_name = bkgNames[hist_index][bkg_index]
legend_info[this_bkg_name] = bkg
# Deal with legend which needs ordering reversed from stack build
for bname in reversed(legend_info.keys()):
if bname not in legend_duplicates:
legends[hist_index].AddEntry(legend_info[bname],bname,'f')
legend_duplicates.append(bname)
# Go to main pad, set logy if needed
mains[hist_index].cd()
# Set y max of all hists to be the same to accommodate the tallest
histList = [stacks[hist_index],tot_hists[hist_index],hist]
yMax = histList[0].GetMaximum()
for h in range(1,len(histList)):
if histList[h].GetMaximum() > yMax:
yMax = histList[h].GetMaximum()
for h in histList:
h.SetMaximum(yMax*(2.5-legend_topY+0.03))
if logy == True:
h.SetMaximum(yMax*10**(2.5-legend_topY+0.1))
mLS = 0.08
# Now draw the main pad
data_leg_title = hist.GetTitle()
if len(titles) > 0:
hist.SetTitle(titles[hist_index])
hist.SetTitleOffset(1.15,"xy")
hist.GetYaxis().SetTitleOffset(1.04)
hist.GetYaxis().SetLabelSize(0.07)
hist.GetYaxis().SetTitleSize(titleSize)
hist.GetXaxis().SetLabelSize(0.07)
hist.GetXaxis().SetTitleSize(titleSize)
hist.GetXaxis().SetLabelOffset(0.05)
if logy == True:
hist.SetMinimum(1e-3)
hist.GetYaxis().SetNdivisions(508)
hist.Draw(datastyle+' X0')
#gStyle.SetErrorX(0.5)
if logy == True:stacks[hist_index].SetMinimum(1e-3)
stacks[hist_index].Draw('same hist') # need to draw twice because the axis doesn't exist for modification until drawing
try:
stacks[hist_index].GetYaxis().SetNdivisions(508)
except:
stacks[hist_index].GetYaxis().SetNdivisions(8,5,0)
stacks[hist_index].Draw('same hist')
# Do the signals
sigs_to_plot = []
if len(signals) > 0:
# Can add together for total signal
if addSignals:
totsig = signals[hist_index][0].Clone()
for isig in range(1,len(signals[hist_index])):
totsig.Add(signals[hist_index][isig])
sigs_to_plot = [totsig]
# or treat separately
else:
for sig in signals[hist_index]:
sigs_to_plot.append(sig)
# Plot either way
tot_sigs.append(sigs_to_plot)
for isig,sig in enumerate(sigs_to_plot):
sig.SetLineColor(kBlack)
sig.SetLineWidth(2)
if logy == True:
sig.SetMinimum(1e-3)
# if signalNames == []: this_sig_name = sig.GetName().split('_')[0]
if type(signalNames) == str: this_sig_name = signalNames
else: this_sig_name = signalNames[isig]
legends[hist_index].AddEntry(sig,this_sig_name,'L')
sig.Draw('hist same')
# Draw total hist and error
if logy:
tot_hists[hist_index].SetMinimum(1e-3)
tot_hists_err[hist_index].SetMinimum(1e-3)
tot_hists[hist_index].Draw('hist same')
tot_hists_err[hist_index].Draw('e2 same')
legends[hist_index].SetBorderSize(0)
legends[hist_index].Draw()