-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhmc2.py
356 lines (292 loc) · 11.6 KB
/
hmc2.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
import jax
import jax.numpy as np
import jax.random as jr
import numpyro as npy
import numpyro.distributions as dist
import os
os.environ["XLA_FLAGS"] = '--xla_force_host_platform_device_count=2'
import equinox as eqx
import optax
import dLux as dl
import matplotlib.pyplot as plt
import chainconsumer as cc
import jupyterthemes.jtplot as jtplot
from pupils import NicmosColdMask, HubblePupil
# %matplotlib inline
plt.rcParams['image.cmap'] = 'inferno'
plt.rcParams["font.family"] = 'serif'
plt.rcParams["text.usetex"] = 'true'
plt.rcParams['figure.dpi'] = 120
# +
with open("data/filters/HST_NICMOS1.F170M.dat") as filter_data:
next(filter_data)
nicmos_filter = np.array([
[float(entry) for entry in line.strip().split(" ")]
for line in filter_data])
plt.figure(figsize=(15, 6))
plt.subplot(1, 2, 1)
plt.title("Raw filter")
plt.scatter(nicmos_filter[:, 0], nicmos_filter[:, 1])
nicmos_filter = nicmos_filter\
.reshape(10, 80, 2)\
.mean(axis=1)\
.at[:, 0]\
.mul(1e-9)
# Nicmos filter is defined in percentages, not throughput, so divide by 100
nicmos_filter = nicmos_filter.at[:, 1].divide(100)
dl_nicmos_filter = dl.Filter(nicmos_filter[:, 0], nicmos_filter[:, 1])
plt.subplot(1, 2, 2)
plt.title("Input filter")
plt.scatter(dl_nicmos_filter.wavelengths, dl_nicmos_filter.throughput)
plt.show()
total_throughput = dl_nicmos_filter.throughput.sum()/len(dl_nicmos_filter.throughput)
print("Total filter throughput: {}%".format(total_throughput*100))
# wavelengths = np.tile(nicmos_filter[:, 0], (2, 1))
wavelengths = np.tile(1e-6*np.linspace(1.6, 1.8, 3), (2, 1))
# weights = np.ones((2,) + nicmos_filter[:, 0].shape)
weights = np.ones(wavelengths.shape)
combined_spectrum = dl.CombinedSpectrum(wavelengths, weights).normalise()
# Create Binary Source,
true_position = np.zeros(2)
true_separation, true_field_angle = dl.utils.arcsec2rad(5e-1), 0
true_flux, true_flux_ratio = 1e5, 10
resolved = [False, False]
binary_source = dl.BinarySource(true_position, true_flux, true_separation,
true_field_angle, true_flux_ratio,
combined_spectrum, resolved, name="Binary")
# Construct Optical system
wf_npix = 128
det_npix = 64
# Zernike aberrations,
basis = dl.utils.zernike_basis(6, npix=wf_npix)[3:] * 1e-9
true_coeffs = jr.normal(jr.PRNGKey(0), (basis.shape[0],))
basis.shape[0]
true_x_offset, true_y_offset = 0.067, -0.067
pupils = {"Hubble": HubblePupil(), "Nicmos": NicmosColdMask(true_x_offset, true_y_offset)}
# Construct optical layers,
true_pixel_scale = dl.utils.arcsec2rad(0.043)
layers = [dl.CreateWavefront(wf_npix, 2.4, wavefront_type="Angular"),
dl.TiltWavefront(),
dl.CompoundAperture(pupils),
dl.ApplyBasisOPD(basis, true_coeffs),
dl.NormaliseWavefront(),
dl.AngularMFT(true_pixel_scale, det_npix)]
# Construct Detector,
true_bg = 10.
true_pixel_response = 1 + 0.05*jr.normal(jr.PRNGKey(0), (det_npix, det_npix))
detector_layers = [
dl.AddConstant(true_bg),
# dl.ApplyPixelResponse(true_pixel_response),
]
# Construct Telescope,
telescope = dl.Telescope(dl.Optics(layers),
dl.Scene([binary_source]),
filter=dl_nicmos_filter,
detector=dl.Detector(detector_layers))
## Gerenate psf,
psf = telescope.model_scene()
psf_photon = jr.poisson(jr.PRNGKey(0), psf)
bg_noise = true_bg + jr.normal(jr.PRNGKey(0), psf_photon.shape)
image = psf_photon + bg_noise
data = image.flatten()
plt.figure(figsize=(15, 4))
plt.subplot(1, 3, 1)
plt.title("PSF")
plt.imshow(psf ** 0.25)
plt.colorbar()
plt.subplot(1, 3, 2),
plt.title("PSF + Photon")
plt.imshow(psf_photon ** 0.25)
plt.colorbar()
plt.subplot(1, 3, 3)
plt.title("Data")
plt.imshow(image ** 0.25)
plt.colorbar()
plt.show()
# -
# Lets define our path dict to simplify accessing these attributes
# These can all always be defined, there is no need to comment them out
path_dict = {
'pos' : ['scene', 'sources', 'Binary', 'position' ],
'sep' : ['scene', 'sources', 'Binary', 'separation' ],
'angle' : ['scene', 'sources', 'Binary', 'field_angle' ],
'flx' : ['scene', 'sources', 'Binary', 'flux' ],
'cont' : ['scene', 'sources', 'Binary', 'flux_ratio' ],
'zern' : ['optics', 'layers', 'Apply Basis OPD', 'coeffs' ],
'bg' : ['detector', 'layers', 'AddConstant', 'value' ],
'FF' : ['detector', 'layers', 'ApplyPixelResponse', 'pixel_response' ],
'xoffset' : ['optics', 'layers', 'CompoundAperture', 'apertures', 'Nicmos', 'x_offset'],
'yoffset' : ['optics', 'layers', 'CompoundAperture', 'apertures', 'Nicmos', 'y_offset']
}
# telescope.get_leaves(['yoffset'], path_dict=path_dict)
# telescope.get_leaves([['optics', 'layers', 'CompoundAperture', 'apertures', 'Nicmos']], path_dict=path_dict)[0]
telescope.scene.sources['Binary'].field_angle
np.arctan2(-0.1, 1)
def psf_model(data, model, path_dict=None):
# Define empty paths and values lists to append to,
paths, values = [], []
# # Position
position_pix = npy.sample("position_pix", dist.Uniform(-4, 4), sample_shape=(2,))
position = npy.deterministic('position', position_pix * true_pixel_scale)
paths.append('pos'), values.append(position)
# Separation
log_sep_min = np.log(true_separation - 5 * true_pixel_scale)
log_sep_max = np.log(true_separation + 5 * true_pixel_scale)
separation_log = npy.sample("log_sep", dist.Uniform(log_sep_min, log_sep_max))
separation = npy.deterministic('separation', np.exp(separation_log))
paths.append('sep'), values.append(separation)
# Field Angle (Position Angle),
theta_x = npy.sample("theta_x", dist.Normal(0, 1))
theta_y = npy.sample("theta_y", dist.Normal(0, 1))
field_angle = npy.deterministic('field_angle', np.arctan2(theta_y, theta_x))
# field_angle = npy.sample("field_angle", dist.Uniform(-np.pi/4, np.pi/4))
paths.append('angle'), values.append(field_angle)
# Flux,
flux_log = npy.sample('log_flux', dist.Uniform(4, 8))
flux = npy.deterministic('flux', 10**flux_log)
paths.append('flx'), values.append(flux)
# Flux ratio,
flux_ratio_log = npy.sample('log_flux_ratio', dist.Uniform(0, 2))
flux_ratio = npy.deterministic('flux_ratio', 10**flux_ratio_log)
paths.append('cont'), values.append(flux_ratio)
# Zernikes
coeffs = npy.sample("coeffs", dist.Normal(0, 2), sample_shape=true_coeffs.shape)
paths.append('zern'), values.append(coeffs)
# Background
bg = npy.sample("bg", dist.Uniform(5, 15))
paths.append('bg'), values.append(bg)
# Offset
x_offset_latent = npy.sample("offset_x_latent", dist.HalfNormal(1))
y_offset_latent = npy.sample("offset_y_latent", dist.HalfNormal(1))
x_offset = npy.deterministic('offset_x', 0.1*x_offset_latent)
y_offset = npy.deterministic('offset_y', -0.1*y_offset_latent)
paths.append('xoffset'), values.append(x_offset)
paths.append('yoffset'), values.append(y_offset)
with npy.plate("data", len(data)):
poisson_model = dist.Poisson(model.update_and_model(
"model_image", paths, values, path_dict=path_dict, flatten=True))
return npy.sample("psf", poisson_model, obs=data)
sampler = npy.infer.MCMC(
npy.infer.NUTS(psf_model),
num_warmup=1000,
num_samples=1000,
num_chains=jax.device_count(),
progress_bar=True)
sampler.run(jr.PRNGKey(0), data, telescope, path_dict=path_dict)
values_out = sampler.get_samples()
sampler.print_summary()
def make_dict(dict_in, truth=False):
znames = ['Focus', 'Astig45', 'Astig0', 'ComaY', 'ComaX', 'TfoilY', 'TfoilX']
pos_names = ['Pos_x', 'Pos_y']
name_dict = {'separation': 'r',
'field_angle': r'$\\phi$',
'flux_ratio': 'Contrast',
'flux': r'$\\overline{flux}$',
'bg': r'$\\mu_{BG}$',
'bg_var': r'$\\sigma_{BG}$',
'pixel_scale': 'pixscale',
'offset_x': 'offset_x',
'offset_y': 'offset_y'}
dict_out = {}
keys = list(dict_in.keys())
for i in range(len(keys)):
key = keys[i]
# if 'latent' in key or 'log' in key or 'theta' in key or '_pix' in key or '_raw' in key:# or key == 'bg':,
if 'latent' in key or 'log' in key or '_pix' in key or '_raw' in key:# or key == 'bg':,
continue
item = dict_in[key]
if key == 'position':
for j in range(item.shape[-1]):
dict_out[pos_names[j]] = item[j] if truth else item[:, j]
elif key == 'coeffs':
for j in range(item.shape[-1]):
dict_out[znames[j]] = item[j] if truth else item[:, j]
else:
dict_out[name_dict[key]] = item
# print(list(dict_out.keys()))
# Now re-order for nicer plotting
order = [
'r',
r'$\\phi$',
'Pos_x',
'Pos_y',
r'$\\overline{flux}$',
'Contrast',
r'$\\mu_{BG}$',
'offset_x',
'offset_y',
'Focus',
'Astig45',
'Astig0'
]
new_dict = {}
for key in order:
new_dict[key] = dict_out[key]
return new_dict
# Format chains for plotting
# This can always stay defined, no need to comment out
truth_dict = {
'bg': true_bg,
'coeffs': true_coeffs,
'field_angle': true_field_angle,
'flux': true_flux,
'flux_ratio': true_flux_ratio,
'position': true_position,
'separation': true_separation,
'bg_var': 1.,
'pixel_scale': true_pixel_scale,
'offset_x': 0.067,
'offset_y': -0.067,
}
truth_dict_in = make_dict(truth_dict, truth=True)
# chain_dict = make_dict(values_out)
chain = cc.ChainConsumer()
chain.add_chain(chain_dict)
chain.configure(serif=True, shade=True, bar_shade=True,
shade_alpha=0.2, spacing=1., max_ticks=3)
fig = chain.plotter.plot(truth=truth_dict_in)
# fig.set_size_inches((4,4))
fig.set_size_inches((12,12))
fig.savefig('hmc', dpi=200, facecolor='w')
est_field_angle = values_out['field_angle'].mean()
binary_source = dl.BinarySource(true_position, true_flux, true_separation,
est_field_angle, true_flux_ratio,
combined_spectrum, resolved, name="Binary")
# Construct Telescope,
telescope_est = dl.Telescope(dl.Optics(layers),
dl.Scene([binary_source]),
filter=dl_nicmos_filter,
detector=dl.Detector(detector_layers))
# +
## Gerenate psf,
psf = telescope_est.model_scene()
psf_photon = jr.poisson(jr.PRNGKey(0), psf)
bg_noise = true_bg + jr.normal(jr.PRNGKey(0), psf_photon.shape)
image = psf_photon + bg_noise
data = image.flatten()
plt.figure(figsize=(15, 4))
plt.subplot(1, 2, 1)
plt.title("PSF")
plt.imshow(psf ** 0.25)
plt.colorbar()
plt.subplot(1, 2, 2),
plt.title("PSF + Photon")
plt.imshow(psf_photon ** 0.25)
plt.colorbar()
# -
import h5py
import hdfdict
data_file = h5py.File("chains.hdf5")
chain_dict = hdfdict.load(data_file)
chain_dict = {key: np.array(chain_dict[key]) for key in chain_dict}
truth_dict_in = make_dict(truth_dict, truth=True)
# chain_dict = make_dict(values_out)
chain = cc.ChainConsumer()
chain.add_chain(test)
chain.configure(serif=True, shade=True, bar_shade=True,
shade_alpha=0.2, spacing=1., max_ticks=3)
fig = chain.plotter.plot(truth=truth_dict_in)
# fig.set_size_inches((4,4))
fig.set_size_inches((12,12))
fig.savefig('hmc', dpi=200, facecolor='w')
fig.axes