-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathutils.py
More file actions
1860 lines (1390 loc) · 77.2 KB
/
Copy pathutils.py
File metadata and controls
1860 lines (1390 loc) · 77.2 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
"""Module to plot, create, and edit ROOT histograms.
To use ROOT.RDataFrame to process TreeSamples a rather recent ROOT version is required, e.g.,
source /cvmfs/sft.cern.ch/lcg/app/releases/ROOT/6.24.06/x86_64-centos7-gcc48-opt/bin/thisroot.sh
"""
import os
import sys
import math
import time
import json
import ctypes
import random
import ROOT
from copy import copy
from glob import glob
from array import array
from collections import OrderedDict
from plotstyle import Plotstyle
ROOT.gEnv.SetValue('RooFit.Banner', 0)
# enable multi-threading to speed up processing of ROOT.RDataFrame (if supported by ROOT version)
try:
# ROOT.EnableImplicitMT() # doesn't work with ROOT.RDataFrame().Range()
ROOT.DisableImplicitMT() # doesn't work with ROOT.RDataFrame().Range()
except AttributeError:
pass
class PlotFactory:
"""Main class to make plots and/or create histograms.
Methods
-------
process()
Create plots and/or save histograms according to the added variables, samples, and ratios.
add_variables(variablelist)
Add a list of variables to be processed.
add_variable(variable)
Add a variable to be processed.
add_samples(samplelist)
Add a list of samples to be processed.
add_sample(sample)
Add a sample to be processed.
add_ratios(ratiolist)
Add a list of ratios to be processed.
add_ratio(ratio)
Add a ratio to be processed.
"""
def __init__(self,
inputfiles=None,
inputpattern='VARIABLESAMPLE',
outputpath='.',
outputsubfolder='',
outputpattern='VARIABLE',
outputformat='pdf',
normalize=False,
axes='linlog',
ylabel='Events',
ylabelratio='Data / Prediction',
yaxisrangeratio=(0.0001, 1.9999),
yaxislogratio=False,
ratiohlines=None,
linewidth=1,
markersize=2,
poslegend=(0.4, 0.55, 0.93, 0.9),
ncolumnslegend=1,
boldlegend=False,
text='36 fb^{-1} (13 TeV)',
cmstext='CMS',
extratext='#splitline{Private Work}{Simulation}',
height=1280,
width=None,
ipos=11,
uoflowbins=False):
"""
Parameters
----------
inputfiles : list[str], optional
List of input ROOT files containing histograms.
inputpattern : str, optional
Naming scheme for histograms stored in the inputfiles,
VARIABLE is replaced by the variable name, SAMPLE is replaced by the sample name.
outputpath : str, default '.'
Where to save the output plots and histograms, directory is created if it doesn't exist.
outputpattern : str, default 'VARIABLE'
Naming scheme for output plots, VARIABLE is replaced by the variable name.
outputformat : str or list[str], default 'pdf'
Format(s) to save output plots, has to be supported by ROOT.TCanvas.Print()
normalize : bool, default False
Scale all histograms to unity.
axes : {'linlog', 'lin', 'log'}
Draw plots with a linear y-axis, logarithmic y-axis, or both.
ylabel : str, default 'Events'
Label for y-axis of main plot (upper panel).
ylabelratio : str, default 'Data / Prediction'
Label for y-axis of lower panel.
yaxisrangeratio : tuple[float], default (0.0001, 1.9999)
Range of y-axis of lower panel, choose values just above/below a round number
to avoid the respective tick label.
ratiohlines : list[float or tuple[float]], default [1.]
Straight line(s) to draw in lower panel, if element is float a horizontal line is drawn at the given value,
if element is tuple of the form (x1, y1, x2, y2) a line is drawn from (x1,y1) to (x2,y2).
linewidth : int, default 1
Linewidth used for samples of category marker or line and for ratios,
corresponding to ROOT.TAttLine.
markersize : int, default 2
Markersize used for samples of category marker,
corresponding to ROOT.TAttMarker.
poslegend : tuple[float], default (0.4, 0.55, 0.93, 0.9)
Position of legend, specified by tuple (x1, y1, x2, y2).
ncolumnslegend : int, default 1
Number of columns used in legend.
boldlegend : bool, default False
Use bold font in legend.
text : str, default '36 fb^{-1} (13 TeV)'
Text to write on top right corner.
extratext : str, default '#splitline{Work in progress}{Simulation}'
Text to write next to CMS stamp.
height : int, default 1280
Height of plot in pixels.
width : int or None, default None
Width of plot in pixels, if None then width is chosen proportionally to height.
ipos : int, default 0
Position of CMS stamp + extratext, e.g., 0 for top left out of frame, 11 for top left inside frame.
For details see CMS_lumi.py.
uoflowbins : bool, default False
Whether to plot the under- and overflow bins
"""
if inputfiles is None:
inputfiles = []
if ratiohlines is None:
ratiohlines = [1.]
self.variables = []
self.stacksamples = []
self.markersamples = []
self.linesamples = []
self.groups = OrderedDict() # {}
self.ratios = []
self.inputfiles = [ROOT.TFile(inputfile) for inputfile in inputfiles]
self.inputpattern = inputpattern
if outputpath[-1] == '/':
self.outputpath = outputpath[:-1]
else:
self.outputpath = outputpath
self.outputpath = self.outputpath.replace('ht5/ht', 'ht5overht')
if len(outputsubfolder) > 0 and outputsubfolder[-1] == '/':
outputsubfolder = outputsubfolder[:-1]
if len(outputsubfolder) > 0 and outputsubfolder[0] == '/':
self.outputsubfolder = outputsubfolder
else:
if len(outputsubfolder) > 0:
self.outputsubfolder = '/' + outputsubfolder
else:
self.outputsubfolder = ''
if not os.path.exists(self.outputpath + self.outputsubfolder):
os.makedirs(self.outputpath + self.outputsubfolder)
self.outputpattern = outputpattern
self.outputformat = outputformat
self.normalize = normalize
if axes not in ['linlog', 'lin', 'log']:
raise NotImplementedError('axes must be one of: lin, log, linlog')
self.axes = axes
self.ylabel = ylabel
self.ylabelratio = ylabelratio
self.yaxisrangeratio = yaxisrangeratio
self.yaxislogratio = yaxislogratio
self.ratiohlines = ratiohlines
self.linewidth = linewidth
self.markersize = markersize
self.p = None
self.text = text
self.extratext = extratext
self.cmstext = cmstext
self.height = height
self.width = width
self.ipos = ipos
self.legend = None
self.poslegend = poslegend
self.ncolumnslegend = ncolumnslegend
self.boldlegend = boldlegend
self.uoflowbins = uoflowbins
self.histos = {}
self.stacks = {}
self.sums = {}
self.ratiohistos = {}
self.emptylinhistos = {}
self.emptyloghistos = {}
def process(self, dryrun=False, verbose=1):
if dryrun:
print('\nthis is a dry run, these samples are registered:\n')
for s in self.stacksamples + self.markersamples + self.linesamples:
print(s.name)
else:
if self.width is None:
if len(self.ratios) > 0:
self.width = int(1. * self.height)
else:
self.width = int(1.35 * self.height) # TODO: make plots w/o ratio also square-like
self.p = Plotstyle(text=self.text, extratext=self.extratext, cmstext=self.cmstext, H_ref=self.height, W_ref=self.width, iPos=self.ipos)
mystyle = self.p.setStyle()
mystyle.cd()
self.legend = ROOT.TLegend(self.poslegend[0], self.poslegend[1], self.poslegend[2], self.poslegend[3])
self.legend.SetNColumns(self.ncolumnslegend)
self.legend.SetFillStyle(0)
self.legend.SetBorderSize(0)
if self.boldlegend: self.legend.SetTextFont(62)
else: self.legend.SetTextFont(42)
self._complete_dfs_and_weights()
self._get_histos()
self._make_ratios(verbose=verbose)
self._style_histos(verbose=verbose)
self._draw_plots(verbose=verbose)
self._save_histos()
def add_variables(self, variablelist):
"""
Parameters
----------
variablelist :
"""
for variable in variablelist:
self.add_variable(variable)
def add_variable(self, variable):
if str(variable) in [str(v) for v in self.variables]:
raise AssertionError(str(variable) + ' is a duplicate (names must be unique)')
self.variables.append(variable)
def add_samples(self, samplelist):
for sample in samplelist:
self.add_sample(sample)
def add_sample(self, sample):
if str(sample) in [str(s) for s in self.stacksamples + self.markersamples + self.linesamples]:
raise AssertionError(str(sample) + ' is a duplicate (names must be unique)')
if sample.category == 'stack':
self.stacksamples.append(sample)
elif sample.category == 'marker':
self.markersamples.append(sample)
elif sample.category == 'line':
self.linesamples.append(sample)
else:
raise NotImplementedError('unknown sample category')
if sample.group is not None:
if sample.group in [str(s) for s in self.stacksamples + self.markersamples + self.linesamples]:
raise AssertionError(sample.group + ' is a duplicate (names must be unique)')
if sample.group in self.groups.keys():
self.groups[sample.group].append(sample)
else:
self.groups[sample.group] = [sample]
def add_ratios(self, ratiolist):
for ratio in ratiolist:
self.add_ratio(ratio)
def add_ratio(self, ratio):
self.ratios.append(ratio)
def _complete_dfs_and_weights(self):
for s in self.stacksamples + self.markersamples + self.linesamples:
if isinstance(s, TreeSample) and s.usedataframeandweightfrom and not s.usehistocache:
s.df = {_s.name: _s.df for _s in self.stacksamples + self.markersamples + self.linesamples}[s.usedataframeandweightfrom]
s.weight = {_s.name: _s.weight for _s in self.stacksamples + self.markersamples + self.linesamples}[s.usedataframeandweightfrom]
def _get_histos(self):
print('\n# Get Histos')
makeflat = {}
for s in self.stacksamples + self.markersamples + self.linesamples:
print(s)
if isinstance(s, TreeSample) and not s.usehistocache:
# first book all histograms
for v in self.variables:
if not s.modifyvarname(v.vartoplot) == s.modifyvarname(v.name) and s.modifyvarname(v.name) not in s.df.GetColumnNames():
s.df = s.df.Define(
s.modifyvarname(v.name), s.modifyvarname(v.vartoplot)
)
if type(v.nbins) == str and 'flat' in v.nbins:
makeflat[v] = v.nbins
v.nbins = 1000
if s.vectorselection is None:
if s.weight is None:
self.histos[v + s] = s.df.Histo1D(
(self.inputpattern.replace('VARIABLE', str(v)).replace('SAMPLE', str(s)), '',
v.nbins, v.axisrange[0], v.axisrange[1]), s.modifyvarname(v.name)
)
else:
self.histos[v + s] = s.df.Define(
'_w', s.weight
).Histo1D(
(self.inputpattern.replace('VARIABLE', str(v)).replace('SAMPLE', str(s)), '',
v.nbins, v.axisrange[0], v.axisrange[1]), s.modifyvarname(v.name), '_w'
)
else:
if s.weight is None:
self.histos[v + s] = s.df.Define(
s.modifyvarname(v.name) + '_pass', s.modifyvarname(v.name) + '[' + s.vectorselection + ']'
).Histo1D(
(self.inputpattern.replace('VARIABLE', str(v)).replace('SAMPLE', str(s)), '',
v.nbins, v.axisrange[0], v.axisrange[1]), s.modifyvarname(v.name) + '_pass'
)
else:
self.histos[v + s] = s.df.Define(
s.modifyvarname(v.name) + '_pass', s.modifyvarname(v.name) + '[' + s.vectorselection + ']'
).Define(
'_w', s.weight
).Histo1D(
(self.inputpattern.replace('VARIABLE', str(v)).replace('SAMPLE', str(s)), '',
v.nbins, v.axisrange[0], v.axisrange[1]), s.modifyvarname(v.name) + '_pass', '_w'
)
# then trigger the filling of the histos
s.df.Report().Print()
# get the pointer to the real histogram instead of the RResultPtr
for v in self.variables:
self.histos[v + s] = self.histos[v + s].GetPtr()
self.histos[v + s].UseCurrentStyle()
else:
if isinstance(s, TreeSample):
if s.histocachefile is None:
possiblefiles = [self.outputpath + self.outputsubfolder + '/histos_' + str(s) + '.root'] \
+ glob(self.outputpath + '/era*/part*/histos_' + str(s) + '.root') \
+ glob(self.outputpath + '/era*/part*/histos.root') \
+ glob(self.outputpath + '/era*/histos_' + str(s) + '.root') \
+ glob(self.outputpath + '/era*/histos.root') \
+ glob(self.outputpath + '/part*/histos_' + str(s) + '.root') \
+ glob(self.outputpath + '/part*/histos.root') \
+ glob(self.outputpath + self.outputsubfolder + '_part*/histos_' + str(s) + '.root') \
+ glob(self.outputpath + self.outputsubfolder + '_part*/histos.root') \
+ [self.outputpath + self.outputsubfolder + '/histos.root']
else:
possiblefiles = [s.histocachefile]
for possiblefile in possiblefiles:
if os.path.exists(possiblefile):
s.file = ROOT.TFile(possiblefile, 'read')
if s.modifysamplename(str(s)) in [key.GetName() for key in list(s.file.GetListOfKeys())]:
print(' taking histos from ' + possiblefile)
break
else:
s.file = None
for v in self.variables:
if type(v.nbins) == str and 'flat' in v.nbins:
makeflat[v] = v.nbins
if s.file is None:
if isinstance(s, TreeSample):
print(' possible files:')
print(possiblefiles)
raise AssertionError('No histo cache file found for TreeSample ' + str(s))
if s.inputpattern is None:
self.histos[v + s] = self.inputfiles[s.inputfileindex if v.inputfileindex is None else v.inputfileindex].Get(
self.inputpattern.replace('VARIABLE', str(v)).replace('SAMPLE', str(s))
)
else:
self.histos[v + s] = self.inputfiles[s.inputfileindex if v.inputfileindex is None else v.inputfileindex].Get(
s.inputpattern.replace('VARIABLE', str(v)).replace('SAMPLE', str(s))
)
else:
if isinstance(s, TreeSample) or s.inputpattern is None:
self.histos[v + s] = s.file.Get(
(s.modifysamplename(s.name) + '/' if isinstance(s, TreeSample) else '') + self.inputpattern.replace('VARIABLE', s.modifyvarname(str(v))).replace('SAMPLE', s.modifysamplename(s.name))
)
else:
self.histos[v + s] = s.file.Get(
s.inputpattern.replace('VARIABLE', s.modifyvarname(str(v))).replace('SAMPLE', str(s))
)
try:
self.histos[v + s].GetXaxis().SetRangeUser(v.axisrange[0], v.axisrange[1])
self.histos[v + s].UseCurrentStyle()
self.histos[v + s].SetDirectory(0)
except AttributeError:
raise Exception('no histogram found for variable ' + str(v))
for v in self.variables:
if not v.rebin == 1:
if type(v.rebin) == list:
self.histos[v + s] = self.histos[v + s].Rebin(
len(v.rebin)-1, self.histos[v + s].GetName() + 'rebinned', array('d', v.rebin)
)
else:
self.histos[v + s].Rebin(v.rebin)
for g in self.groups:
group = copy(self.groups[g][0])
group.name = g
group.group = None
if group.category == 'stack':
self.stacksamples.append(group)
elif group.category == 'marker':
self.markersamples.append(group)
elif group.category == 'line':
self.linesamples.append(group)
else:
raise NotImplementedError('unknown sample category')
for v in self.variables:
self.histos[v + g] = self.histos[v + self.groups[g][0]].Clone(g + v.name)
self.histos[v + g].Reset('ICESM')
for part in self.groups[g]:
if not part.scaleby == 1.:
if type(part.scaleby) == dict:
if v.name in part.scaleby:
for bintoscale in part.scaleby[v.name]:
scalethisbinby = part.scaleby[v.name][bintoscale]
if bintoscale < 0: bintoscale = self.histos[v + part].GetNbinsX() + 1 + bintoscale
if hasattr(scalethisbinby, '__call__'):
self.histos[v + part].SetBinContent(bintoscale, scalethisbinby(self.histos[v + part].GetBinLowEdge(bintoscale)) * self.histos[v + part].GetBinContent(bintoscale))
else:
self.histos[v + part].SetBinContent(bintoscale, scalethisbinby * self.histos[v + part].GetBinContent(bintoscale))
else:
self.histos[v + part].Scale(part.scaleby)
self.histos[v + g].Add(self.histos[v + part])
for iv, v in enumerate(self.variables):
if v in makeflat:
flatsample = makeflat[v].split(':')[1]
flatnbins = float(makeflat[v].split(':')[2])
if flatnbins < 1: # interpret as relative stat error in each bin
flatnperbin = 1. / flatnbins**2.
flatnbins = int(self.histos[v + flatsample].Integral() / flatnperbin)
else:
flatnbins = int(flatnbins)
p = array('d', [i/float(flatnbins) for i in range(1, flatnbins)])
quantiles = array('d', (flatnbins-1)*[0.])
self.histos[v + flatsample].GetQuantiles(flatnbins-1, quantiles, p)
# make sure to use existing bin edges
existingbins = [self.histos[v + flatsample].GetBinLowEdge(b) for b in range(self.histos[v + flatsample].GetNbinsX() + 2)]
roundedquantiles = [min(existingbins, key=lambda x: abs(x - q)) for q in quantiles]
roundedquantiles = list(OrderedDict.fromkeys(roundedquantiles)) # TODO: remove duplicates?
if not flatnbins == len(roundedquantiles) + 1:
print('\nchanging number of flat bins to', len(roundedquantiles) + 1)
flatnbins = len(roundedquantiles) + 1
quantiles = array('d', roundedquantiles)
quantiles.insert(0, v.axisrange[0])
quantiles.append(v.axisrange[1])
for s in self.stacksamples + self.markersamples + self.linesamples:
self.histos[v + s] = self.histos[v + s].Rebin(
flatnbins, self.histos[v + s].GetName() + 'rebinned', quantiles
)
if v.blind is not None:
for blindthis in v.blind:
if not len(blindthis.split(':')) == 3:
raise NotImplementedError('cannot interpret blind: ' + blindthis)
blindsample, blindstart, blindend = blindthis.split(':')
blindstart = blindstart.replace('START', str(v.axisrange[0])).replace('END', str(v.axisrange[1]))
blindend = blindend.replace('START', str(v.axisrange[0])).replace('END', str(v.axisrange[1]))
blindstartbin = self.histos[v + blindsample].FindBin(float(blindstart))
blindendbin = self.histos[v + blindsample].FindBin(float(blindend))
for blindbin in range(blindstartbin, blindendbin+1):
self.histos[v + blindsample].SetBinContent(blindbin, 0.)
self.histos[v + blindsample].SetBinError(blindbin, 0.)
# also blind the under- and overflow bins
if blindbin == 1:
self.histos[v + blindsample].SetBinContent(0, 0.)
self.histos[v + blindsample].SetBinError(0, 0.)
if blindbin == self.histos[v + blindsample].GetNbinsX():
self.histos[v + blindsample].SetBinContent(self.histos[v + blindsample].GetNbinsX() + 1, 0.)
self.histos[v + blindsample].SetBinError(self.histos[v + blindsample].GetNbinsX() + 1, 0.)
for s in self.stacksamples + self.markersamples + self.linesamples:
if not self.histos[v + s].GetSumw2N():
self.histos[v + s].Sumw2()
if self.uoflowbins:
self.histos[v + s].GetXaxis().SetRange(0, self.histos[v + s].GetNbinsX() + 1)
if s.group is None and s.name not in self.groups and not s.scaleby == 1.:
if type(s.scaleby) == dict:
if v.name in s.scaleby:
for bintoscale in s.scaleby[v.name]:
scalethisbinby = s.scaleby[v.name][bintoscale]
if bintoscale < 0: bintoscale = self.histos[v + s].GetNbinsX() + 1 + bintoscale
if hasattr(scalethisbinby, '__call__'):
self.histos[v + s].SetBinContent(bintoscale, scalethisbinby(self.histos[v + s].GetBinLowEdge(bintoscale)) * self.histos[v + s].GetBinContent(bintoscale))
else:
self.histos[v + s].SetBinContent(bintoscale, scalethisbinby * self.histos[v + s].GetBinContent(bintoscale))
else:
self.histos[v + s].Scale(s.scaleby)
if len(self.stacksamples) > 0:
self.sums[v] = self.histos[v + self.stacksamples[0]].Clone('sum' + v.name)
self.sums[v].Reset('ICESM')
for s in self.stacksamples:
if s.group is None: self.sums[v].Add(self.histos[v + s])
if self.normalize:
for s in self.markersamples + self.linesamples:
if self.histos[v + s].Integral() > 0:
print('Integral ' + str(s))
print(self.histos[v + s].Integral())
self.histos[v + s].Scale(1. / self.histos[v + s].Integral())
if len(self.stacksamples) > 0 and self.sums[v].Integral() > 0:
for s in self.stacksamples:
self.histos[v + s].Scale(1. / self.sums[v].Integral())
self.sums[v].Scale(1. / self.sums[v].Integral())
for s in self.markersamples + self.linesamples:
if s.scaleto is None: continue
if s.group is not None: continue
scaletoargs = s.scaleto.split(':')
if len(scaletoargs) == 3 and scaletoargs[0] in [str(_s) for _s in self.stacksamples + self.markersamples + self.linesamples] or scaletoargs[0] == 'STACK':
scaletostart = float(scaletoargs[1].replace('START', str(v.axisrange[0])))
scaletoend = float(scaletoargs[2].replace('END', str(v.axisrange[1])))
scaletostartbin = self.histos[v + s].GetXaxis().FindBin(scaletostart)
scaletoendbin = self.histos[v + s].GetXaxis().FindBin(scaletoend)
if scaletoargs[0] == 'STACK':
scaletotarget = self.sums[v].Integral(scaletostartbin, scaletoendbin)
else:
scaletotarget = self.histos[str(v) + scaletoargs[0]].Integral(scaletostartbin, scaletoendbin)
if self.histos[v + s].Integral(scaletostartbin, scaletoendbin) > 0:
self.histos[v + s].Scale(scaletotarget / self.histos[v + s].Integral(scaletostartbin, scaletoendbin))
elif len(scaletoargs) == 1 and scaletoargs[0].replace('.', '', 1).isdigit():
if self.histos[v + s].Integral() > 0:
self.histos[v + s].Scale(float(scaletoargs[0]) / self.histos[v + s].Integral())
else:
raise NotImplementedError('cannot interpret scaleto: ' + s.scaleto)
if len(self.stacksamples) > 0:
self.stacks[v] = ROOT.THStack('stack' + v.name, '')
for s in self.stacksamples:
if s.group is None: self.stacks[v].Add(self.histos[v + s])
if iv == 0:
for s in self.markersamples[::-1]:
if len(s.title) > 0 and s.group is None:
self.legend.AddEntry(self.histos[v + s], s.title, 'pe')
for s in self.stacksamples[::-1]:
if len(s.title) > 0 and s.group is None:
self.legend.AddEntry(self.histos[v + s], s.title, 'f')
for s in self.linesamples:
if len(s.title) > 0 and s.group is None:
self.legend.AddEntry(self.histos[v + s], s.title, 'l')
if any([s.usehistocache for s in self.stacksamples + self.markersamples + self.linesamples if isinstance(s, TreeSample)]):
print('\n5 seconds to check histo cache files')
time.sleep(5)
def _make_ratios(self, verbose=1):
print('\n# Make Ratios')
for v in self.variables:
if verbose > 1: print(v)
if len(v.systematics) > 0:
self.ratiohistos[v + 'systUp'] = self.sums[v].Clone(v + 'systUp')
self.ratiohistos[v + 'systDn'] = self.sums[v].Clone(v + 'systDn')
for isyst, syst in enumerate(v.systematics):
for nbin in range(self.sums[v].GetNbinsX()):
if type(syst[nbin]) == tuple:
errsample = syst[nbin][0]
errvalue = syst[nbin][1]
if hasattr(errvalue, '__call__'):
errvalue = abs(1 - errvalue(self.ratiohistos[v + 'systUp'].GetBinLowEdge(nbin+1)))
if errsample == 'STACK':
err = errvalue
else:
if self.sums[v].GetBinContent(nbin+1) > 0:
err = errvalue * self.histos[v + errsample].GetBinContent(nbin+1) / self.sums[v].GetBinContent(nbin+1)
else:
err = 0
else:
err = syst[nbin]
if isyst == 0:
self.ratiohistos[v + 'systUp'].SetBinError(nbin+1, 0)
self.ratiohistos[v + 'systUp'].SetBinContent(nbin+1, err)
else:
self.ratiohistos[v + 'systUp'].SetBinContent(
nbin+1,
ROOT.TMath.Sqrt(self.ratiohistos[v + 'systUp'].GetBinContent(nbin+1)**2 + err**2)
)
if isyst == len(v.systematics)-1:
self.ratiohistos[v + 'systDn'].SetBinContent(nbin+1, 1 - self.ratiohistos[v + 'systUp'].GetBinContent(nbin+1))
self.ratiohistos[v + 'systUp'].SetBinContent(nbin+1, 1 + self.ratiohistos[v + 'systUp'].GetBinContent(nbin+1))
issecondfit = False
for r in self.ratios:
if 'ratio' in r.category:
if not len(r.name.split(':')) == 2:
raise NotImplementedError('cannot interpret ratio')
numerator = r.name.split(':')[0]
denominator = r.name.split(':')[1].replace('_ALT', '')
if numerator == 'STACK':
self.ratiohistos[v + r] = self.sums[v].Clone(v + r)
elif 'DIFF' in numerator:
self.ratiohistos[v + r] = self.ratiohistos[v.name + 'diff' + numerator.replace('DIFF', ':')].Clone(v + r)
else:
self.ratiohistos[v + r] = self.histos[v.name + numerator].Clone(v + r)
if denominator == 'STACK':
self.ratiohistos[v + r].Divide(self.sums[v])
elif 'DIFF' in denominator:
self.ratiohistos[v + r].Divide(self.ratiohistos[v.name + 'diff' + denominator.replace('DIFF', ':')])
else:
self.ratiohistos[v + r].Divide(self.histos[v.name + denominator])
self.ratiohistos[v + r].SetName(self.ratiohistos[v + r].GetName().replace(':', 'VS')) # TODO: do this?
if v.verboseratio:
print(' ' + r.name)
print(' ' + v.name)
for nbin in range(self.ratiohistos[v + r].GetNbinsX()):
print(str(nbin+1) + ' (' + str(self.ratiohistos[v + r].GetBinLowEdge(nbin+1)) + ')')
print(self.ratiohistos[v + r].GetBinContent(nbin+1))
print(self.ratiohistos[v + r].GetBinError(nbin+1))
if r.category == 'ratiowithfit' and v.name in r.ratiofitvariables:
ROOT.gStyle.SetOptFit(0)
self.ratiohistos[v + r + 'func'] = ROOT.TF1('func' + v.name + r.name, '[0] + [1] * x')
fitresult = self.ratiohistos[v + r].Fit(
self.ratiohistos[v + r + 'func'], # 'pol1',
'S+',
'',
float(str(r.ratiofitlimits[0]).replace('START', str(v.axisrange[0]))),
float(str(r.ratiofitlimits[1]).replace('END', str(v.axisrange[1]))),
)
slope = fitresult.Parameter(1)
slope_error = fitresult.ParError(1)
intercept = fitresult.Parameter(0)
intercept_error = fitresult.ParError(0)
if issecondfit:
self.ratiohistos[v + r].GetListOfFunctions().FindObject('func' + v.name + r.name).SetLineColor(4)
self.ratiohistos[v + r + 'label'] = ROOT.TPaveLabel(v.axisrange[0] + 0.05 * (v.axisrange[1] - v.axisrange[0]), self.yaxisrangeratio[0],
v.axisrange[0] + 0.333 * (v.axisrange[1] - v.axisrange[0]), self.yaxisrangeratio[0] + 0.5 * (self.yaxisrangeratio[1] - self.yaxisrangeratio[0]),
'#color[4]{#splitline{slope = ' + str(round(slope, 6)) + ' #pm ' + str(round(slope_error, 6)) + '}{intercept = ' + str(round(intercept, 6)) + ' #pm ' + str(round(intercept_error, 6)) + '}}')
else:
self.ratiohistos[v + r + 'label'] = ROOT.TPaveLabel(v.axisrange[0] + 0.05 * (v.axisrange[1] - v.axisrange[0]), self.yaxisrangeratio[0] + 0.5 * (self.yaxisrangeratio[1] - self.yaxisrangeratio[0]),
v.axisrange[0] + 0.333 * (v.axisrange[1] - v.axisrange[0]), self.yaxisrangeratio[1],
'#color[2]{#splitline{slope = ' + str(round(slope, 6)) + ' #pm ' + str(round(slope_error, 6)) + '}{intercept = ' + str(round(intercept, 6)) + ' #pm ' + str(round(intercept_error, 6)) + '}}')
self.ratiohistos[v + r + 'label'].SetFillStyle(0)
self.ratiohistos[v + r + 'label'].SetBorderSize(0)
self.ratiohistos[v + r + 'label'].SetTextSize(0.2)
issecondfit = True
elif r.category == 'diff':
if not len(r.name.split(':')) == 2:
raise NotImplementedError('cannot interpret ratio')
minuend = r.name.split(':')[0]
subtrahend = r.name.split(':')[1]
if minuend == 'STACK':
self.ratiohistos[v + r] = self.sums[v].Clone(v + r)
else:
self.ratiohistos[v + r] = self.histos[v.name + minuend].Clone(v + r)
if subtrahend == 'STACK':
self.ratiohistos[v + r].Add(self.sums[v], -1)
else:
self.ratiohistos[v + r].Add(self.histos[v.name + subtrahend], -1)
self.ratiohistos[v + r].SetName(self.ratiohistos[v + r].GetName().replace(':', 'DIFF')) # TODO: do this?
elif r.category in ['cutsig', 'binsig']:
if not len(r.name.split(':')) == 3:
raise NotImplementedError('cannot interpret ratio')
signal = r.name.split(':')[0]
background = r.name.split(':')[1]
syserrB = float(r.name.split(':')[2])
for s in self.stacksamples + self.markersamples + self.linesamples:
self.ratiohistos[v + r] = self.histos[v + s].Clone(v + r)
self.ratiohistos[v + r].Reset()
break
maxsig = 0.
maxsigerr = None
maxsigbin = None
maxsigS = None
maxsigB = None
nbins = self.ratiohistos[v + r].GetNbinsX()
for b in range(nbins):
b += 1
if r.category == 'binsig': nbins = b
staterrS = ctypes.c_double(0.)
staterrB = ctypes.c_double(0.)
if signal == 'STACK':
S = self.sums[v].IntegralAndError(b, nbins, staterrS)
else:
S = self.histos[v.name + signal].IntegralAndError(b, nbins, staterrS)
if background == 'STACK':
B = self.sums[v].IntegralAndError(b, nbins, staterrB)
else:
B = self.histos[v.name + background].IntegralAndError(b, nbins, staterrB)
# TODO: implement error like this?
if S > 0 and B > 0:
sig = ROOT.RooStats.AsimovSignificance(S, B, syserrB*B)
sigUp = ROOT.RooStats.AsimovSignificance(S+staterrS.value, B-staterrB.value, syserrB*(B-staterrB.value))
sigDown = ROOT.RooStats.AsimovSignificance(S-staterrS.value, B+staterrB.value, syserrB*(B+staterrB.value))
if not (math.isnan(sig) or math.isnan(sigUp) or math.isnan(sigDown)):
self.ratiohistos[v + r].SetBinContent(b, sig)
self.ratiohistos[v + r].SetBinError(b, 0.5*(sigUp-sigDown))
if sigDown > maxsig:
maxsig = sig
maxsigerr = 0.5*(sigUp-sigDown)
maxsigbin = b
maxsigS = S
maxsigB = B
# print('')
# print(self.ratiohistos[v + r].GetBinLowEdge(b))
# print(S)
# print(staterrS)
# print(B)
# print(staterrB)
# print(sig)
# print(sigUp)
# print(sigDown)
if v.verbosesignificance:
print(' ' + r.name)
if maxsig > 0:
print(' max significance for bin ' + str(maxsigbin)
+ ' (low edge: ' + str(self.ratiohistos[v + r].GetBinLowEdge(maxsigbin)) + ')'
+ ' = ' + str(round(maxsig, 3)) + ' +- ' + str(round(maxsigerr, 3)))
print(' S = ' + str(round(maxsigS, 2)) + ' (' + str(round(100 * maxsigS / self.histos[v.name + signal].Integral(), 1)) + '%), B = ' + str(round(maxsigB, 2)))
else:
print(' no significance > 0')
elif r.category == 'calibration':
if not len(r.name.split(':')) == 2:
raise NotImplementedError('cannot interpret calibration')
signal = r.name.split(':')[0]
background = r.name.split(':')[1]
if signal == 'STACK':
signalhisto = self.sums[v].Clone('calibration_signalhisto')
else:
signalhisto = self.histos[v.name + signal].Clone('calibration_signalhisto')
if background == 'STACK':
backgroundhisto = self.sums[v].Clone('calibration_backgroundhisto')
else:
backgroundhisto = self.histos[v.name + background].Clone('calibration_backgroundhisto')
if signalhisto.Integral() == 0 or backgroundhisto.Integral() == 0:
self.ratiohistos[v + r] = None
print('skipping calibration histogram because integral is zero')
else:
# TODO: do this scaling??
signalhisto.Scale(1. / signalhisto.Integral())
backgroundhisto.Scale(1. / backgroundhisto.Integral())
backgroundhisto.Add(signalhisto)
self.ratiohistos[v + r] = signalhisto.Clone(v + r)
self.ratiohistos[v + r].Divide(backgroundhisto)
elif r.category == 'efficiency':
if not len(r.name.split(':')) == 2:
raise NotImplementedError('cannot interpret efficiency')
name_pass = r.name.split(':')[0]
name_total = r.name.split(':')[1]
if name_pass == 'STACK':
histo_pass = self.sums[v].Clone('efficiency_passhisto')
else:
histo_pass = self.histos[v.name + name_pass].Clone('efficiency_passhisto')
if name_total == 'STACK':
histo_total = self.sums[v].Clone('efficiency_totalhisto')
else:
histo_total = self.histos[v.name + name_total].Clone('efficiency_totalhisto')
if ROOT.TEfficiency.CheckConsistency(histo_pass, histo_total):
self.ratiohistos[v + r + 'eff'] = ROOT.TEfficiency(histo_pass, histo_total)
self.ratiohistos[v + r + 'eff'].SetName(r.name + 'eff')
self.ratiohistos[v + r] = histo_pass.Clone(r.name + 'empty')
self.ratiohistos[v + r].Reset()
else:
self.ratiohistos[v + r] = None
print('skipping efficiency because histograms are not compatible')
else:
raise NotImplementedError('unknown ratio type')
def _style_histos(self, verbose=1):
print('\n# Style Histos')
for v in self.variables:
if verbose > 1: print(v)
for s in self.stacksamples + self.markersamples + self.linesamples:
self.emptylinhistos[v] = self.histos[v + s].Clone('emptylin' + v.name)
self.emptyloghistos[v] = self.histos[v + s].Clone('emptylog' + v.name)
break
for emptyhisto in [self.emptylinhistos[v], self.emptyloghistos[v]]:
emptyhisto.Reset()
emptyhisto.GetYaxis().SetTitle(self.ylabel)
if len(self.ratios) > 0:
emptyhisto.GetXaxis().SetLabelSize(0)
else:
emptyhisto.GetXaxis().SetTitle(v.title)
globalmin = min([self.sums[v].GetMinimum(0) if len(self.stacksamples) > 0 else float('inf')] +
[self.histos[v + s].GetMinimum(0) for s in self.markersamples + self.linesamples if s.group is None])
globalmax = max([self.sums[v].GetMaximum() if len(self.stacksamples) > 0 else 0] +
[self.histos[v + s].GetMaximum() for s in self.markersamples + self.linesamples if s.group is None])
if v.ymaxlog is None: logmax = globalmax
else: logmax = v.ymaxlog
if v.yminlog is None: logmin = globalmin
else: logmin = v.yminlog
logrange = ROOT.TMath.Log10(logmax) - ROOT.TMath.Log10(logmin)
if v.yminlin is None:
self.emptylinhistos[v].SetMinimum(0.)
else:
self.emptylinhistos[v].SetMinimum(v.yminlin)
if v.ymaxlin is None:
self.emptylinhistos[v].SetMaximum(2. * globalmax)
else:
self.emptylinhistos[v].SetMaximum(v.ymaxlin)
if v.yminlog is None:
self.emptyloghistos[v].SetMinimum(0.5 * globalmin)
else:
self.emptyloghistos[v].SetMinimum(v.yminlog)
if v.ymaxlog is None:
self.emptyloghistos[v].SetMaximum(globalmax * 10 ** max(1, logrange))
else:
self.emptyloghistos[v].SetMaximum(v.ymaxlog)
for s in self.stacksamples:
self.histos[v + s].SetLineWidth(0)
self.histos[v + s].SetLineColor(s.color)
self.histos[v + s].SetMarkerSize(0)
self.histos[v + s].SetFillStyle(s.fillstyle)
self.histos[v + s].SetFillColor(s.color)
for s in self.markersamples:
self.histos[v + s].SetLineWidth(self.linewidth)
self.histos[v + s].SetLineColor(s.color)
self.histos[v + s].SetMarkerSize(self.markersize)
self.histos[v + s].SetMarkerColor(s.color)
for s in self.linesamples:
self.histos[v + s].SetLineWidth(self.linewidth)
self.histos[v + s].SetLineStyle(s.linestyle)
self.histos[v + s].SetLineColor(s.color)
self.histos[v + s].SetMarkerSize(0)
isfirstratiohisto = True
if len(v.systematics) > 0: