-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.py
2379 lines (1847 loc) · 76.5 KB
/
utils.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 re
import pandas as pd
import uproot
import copy
import hist
import os
import sys
import math
from legend_plot_style import LEGENDPlotStyle as lps
from warnings import simplefilter
from datetime import datetime, timezone
from scipy.stats import poisson
from scipy.stats import norm
lps.use('legend')
import matplotlib.pyplot as plt
import numpy as np
import tol_colors as tc
from hist import Hist
import json
from legendmeta import LegendMetadata
import warnings
from iminuit import Minuit, cost
from scipy.stats import expon
from scipy.stats import truncnorm
from matplotlib.backends.backend_pdf import PdfPages
from numba import jit
def get_list_of_directories(file):
""" Get the list of directories inside a root file
Parameters:
- the file object from uproot
Returns:
- a list of str of directories
"""
directories = [key for key in file.keys() if isinstance(file[key], uproot.reading.ReadOnlyDirectory)]
return directories
def get_list_of_not_directories(file):
""" Get the list of directories inside a root file
Parameters:
- the file oject from uproot
Returns:
- a list of objects (not directory) in the file
"""
not_directories = [key for key in file.keys() if not isinstance(file[key], uproot.reading.ReadOnlyDirectory)]
return not_directories
def csv_string_to_list(value:str,data_type:type=int)->list:
"""
Convert a string containg a list of csv values to a list
Parameters:
- value (str): The input string
- data_type(type): The data type to convert to (default: int)
Returns:
- a list of type 'data_type'
Example:
l = csv_string_to_list("1,2,3",int)
"""
return [data_type(x) for x in value.split(',')]
def find_and_capture(text:str, pattern:str):
"""Function to find the start index of a pattern in a string
Parameters:
- text: string
- pattern: string
Returns:
-index: Integer corresponding to the first letter of the first instance of the pattern
"""
match = re.search(pattern, text)
if match:
start_index = match.end()
return start_index
else:
raise ValueError("pattern {} not found in text {} ".format(pattern,text))
def manipulate_title(text:str):
"""Replace all the # with \ and add $ $
Parameters:
- text (str) of the text to manipulate
Returns:
- the manipulated text
"""
new_string=""
for char in text:
if (char=="#"):
new_string+="$\\"
return new_string
def format_latex(list_str:list):
"""
Format a string as latex with the radioisotopes formatted
Parameters
- list_str : a list of strings
Returns
- a list of formatted strings
Example:
>>> format_latex(["Pb214])
>>> [$^{214}$Pb]
"""
list_new=[]
for text in list_str:
modified_string =text.replace("Pb214", "$^{214}$Pb")
modified_string =modified_string.replace("2vbb", "$2\\nu\\beta\\beta$")
modified_string=modified_string.replace("Co60","$^{60}$Co")
modified_string=modified_string.replace("Bi214","$^{214}$Bi")
modified_string=modified_string.replace("Tl208","$^{208}$Tl")
modified_string=modified_string.replace("K40","$^{40}$K")
modified_string=modified_string.replace("K42","$^{42}$K")
modified_string=modified_string.replace("Bi212","$^{212}$Bi")
modified_string=modified_string.replace("Ac228","$^{228}$Ac")
modified_string=modified_string.replace("Ar39","$^{39}$Ar")
list_new.append(modified_string)
return list_new
def ttree2df_all(filename:str,data:str)->pd.DataFrame:
"""Use uproot to import a TTree and save to a dataframe
Parameters:
- filename: file to open
- tree_name: Which TTree to look at
Returns:
- Pandas DataFrame of the data
"""
file = uproot.open(filename,object_cache=None)
# Access the TTree inside the file
tree =None
for key in file.keys():
if (data in key):
tree = file[key]
if (tree==None):
raise ValueError("a tree containing {} not found in the file {}".format(data,filename))
# Get the list of branches in the TTree
branches = tree.keys()
# Define a dictionary to store the branch data
data = {}
# Loop through each branch and extract the data
cache=10000
leng = tree.num_entries
idx=0
list_of_df=[]
tot_length=0
for branch_name in branches:
# Use uproot to read the branch into a NumPy array
data[branch_name] = tree[branch_name].array()
df= pd.DataFrame(data)
return df
def ttree2df(filename:str,data:str,query:str=None,N:int=500000)->pd.DataFrame:
"""
Use uproot to import a TTree and save to a dataframe only reads a subset defined by the query and N
To read all a dataframe instead use tree2df_all
Parameters:
- filename: file to open
- tree_name: Which TTree to look at
- query: str of a selection to make (default None)
- N number of events to read (default: 50000)
Returns:
Pandas DataFrame of the data
"""
file = uproot.open(filename,object_cache=None)
# Access the TTree inside the file
tree =None
for key in file.keys():
if (data in key):
tree = file[key]
if (tree==None):
raise ValueError("a tree containing {} not found in the file {}".format(data,filename))
# Get the list of branches in the TTree
branches = tree.keys()
# Define a dictionary to store the branch data
data = {}
# Loop through each branch and extract the data
cache=10000
leng = tree.num_entries
idx=0
list_of_df=[]
tot_length=0
while ((idx+1)*cache<leng and tot_length<N):
for branch_name in branches:
# Use uproot to read the branch into a NumPy array
data[branch_name] = tree[branch_name].array(entry_start=idx*cache,entry_stop=(idx+1)*cache)
df= pd.DataFrame(data)
if (query!=None):
df=df.query(query)
idx+=1
tot_length+=len(df)
list_of_df.append(df)
### read the rest
for branch_name in branches:
data[branch_name] = tree[branch_name].array(entry_start=idx*cache,entry_stop = (N-tot_length+idx*cache))
df= pd.DataFrame(data)
if (query!=None):
df=df.query(query)
list_of_df.append(df)
# Create a Pandas DataFrame from the dictionary
return pd.concat(list_of_df,ignore_index=True)
def plot_two_dim(varx:np.ndarray,vary:np.ndarray,rangex:tuple,rangey:tuple,titlex:str,titley:str,title:str,bins:tuple,show=False,save="",pdf=None):
"""
A 2D scatter plot
Parameters:
- varx: Numpy array of the x data
- vary: Numpy array of the y data
- rangex: tuple (low,high) for range of the x axis
- rangey: tuple (low,high) for range of the y axis
- titlex: Title for x-axis
- titley: Title for the y-axis
- title: Plot title
- bins: Tuple of (binsx,binsy)
Returns:
None
"""
## create the axis
if (show==True):
fig, axes = lps.subplots(1, 1, figsize=(4,6), sharex=True, gridspec_kw = {'hspace': 0})
h = axes.hist2d(varx,vary, bins=bins, cmap='viridis', range=[rangex,rangey], cmin=1,edgecolor='none')
#fig.colorbar(h[3], ax=axes, label='Counts')
axes.set_xlabel(titlex)
axes.set_ylabel(titley)
axes.set_title(title)
plt.grid()
correlation_coefficient = np.corrcoef(varx, vary)[0, 1]
# Annotate the plot with correlation coefficient
if (show==True):
axes.annotate("Correlation = {:0.2f}".format(correlation_coefficient), (0.6, 0.88), xycoords="axes fraction", fontsize=10)
if (pdf==None):
plt.savefig(save)
else:
pdf.savefig()
plt.close()
return correlation_coefficient
def plot_correlation_matrix(corr_matrix:np.ndarray,title:str,pdf,show=False):
"""
Plots a correlation matrix
Parameters:
- corr_matrix (numpy.ndarray): 2D NumPy array representing the correlation matrix.
- title (str): title for the plot
- pdf: PdfPages object to save the plot
- show: boolean to show (True) or Save (false) the plot
"""
# Set up the matplotlib figure
fig, axes = lps.subplots(1, 1, figsize=(6, 4), sharex=True, gridspec_kw = {'hspace': 0})
# Create a heatmap
cax = axes.matshow(corr_matrix, cmap='coolwarm',vmin=-1,vmax=1)
axes.set_title(title)
# Add a colorbar
cbar = fig.colorbar(cax,shrink=1.0)
cbar.set_label('$\\rho$')
plt.grid()
# Show the plot
pdf.savefig()
if (show==False):
plt.close()
else:
plt.show()
def plot_table(df,pdf):
"""
Plot a df as a table
Parameters:
-df: pandas dataframe to plot
-pdf:PdfPages object to save output
"""
# Create a DataFrame
# Plot a table
fig, ax = plt.subplots(figsize=(2, 6*len(df.values)/29)) # Adjust the figsize as needed
ax.axis('off') # Turn off axis labels
# Create the table
table_data = df.T.reset_index().values
table = ax.table(cellText=df.values,colLabels= df.keys(), cellLoc='center', loc='center',colWidths=(0.2,0.8))
# Style the table
table.auto_set_font_size(True)
ax.xaxis.grid(False)
ax.yaxis.grid(False)
ax.xaxis.set_visible(False)
ax.yaxis.set_visible(False)
table.set_zorder(100)
# Show the plot
pdf.savefig()
plt.close()
def twoD_slice(matrix,index):
"""
Function to make a slicing of a matrix
Parameters:
- matrix (np.ndarray) of the correaltion matrix
- index: the indexs to select
Returns:
- new sliced np.ndarray
"""
index=np.array(index)
matrix_new=matrix[:,index]
matrix_new = matrix_new[index,:]
return matrix_new
def get_nth_largest(matrix,n):
"""
Get the nth largest element in the matrix and its index
Parameters:
- matrix: np.ndarray
- n: the number of elements to extract
Returns:
- the values for the n-largest elements
- the row indices
- the column indices
"""
sort_m=matrix
for i in range(matrix.shape[0]):
for j in range(matrix.shape[1]):
if (i>=j):
sort_m[i,j]=0
indices_nth_largest = np.argsort(sort_m.flatten())[-(n+1)]
row_indices, col_indices = np.unravel_index(indices_nth_largest, matrix.shape)
return sort_m[row_indices,col_indices],row_indices,col_indices
def plot_corr(df:pd.DataFrame,i:int,j:int,labels:list,pdf=None):
"""
Makes a 2D correalation plot
Parameters:
"""
key1=df.keys()[i]
key2=df.keys()[j]
x=np.array(df[key1])
y=np.array(df[key2])
rangex=(0,max(x))
rangey=(0,max(y))
bins=(100,100)
cor=plot_two_dim(x,y,rangex,rangey,"{} [1/yr]".format(labels[i]),
"{} [1/yr]".format(labels[j]),
"{} vs {}".format(labels[i],labels[j]),bins,True,pdf=pdf)
def get_data_numpy(type_plot:str,df_tot:pd.DataFrame,name:str,type="marg")->tuple[np.ndarray,np.ndarray,np.ndarray,np.ndarray,float]:
"""
Get the data from the dataframe into some numpy arrays:
Parameters:
- type_plot (str): The type of data to extract (parameter,scaling_factor,fit_range or bi_range)
- df_tot (pd.DataFrame) a pandas dataframe of the data
- name (str): The type of data (M1,M2,all or a particular spectrum name)
Returns:
- a numpy array of the x (indexs)
- a numpy array of the y data (activity)
- numpy arrays of y (activity) low/high errors
- a norm factor for assay measurments
"""
if (type_plot=="parameter"):
x,y,y_low,y_high=get_from_df(df_tot,"fit_range",label="_{}".format(name),type=type)
norm = np.array(df_tot["fit_range_orig_{}".format(name)])
x=x/norm
y=y/norm
y_low=y_low/norm
y_high=y_high/norm
assay_norm=1
elif (type_plot=="scaling_factor"):
x,y,y_low,y_high=get_from_df(df_tot,"scaling_factor")
assay_norm=1
elif (type_plot=="fit_range" or type_plot=="bi_range"):
x,y,y_low,y_high=get_from_df(df_tot,type_plot,label="_"+name)
norm = np.array(df_tot["{}_orig_{}".format(type_plot,name)])
assay_norm=norm
else:
raise ValueError("Error type plot must be 'parameter', 'scaling_factor', 'fit_range' or 'bi_range'")
return x,y,abs(y_low),abs(y_high),assay_norm
def get_df_results(trees:list,dataset_name:str,specs:list,outfile:str)->pd.DataFrame:
"""
Get the fit results into a dataframe merging the different spectrums
Parameters:
-trees (list): A list of TTrees in the analysis file (corresponding to spectra in the fit)
-dataset_name (str): The name of the fitted dataset
-specs (list): List of spectra for the fit
-outfile (str):Path to the analysis file
Returns:
-pd.DataFrame combining the results
"""
firstM1=True
firstM2=True
idx=0
for tree in trees:
## get spectrum name and multiplicity
## ---------------------------------
index = tree.find(dataset_name)
print(index)
print(tree)
print(specs)
if index != -1:
spec_name = tree[index +1+len(dataset_name):].split(";")[0]
multi_string = [string for string in specs if spec_name in string]
print(spec_name)
print(multi_string)
if (len(multi_string)!=1):
raise ValueError("Error we have multiple spectrum per dataset in the out file")
else:
multi=multi_string[0].split("/")[0]
else:
continue
df =pd.DataFrame(ttree2df_all(outfile,tree))
df=df[df["fit_range_orig"]!=0]
### add total range (M1 and M2)
### ------------------------------------------
for key in df.keys():
if ("range" in key):
df[key+"_all_spec"]=df[key]
if (multi=="mul_surv"):
for key in df.keys():
if (("range" in key) and ("all" not in key)):
df[key+"_M1"]=df[key]
firstM1=False
elif ("mul2" in multi):
for key in df.keys():
if ("range" in key) and ("all" not in key):
df[key+"_M2"]=df[key]
firstM2=False
for key in df.keys():
if ("range" in key) and ("M2" not in key) and ("M1" not in key) and ("all" not in key):
df.rename(columns={key: key+"_"+spec_name}, inplace=True)
### merge dataframes
if idx==0:
df_tot = df
else:
### append info in an appropriate
df_tot=merge_dfs(df_tot,df)
idx=idx+1
return df_tot
def make_error_bar_plot(indexs,labels:list,y:np.ndarray,ylow:np.ndarray,yhigh:np.ndarray,data="all",name_out=None,obj="parameter",
y2=None,ylow2=None,yhigh2=None,label1=None,label2=None,extra=None,do_comp=0,low=0.1,scale="log",upper=0,
data_band =None,categories=None,split_priors=False,has_prior=None,
assay_mean=None,assay_high=None,assay_low=None
):
"""
Make the error bar plot
"""
indexs=np.array(indexs,dtype="int")
vset = tc.tol_cset('vibrant')
labels=np.array(labels)
y=y[indexs]
labels=labels[indexs]
ylow=ylow[indexs]
yhigh=yhigh[indexs]
if (assay_mean is not None):
assay_mean=assay_mean[indexs]
assay_high=assay_high[indexs]
assay_low=assay_low[indexs]
if (split_priors==True):
has_prior=np.array(has_prior,dtype="bool")[indexs]
index_prior=np.where(has_prior)[0]
index_no_prior=np.where(~has_prior)[0]
if (do_comp==True):
ylow2=ylow2[indexs]
yhigh2=yhigh2[indexs]
y2=y2[indexs]
### get the indexs with prior and those without priors
### ------------------------------------------------------------
xin=np.arange(len(labels))
height= 1+len(y)*0.32
lps.use("legend")
fig, axes = lps.subplots(1, 1, figsize=(4.5,4), sharex=True, gridspec_kw = {'hspace': 0})
### get the priors
### ----------------------------------------------
if (split_priors==True and has_prior is None):
raise ValueError("Splitting by those component with priors requires to set 'has_prior'")
### shorten labels
for i in range(len(labels)):
label = labels[i]
### shorten
if "hpge_support_copper" in label:
labels[i]=labels[i].split("hpge")[0]+"hpge_copper"
if "front" in label:
labels[i]=labels[i].split("front")[0]+"fe_electr"
if "hpge_in" in label:
labels[i]=labels[i].split("hpge")[0]+"insulators"
### split into contributions with and without priors
if (split_priors==True):
if (do_comp==True):
raise NotImplementedError("It is not implemented to both split priors and compare 2 fits")
yo=np.array(y)
ylowo=np.array(ylow)
yhigho=np.array(yhigh)
y=yo[index_prior]
ylow=ylowo[index_prior]
yhigh=yhigho[index_prior]
y2=yo[index_no_prior]
ylow2=ylowo[index_no_prior]
yhigh2=yhigho[index_no_prior]
xin1=xin[index_prior]
xin2=xin[index_no_prior]
### either split by category or not
if categories is None:
if (assay_mean is not None):
axes.errorbar(y=xin,x=assay_mean,fmt="o",color="black",ecolor="grey",markersize=1,label="Radioassy",alpha=0.4)
for i in range(len(xin)):
axes.fill_betweenx([xin[i] - 0.2, xin[i] + 0.2], assay_mean[i]-assay_low[i] , assay_mean[i]+assay_high[i], alpha=0.4, color='gray',linewidth=0)
if (do_comp==False and split_priors==False):
axes.errorbar(y=xin,x=y,xerr=[abs(ylow),abs(yhigh)],fmt="o",color=vset.blue,ecolor=vset.cyan,markersize=1,label="MC")
#a=1
else:
if (split_priors==True):
axes.errorbar(y=xin1,x=y,xerr=[abs(ylow),yhigh],fmt="o",color=vset.blue,ecolor=vset.cyan,markersize=1,
label="With prior")
axes.errorbar(y=xin2,x=y2,xerr=[abs(ylow2),abs(yhigh2)],fmt="o",color=vset.red,ecolor=vset.orange,markersize=1,
label="Without prior")
else:
axes.errorbar(y=xin+0.15*len(y)/30,x=y,xerr=[abs(ylow),abs(yhigh)],fmt="o",color=vset.blue,ecolor=vset.cyan,markersize=1,label=label1)
axes.errorbar(y=xin-0.15*len(y)/30,x=y2,xerr=[abs(ylow2),abs(yhigh2)],fmt="o",color=vset.orange,ecolor=vset.magenta,markersize=1,label=label2)
else:
if (do_comp==True):
raise ValueError("Splitting by category not implemented for comparison")
cat_sort=np.argsort(categories)
labels=labels[cat_sort]
categories=categories[cat_sort]
y=y[cat_sort]
ylow=ylow[cat_sort]
yhigh=yhigh[cat_sort]
colors=[vset.blue,vset.teal,vset.magenta,vset.cyan]
for cat,col in zip(sorted(set(categories)),colors):
y_tmp = y[categories==cat]
ylow_tmp = ylow[categories==cat]
yhigh_tmp = yhigh[categories==cat]
xin_tmp = xin[categories==cat]
axes.errorbar(y=xin_tmp,x=y_tmp,xerr=[ylow_tmp,yhigh_tmp],fmt="o",color=col,ecolor=col,markersize=1,label=cat)
if data_band is not None:
axes.axvline(x=data_band[0], color='red', linestyle='--', label='Data')
axes.axvspan(xmin=data_band[0]-data_band[1],xmax=data_band[0]+data_band[2], color=vset.orange, alpha=0.3)
### set upper limits for plots
if (upper==0):
if (scale=="linear"):
if (len(y)>0):
upper = np.max(y+1.5*yhigh)
else:
if (len(y)>0):
upper = np.max(y+1.5*yhigh)
if ((do_comp==True or split_priors==True) ):
upper=max(upper,np.max(y2+1.5*yhigh2))
if (scale=="log"):
upper*=3
axes.set_yticks(xin, labels)
## draw data band
if (data_band is not None):
upper =data_band[0]+2*data_band[2]
print(data_band)
print(upper)
### set the labels
### -------------------------
if (obj=="fit_range"):
axes.set_xlabel("Recon. counts / yr in {} data".format(data))
axes.set_xlim(1,upper)
elif (obj=="bi_range"):
axes.set_xlabel("Recon. bkg counts / yr in {} data".format(data))
axes.set_xlim(low,upper)
elif (obj=="scaling_factor"):
axes.set_xlabel("Scaling factor [1/yr] ")
axes.set_xlim(1E-7,upper)
elif obj=="parameter":
axes.set_xlabel("Activity [$\mu$Bq]")
axes.set_xlim(low,upper)
elif obj=="frac":
axes.set_xlabel("Frac. of counts in {} [%]".format(data))
axes.set_xlim(1,upper)
else:
axes.set_xlabel("Recon. counts / yr in {} data".format(obj))
axes.set_xlim(1,upper)
axes.set_yticks(axes.get_yticks())
fonti=11
length=len(y)
if (y2 is not None):
length+=len(y2)
if (length>15 and do_comp==False):
fonti=4
axes.set_yticklabels([val for val in labels],fontsize=fonti)
axes.set_xscale(scale)
plt.grid()
if (do_comp==True or split_priors==True or data_band is not None or categories is not None):
leg=axes.legend(loc='best',edgecolor="black",frameon=True, facecolor='white',framealpha=1)
leg.set_zorder(10)
def replace_e_notation(my_string):
# Using regular expression to match e+0n where n is any character
pattern = re.compile(r'e\+0(.)')
modified_string = re.sub(pattern, r'\\cdot 10^{\1}', my_string)
return modified_string
def priors2table(priors:dict):
""" Convert the priors json into a latex table"""
print(json.dumps(priors,indent=1))
convert_fact=1/31.5
print("\multicolumn{1}{c}{\cellcolor[HTML]{CBCEFB}\\textbf{Source} &\multicolumn{1}{c}{\cellcolor[HTML]{CBCEFB} \\textbf{} Decay} & \multicolumn{1}{c}{\cellcolor[HTML]{CBCEFB} \\textbf{Activity [$\mu$Bq]} & \multicolumn{1}{c}{\cellcolor[HTML]{CBCEFB}\\textbf{Type} \\\\ \hline \hline ")
first_Bi=0
first_Tl=0
for comp in priors["components"]:
source = comp["full-name"]
if ("Bi212Tl208" in comp["name"] and first_Tl==0):
decay = "$^{212}$Bi+$^{208}$Tl"
first_Tl=1
elif ("Pb214Bi214" in comp["name"] and first_Bi==0):
decay = "$^{214}$Pb+$^{214}$Bi"
first_Bi=1
else:
decay= ""
type_meas = comp["type"]
if (type_meas=="icpms"):
type_meas="ICP-MS"
if (type_meas=="guess"):
type_meas="Guess"
if (type_meas=="hpge"):
type_meas="HPGe"
prior = comp["prior"]
if ("gaus" in prior):
split_values = prior.split(":")
param1, param2, param3 = map(float, split_values[1].split(","))
a=-param2/param3
rv = truncnorm(a=a,b=5, loc=param2, scale=param3)
high=param2+5*param3
low_err = 0 if param3 > param2 else param2-param3
high_err= param3+param2
best=param2
low_err*=convert_fact
high_err=convert_fact*param3
best*=convert_fact
meas = "${:.2g} \pm{:.2g}$".format(best,high_err)
meas = replace_e_notation(meas)
elif ("exp" in prior):
split_parts = prior.split("/")
# Extract the upper limit from the exponenital
if len(split_parts) > 1:
upper_limit = float( split_parts[1][:-1])
rv= expon(scale=upper_limit/2.3)
high = 2*upper_limit
low_err=0
high_err= upper_limit
high_err*=convert_fact
meas="$<{:.2g}$".format(high_err)
meas = replace_e_notation(meas)
print("{} & {} & {} & {} \\\\".format(source,decay,meas,type_meas))
def get_index_by_type(names):
""" Get the index for each type (U,Th,K)"""
i=0
index_U = []
index_Th =[]
index_K=[]
index_2nu=[]
for key in names:
if (key.find("Bi212")!=-1):
index_Th.append(i)
elif(key.find("Bi214")!=-1):
index_U.append(i)
elif(key.find("K42")!=-1):
index_K.append(i)
elif (key.find("2v")!=-1):
index_2nu.append(i)
i=i+1
return {"U":index_U,"2nu":index_2nu,"Th":index_Th,"K":index_K}
def get_from_df(df,obj,label="",type="marg"):
"""Get the index, y and errors from dataframe"""
x=np.array(df.index)
if ("{}_{}_mod{}".format(obj,type,label) in df):
mode="mod"
else:
mode="mode"
y=np.array(df["{}_{}_{}{}".format(obj,type,mode,label)])
y_low = y-np.array(df["{}_qt16{}".format(obj,label)])
y_high=np.array(df["{}_qt84{}".format(obj,label)])-y
for i in range(len(y_low)):
if (y_low[i]<0):
y_low[i]=0
y_high[i] +=y[i]
y[i]=0
return x,y,y_low,y_high
def get_error_bar(N:float):
"""
A poisson error-bar for N observed counts.
"""
x= np.linspace(0,5+2*N,5000)
y=poisson.pmf(N,x)
integral = y[np.argmax(y)]
bin_id_l = np.argmax(y)
bin_id_u = np.argmax(y)
integral_tot = np.sum(y)
while integral<0.683*integral_tot:
### get left bin
if (bin_id_l>0 and bin_id_l<len(y)):
c_l =y[bin_id_l-1]
else:
c_l =0
if (bin_id_u>0 and bin_id_u<len(y)):
c_u =y[bin_id_u+1]
else:
c_u =0
if (c_l>c_u):
integral+=c_l
bin_id_l-=1
else:
integral+=c_u
bin_id_u+=1
low_quant = x[bin_id_l]
high_quant=x[bin_id_u]
return N-low_quant,high_quant-N
def integrate_hist(hist,low,high):
""" Integrate the histogram"""
bin_centers= hist.axes.centers[0]
values = hist.values()
lower_index = np.searchsorted(bin_centers, low, side="right")
upper_index = np.searchsorted(bin_centers, high, side="left")
bin_contents_range =values[lower_index:upper_index]
bin_centers_range=bin_centers[lower_index:upper_index]
return np.sum(bin_contents_range)
def get_total_efficiency(det_types,cfg,spectrum,regions,pdf_path,det_sel="all",mc_list=None):
eff_total={}
### creat the efficiency maps (per dataset)
for det_name, det_info in det_types.items():
det_list=det_info["names"]
effs={}
for key in regions:
effs[key]={}
for det,named in zip(det_list,det_info["types"]):
eff_new,good = get_efficiencies(cfg,spectrum,det,regions,pdf_path,named,"mul_surv",mc_list=mc_list)
if (good==1 and (named==det_sel or det_sel=="all")):
effs=sum_effs(effs,eff_new)
eff_total[det_name]=effs
return eff_total
def get_efficiencies(cfg,spectrum,det_type,regions,pdf_path,name,spectrum_fit="",mc_list=None,type_fit="icpc",idx=0):
""" Get the efficiencies or the fraction of events in a given spectrum depositing energy in each region.
Parameters:
-cfg (dict): the fit configuration file
- spectrum (str): name of the spectrum
- det_type (str): detector type to look at
- regions (dict): dictonary of regions to look at
- pdf_path (str): path to the pdf files
- spectrum_fit (str): the spectrum used for the fit (to get the list of components)
- mc_list (list): list of MC files to consider
- type_fit (str): used to extract list of MC files
- idx (int ) : index of the datafile to look into
Returns
dict of the efficiencies
"""
if (det_type in ["icpc","ppc","coax","bege"] and type_fit!="all"):
type_fit=det_type
effs={}
for key in regions:
effs[key]={}
if (spectrum_fit==""):
spectrum_fit=spectrum
if mc_list is None:
for key,region in regions.items():
if (type_fit!="all"):
effs[key]["2vbb_bege"]=0
effs[key]["2vbb_coax"]=0
effs[key]["2vbb_ppc"]=0
effs[key]["2vbb_icpc"]=0
effs[key]["K42_hpge_surface_bege"]=0
effs[key]["K42_hpge_surface_coax"]=0
effs[key]["K42_hpge_surface_ppc"]=0
effs[key]["K42_hpge_surface_icpc"]=0
effs[key]["alpha_ppc"]=0
effs[key]["alpha_bege"]=0
effs[key]["alpha_coax"]=0
effs[key]["alpha_icpc"]=0
for key in cfg["fit"]["theoretical-expectations"].keys():
if ".root" in key:
filename = key
filename=list(cfg["fit"]["theoretical-expectations"].keys())[idx]
print(filename)
if "{}/{}".format(spectrum_fit,type_fit) in cfg["fit"]["theoretical-expectations"][filename]:
icpc_comp_list=cfg["fit"]["theoretical-expectations"][filename]["{}/{}".format(spectrum_fit,type_fit)]["components"]
else:
warnings.warn("{}/{} not in MC PDFs".format(spectrum_fit,det_type))
return effs,0
else:
icpc_comp_list=mc_list
comp_list = copy.deepcopy(icpc_comp_list)
for comp in comp_list:
for key in comp["components"].keys():
par = key
## now open the file
if "root-file" in comp.keys():
with uproot.open(pdf_path+comp["root-file"],object_cache=None) as file:
if "{}/{}".format(spectrum,det_type) in file:
hist = file["{}/{}".format(spectrum,det_type)]
N = int(file["number_of_primaries"])
hist = hist.to_hist()
for key,region in regions.items():
eff=0
for region_tmp in region:
eff+=float(integrate_hist(hist,region_tmp[0],region_tmp[1]))
effs[key][par]=eff/N
else:
warnings.warn("{}/{} not in MC PDFs".format(spectrum,det_type))
for key,region in regions.items():
effs[key][par]=0
### a formula not a file
else:
comps = comp["components"]
for name in comps:
formula = comps[name]["TFormula"]
## curren y only pol1 implemented
if "pol1" not in formula:
raise ValueError("Currently integration only works for pol1")
split_values = formula.split(":")
p0, p1 = map(float, split_values[1].split(","))
for key,region in regions.items():
eff =0
for region_tmp in region:
eff+= p0*(region_tmp[1]-region_tmp[0])+p1*(region_tmp[1]*region_tmp[1]-region_tmp[0]*region_tmp[0])/2
effs[key][par]=eff
if (det_type not in ["icpc","bege","ppc","coax"]):
effs[key][par]=0
return effs,1
def sum_effs(eff1:dict,eff2:dict)->dict:
"""
Function to sum the two efficiency dictonaries up to two layers
Parameters:
- eff1: (dict) the first dictonary
- eff2: (dict) the second
Returns:
- dictonary where every item with the same key is summed
"""
dict_sum={}
for key in set(eff1) | set(eff2): # Union of keys from both dictionaries
## sum two layers
dict_sum[key]={}
if (isinstance(eff1[key],dict) or isinstance(eff2[key],dict)):
for key2 in set(eff1[key]) | set(eff2[key]):
dict_sum[key][key2] = eff1[key].get(key2, 0) + eff2[key].get(key2, 0)
## sum one layer
else: