forked from alisw/MachineLearningHEP
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutilities_plot.py
More file actions
1397 lines (1227 loc) · 54.1 KB
/
utilities_plot.py
File metadata and controls
1397 lines (1227 loc) · 54.1 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
#############################################################################
## © Copyright CERN 2023. All rights not expressly granted are reserved. ##
## Author: Gian.Michele.Innocenti@cern.ch ##
## This program is free software: you can redistribute it and/or modify it ##
## under the terms of the GNU General Public License as published by the ##
## Free Software Foundation, either version 3 of the License, or (at your ##
## option) any later version. This program is distributed in the hope that ##
## it will be useful, but WITHOUT ANY WARRANTY; without even the implied ##
## warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. ##
## See the GNU General Public License for more details. ##
## You should have received a copy of the GNU General Public License ##
## along with this program. if not, see <https://www.gnu.org/licenses/>. ##
#############################################################################
"""
Script containing all helper functions related to plotting with ROOT
Script also contains the "class Errors", used for systematic uncertainties (to
replace AliHFSystErr from AliPhysics).
"""
# pylint: disable=too-many-lines
import math
from array import array
import matplotlib.pyplot as plt
import numpy as np
# from root_numpy import fill_hist # pylint: disable=import-error, no-name-in-module
# pylint: disable=import-error, no-name-in-module
from ROOT import (
TH1,
TH1F,
TH2,
TH2F,
TH3F,
TCanvas,
TFile,
TGraphAsymmErrors,
TLegend,
TMatrixD,
TPad,
gROOT,
gStyle,
kBlack,
kBlue,
kGreen,
kRed,
kWhite,
)
from machine_learning_hep.io_ml_utils import dump_yaml_from_dict, parse_yaml
from machine_learning_hep.logger import get_logger
def prepare_fig(plot_count):
"""
Prepare figure for ML optimiser plots
"""
if plot_count == 1:
figure = plt.figure(figsize=(20, 15))
nrows, ncols = (1, 1)
else:
figure = plt.figure(figsize=(25, 15))
nrows, ncols = (2, (plot_count + 1) / 2)
figure.subplots_adjust(hspace=0.5)
return figure, nrows, ncols
def buildarray(listnumber):
"""
Build an array out of a list, useful for histogram binning
"""
arraynumber = array("d", listnumber)
return arraynumber
def buildbinning(nbinsx, xlow, xup):
"""
Build a list for binning out of bin limits and number of bins
"""
listnumber = [xlow + (xup - xlow) / nbinsx * i for i in range(nbinsx + 1)]
return buildarray(listnumber)
def buildhisto(h_name, h_tit, arrayx, arrayy=None, arrayz=None):
"""
Create a histogram of size 1D, 2D, 3D, depending on the number of arguments given
"""
histo = None
def binning(binning_array):
return len(binning_array) - 1, binning_array
if arrayz:
histo = TH3F(h_name, h_tit, *binning(arrayx), *binning(arrayy), *binning(arrayz))
elif arrayy:
histo = TH2F(h_name, h_tit, *binning(arrayx), *binning(arrayy))
else:
histo = TH1F(h_name, h_tit, *binning(arrayx))
histo.Sumw2()
return histo
# def makefill1dhist(df_, h_name, h_tit, arrayx, nvar1):
# """
# Create a TH1F histogram and fill it with one variables from a dataframe.
# """
# histo = buildhisto(h_name, h_tit, arrayx)
# fill_hist(histo, df_[nvar1])
# return histo
def build2dhisto(titlehist, arrayx, arrayy):
"""
Create a TH2 histogram from two axis arrays.
"""
return buildhisto(titlehist, titlehist, arrayx, arrayy)
# def makefill2dhist(df_, titlehist, arrayx, arrayy, nvar1, nvar2):
# """
# Create a TH2F histogram and fill it with two variables from a dataframe.
# """
# histo = build2dhisto(titlehist, arrayx, arrayy)
# df_rd = df_[[nvar1, nvar2]]
# arr2 = df_rd.to_numpy()
# fill_hist(histo, arr2)
# return histo
def makefill2dweighed(df_, titlehist, arrayx, arrayy, nvar1, nvar2, weight):
"""
Create a TH2F histogram and fill it with two variables from a dataframe.
"""
histo = build2dhisto(titlehist, arrayx, arrayy)
for row in df_.itertuples():
histo.Fill(getattr(row, nvar1), getattr(row, nvar2), getattr(row, weight))
return histo
def makefill3dhist(df_, titlehist, arrayx, arrayy, arrayz, nvar1, nvar2, nvar3):
"""
Create a TH3F histogram and fill it with three variables from a dataframe.
"""
histo = buildhisto(titlehist, titlehist, arrayx, arrayy, arrayz)
# df_rd = df_[[nvar1, nvar2, nvar3]]
# arr3 = df_rd.to_numpy()
# fill_hist(histo, arr3) # this does not work, gives an empty histogram
for row in df_.itertuples():
histo.Fill(getattr(row, nvar1), getattr(row, nvar2), getattr(row, nvar3))
return histo
def makefill3dweighed(df_, titlehist, arrayx, arrayy, arrayz, nvar1, nvar2, nvar3, weight):
"""
Create a TH3F histogram and fill it with three variables from a dataframe.
"""
histo = buildhisto(titlehist, titlehist, arrayx, arrayy, arrayz)
# df_rd = df_[[nvar1, nvar2, nvar3]]
# arr3 = df_rd.to_numpy()
# fill_hist(histo, arr3) # this does not work, gives an empty histogram
for row in df_.itertuples():
histo.Fill(getattr(row, nvar1), getattr(row, nvar2), getattr(row, nvar3), getattr(row, weight))
return histo
# def fill2dhist(df_, histo, nvar1, nvar2):
# """
# Fill a TH2 histogram with two variables from a dataframe.
# """
# df_rd = df_[[nvar1, nvar2]]
# arr2 = df_rd.values
# fill_hist(histo, arr2)
# return histo
def fill2dweighed(df_, histo, nvar1, nvar2, weight):
"""
Fill a TH2 histogram with two variables from a dataframe.
"""
# df_rd = df_[[nvar1, nvar2]]
# arr2 = df_rd.values
# fill_hist(histo, arr2)
if isinstance(histo, TH2):
for row in df_.itertuples():
histo.Fill(getattr(row, nvar1), getattr(row, nvar2), getattr(row, weight))
else:
print("WARNING!Incorrect histogram type (should be TH2F) ")
return histo
def fillweighed(df_, histo, nvar1, weight):
"""
Fill a TH1 weighted histogram.
"""
# df_rd = df_[[nvar1, nvar2]]
# arr2 = df_rd.values
# fill_hist(histo, arr2)
if isinstance(histo, TH1):
for row in df_.itertuples():
histo.Fill(getattr(row, nvar1), getattr(row, weight))
else:
print("WARNING!Incorrect histogram type (should be TH1F) ")
return histo
def rebin_histogram(src_histo, new_histo):
"""
Rebins the content of the histogram src_histo into new_histo.
If average is set to True, the bin width is considered when rebinning.
"""
if "TH1" not in src_histo.ClassName() and "TH1" not in new_histo.ClassName():
get_logger().fatal("So far, can only work with TH1")
x_axis_new = new_histo.GetXaxis()
x_axis_src = new_histo.GetXaxis()
for i in range(1, x_axis_new.GetNbins() + 1):
x_new = [
x_axis_new.GetBinLowEdge(i),
x_axis_new.GetBinUpEdge(i),
x_axis_new.GetBinWidth(i),
x_axis_new.GetBinCenter(i),
]
width_src = []
y_src = []
ye_src = []
for j in range(1, x_axis_src.GetNbins() + 1):
x_src = [x_axis_src.GetBinLowEdge(j), x_axis_src.GetBinUpEdge(j), x_axis_src.GetBinWidth(j)]
if x_src[1] <= x_new[0]:
continue
if x_src[0] >= x_new[1]:
continue
if x_src[0] < x_new[0]:
get_logger().fatal(
"For bin %i, bin %i low edge is too low! [%f, %f] vs [%f, %f]",
i,
j,
x_new[0],
x_new[1],
x_src[0],
x_src[1],
)
if x_src[1] > x_new[1]:
get_logger().fatal(
"For bin %i, bin %i up edge is too high! [%f, %f] vs [%f, %f]",
i,
j,
x_new[0],
x_new[1],
x_src[0],
x_src[1],
)
y_src.append(src_histo.GetBinContent(j))
ye_src.append(src_histo.GetBinError(j))
width_src.append(x_src[-1])
if abs(sum(width_src) - x_new[2]) > 0.00001:
get_logger().fatal("Width does not match")
new_histo.SetBinContent(i, sum(y_src))
new_histo.SetBinError(i, np.sqrt(sum(j**2 for j in ye_src)))
return new_histo
def load_root_style_simple():
"""
Set basic ROOT style for histograms
"""
gStyle.SetOptStat(0)
gStyle.SetPalette(0)
gStyle.SetCanvasColor(0)
gStyle.SetFrameFillColor(0)
def load_root_style():
"""
Set more advanced ROOT style for histograms
"""
gROOT.SetStyle("Plain")
gStyle.SetOptStat(0)
gStyle.SetPalette(0)
gStyle.SetCanvasColor(0)
gStyle.SetFrameFillColor(0)
gStyle.SetTitleOffset(1.15, "y")
gStyle.SetTitleFont(42, "xy")
gStyle.SetLabelFont(42, "xy")
gStyle.SetTitleSize(0.042, "xy")
gStyle.SetLabelSize(0.035, "xy")
gStyle.SetPadTickX(1)
gStyle.SetPadTickY(1)
# def scatterplotroot(dfevt, nvar1, nvar2, nbins1, min1, max1, nbins2, min2, max2):
# """
# Make TH2F scatterplot between two variables from dataframe
# """
# hmult1_mult2 = TH2F(nvar1 + nvar2, nvar1 + nvar2, nbins1, min1, max1, nbins2, min2, max2)
# dfevt_rd = dfevt[[nvar1, nvar2]]
# arr2 = dfevt_rd.values
# fill_hist(hmult1_mult2, arr2)
# return hmult1_mult2
def find_axes_limits(histos, use_log_y=False):
"""
Finds common axes limits for list of histograms provided
"""
# That might be considered to be a hack since it now only has a chance to work
# reasonably well if there is at least one histogram.
max_y = max(h.GetMaximum() for h in histos if isinstance(h, TH1))
min_y = min(h.GetMinimum() for h in histos if isinstance(h, TH1))
if not min_y > 0.0 and use_log_y:
min_y = 10.0e-9
max_x = max(h.GetXaxis().GetXmax() for h in histos)
min_x = min(h.GetXaxis().GetXmin() for h in histos)
return min_x, max_x, min_y, max_y
def style_histograms(
histos, linestyles=None, markerstyles=None, colors=None, linewidths=None, fillstyles=None, fillcolors=None
):
"""
Loops over given line- and markerstyles as well as colors applying them to the given list
of histograms. The list of histograms might be larger than the styles provided. In that case
the styles start again
"""
if linestyles is None:
linestyles = [1, 1, 1, 1]
if markerstyles is None:
markerstyles = [2, 4, 5, 32]
if colors is None:
colors = [kBlack, kRed, kGreen + 2, kBlue]
if linewidths is None:
linewidths = [1]
if fillstyles is None:
fillstyles = [0]
if fillcolors is None:
fillcolors = [kWhite]
for i, h in enumerate(histos):
h.SetLineColor(colors[i % len(colors)])
h.SetLineStyle(linestyles[i % len(linestyles)])
h.SetMarkerStyle(markerstyles[i % len(markerstyles)])
h.SetMarkerColor(colors[i % len(colors)])
h.SetLineWidth(linewidths[i % len(linewidths)])
h.SetFillStyle(fillstyles[i % len(fillstyles)])
h.SetFillColor(fillcolors[i % len(fillcolors)])
h.GetXaxis().SetTitleSize(0.02)
h.GetXaxis().SetTitleSize(0.02)
h.GetYaxis().SetTitleSize(0.02)
def divide_all_by_first(histos):
"""
Divides all histograms in the list by the first one in the list and returns the
divided histograms in the same order
"""
histos_ratio = []
for h in histos:
histos_ratio.append(h.Clone(f"{h.GetName()}_ratio"))
histos_ratio[-1].Divide(histos[0])
return histos_ratio
def divide_by_eachother(histos1, histos2, scale=None, rebin2=None):
"""
Divides all histos1 by histos2 and returns the
divided histograms in the same order
"""
if len(histos1) != len(histos2):
get_logger().fatal("Number of histograms mismatch, %i vs. %i", len(histos1), len(histos2))
histos_ratio = []
for i, _ in enumerate(histos1):
origname = histos1[i].GetName()
if rebin2 is not None:
rebin = array("d", rebin2)
histos1[i] = histos1[i].Rebin(len(rebin2) - 1, f"{histos1[i].GetName()}_rebin", rebin)
histos2[i] = histos2[i].Rebin(len(rebin2) - 1, f"{histos2[i].GetName()}_rebin", rebin)
if scale is not None:
histos1[i].Scale(1.0 / scale[0])
histos2[i].Scale(1.0 / scale[1])
histos_ratio.append(histos1[i].Clone(f"{origname}_ratio"))
histos_ratio[-1].Divide(histos2[i])
return histos_ratio
def divide_by_eachother_barlow(histos1, histos2, scale=None, rebin2=None):
"""
Divides all histos1 by histos2 using Barlow for stat. unc. and returns the
divided histograms in the same order
"""
if len(histos1) != len(histos2):
get_logger().fatal("Number of histograms mismatch, %i vs. %i", len(histos1), len(histos2))
histos_ratio = []
for i, _ in enumerate(histos1):
origname = histos1[i].GetName()
if rebin2 is not None:
rebin = array("d", rebin2)
histos1[i] = histos1[i].Rebin(len(rebin2) - 1, f"{histos1[i].GetName()}_rebin", rebin)
histos2[i] = histos2[i].Rebin(len(rebin2) - 1, f"{histos2[i].GetName()}_rebin", rebin)
if scale is not None:
histos1[i].Scale(1.0 / scale[0])
histos2[i].Scale(1.0 / scale[1])
stat1 = []
stat2 = []
for j in range(histos1[i].GetNbinsX()):
stat1.append(histos1[i].GetBinError(j + 1) / histos1[i].GetBinContent(j + 1))
stat2.append(histos2[i].GetBinError(j + 1) / histos2[i].GetBinContent(j + 1))
histos_ratio.append(histos1[i].Clone(f"{origname}_ratio"))
histos_ratio[-1].Divide(histos2[i])
for j in range(histos_ratio[-1].GetNbinsX()):
statunc = math.sqrt(abs(stat1[j] * stat1[j] - stat2[j] * stat2[j]))
histos_ratio[-1].SetBinError(j + 1, histos_ratio[-1].GetBinContent(j + 1) * statunc)
return histos_ratio
def divide_all_by_first_multovermb(histos):
"""
Divides all histograms in the list by the first one in the list and returns the
divided histograms in the same order
"""
histos_ratio = []
err = []
for h in histos:
histos_ratio.append(h.Clone(f"{h.GetName()}_ratio"))
stat = []
for j in range(h.GetNbinsX()):
stat.append(h.GetBinError(j + 1) / h.GetBinContent(j + 1))
err.append(stat)
histos_ratio[-1].Divide(histos[0])
for j in range(h.GetNbinsX()):
statunc = math.sqrt(abs(err[-1][j] * err[-1][j] - err[0][j] * err[0][j]))
histos_ratio[-1].SetBinError(j + 1, histos_ratio[-1].GetBinContent(j + 1) * statunc)
return histos_ratio
def put_in_pad(pad, use_log_y, histos, title="", x_label="", y_label="", yrange=None, **kwargs):
"""
Providing a TPad this plots all given histograms in that pad adjusting the X- and Y-ranges
accordingly.
"""
draw_options = kwargs.get("draw_options", None)
min_x, max_x, min_y, max_y = find_axes_limits(histos, use_log_y)
pad.SetLogy(use_log_y)
pad.cd()
scale_frame_y = (0.01, 100.0) if use_log_y else (0.7, 1.2)
if yrange is None:
yrange = [min_y * scale_frame_y[0], max_y * scale_frame_y[1]]
frame = pad.DrawFrame(min_x, yrange[0], max_x, yrange[1], f"{title};{x_label};{y_label}")
frame.GetYaxis().SetTitleOffset(1.2)
pad.SetTicks()
if draw_options is None:
draw_options = ["" for _ in histos]
for h, o in zip(histos, draw_options):
h.Draw(f"same {o}")
# pylint: disable=too-many-statements
def plot_histograms(
histos,
use_log_y=False,
ratio_=False,
legend_titles=None,
title="",
x_label="",
y_label_up="",
y_label_ratio="",
save_path="./plot.eps",
**kwargs,
):
"""
Throws all given histograms into one canvas. If desired, a ratio plot will be added.
"""
gStyle.SetOptStat(0)
justratioplot = False
yrange = None
if isinstance(ratio_, list):
ratio = ratio_[0]
justratioplot = ratio_[1]
yrange = ratio_[2]
else:
justratioplot = ratio_
ratio = ratio_
linestyles = kwargs.get("linestyles", None)
markerstyles = kwargs.get("markerstyles", None)
colors = kwargs.get("colors", None)
draw_options = kwargs.get("draw_options", None)
linewidths = kwargs.get("linewidths", None)
fillstyles = kwargs.get("fillstyles", None)
fillcolors = kwargs.get("fillcolors", None)
canvas_name = kwargs.get("canvas_name", "Canvas")
style_histograms(histos, linestyles, markerstyles, colors, linewidths, fillstyles, fillcolors)
canvas = TCanvas("canvas", canvas_name, 800, 800)
pad_up_start = 0.4 if ratio else 0.0
pad_up = TPad("pad_up", "", 0.0, pad_up_start, 1.0, 1.0)
if ratio:
pad_up.SetBottomMargin(0.0)
pad_up.Draw()
x_label_up_tmp = x_label if not ratio else ""
put_in_pad(pad_up, use_log_y, histos, title, x_label_up_tmp, y_label_up, yrange, draw_options=draw_options)
pad_up.cd()
legend = None
if legend_titles is not None:
if justratioplot:
legend = TLegend(0.2, 0.65, 0.6, 0.85)
else:
legend = TLegend(0.45, 0.65, 0.85, 0.85)
legend.SetBorderSize(0)
legend.SetFillColor(0)
legend.SetFillStyle(0)
legend.SetTextFont(42)
legend.SetTextSize(0.02)
for h, l in zip(histos, legend_titles):
if l is not None:
legend.AddEntry(h, l)
legend.Draw()
canvas.cd()
pad_ratio = None
histos_ratio = None
if ratio and justratioplot is False:
histos_ratio = divide_all_by_first(histos)
pad_ratio = TPad("pad_ratio", "", 0.0, 0.05, 1.0, pad_up_start)
pad_ratio.SetTopMargin(0.0)
pad_ratio.SetBottomMargin(0.3)
pad_ratio.Draw()
put_in_pad(pad_ratio, False, histos_ratio, "", x_label, y_label_ratio)
canvas.SaveAs(save_path)
index = save_path.rfind(".")
# Save also everything into a ROOT file
root_save_path = save_path[:index] + ".root"
root_file = TFile.Open(root_save_path, "RECREATE")
for h in histos:
h.Write()
canvas.Write()
root_file.Close()
canvas.Close()
def save_histograms(histos, save_path="./plot.root"):
"""
Save everything into a ROOT file for offline plotting
"""
index = save_path.rfind(".")
# Save also everything into a ROOT file
root_save_path = save_path[:index] + ".root"
root_file = TFile.Open(root_save_path, "RECREATE")
for h in histos:
h.Write()
root_file.Close()
# pylint: disable=too-many-branches
def calc_systematic_multovermb(errnum_list, errden_list, n_bins, same_mc_used=False, justfd=-99):
"""
Returns a list of total errors taking into account the defined correlations
Propagation uncertainties defined for Ds(mult) / Ds(MB). Check if applicable to your situation
"""
tot_list = [[0.0, 0.0, 0.0, 0.0] for _ in range(n_bins)]
if n_bins != len(list(errnum_list.errors.values())[0]) or n_bins != len(list(errden_list.errors.values())[0]):
get_logger().fatal(
"Number of bins and number of errors mismatch, %i vs. %i vs. %i",
n_bins,
len(list(errnum_list.errors.values())[0]),
len(list(errden_list.errors.values())[0]),
)
listimpl = [
"yield",
"cut",
"pid",
"feeddown_mult",
"feeddown_mult_spectra",
"trigger",
"multiplicity_interval",
"multiplicity_weights",
"track",
"ptshape",
"feeddown_NB",
"sigmav0",
"branching_ratio",
"statunceff",
]
j = 0
for (_, errnum), (_, errden) in zip(errnum_list.errors.items(), errden_list.errors.items()):
for i in range(n_bins):
if errnum_list.names[j] not in listimpl:
get_logger().fatal("Unknown systematic name: %s", errnum_list.names[j])
if errnum_list.names[j] != errden_list.names[j]:
get_logger().fatal("Names not in same order: %s vs %s", errnum_list.names[j], errden_list.names[j])
for nb in range(len(tot_list[i])):
if errnum_list.names[j] == "yield" and justfd is not True:
# Partially correlated, take largest
tot_list[i][nb] += max(errnum[i][nb], errden[i][nb]) * max(errnum[i][nb], errden[i][nb])
elif errnum_list.names[j] == "cut" and justfd is not True:
# Partially correlated, take largest
tot_list[i][nb] += max(errnum[i][nb], errden[i][nb]) * max(errnum[i][nb], errden[i][nb])
elif errnum_list.names[j] == "pid" and justfd is not True:
# Correlated, do nothing
pass
elif errnum_list.names[j] == "feeddown_mult" and justfd is not False:
# Assign directly from multiplicity case, no syst for MB
tot_list[i][nb] += errnum[i][nb] * errnum[i][nb]
elif errnum_list.names[j] == "feeddown_mult_spectra" and justfd is not False:
# Ratio here, skip spectra syst
pass
elif errnum_list.names[j] == "trigger" and justfd is not True:
# Assign directly from multiplicity case, no syst for MB
tot_list[i][nb] += errnum[i][nb] * errnum[i][nb]
elif errnum_list.names[j] == "multiplicity_interval" and justfd is not True:
# FD: estimated using 7TeV strategy directly for ratio
tot_list[i][nb] += errnum[i][nb] * errnum[i][nb]
elif errnum_list.names[j] == "multiplicity_weights" and justfd is not True:
# Uncorrelated
tot_list[i][nb] += errnum[i][nb] * errnum[i][nb] + errden[i][nb] * errden[i][nb]
elif errnum_list.names[j] == "track" and justfd is not True:
# Correlated, do nothing
pass
elif errnum_list.names[j] == "ptshape" and justfd is not True:
# Correlated, assign difference
diff = abs(errnum[i][nb] - errden[i][nb])
tot_list[i][nb] += diff * diff
elif errnum_list.names[j] == "feeddown_NB" and justfd is not False:
# Correlated, do nothing
pass
elif errnum_list.names[j] == "sigmav0" and justfd is not True:
# Correlated and usually not plotted in boxes, do nothing
pass
elif errnum_list.names[j] == "branching_ratio" and justfd is not True:
# Correlated, do nothing
pass
elif errnum_list.names[j] == "statunceff" and justfd is not True:
# Uncorrelated (new since June 2020, add it in syst boxes)
# Part of stat is in common when same MC is used, so doing Barlow test there
if same_mc_used is False:
tot_list[i][nb] += errnum[i][nb] * errnum[i][nb] + errden[i][nb] * errden[i][nb]
else:
tot_list[i][nb] += abs(errnum[i][nb] * errnum[i][nb] - errden[i][nb] * errden[i][nb])
j = j + 1
tot_list = np.sqrt(tot_list)
return tot_list
# pylint: disable=too-many-branches
def calc_systematic_mesonratio(errnum_list, errden_list, n_bins, justfd=-99):
"""
Returns a list of total errors taking into account the defined correlations
Propagation uncertainties defined for Ds(MB or mult) / D0(MB or mult).
Check if applicable to your situation
"""
tot_list = [[0.0, 0.0, 0.0, 0.0] for _ in range(n_bins)]
if n_bins != len(list(errnum_list.errors.values())[0]) or n_bins != len(list(errden_list.errors.values())[0]):
get_logger().fatal(
"Number of bins and number of errors mismatch, %i vs. %i vs. %i",
n_bins,
len(list(errnum_list.errors.values())[0]),
len(list(errden_list.errors.values())[0]),
)
listimpl = [
"yield",
"cut",
"pid",
"feeddown_mult",
"feeddown_mult_spectra",
"trigger",
"multiplicity_interval",
"multiplicity_weights",
"track",
"ptshape",
"feeddown_NB",
"sigmav0",
"branching_ratio",
"statunceff",
]
j = 0
for (_, errnum), (_, errden) in zip(errnum_list.errors.items(), errden_list.errors.items()):
for i in range(n_bins):
if errnum_list.names[j] not in listimpl:
get_logger().fatal("Unknown systematic name: %s", errnum_list.names[j])
if errnum_list.names[j] != errden_list.names[j]:
get_logger().fatal("Names not in same order: %s vs %s", errnum_list.names[j], errden_list.names[j])
for nb in range(len(tot_list[i])):
if errnum_list.names[j] == "yield" and justfd is not True:
# Uncorrelated
tot_list[i][nb] += errnum[i][nb] * errnum[i][nb] + errden[i][nb] * errden[i][nb]
elif errnum_list.names[j] == "cut" and justfd is not True:
# Uncorrelated
tot_list[i][nb] += errnum[i][nb] * errnum[i][nb] + errden[i][nb] * errden[i][nb]
elif errnum_list.names[j] == "pid" and justfd is not True:
# Correlated, assign difference
diff = abs(errnum[i][nb] - errden[i][nb])
tot_list[i][nb] += diff * diff
elif errnum_list.names[j] == "feeddown_mult_spectra" and justfd is not False:
# Fully correlated
ynum = errnum_list.errors["feeddown_NB"][i][4]
yden = errden_list.errors["feeddown_NB"][i][4]
# Relative uncertainties stored, make absolute
ynuml = ynum - ynum * errnum[i][2]
ydenl = yden - yden * errden[i][2]
ynumh = ynum + ynum * errnum[i][3]
ydenh = yden + yden * errden[i][3]
rat = [ynuml / ydenl, ynum / yden, ynumh / ydenh]
minsys = min(rat)
maxsys = max(rat)
if nb == 2:
tot_list[i][nb] += (rat[1] - minsys) * (rat[1] - minsys) / (rat[1] * rat[1])
if nb == 3:
tot_list[i][nb] += (maxsys - rat[1]) * (maxsys - rat[1]) / (rat[1] * rat[1])
elif errnum_list.names[j] == "feeddown_mult" and justfd is not False:
# Spectra here, skip ratio systematic
pass
elif errnum_list.names[j] == "trigger" and justfd is not True:
# Correlated, do nothing
pass
elif errnum_list.names[j] == "feeddown_NB" and justfd is not False:
# Fully correlated under assumption central Fc value stays within Nb syst
ynum = errnum[i][4]
yden = errden[i][4]
# Absolute uncertainties stored
ynuml = ynum - errnum[i][2]
ydenl = yden - errden[i][2]
ynumh = ynum + errnum[i][3]
ydenh = yden + errden[i][3]
rat = [ynuml / ydenl, ynum / yden, ynumh / ydenh]
minsys = min(rat)
maxsys = max(rat)
if nb == 2:
tot_list[i][nb] += (rat[1] - minsys) * (rat[1] - minsys) / (rat[1] * rat[1])
if nb == 3:
tot_list[i][nb] += (maxsys - rat[1]) * (maxsys - rat[1]) / (rat[1] * rat[1])
elif errnum_list.names[j] == "multiplicity_weights" and justfd is not True:
# Correlated, assign difference
diff = abs(errnum[i][nb] - errden[i][nb])
tot_list[i][nb] += diff * diff
elif errnum_list.names[j] == "track" and justfd is not True:
# Correlated, assign difference
diff = abs(errnum[i][nb] - errden[i][nb])
tot_list[i][nb] += diff * diff
elif errnum_list.names[j] == "ptshape" and justfd is not True:
# Uncorrelated
tot_list[i][nb] += errnum[i][nb] * errnum[i][nb] + errden[i][nb] * errden[i][nb]
elif errnum_list.names[j] == "multiplicity_interval" and justfd is not True:
# NB: Assuming ratio: 3prongs over 2prongs here! 2prong part cancels
# We use 1/3 of systematic of numerator
tot_list[i][nb] += errnum[i][nb] * errnum[i][nb] / 9
elif errnum_list.names[j] == "sigmav0" and justfd is not True:
# Correlated and usually not plotted in boxes, do nothing
pass
elif errnum_list.names[j] == "branching_ratio" and justfd is not True:
# Uncorrelated (new since May 2020, add it in syst boxes)
tot_list[i][nb] += errnum[i][nb] * errnum[i][nb] + errden[i][nb] * errden[i][nb]
elif errnum_list.names[j] == "statunceff" and justfd is not True:
# Uncorrelated (new since June 2020, add it in syst boxes)
tot_list[i][nb] += errnum[i][nb] * errnum[i][nb] + errden[i][nb] * errden[i][nb]
j = j + 1
tot_list = np.sqrt(tot_list)
return tot_list
def calc_systematic_mesondoubleratio(
errnum_list1, errnum_list2, errden_list1, errden_list2, n_bins, same_mc_used=False, dropbins=None, justfd=-99
):
"""
Returns a list of total errors taking into account the defined correlations
Propagation uncertainties defined for Lc/D0_mult-i / Lc/D0_mult-j.
Check if applicable to your situation
"""
tot_list = [[0.0, 0.0, 0.0, 0.0] for _ in range(n_bins)]
if n_bins != len(list(errnum_list1.errors.values())[0]) or n_bins != len(list(errden_list1.errors.values())[0]):
if dropbins is None:
get_logger().fatal(
"Number of bins and number of errors mismatch, %i vs. %i vs. %i",
n_bins,
len(list(errnum_list1.errors.values())[0]),
len(list(errden_list1.errors.values())[0]),
)
listimpl = [
"yield",
"cut",
"pid",
"feeddown_mult",
"feeddown_mult_spectra",
"trigger",
"multiplicity_interval",
"multiplicity_weights",
"track",
"ptshape",
"feeddown_NB",
"sigmav0",
"branching_ratio",
"statunceff",
]
j = 0
for (_, errnum1), (_, errnum2), (_, errden1), (_, errden2) in zip(
errnum_list1.errors.items(),
errnum_list2.errors.items(),
errden_list1.errors.items(),
errden_list2.errors.items(),
):
for i in range(n_bins):
inum = i
iden = i
if dropbins is not None:
inum = dropbins[0][i]
iden = dropbins[1][i]
if errnum_list1.names[j] not in listimpl:
get_logger().fatal("Unknown systematic name: %s", errnum_list1.names[j])
if errnum_list1.names[j] != errden_list2.names[j]:
get_logger().fatal("Names not in same order: %s vs %s", errnum_list1.names[j], errden_list2.names[j])
for nb in range(len(tot_list[i])):
if errnum_list1.names[j] == "yield" and justfd is not True:
# Uncorrelated
tot_list[i][nb] += (
errnum1[inum][nb] * errnum1[inum][nb]
+ errnum2[inum][nb] * errnum2[inum][nb]
+ errden1[iden][nb] * errden1[iden][nb]
+ errden2[iden][nb] * errden2[iden][nb]
)
elif errnum_list1.names[j] == "cut" and justfd is not True:
# Uncorrelated
tot_list[i][nb] += (
errnum1[inum][nb] * errnum1[inum][nb]
+ errnum2[inum][nb] * errnum2[inum][nb]
+ errden1[iden][nb] * errden1[iden][nb]
+ errden2[iden][nb] * errden2[iden][nb]
)
elif errnum_list1.names[j] == "pid" and justfd is not True:
# Correlated, do nothing
pass
elif errnum_list1.names[j] == "feeddown_mult_spectra" and justfd is not False:
# Correlated, do nothing
pass
elif errnum_list1.names[j] == "feeddown_mult" and justfd is not False:
# Correlated, do nothing
pass
elif errnum_list1.names[j] == "trigger" and justfd is not True:
# Correlated, do nothing
pass
elif errnum_list1.names[j] == "feeddown_NB" and justfd is not False:
# Correlated, do nothing
pass
elif errnum_list1.names[j] == "multiplicity_weights" and justfd is not True:
# Correlated, do nothing
pass
elif errnum_list1.names[j] == "track" and justfd is not True:
# Correlated, do nothing
pass
elif errnum_list1.names[j] == "ptshape" and justfd is not True:
# Uncorrelated
tot_list[i][nb] += (
errnum1[inum][nb] * errnum1[inum][nb]
+ errnum2[inum][nb] * errnum2[inum][nb]
+ errden1[iden][nb] * errden1[iden][nb]
+ errden2[iden][nb] * errden2[iden][nb]
)
elif errnum_list1.names[j] == "multiplicity_interval" and justfd is not True:
# NB: Assuming ratio: 3prongs over 2prongs here! 2prong part cancels
# We use 1/3 of systematic of numerator
tot_list[i][nb] += errden1[iden][nb] * errden1[iden][nb] / 9
elif errnum_list1.names[j] == "sigmav0" and justfd is not True:
# Correlated and usually not plotted in boxes, do nothing
pass
elif errnum_list1.names[j] == "branching_ratio" and justfd is not True:
# Correlated, do nothing
pass
elif errnum_list1.names[j] == "statunceff" and justfd is not True:
# Uncorrelated (new since June 2020, add it in syst boxes)
# Part of stat is in common when same MC is used, so doing Barlow test there
if same_mc_used is False:
tot_list[i][nb] += (
errnum1[inum][nb] * errnum1[inum][nb]
+ errnum2[inum][nb] * errnum2[inum][nb]
+ errden1[iden][nb] * errden1[iden][nb]
+ errden2[iden][nb] * errden2[iden][nb]
)
else:
tot_list[i][nb] += abs(
errnum1[inum][nb] * errnum1[inum][nb] - errden1[iden][nb] * errden1[iden][nb]
) + abs(errnum2[inum][nb] * errnum2[inum][nb] - errden2[iden][nb] * errden2[iden][nb])
j = j + 1
tot_list = np.sqrt(tot_list)
return tot_list
# pylint: disable=too-many-locals
def average_pkpi_pk0s(
histo_pkpi,
histo_pk0s,
graph_pkpi,
graph_pk0s,
err_pkpi,
err_pk0s,
matchbins_pkpi,
matchbins_pk0s,
matchbinsgr_pkpi,
matchbinsgr_pk0s,
):
"""
Strategy described in https://alice-notes.web.cern.ch/node/613
The cross section from each decay channel is given a weight w_{i}^{uncorr} of the
quadratic sum of the relative statistical and uncorrelated systematic uncertainties.
The different decay channels are then averaged using 1/(w_{i}^{uncorr}) as weights
The sources assumed to be uncorrelated are the: yield, cut, pid, BR and stat. unc. eff
The sources assumed to be correlated are the: tracking, pT shape, feed-down (both),
trigger, multiplicity weights,
multiplicity interval, and lumi
The `matchbins_*' parameters are used when there are different binnings.
Example: pK0s has an extra bin [1-2]:
matchbins_pk0s = [1,2,3,4,5,6]
matchbins_pkpi = [-99,1,2,3,4,5]
The input error yaml files should have the same length!
Preferably add [0,0,99,99] for a missing bin
Input files need to be scaled with BR!
"""
if len(matchbins_pkpi) != len(matchbins_pk0s):
get_logger().fatal(
"Length matchbins_pkpi != matchbins_pk0s: %d != %d", len(matchbins_pkpi), len(matchbins_pk0s)
)
nbins = len(matchbins_pkpi)
arr_errors = [err_pkpi, err_pk0s]
arr_histo = [histo_pkpi, histo_pk0s]
arr_graph = [graph_pkpi, graph_pk0s]
arr_binmatch = [matchbins_pkpi, matchbins_pk0s]
arr_binmatchgr = [matchbinsgr_pkpi, matchbinsgr_pk0s]
average_corryield = [0 for _ in range(nbins)]
average_fprompt = [0 for _ in range(nbins)]
average_statunc = [0 for _ in range(nbins)]
arr_weights = [[-99 for _ in range(nbins)], [-99 for _ in range(nbins)]]
arr_weightsum = [-99 for _ in range(nbins)]
# Fill arrays with corryield and fprompt from pkpi and pk0s
stat_unc = [[0 for _ in range(nbins)], [0 for _ in range(nbins)]]
rel_stat_unc = [[0 for _ in range(nbins)], [0 for _ in range(nbins)]]
corr_yield = [[0 for _ in range(nbins)], [0 for _ in range(nbins)]]
fprompt = [[0 for _ in range(nbins)], [0 for _ in range(nbins)]]
fpromptlow = [[0 for _ in range(nbins)], [0 for _ in range(nbins)]]
fprompthigh = [[0 for _ in range(nbins)], [0 for _ in range(nbins)]]
for j in range(2):
for ipt in range(nbins):
binmatch = arr_binmatch[j][ipt]
binmatchgr = arr_binmatchgr[j][ipt]
if binmatch < 0:
stat_unc[j][ipt] = -99
rel_stat_unc[j][ipt] = -99
corr_yield[j][ipt] = -99
fprompt[j][ipt] = -99
fpromptlow[j][ipt] = -99
fprompthigh[j][ipt] = -99
else:
stat_unc[j][ipt] = arr_histo[j].GetBinError(binmatch)
rel_stat_unc[j][ipt] = arr_histo[j].GetBinError(binmatch) / arr_histo[j].GetBinContent(binmatch)