Belle II Software development
prepareAsicCrosstalkSimDB.py
1
8'''
9 Prepare CDC x-talk simulation DB object, usage:
10
11 python3 prepareAsicCrosstalkSimDB.py <input_asic_root> <output_path> <exp_num> <data_type>
12
13 input_asic_root: input path and files containing asic information,
14 produced by AsicBackgroundLibraryCreator.py
15 output_path: output path
16 exp_num: experiment number of raw data or mc samples
17 data_type: data or mc
18
19'''
20
21import uproot
22import matplotlib.pyplot as plt
23import numpy as np
24from scipy.interpolate import UnivariateSpline
25
26import basf2
27from ROOT.Belle2 import FileSystem
28from ROOT.Belle2 import CDCDatabaseImporter
29from ROOT import TH1F, TFile
30import sys
31
32
33def getEff(var, cut, n=40, limits=(0., 2500.)):
34 ''' Simple efficiency estimator
35 var: pandas series/np array of variable to study
36 cut: bool series/np array pass/fail
37 n : number of bins
38 limits : histogram limits
39 '''
40 a = np.histogram(var, n, limits)
41 b = np.histogram(var[cut], n, limits)
42 eff = b[0]/a[0]
43 # Simple binomial formula:
44 effErr = 1/a[0]*np.sqrt(a[0]*eff*(1-eff))
45 x = 0.5*(a[1][1:]+a[1][:-1])
46 return x, eff, effErr
47
48
49# Problematic boards ID in each run
50bad_boards = {'22': [24, 196],
51 '24': [0, 15, 24, 40, 117, 175, 196, 202, 86, 89],
52 '25': [0, 24, 15],
53 '26': [24, 210, 62],
54 '27': [92, 24, 51, 106, 53],
55 }
56# Input arguments
57if len(sys.argv) != 5:
58 sys.exit("Four arguments are required: input_root, output_path, experiemnt numebr and data_type")
59InputFile = sys.argv[1]
60OutputPath = sys.argv[2]
61exp = sys.argv[3]
62data_type = sys.argv[4]
63
64# Dataframe, containing relevant variables from the root file
65df = uproot.open(InputFile, flatten=True)["ASIC"].arrays(["Channel", "ADC", "Board", "Nhit", "Asic"], library="pd")
66df.columns = ['_'.join(col) if col[1] != '' else col[0] for col in df.columns.values]
67# Defining asic
68df['asic'] = df.Channel//8
69# Remove the problematic boards
70mask = df['Board'].isin([m for m in bad_boards[f'{exp}']])
71df = df[~mask]
72
73nhits = 3
74
75u1 = getEff(df[(df.asic % 3 == 1)].ADC_ADC_Sig, df.Nhit > f'{nhits}', 128, (0, 1024.))
76
77u2 = getEff(df[(df.asic % 3 == 1)].ADC_ADC_Sig, df.Nhit > f'{nhits}', 8, (1024, 4096.))
78
79u = np.append(u1, u2, axis=1)
80
81plt.figure(figsize=(10, 4))
82
83x = np.nan_to_num(u[0])
84
85e = np.nan_to_num(u[1])
86
87ee = np.where(np.nan_to_num(u[2]) == 0, 1000., u[2])
88
89
90f = UnivariateSpline(x, e, 1/ee)
91
92xp = np.arange(-0.5, 4096.5, 1)
93
94plt.subplot(121)
95plt.xlim(0, 4096.)
96plt.ylim(0., 1.02)
97plt.errorbar(x, e, u[2], fmt='.')
98plt.ylabel(f'Fraction of Nhit>{nhits}')
99plt.title(f'exp{exp} {data_type}')
100plt.plot(xp, f(xp))
101
102plt.subplot(122)
103plt.xlim(0, 1000.)
104plt.ylim(0., 0.5)
105plt.errorbar(x, e, u[2], fmt='.', label='eff: asic=1,4; Nhit>3')
106plt.plot(xp, f(xp), label='spline fit')
107plt.xlabel('ADC')
108plt.legend()
109plt.savefig(f'{OutputPath}/xTalkProb_{exp}_{data_type}.pdf')
110
111# Write out root file
112
113names = ["Board", "Channel", 'Nhit', 'asic']
114for i in range(8):
115 names += [f'Asic_ADC{i:d}', f'Asic_TDC{i:d}', f'Asic_TOT{i:d}']
116
117with uproot.recreate(f'{OutputPath}/xTalkProb_{exp}_{data_type}.root') as output:
118 df_tmp = df.query('nhit>3 & asic==1')
119 output['ASIC'] = uproot.newtree({name: df_tmp[name].dtype for name in names})
120 output['ASIC'].extend({name: df_tmp[name].values for name in names})
121
122
123fi = TFile(f'{OutputPath}/xTalkProb_{exp}_{data_type}.root', "update")
124
125t = TH1F("ProbXTalk", "Prob xTalk", 4096, 0, 4096)
126t.SetContent(f(xp))
127fi.Write()
128fi.Close()
129
130
131INPUT = FileSystem.findFile(f'{OutputPath}/xTalkProb_{exp}_{data_type}.root')
132
133# Specify the exp and run where iov is valid.
134# N.B. -1 means unbound.
135
136expFirst = 0
137
138expLast = -1
139
140runFirst = 0
141
142runLast = -1
143# basf2.use_local_database("localdb/database.txt", "localdb")
144basf2.conditions.testing_payloads = [f'localdb/exp{exp}/database_{exp}.txt']
145
146
147main = basf2.create_path()
148
149
150eventinfosetter = basf2.register_module('EventInfoSetter')
151main.add_module(eventinfosetter)
152
153# process single event
154basf2.process(main)
155
156
157dbImporter = CDCDatabaseImporter(expFirst, runFirst, expLast, runLast)
158dbImporter.importCDCCrossTalkLibrary(INPUT)
159
160dbImporter.printCDCCrossTalkLibrary()
161dbImporter.testCDCCrossTalkLibrary()