-
Notifications
You must be signed in to change notification settings - Fork 1
/
clean4b.py
231 lines (190 loc) · 9.38 KB
/
clean4b.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
# Load libraries
import numpy as np
import matplotlib.pyplot as plt
import multiprocessing as mp
import scipy.integrate
import scipy.optimize as opt
# Use Gaussian process from scikit-learn
from sklearn.gaussian_process import GaussianProcessRegressor as GPR
from sklearn.gaussian_process import kernels
# suppression warning messages
import warnings
warnings.filterwarnings('ignore')
# Make Changes Here #
pairList = np.array([(8, 8192), (16, 4096), (32, 2048), (64, 1024), (128, 512), (256, 256),
(512, 128), (1024, 64), (2048, 32)])
folderName = "./2to16/"
emulatorGraphs = True
posteriorGraphs = True
# Feel free to change the integration method on line 190)
# DO NOT MAKE CHANGES BELOW (except line 190 and print statements) #
####################################################################
def do_something(bb):
# Storage: [data file names], amount of Design Points, [parameter names], [parameter min values],
# [parameter max values], [parameter truths], [observable names], [observable truths],
# number of trento runs per design point
savedValues = np.load("" + folderName + str(pairList[bb][0]) + "dp"
+ str(pairList[bb][1]) + "tr.npy", allow_pickle=True)
totDesPoints = savedValues[1]
paramNames = savedValues[2]
paramMins = savedValues[3]
paramMaxs = savedValues[4]
paramTruths = savedValues[5]
obsNames = savedValues[6]
obsTruths = savedValues[7][0]
truthUncert = savedValues[7][1]
nTrento = savedValues[8]
# datum: np.array([[design_points], [observables]])
desPts = np.load(str(savedValues[0][0]) + ".npy", allow_pickle=True)
observables = np.load(str(savedValues[0][1]) + ".npy", allow_pickle=True)
### Make emulator for each observable ###
emul_d = {}
for nn in range(len(obsTruths)):
# Kernels
k0 = 1. * kernels.RBF(
# length_scale=(param1_paramspace_length / 2., param2_paramspace_length / 2.)
# length_scale_bounds=(
# (param1_paramspace_length / param1_nb_design_pts, 3. * param1_paramspace_length),
# (param2_paramspace_length / param2_nb_design_pts, 3. * param2_paramspace_length)
# )
)
k2 = 1. * kernels.WhiteKernel(
noise_level=truthUncert[nn],
# noise_level_bounds='fixed'
noise_level_bounds=(truthUncert[nn] / 4., 4 * truthUncert[nn])
)
kernel = (k0 + k2)
nrestarts = 10
emulator_design_pts_value = np.array(desPts)
emulator_obs_mean_value = np.array(observables[:, nn])
# Fit a GP (optimize the kernel hyperparameters) to each PC.
gaussian_process = GPR(
kernel=kernel,
alpha=0.0001,
n_restarts_optimizer=nrestarts,
copy_X_train=True
).fit(emulator_design_pts_value, emulator_obs_mean_value)
"""
# https://github.com/keweiyao/JETSCAPE2020-TRENTO-BAYES/blob/master/trento-bayes.ipynb
print('Information on emulator for observable ' + obs_label)
print('RBF: ', gaussian_process.kernel_.get_params()['k1'])
print('White: ', gaussian_process.kernel_.get_params()['k2'])
"""
emul_d[obsNames[nn]] = {
'gpr': gaussian_process
# 'mean':scipy.interpolate.interp2d(calc_d[obs_name]['x_list'], calc_d[obs_name]['y_list'], np.transpose(
# calc_d[obs_name]['mean']), kind='linear', copy=True, bounds_error=False, fill_value=None),
# 'uncert':scipy.interpolate.interp2d(calc_d[obs_name]['x_list'], calc_d[obs_name]['y_list'], np.transpose(
# calc_d[obs_name]['uncert']), kind='linear', copy=True, bounds_error=False, fill_value=None)
}
#####################
# Plot the emulator #
#####################
if emulatorGraphs:
# Label for the observable
obs_label = obsNames[nn]
# observable vs value of one parameter (with the other parameter fixed)
# for pl in range(len(paramTruths)):
if True:
plt.figure(1)
plt.rc('font', size=16)
plt.xscale('linear')
plt.yscale('linear')
# plt.title("Number of design points: " + str(totDesPoints) + ", Ensemble size: " + str(nTrento))
plt.xlabel(obs_label + " truth")
plt.ylabel(obs_label + " emulator")
"""# Plot design points
plt.errorbar(desPts[:, pl], np.array(observables[:, nn]),
yerr=np.array(truthUncert)[nn], fmt='D', color='orange', capsize=4)"""
# Plot interpolator
z_list, z_list_uncert = gaussian_process.predict(desPts, return_std=True)
xx = np.array(observables[:, nn])
plt.scatter(xx, z_list, color='blue', marker='.')
line = np.linspace(min(min(z_list), min(xx)), max(max(z_list), max(xx)), 2)
plt.plot(line, line, 'r-', alpha=0.5)
plt.ticklabel_format(axis='y', style='sci', scilimits=(0, 0))
plt.tight_layout()
savepath = "/mnt/c/Users/bmwei/Pictures/QCD Images/CT graphs/" + \
str(pairList[bb][0]) + str(obs_label) + " closure.png"
plt.savefig(savepath, dpi=300)
plt.close(1)
print(str(pairList[bb]) + " emulators trained")
breakpoint()
### Compute the Posterior ###
# We assume uniform priors (integral across the whole parameter space should = 1)
dims = np.array([paramMaxs[vv] - paramMins[vv] for vv in range(len(paramMins))])
area = np.prod(dims)
height = 1.0/area
def prior():
return height
# Under the approximations that we're using, the posterior is
# Likelihood = exp((-1/2)ln((2 pi)^n\prod_n{modelErr(observable, pT)^2 + dataErr(observable, pT)^2})
# - (1/2)\sum_{observables, pT}(model(observable, pT) - data(observable, pT))^2
# / (modelErr(observable, pT)^2 + dataErr(observable, pT)^2))
def likelihood(params):
res = 0.0
norm = (2*np.pi)**len(obsTruths)
# Sum over observables
for xx in range(len(obsTruths)):
# Function that returns the value of an observable
data_mean2 = obsTruths[xx]
data_uncert2 = truthUncert[xx]
tmp_data_mean, tmp_data_uncert = data_mean2, data_uncert2
emulator = emul_d[obsNames[xx]]['gpr']
tmp_model_mean, tmp_model_uncert = emulator.predict(np.atleast_2d(np.transpose(params)), return_std=True)
cov = (tmp_model_uncert * tmp_model_uncert + tmp_data_uncert * tmp_data_uncert)
res += np.power(tmp_model_mean - tmp_data_mean, 2) / cov
norm *= cov
res *= -0.5
return (norm ** -0.5) * (np.e ** res)
def posterior(*params):
return prior() * likelihood(np.array([*params]))
# Compute the posterior, evidence, and AIC #
div = totDesPoints
if totDesPoints < 50:
div = 50
param_ranges = np.zeros((len(paramMins), div))
for qq in range(len(paramMins)):
param_ranges[qq] = np.arange(paramMins[qq], paramMaxs[qq], (paramMaxs[qq] - paramMins[qq])/div)
paramTruthPost = float(posterior(*paramTruths))
ranges = np.zeros((len(paramMins), 2))
for dex in range(len(paramMins)):
ranges[dex][0] = paramMins[dex]
ranges[dex][1] = paramMaxs[dex]
vol1 = scipy.integrate.nquad(posterior, [*ranges], opts={'epsrel': 0.01})[0]
normish = paramTruthPost / vol1
print(vol1)
def minPost(*params):
return -1*posterior(*params[0])
maxPostPar = opt.fmin(minPost, paramTruths)
maxLike = float(likelihood(maxPostPar))
AIC = -2 * np.log(maxLike) + 2*len(paramMins)
subtitle = "NormP: " + str(normish) + ", AIC: " + str(AIC)
print(str(pairList[bb]) + " normP(truth): " + str(normish))
print(str(pairList[bb]) + " AIC: " + str(AIC))
###############################
# Plotting marginal posterior #
###############################
if posteriorGraphs:
for i in range(len(paramNames)):
plt.figure()
plt.xscale('linear')
plt.yscale('linear')
plt.xlabel(paramNames[i])
plt.ylabel(r'Posterior')
plt.title("Number of design points: " + str(totDesPoints) + ", Ensemble size: " + str(nTrento))
plt.figtext(.5, 0.01, subtitle, ha='center')
# The marginal posterior for a parameter is obtained by integrating over a subset of other model parameters
# Compute the posterior for a range of values of the parameter "param_1"
posterior_list = np.array([])
param_vals = np.array([*paramTruths])
for ee in param_ranges[i]:
param_vals[i] = ee
posterior_list = np.append(posterior_list, posterior(*param_vals))
plt.plot(param_ranges[i], posterior_list, "-", color='black', lw=4)
plt.axvline(x=paramTruths[i], color='red')
plt.tight_layout()
plt.show()
# Use multiprocessing to make the script run faster
pool = mp.Pool()
pool.map(do_something, range(len(pairList)))