forked from liamconnor/polish-pub
-
Notifications
You must be signed in to change notification settings - Fork 1
/
revisualize.py
345 lines (317 loc) · 10.3 KB
/
revisualize.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
import optparse
import os
import sys
import time
import matplotlib.pylab as plt
import numpy as np
import tensorflow as tf
import model.wdsr as mwdsr
from model import resolve16, resolve_single
from model.common import denormalize
from utils import load_image, plot_sample
from visualize import plot_dictionary
vminlr = 0
vmaxlr = 22500
vminsr = 0
vmaxsr = 22500
vminhr = 0
vmaxhr = 22500
plt.rcParams.update(
{
"font.size": 12,
"font.family": "serif",
"axes.labelsize": 14,
"axes.titlesize": 15,
"xtick.labelsize": 12,
"ytick.labelsize": 12,
"xtick.direction": "in",
"ytick.direction": "in",
"xtick.top": True,
"ytick.right": True,
"lines.linewidth": 0.5,
"lines.markersize": 5,
"legend.fontsize": 14,
"legend.borderaxespad": 0,
"legend.frameon": False,
"legend.loc": "lower right",
}
)
def reconstruct(
fn_img,
fn_model,
model_struct,
iter,
scale,
fnhr=None,
nbit=16,
regular_image=False,
dropout_rate=None,
):
if iter is None:
iter = 1
print("Loading image from ", fn_img)
if fn_img.endswith("npy"):
datalr = np.load(fn_img)[:, :]
elif fn_img.endswith("png"):
try:
datalr = load_image(fn_img)
if regular_image:
# find maximum and minimum values of datalr
# scale to the range 0 - vmaxlr
# print("datalr min", np.min(datalr))
# print("datalr max", np.max(datalr))
# print('scale', ((vmaxlr) / (np.max(datalr) - np.min(datalr))))
datalr = datalr * ((vmaxlr) / (np.max(datalr) - np.min(datalr)))
# print("datalr min", np.min(datalr))
# print("datalr max", np.max(datalr))
# print('datalr shape', datalr.shape)
except:
return
print("Loading HR image from ", fnhr)
if fnhr is not None:
if fnhr.endswith("npy"):
datalr = np.load(fnhr)[:, :]
elif fnhr.endswith("png"):
try:
datahr = load_image(fnhr)
except:
return
else:
datahr = None
print("Loading model from ", fn_model)
model = model_struct(scale=scale, num_res_blocks=32)
if dropout_rate:
print("Loading dropout")
model = model_struct(scale=scale, num_res_blocks=32, dropout_rate=dropout_rate)
model.load_weights(fn_model)
print("Model loaded")
# for tf_var in model.trainable_weights:
# # plot a histogram of the tensor values
# plt.hist(tf_var.numpy().flatten(), bins=100)
# plt.show()
datalr = datalr[:, :, None]
# print("datalrshape")
# print(datalr.shape)
# datalr = tf.stack([datalr, datalr], axis=3)
if len(datalr.shape) == 4:
# datalr = datalr.squeeze()
datalr = datalr[:, :, :, 0]
srs = []
for idx in range(iter):
print("Reconstructing image #%d" % (idx + 1))
output, datasr = resolve16(
model, tf.expand_dims(datalr, axis=0), nbit=nbit, get_raw=True
) # hack
datasr = datasr.numpy()
print(
"SR Range: %f , %f"
% (np.min(datasr[:, :, :, 0]), np.max(datasr[:, :, :, 0]))
)
print(
"UQ Range: %f , %f"
% (np.min(datasr[:, :, :, 1]), np.max(datasr[:, :, :, 1]))
)
srs.append(datasr)
datasr = np.array(srs)
datasr = np.mean(datasr, axis=0)
return datalr, datasr, datahr
# def plot_reconstruction(
# datalr,
# datasr,
# datahr=None,
# vm=1,
# nsub=2,
# cmap="afmhot",
# regular_image=False,
# mc_data=None,
# ):
# """Plot the dirty image, POLISH reconstruction,
# and (optionally) the high resolution true sky image
# """
# if nsub == 2:
# fig = plt.figure(figsize=(10, 6))
# if nsub == 3:
# fig = plt.figure(figsize=(13, 6))
# if mc_data is not None:
# fig = plt.figure(figsize=(16, 6))
# ax1 = plt.subplot(1, nsub, 1)
# plt.title("Dirty map", color="C1", fontsize=17)
# plt.axis("off")
# if regular_image:
# print("datalr shape", datalr.shape)
# plt.imshow(tf.squeeze(datalr), cmap="RdBu")
# else:
# plt.imshow(
# datalr[..., 0],
# cmap=cmap,
# vmax=vmaxlr,
# vmin=vminlr,
# aspect="auto",
# extent=[0, 1, 0, 1],
# )
# plt.setp(ax1.spines.values(), color="C1")
# ax2 = plt.subplot(1, nsub, 2, sharex=ax1, sharey=ax1)
# plt.title("POLISH reconstruction", c="C2", fontsize=17)
# if regular_image:
# print("datasr shape", datasr.shape)
# plt.imshow(tf.squeeze(datasr), cmap="RdBu")
# else:
# plt.imshow(
# tf.squeeze(datasr),
# cmap=cmap,
# vmax=vmaxsr,
# vmin=vminsr,
# aspect="auto",
# extent=[0, 1, 0, 1],
# )
# plt.axis("off")
# # print(np.sum(datahr))
# # print(np.sum(mc_data))
# ax3 = plt.subplot(1, nsub, 3, sharex=ax1, sharey=ax1)
# plt.title("True sky", c="k", fontsize=17)
# plt.imshow(
# tf.squeeze(datahr),
# cmap=cmap,
# vmax=vmaxsr,
# vmin=vminsr,
# aspect="auto",
# extent=[0, 1, 0, 1],
# )
# plt.axis("off")
# if mc_data is not None:
# ax4 = plt.subplot(1, nsub, 4, sharex=ax1, sharey=ax1)
# plt.title("Uncertainty", c="k", fontsize=17)
# plt.imshow(
# tf.squeeze(mc_data),
# cmap=cmap,
# vmax=vmaxsr,
# vmin=vminsr,
# aspect="auto",
# extent=[0, 1, 0, 1],
# )
# plt.axis("off")
# plt.tight_layout()
# plt.colorbar()
# plt.show()
# def main(
# fn_img, fn_model, scale=4, fnhr=None, nbit=16, plotit=True, regular_image=False
# ):
# datalr, datasr, datahr = reconstruct(
# fn_img, fn_model, scale, fnhr, nbit, regular_image=regular_image
# )
# if datahr is not None:
# nsub = 3
# else:
# nsub = 2
# print(datalr.shape)
# if plotit:
# plot_reconstruction(
# datalr,
# datasr[:, :, 0],
# datahr=datahr,
# vm=1,
# nsub=4,
# regular_image=regular_image,
# mc_data=datasr[:, :, 1],
# )
# def main_mc_dropout(
# fn_img,
# fn_model,
# scale=4,
# fnhr=None,
# nbit=16,
# plotit=True,
# regular_image=False,
# num_iter=50,
# ):
# datalr, datasr, datahr, mc_data = reconstruct_mc(
# fn_img,
# fn_model,
# scale,
# fnhr,
# nbit,
# regular_image=regular_image,
# num_iter=num_iter,
# )
# if datahr is not None:
# nsub = 3
# else:
# nsub = 2
# if plotit:
# mc_data = np.var(mc_data, axis=-1)
# plot_reconstruction(
# datalr,
# datasr,
# datahr=datahr,
# vm=1,
# nsub=4,
# regular_image=regular_image,
# mc_data=mc_data,
# )
# return mc_data
if __name__ == "__main__":
# Example usage:
# Generate images on training data:
# for im in ./images/PSF-nkern64-4x/train/X4/*png;do python generate-hr.py $im ./weights-psf-4x.h5;done
# Generate images on validation data
# for im in ./images/PSF-nkern64-4x/valid/*png;do python generate-hr.py $im ./weights-psf-4x.h5;done
parser = optparse.OptionParser(
prog="hr2lr.py",
version="",
usage="%prog image weights.h5 [OPTIONS]",
description="Take high resolution images, deconvolve them, \
and save output.",
)
parser.add_option("-f", dest="fnhr", help="high-res file name", default='None')
parser.add_option("-x", dest="scale", help="spatial rebin factor", default=4)
parser.add_option("-d", dest="dropout_rate", help="drop out rate", default=0)
parser.add_option(
"-b",
"--nbit",
dest="nbit",
type=int,
help="number of bits in image",
default=16,
)
options, args = parser.parse_args()
fn_img, fn_model = args
num_mcs = 1
datalr, datasr, datahr = reconstruct(
fn_img,
fn_model,
mwdsr.wdsr_b_uq_norelu,
iter=num_mcs,
scale=options.scale,
fnhr=options.fnhr,
nbit=options.nbit,
dropout_rate=options.dropout_rate,
) # type: ignore
raw_reconstruction = datasr[:, :, :, 0]
reconstruction = tf.clip_by_value(denormalize(datasr[:, :, :, 0]), 0, 2**16)
raw_uncertainty = datasr[:, :, :, 1]
uncertainty = (2**16) * (np.exp(raw_uncertainty))
z_error = tf.math.abs(tf.math.divide((datahr - reconstruction), uncertainty))
plot_dictionary(
{
"Dirty Map": ((datalr), 0, 2**10),
f"Reconstruction avg n={num_mcs}": (reconstruction, 0, 2**10),
"True Sky": ((datahr), 0, 2**10),
"-": (np.zeros(uncertainty.shape), -2, -1),
f"Uncertainty avg n={num_mcs}": (uncertainty, 0, 2**10),
# f"LOG Uncertainty avg n={num_mcs}": (raw_uncertainty, 0, 0),
f"Error / Uncertainty": (z_error, 0, 2**10),
# "--": (np.zeros(uncertainty.shape), -2, -1),
"LOG 1 + Dirty Map": ((np.log(1 + datalr)), 0, 0),
f"LOG 1 + Reconstruction avg n={num_mcs}": (
np.log(1 + reconstruction),
0,
0,
),
"LOG 1 + True Sky": ((np.log(1 + datahr)), 0, 0),
f"Z-Score of Error": (z_error, 0, 100),
f"LOG Uncertainty avg n={num_mcs}": (np.log(1 + uncertainty), 0, 11.0903),
# f"Z-norm of Error": (z_norm, 0, 2**2),
},
title=f"{fn_img}\n@ {fn_model}",
interpolation="none",
)