-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathinversion_plots.py
More file actions
374 lines (339 loc) · 10.4 KB
/
inversion_plots.py
File metadata and controls
374 lines (339 loc) · 10.4 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
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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
import csv
import logging
import numpy as np
from pathlib import Path
from typing import Optional, Union
import matplotlib.pyplot as plt
from autoconf import conf
from autoarray.inversion.mappers.abstract import Mapper
from autoarray.plot.array import plot_array
from autoarray.plot.utils import numpy_grid, numpy_lines, numpy_positions, subplot_save, hide_unused_axes
from autoarray.inversion.plot.mapper_plots import plot_mapper
from autoarray.structures.arrays.uniform_2d import Array2D
logger = logging.getLogger(__name__)
def subplot_of_mapper(
inversion,
mapper_index: int = 0,
output_path: Optional[str] = None,
output_filename: str = "subplot_inversion",
output_format: str = "png",
colormap=None,
use_log10: bool = False,
mesh_grid=None,
lines=None,
grid=None,
positions=None,
):
"""
3×4 subplot showing all pixelization diagnostics for one mapper.
Parameters
----------
inversion
An ``AbstractInversion`` instance.
mapper_index
Which mapper in the inversion to visualise.
output_path
Directory to save the figure. ``None`` calls ``plt.show()``.
output_filename
Base filename prefix (``_{mapper_index}`` is appended).
output_format
File format.
colormap
Matplotlib colormap name.
use_log10
Apply log10 normalisation.
mesh_grid, lines, grid, positions
Optional overlays.
"""
mapper = inversion.cls_list_from(cls=Mapper)[mapper_index]
fig, axes = plt.subplots(3, 4, figsize=(28, 21))
axes = axes.flatten()
# panel 0: data subtracted
try:
plot_array(
inversion.data_subtracted_dict[mapper],
ax=axes[0],
title="Data Subtracted",
colormap=colormap,
use_log10=use_log10,
grid=grid,
positions=positions,
lines=lines,
)
except (AttributeError, KeyError):
pass
# panels 1-3: reconstructed operated data (plain, log10, + mesh grid overlay)
def _recon_array():
array = inversion.mapped_reconstructed_operated_data_dict[mapper]
from autoarray.structures.visibilities import Visibilities
if isinstance(array, Visibilities):
array = inversion.mapped_reconstructed_data_dict[mapper]
return array
try:
plot_array(
_recon_array(),
ax=axes[1],
title="Reconstructed Image",
colormap=colormap,
use_log10=use_log10,
grid=grid,
positions=positions,
lines=lines,
)
plot_array(
_recon_array(),
ax=axes[2],
title="Reconstructed Image (log10)",
colormap=colormap,
use_log10=True,
grid=grid,
positions=positions,
lines=lines,
)
plot_array(
_recon_array(),
ax=axes[3],
title="Mesh Pixel Grid Overlaid",
colormap=colormap,
use_log10=use_log10,
grid=numpy_grid(mapper.image_plane_mesh_grid),
positions=positions,
lines=lines,
)
except (AttributeError, KeyError):
pass
# panels 4-5: source reconstruction zoomed / unzoomed
pixel_values = inversion.reconstruction_dict[mapper]
plot_mapper(
mapper,
solution_vector=pixel_values,
ax=axes[4],
title="Source Reconstruction",
colormap=colormap,
use_log10=use_log10,
zoom_to_brightest=True,
mesh_grid=mesh_grid,
lines=lines,
)
plot_mapper(
mapper,
solution_vector=pixel_values,
ax=axes[5],
title="Source Reconstruction (Unzoomed)",
colormap=colormap,
use_log10=use_log10,
zoom_to_brightest=False,
mesh_grid=mesh_grid,
lines=lines,
)
# panel 6: noise map
try:
nm = inversion.reconstruction_noise_map_dict[mapper]
plot_mapper(
mapper,
solution_vector=nm,
ax=axes[6],
title="Noise-Map (Unzoomed)",
colormap=colormap,
use_log10=use_log10,
zoom_to_brightest=False,
mesh_grid=mesh_grid,
lines=lines,
)
except (KeyError, TypeError):
pass
# panel 7: regularization weights
try:
rw = inversion.regularization_weights_mapper_dict[mapper]
plot_mapper(
mapper,
solution_vector=rw,
ax=axes[7],
title="Regularization Weights (Unzoomed)",
colormap=colormap,
use_log10=use_log10,
zoom_to_brightest=False,
mesh_grid=mesh_grid,
lines=lines,
)
except (IndexError, ValueError, KeyError, TypeError):
pass
# panel 8: sub pixels per image pixels
try:
sub_size = Array2D(
values=mapper.over_sampler.sub_size, mask=inversion.dataset.mask
)
plot_array(
sub_size,
ax=axes[8],
title="Sub Pixels Per Image Pixels",
colormap=colormap,
use_log10=use_log10,
)
except Exception:
pass
# panel 9: mesh pixels per image pixels
try:
plot_array(
mapper.mesh_pixels_per_image_pixels,
ax=axes[9],
title="Mesh Pixels Per Image Pixels",
colormap=colormap,
use_log10=use_log10,
)
except Exception:
pass
# panel 10: image pixels per mesh pixel
try:
pw = mapper.data_weight_total_for_pix_from()
plot_mapper(
mapper,
solution_vector=pw,
ax=axes[10],
title="Image Pixels Per Source Pixel",
colormap=colormap,
use_log10=use_log10,
zoom_to_brightest=True,
mesh_grid=mesh_grid,
lines=lines,
)
except (TypeError, Exception):
pass
hide_unused_axes(axes)
plt.tight_layout()
subplot_save(fig, output_path, f"{output_filename}_{mapper_index}", output_format)
def subplot_mappings(
inversion,
pixelization_index: int = 0,
output_path: Optional[str] = None,
output_filename: str = "subplot_mappings",
output_format: str = "png",
colormap=None,
use_log10: bool = False,
mesh_grid=None,
lines=None,
grid=None,
positions=None,
):
"""
2×2 subplot showing data, model image, reconstruction and unzoomed reconstruction.
Parameters
----------
inversion
An ``AbstractInversion`` instance.
pixelization_index
Which mapper in the inversion to visualise.
output_path
Directory to save the figure. ``None`` calls ``plt.show()``.
output_filename
Base filename prefix (``_{pixelization_index}`` is appended).
output_format
File format.
colormap
Matplotlib colormap name.
use_log10
Apply log10 normalisation.
mesh_grid, lines, grid, positions
Optional overlays.
"""
mapper = inversion.cls_list_from(cls=Mapper)[pixelization_index]
try:
total_pixels = conf.instance["visualize"]["general"]["inversion"][
"total_mappings_pixels"
]
except Exception:
total_pixels = 10
pix_indexes = inversion.max_pixel_list_from(
total_pixels=total_pixels,
filter_neighbors=True,
mapper_index=pixelization_index,
)
mapper.slim_indexes_for_pix_indexes(pix_indexes=pix_indexes)
fig, axes = plt.subplots(2, 2, figsize=(14, 14))
axes = axes.flatten()
# panel 0: data subtracted
try:
plot_array(
inversion.data_subtracted_dict[mapper],
ax=axes[0],
title="Data Subtracted",
colormap=colormap,
use_log10=use_log10,
grid=grid,
positions=positions,
lines=lines,
)
except (AttributeError, KeyError):
pass
# panel 1: reconstructed operated data
try:
array = inversion.mapped_reconstructed_operated_data_dict[mapper]
from autoarray.structures.visibilities import Visibilities
if isinstance(array, Visibilities):
array = inversion.mapped_reconstructed_data_dict[mapper]
plot_array(
array,
ax=axes[1],
title="Reconstructed Image",
colormap=colormap,
use_log10=use_log10,
grid=grid,
positions=positions,
lines=lines,
)
except (AttributeError, KeyError):
pass
pixel_values = inversion.reconstruction_dict[mapper]
plot_mapper(
mapper,
solution_vector=pixel_values,
ax=axes[2],
title="Source Reconstruction",
colormap=colormap,
use_log10=use_log10,
zoom_to_brightest=True,
mesh_grid=mesh_grid,
lines=lines,
)
plot_mapper(
mapper,
solution_vector=pixel_values,
ax=axes[3],
title="Source Reconstruction (Unzoomed)",
colormap=colormap,
use_log10=use_log10,
zoom_to_brightest=False,
mesh_grid=mesh_grid,
lines=lines,
)
hide_unused_axes(axes)
plt.tight_layout()
subplot_save(
fig, output_path, f"{output_filename}_{pixelization_index}", output_format
)
def save_reconstruction_csv(
inversion,
output_path: Union[str, Path],
) -> None:
"""Write a CSV of each mapper's reconstruction and noise map to *output_path*.
One file is written per mapper: ``source_plane_reconstruction_{i}.csv``,
with columns ``y``, ``x``, ``reconstruction``, ``noise_map``.
Parameters
----------
inversion
An ``AbstractInversion`` instance.
output_path
Directory in which to write the CSV files.
"""
output_path = Path(output_path)
mapper_list = inversion.cls_list_from(cls=Mapper)
for i, mapper in enumerate(mapper_list):
y = mapper.source_plane_mesh_grid[:, 0]
x = mapper.source_plane_mesh_grid[:, 1]
reconstruction = inversion.reconstruction_dict[mapper]
noise_map = inversion.reconstruction_noise_map_dict[mapper]
with open(output_path / f"source_plane_reconstruction_{i}.csv", mode="w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["y", "x", "reconstruction", "noise_map"])
for j in range(len(x)):
writer.writerow([float(y[j]), float(x[j]), float(reconstruction[j]), float(noise_map[j])])