-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmakeData_calibration.py
More file actions
229 lines (177 loc) · 6.86 KB
/
Copy pathmakeData_calibration.py
File metadata and controls
229 lines (177 loc) · 6.86 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
''' Read in csv data file of 1M calibration events
'''
#########################
### imports ###
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
import uproot as ur
import uproot3 as ur3
########################
### MPL Settings ###
params = {
'font.size': 14
}
plt.rcParams.update(params)
#########################
def make_all_plots(df, output_path):
# for making plots
with PdfPages(output_path) as pdf:
# loop over field names
for idx, key in enumerate(df):
print(f"Accessing variable with name = {key} ({idx+1} / {df.shape[1]})")
data = df[key].to_numpy()
##############
# make plots #
fig, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=[5.5*3, 5.])
# linear scale plot
bins = 50
_, bin_edges, _ = ax1.hist(data, bins=bins, histtype="step", density=False, label="linear")
ax1.set_xlabel(key)
ax1.set_ylabel("Frequency")
if data.min() <= 0:
data_upshifted = data + np.abs(data.min()) + 1e-30
label = "log (upshifted)"
else:
data_upshifted = data
label = "log"
# log scale for y-axis
ax2.hist(data_upshifted, bins=bin_edges, histtype="step", density=False, label=label)
ax2.set_yscale("log")
ax2.set_xlabel(key)
ax2.legend(frameon=False, loc="upper right")
ax2.set_ylabel("Frequency")
# log scale for both axis
bins_log = np.logspace(np.log10(data_upshifted.min()), np.log10(data_upshifted.max()), len(bin_edges)-1)
ax3.hist(data_upshifted, bins=bins_log, histtype="step", density=False, label=label)
ax3.set_yscale("log")
ax3.set_xscale("log")
ax3.set_xlabel(key)
ax3.legend(frameon=False, loc="upper right")
ax3.set_ylabel("Frequency")
fig.tight_layout()
pdf.savefig(fig)
plt.close(fig)
print(f"Saving all figures into {output_path}")
def normalize(x):
mean, std = np.mean(x), np.std(x)
out = (x - mean) / std
return out, mean, std
def apply_save_log(x):
#########
epsilon = 1e-10
#########
minimum = x.min()
if x.min() <= 0:
x = x - x.min() + epsilon
else:
minimum = 0
epsilon = 0
return np.log(x), minimum, epsilon
#########################
def main():
################
### params ###
file_path = "all_info_df"
filename = ur.open('/home/jmsardain/JetCalib/PUMitigation/final/MakeROOT/output_calib.root')["ClusterTree"]
# filename = ur.open('/data/jmsardain/JetCalib/Akt4EMTopo.topo-cluster.root')
df = filename.arrays(library="pd")
df = df[ df['jetCnt']%5 == 0]
df = df[df["cluster_ENG_CALIB_TOT"]>0.3]
df = df[df["clusterE"]>0.]
df = df[df["cluster_CENTER_LAMBDA"]>0.]
df = df[df["cluster_FIRST_ENG_DENS"]>0.]
df = df[df["cluster_SECOND_TIME"]>0.]
df = df[df["cluster_SIGNIFICANCE"]>0.]
resp = np.array( df.clusterE.values ) / np.array( df.cluster_ENG_CALIB_TOT.values )
df["response"] = resp
df = df[df["response"]>0.1]
print(df.columns)
column_names = ['response', 'clusterECalib', 'cluster_ENG_CALIB_TOT',
'clusterE', 'clusterEta',
'cluster_CENTER_LAMBDA', 'cluster_CENTER_MAG', 'cluster_ENG_FRAC_EM', 'cluster_FIRST_ENG_DENS',
'cluster_LATERAL', 'cluster_LONGITUDINAL', 'cluster_PTD', 'cluster_time', 'cluster_ISOLATION',
'cluster_SECOND_TIME', 'cluster_SIGNIFICANCE', 'nPrimVtx', 'avgMu',
# 'clusterE', 'clusterEta', 'clusterPhi', 'cluster_CENTER_LAMBDA', 'cluster_CENTER_MAG',
# 'cluster_ENG_FRAC_EM', 'cluster_FIRST_ENG_DENS', 'cluster_LATERAL', 'cluster_LONGITUDINAL',
# 'cluster_PTD', 'cluster_time', 'cluster_ISOLATION', 'cluster_SECOND_TIME', 'cluster_SIGNIFICANCE',
# 'nPrimVtx', 'avgMu',
]
df = df[column_names]
before = df
print(df.columns)
output_path_figures_before_preprocessing = "fig.pdf"
output_path_figures_after_preprocessing = "fig2.pdf"
output_path_data = "data/" + file_path + ".npy"
# output_path_data = "data/"
save = True
scales_txt_file = "scales.txt"
print(df)
#####################
### preprocessing ###
print("-"*100)
print("Make preprocessing...")
scales = {}
# log-preprocessing
field_names = ["clusterE", "cluster_CENTER_LAMBDA", "cluster_FIRST_ENG_DENS", "cluster_SECOND_TIME", "cluster_SIGNIFICANCE"]
for field_name in field_names:
x, minimum, epsilon = apply_save_log(df[field_name])
x, mean, std = normalize(x)
scales[field_name] = ("SaveLog / Normalize", minimum, epsilon, mean, std)
df[field_name] = x
# just normalizing
field_names = ["clusterEta", "cluster_CENTER_MAG", "nPrimVtx", "avgMu"]
for field_name in field_names:
x = df[field_name]
x, mean, std = normalize(x)
scales[field_name] = ("Normalize", mean, std)
df[field_name] = x
# params between [0, 1]
# we could also just shift?
field_names = ["cluster_ENG_FRAC_EM", "cluster_LATERAL", "cluster_LONGITUDINAL", "cluster_PTD", "cluster_ISOLATION"]
for field_name in field_names:
x = df[field_name]
x, mean, std = normalize(x)
scales[field_name] = ("Normalize", mean, std)
df[field_name] = x
# special preprocessing
field_name = "cluster_time"
x = df[field_name]
x = np.abs(x)**(1./3.) * np.sign(x)
x, mean, std = normalize(x)
#x = np.tanh(x)
#x = x + np.abs(x.min()) + 1
#x = apply_save_log(df[field_name])
#x = normalize(x)
scales[field_name] = ("Sqrt3", mean, std)
df[field_name] = x
# no preprocessing
#files_names = ["r_e_calculated"]
######################
print("-"*100)
print("Make plots after preprocessing..,")
# plots after preprocessing
# make_all_plots(df, output_path_figures_after_preprocessing)
brr = before.to_numpy()
arr = df.to_numpy()
print(arr.shape)
print(scales)
np.save(output_path_data, arr)
print("Saved as {output_path_data}")
with open(scales_txt_file, "w") as f:
f.write(str(scales))
n = len(arr)
ntrain = int(n * 0.6)
ntest = int(n * 0.2)
train = arr[:ntrain]
val = arr[ntrain+ntest:]
test = arr[ntrain:ntrain+ntest]
## clusterE / response = true energy should be higher than 0.3
test_before= brr[ntrain:ntrain+ntest]
np.save("data/calibration_train.npy", train)
np.save("data/calibration_test.npy", test)
np.save("data/calibration_val.npy", val)
np.save("data/calibration_test_before.npy", test_before)
if __name__ == "__main__":
main()