-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathemulator.py
344 lines (267 loc) · 13.5 KB
/
emulator.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
'''Modified from PhotoMultiEmulator
'''
import os, sys
import numpy as np
import jax
from prospect.models import ProspectorParams
def rt_dir():
dat_dirs = ['/storage/home/bbw5389/group/',
'/Users/bwang/research/']
for _dir in dat_dirs:
if os.path.isdir(_dir): return _dir
def data_dir(data='pirate'):
rt_roar = '/storage/home/bbw5389/group/'
rt_mac = '/Users/bwang/research/'
if data == 'pirate':
dat_dirs = [rt_roar + 'sed/pirate/pirate/data/nn/',
rt_mac + 'software/MathewsEtAl2023/data/']
else:
return None
for _dir in dat_dirs:
if os.path.isdir(_dir): return _dir
multiemul_file = os.path.join(data_dir(data='pirate'), "parrot_v4_obsphot_512n_5l_24s_00z24.npy")
class EmulatorBeta(ProspectorParams):
'''works with the p-beta priors:
'''
def __init__(self, model_params, fp=multiemul_file, obs=None, param_order=None):
super(EmulatorBeta, self).__init__(model_params, param_order=param_order)
# Load all emulator data.
self.dat = np.load(fp, allow_pickle=True).all()
# Determine the indices of the filters in obs['filters']
self.sorter = np.array([self.dat["filter_redir"][f.name] for f in obs["filters"]], dtype=int)
# TODO: Check if prior bounds are with emulbounds.
# This will require messing with the massmet prior (which uses prior.bounds()) to
# bring it in line with the other priors (which use prior.a and prior.b)
# TODO: Use dat["resid_quants"] data to modify obs["maggies_unc"]
# needed for re-ordering thetas
self.zred_index = self.dat["zred_index"]
# Convert ANN things to JAX arrays.
self.nets = self.dat["nets"]
for (i, net) in enumerate(self.nets):
# Unpack this sub-network
norm, denorm, wght, bias, act = net
# Translate things into JAX and remove irrelevant filters
norm = [jax.numpy.array(n) for n in norm]
denorm = [jax.numpy.array(d[self.sorter]) for d in denorm]
wght = [jax.numpy.array(W) for W in wght]
bias = [jax.numpy.array(b) for b in bias]
wght[-1] = wght[-1][self.sorter, :]
bias[-1] = bias[-1][self.sorter]
# The activation function is stored as a string - this converts it
# to the JAX function. Assumes that all nonlinear layers use the same
# activation function in a given sub-network and that the last layer
# is linear activation.
act = getattr(jax.nn, act)
# Repack
self.nets[i] = (norm, denorm, wght, bias, act)
# Split zredmassmet and put each into the correct index
def modify_theta(self, theta):
new_theta = theta[1:]
new_theta = np.insert(new_theta, self.zred_index, theta[0])
return new_theta
# Determine the relevant angle needed for the sin and cos functions in
# transition_coef. z0 is the center of an sub-network overlap and deltaz
# is the full width of the overlap.
def transition_theta(self, z, z0, deltaz):
return (jax.numpy.pi / (2 * deltaz)) * (z - z0 + 0.5*deltaz)
# Compute how much each sub-network should contribute to the overall
# prediction. Equal to 1 where the sub-network is the only one trained,
# 0 where the sub-emulator is not trained, and between 0 and 1 in overlaps.
def transition_coef(self, z, z0l, deltazl, z0r, deltazr):
if (z <= (z0l - 0.5*deltazl)) or (z >= (z0r + 0.5*deltazr)):
return 0.0
elif (z >= (z0l + 0.5*deltazl)) and (z <= (z0r - 0.5*deltazr)):
return 1.0
elif (z > (z0l - 0.5*deltazl)) and (z < (z0l + 0.5*deltazl)):
return jax.numpy.sin(self.transition_theta(z, z0l, deltazl))**2
else:
return jax.numpy.cos(self.transition_theta(z, z0r, deltazr))**2
# Run a forward pass through a sub-network.
def forward_pass(self, in_vec, net):
# Grab NN stuff
norm, denorm, wght, bias, act = net
# Normalize layer
result = (in_vec - norm[0]) / norm[1]
# Nonlinear layers
for i in range(len(wght) - 1):
result = act(jax.numpy.dot(wght[i], result) + bias[i])
# Linear layer.
result = jax.numpy.dot(wght[-1], result) + bias[-1]
# Denormalize layer.
result = (denorm[1] * result) + denorm[0]
return result
# Convert AB magnitudes to maggies.
#
# Note: The emulator actually outputs arsinh magnitudes, but here we
# are assuming that these arsinh mags are exactly equal to their
# logarithmic AB counterparts. This is a very safe assumption for AB
# magnitudes brighter than about +33 (they asymptotically become equal
# as the AB magnitude gets brighter), but becomes very poor fainter than
# +34.
def demagify(self, mag):
result = jax.numpy.multiply(mag, -0.4)
result = jax.numpy.divide(result, jax.numpy.log10(jax.numpy.e))
result = jax.numpy.exp(result)
return result
# Use the full emulator suite to predict a set of photometry for a given input
# theta_in parameter vector.
def predict_phot(self, theta_in, **extras):
# Add redshift to theta if needed.
theta = self.modify_theta(theta_in)
# Grab the redshift from theta.
z = theta[self.zred_index]
# Compute the coefficients to multiply each emulator by.
coefs = [self.transition_coef(z, *emul_lim) for emul_lim in self.dat["emulator_limits"]]
# Initialize an array for the photometry prediction.
result = jax.numpy.zeros(len(self.sorter))
for (i, coef) in enumerate(coefs):
# If the coef is zero, sub-network doesn't contribute - skip.
if coef == 0.0:
continue
# Otherwise, it does contribute and we need to evaluate that sub-network.
else:
result += coef * self.forward_pass(theta, self.nets[i])
# Convert the emulator's output to maggies (see comments on self.demagify)
predict_lin = self.demagify(result)
return predict_lin
# Run self.predict_phot but return the result as a NumPy array
def predict_phot_np(self, theta_in, **extras):
result = self.predict_phot(theta_in)
result = np.array(result)
return result
# We don't predict spectra, both because we don't have an emulator available
# and because it would take too long anyway. Thus, let's just generate a vector
# of zeros and return that in case Prospector complains about not having a
# spectrum predicted.
def predict_spec(self, theta, obs=None, **extras):
return np.zeros(5994)
# Same thing with mfrac, although we *do* have an emulator for this.
def predict_mfrac(self, theta, obs=None, **extras):
return -1.0
# General predict function, returns useless mfrac and spec right now.
def predict(self, theta, obs=None, **extras):
return (self.predict_spec(theta, obs=obs, **extras),
self.predict_phot_np(theta, obs=obs, **extras),
self.predict_mfrac(theta, obs=obs, **extras))
class EmulatorDefault(ProspectorParams):
'''works with the full 18 params default settings (p-alpha: MassMet prior, flat SFH)
'''
def __init__(self, model_params, fp=multiemul_file, obs=None, param_order=None):
super(EmulatorDefault, self).__init__(model_params, param_order=param_order)
# Load all emulator data.
self.dat = np.load(fp, allow_pickle=True).all()
# Determine the indices of the filters in obs['filters']
self.sorter = np.array([self.dat["filter_redir"][f.name] for f in obs["filters"]], dtype=int)
# TODO: Check if prior bounds are with emulbounds.
# This will require messing with the massmet prior (which uses prior.bounds()) to
# bring it in line with the other priors (which use prior.a and prior.b)
# TODO: Use dat["resid_quants"] data to modify obs["maggies_unc"]
# needed for re-ordering thetas
self.zred_index = self.dat["zred_index"]
# Convert ANN things to JAX arrays.
self.nets = self.dat["nets"]
for (i, net) in enumerate(self.nets):
# Unpack this sub-network
norm, denorm, wght, bias, act = net
# Translate things into JAX and remove irrelevant filters
norm = [jax.numpy.array(n) for n in norm]
denorm = [jax.numpy.array(d[self.sorter]) for d in denorm]
wght = [jax.numpy.array(W) for W in wght]
bias = [jax.numpy.array(b) for b in bias]
wght[-1] = wght[-1][self.sorter, :]
bias[-1] = bias[-1][self.sorter]
# The activation function is stored as a string - this converts it
# to the JAX function. Assumes that all nonlinear layers use the same
# activation function in a given sub-network and that the last layer
# is linear activation.
act = getattr(jax.nn, act)
# Repack
self.nets[i] = (norm, denorm, wght, bias, act)
# No modifications needed since we use the full 18 params and default priors
def modify_theta(self, theta):
return theta
# Determine the relevant angle needed for the sin and cos functions in
# transition_coef. z0 is the center of an sub-network overlap and deltaz
# is the full width of the overlap.
def transition_theta(self, z, z0, deltaz):
return (jax.numpy.pi / (2 * deltaz)) * (z - z0 + 0.5*deltaz)
# Compute how much each sub-network should contribute to the overall
# prediction. Equal to 1 where the sub-network is the only one trained,
# 0 where the sub-emulator is not trained, and between 0 and 1 in overlaps.
def transition_coef(self, z, z0l, deltazl, z0r, deltazr):
if (z <= (z0l - 0.5*deltazl)) or (z >= (z0r + 0.5*deltazr)):
return 0.0
elif (z >= (z0l + 0.5*deltazl)) and (z <= (z0r - 0.5*deltazr)):
return 1.0
elif (z > (z0l - 0.5*deltazl)) and (z < (z0l + 0.5*deltazl)):
return jax.numpy.sin(self.transition_theta(z, z0l, deltazl))**2
else:
return jax.numpy.cos(self.transition_theta(z, z0r, deltazr))**2
# Run a forward pass through a sub-network.
def forward_pass(self, in_vec, net):
# Grab NN stuff
norm, denorm, wght, bias, act = net
# Normalize layer
result = (in_vec - norm[0]) / norm[1]
# Nonlinear layers
for i in range(len(wght) - 1):
result = act(jax.numpy.dot(wght[i], result) + bias[i])
# Linear layer.
result = jax.numpy.dot(wght[-1], result) + bias[-1]
# Denormalize layer.
result = (denorm[1] * result) + denorm[0]
return result
# Convert AB magnitudes to maggies.
#
# Note: The emulator actually outputs arsinh magnitudes, but here we
# are assuming that these arsinh mags are exactly equal to their
# logarithmic AB counterparts. This is a very safe assumption for AB
# magnitudes brighter than about +33 (they asymptotically become equal
# as the AB magnitude gets brighter), but becomes very poor fainter than
# +34.
def demagify(self, mag):
result = jax.numpy.multiply(mag, -0.4)
result = jax.numpy.divide(result, jax.numpy.log10(jax.numpy.e))
result = jax.numpy.exp(result)
return result
# Use the full emulator suite to predict a set of photometry for a given input
# theta_in parameter vector.
def predict_phot(self, theta_in, **extras):
# returns theta_in
# No modifications needed since we use the full 18 params and default priors
theta = self.modify_theta(theta_in)
# Grab the redshift from theta.
z = theta[self.zred_index]
# Compute the coefficients to multiply each emulator by.
coefs = [self.transition_coef(z, *emul_lim) for emul_lim in self.dat["emulator_limits"]]
# Initialize an array for the photometry prediction.
result = jax.numpy.zeros(len(self.sorter))
for (i, coef) in enumerate(coefs):
# If the coef is zero, sub-network doesn't contribute - skip.
if coef == 0.0:
continue
# Otherwise, it does contribute and we need to evaluate that sub-network.
else:
result += coef * self.forward_pass(theta, self.nets[i])
# Convert the emulator's output to maggies (see comments on self.demagify)
predict_lin = self.demagify(result)
return predict_lin
# Run self.predict_phot but return the result as a NumPy array
def predict_phot_np(self, theta_in, **extras):
result = self.predict_phot(theta_in)
result = np.array(result)
return result
# We don't predict spectra, both because we don't have an emulator available
# and because it would take too long anyway. Thus, let's just generate a vector
# of zeros and return that in case Prospector complains about not having a
# spectrum predicted.
def predict_spec(self, theta, obs=None, **extras):
return np.zeros(5994)
# Same thing with mfrac, although we *do* have an emulator for this.
def predict_mfrac(self, theta, obs=None, **extras):
return -1.0
# General predict function, returns useless mfrac and spec right now.
def predict(self, theta, obs=None, **extras):
return (self.predict_spec(theta, obs=obs, **extras),
self.predict_phot_np(theta, obs=obs, **extras),
self.predict_mfrac(theta, obs=obs, **extras))