cohere-core 4.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1290 @@
1
+ # #########################################################################
2
+ # Copyright (c) , UChicago Argonne, LLC. All rights reserved. #
3
+ # #
4
+ # See LICENSE file. #
5
+ # #########################################################################
6
+
7
+
8
+ """
9
+ Provides phasing capabilities for the Bragg CDI data.
10
+
11
+ The reconstruction is based on known iterative algorithm, oscillating between direct and reciprocal space and applying projection algorithms. Cohere
12
+ supports the following projection algorithms: ER (error reduction), HIO (hybrid input-output), SF (solvent flipping), and RAAR (relaxed averaged alternating reflectors). The algorithms are described in this publication: https://pubs.aip.org/aip/rsi/article/78/1/011301/349838/Invited-Article-A-unified-evaluation-of-iterative
13
+
14
+ The cohere reconstruction can be tuned to specific cases. Typically every few iteration steps a shrink wrap is applied.
15
+ And typically a twin blocking is performed after a few first iterations. Other factors differentiating reconstruction and supported by cohere are: low pass filter, phase constrain, averaging amplitudes. These are direct space methods.
16
+ Each of these features owns parameters that can be tuned to the projection algorithm. Cohere supports partial coherence feature that is performed in reciprocal space and is used to mitigate coherence of the light source.
17
+
18
+ The software can run code on GPU or CPU, utilizing different library, such as cupy, numpy or torch. User configures the choice depending on hardware and installed software.
19
+
20
+ The reconstruction is utilized by the GA algorithm, where each generation creates multiple Rec objects, and executes parallel reconstructions.
21
+
22
+ In addition two subclasses provide functionality for different types of reconstruction. The CoupleRec class supports multipeak reconstruction.
23
+ The TeRec class supports reconstruction of time-evolving samples with improved temporal resolution.
24
+ """
25
+
26
+ from pathlib import Path
27
+ import time
28
+ import os
29
+ from math import pi
30
+ import random
31
+ import tqdm
32
+
33
+ import numpy as np
34
+ from matplotlib import pyplot as plt
35
+ import tifffile as tf
36
+
37
+ import cohere_core.utilities.dvc_utils as dvut
38
+ import cohere_core.utilities.utils as ut
39
+ import cohere_core.controller.op_flow as of
40
+ import cohere_core.controller.features as ft
41
+
42
+ __author__ = "Barbara Frosik"
43
+ __copyright__ = "Copyright (c) 2016, UChicago Argonne, LLC."
44
+ __docformat__ = 'restructuredtext en'
45
+ __all__ = ['set_lib_from_pkg',
46
+ 'create_rec',
47
+ 'Rec']
48
+
49
+
50
+ def set_lib_from_pkg(pkg):
51
+ """
52
+ Imports package specified in input and sets the device library to this package.
53
+
54
+ :param pkg: supported values: 'cp' for cupy, 'np' for numpy, and 'torch' for torch
55
+ :return:
56
+ """
57
+ global devlib
58
+
59
+ # get the lib object
60
+ devlib = ut.get_lib(pkg)
61
+ # pass the lib object to the features associated with this reconstruction
62
+ ft.set_lib(devlib)
63
+ # the utilities are not associated with reconstruction and the initialization of lib is independent
64
+ dvut.set_lib_from_pkg(pkg)
65
+
66
+
67
+ class Rec:
68
+ """
69
+ Performs phasing using iterative algorithm.
70
+
71
+ The Rec object must have a device set, either to GPU id or set as CPU.
72
+ The functions executed in each iteration are determined at the beginning, during iteration loop initialization. It is based on the reconstruction parameters and the order of functions internally defined in 'iter_functions' field.
73
+ A factory for this class, 'create_rec' returns initialized Rec object.
74
+ The object is then called to run iterations. The results can be retrieved with getters or saved.
75
+ """
76
+
77
+ def __init__(self, params, data_file, pkg, **kwargs):
78
+ """
79
+ Constructor. Sets / initializes reconstruction parameters.
80
+
81
+ :param params: dictionary containing configuration parameters
82
+ :param data_file: path to the data file
83
+ :param pkg: an acronym of the package that will be utilized for reconstruction:
84
+ "np" for numpy, "cp" for cupy, and "torch" for torch
85
+ :param kwargs: can contain "debug" parameter. When activated, it will throw exception, if one happens. Otherwise, an error code of -1 is returned and error printed. The handling of the exception is needed in GA reconstruction.
86
+ """
87
+ set_lib_from_pkg(pkg)
88
+ self.iter_functions = [self.next,
89
+ self.lowpass_filter_operation,
90
+ self.reset_resolution,
91
+ self.shrink_wrap_operation,
92
+ self.phc_operation,
93
+ self.to_reciprocal_space,
94
+ self.new_func_operation,
95
+ self.pc_operation,
96
+ self.pc_modulus,
97
+ self.modulus,
98
+ self.set_prev_pc,
99
+ self.to_direct_space,
100
+ self.er,
101
+ self.hio,
102
+ self.sf,
103
+ self.raar,
104
+ self.twin_operation,
105
+ self.average_operation,
106
+ self.progress_operation,
107
+ self.live_operation]
108
+
109
+ params['init_guess'] = params.get('init_guess', 'random')
110
+ if params['init_guess'] == 'AI_guess':
111
+ if 'AI_threshold' not in params:
112
+ params['AI_threshold'] = params['shrink_wrap_threshold']
113
+ if 'AI_sigma' not in params:
114
+ params['AI_sigma'] = params['shrink_wrap_gauss_sigma']
115
+ params['reconstructions'] = params.get('reconstructions', 1)
116
+ params['hio_beta'] = params.get('hio_beta', 0.9)
117
+ params['raar_beta'] = params.get('raar_beta', 0.45)
118
+ params['initial_support_area'] = params.get('initial_support_area', (.5, .5, .5))
119
+ if 'twin_trigger' in params:
120
+ params['twin_halves'] = params.get('twin_halves', (0, 0))
121
+ if 'pc_interval' in params and 'pc' in params['algorithm_sequence']:
122
+ self.is_pcdi = True
123
+ else:
124
+ self.is_pcdi = False
125
+ # finished setting defaults
126
+ self.params = params
127
+ self.data_file = data_file
128
+ self.ds_image = None
129
+ self.need_save_data = False
130
+ self.saved_data = None
131
+ self.debug = kwargs.get('debug', False)
132
+
133
+
134
+ def init_dev(self, device_id):
135
+ """
136
+ This function initializes GPU device that will be used for reconstruction. When running on CPU, the device_id
137
+ is set to -1, and the initialization is omitted.
138
+ After the device is set, the data array is loaded on that device or cpu memory. The data file can be
139
+ in tif or npy format.
140
+
141
+ :param device_id: device id or -1 if cpu
142
+ :return: 0 if successful, -1 otherwise. In debug mode will re-raise exception instead of returning -1.
143
+ """
144
+ os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
145
+ if device_id != -1:
146
+ self.dev = device_id
147
+ if device_id != -1:
148
+ try:
149
+ devlib.set_device(device_id)
150
+ except Exception as e:
151
+ if self.debug:
152
+ raise
153
+ print(e)
154
+ print('may need to restart GUI')
155
+ return -1
156
+
157
+ if self.data_file.endswith('tif') or self.data_file.endswith('tiff'):
158
+ try:
159
+ data_np = ut.read_tif(self.data_file)
160
+ data = devlib.from_numpy(data_np)
161
+ except Exception as e:
162
+ if self.debug:
163
+ raise
164
+ print(e)
165
+ return -1
166
+ elif self.data_file.endswith('npy'):
167
+ try:
168
+ data = devlib.load(self.data_file)
169
+ except Exception as e:
170
+ if self.debug:
171
+ raise
172
+ print(e)
173
+ return -1
174
+ else:
175
+ print('no data file found')
176
+ return -1
177
+ # in the formatted data the max is in the center, we want it in the corner, so do fft shift
178
+ self.data = devlib.fftshift(data)
179
+ self.dims = devlib.dims(self.data)
180
+ print('data shape', self.dims)
181
+
182
+ if self.params.get("live_trigger", None) is not None:
183
+ self.fig, self.axs = plt.subplots(2, 2, figsize=(12, 13), layout="constrained")
184
+ plt.show(block=False)
185
+ else:
186
+ self.fig = None
187
+ self.axs = None
188
+
189
+ if self.need_save_data:
190
+ self.saved_data = devlib.copy(self.data)
191
+ self.need_save_data = False
192
+
193
+ return 0
194
+
195
+
196
+ def init_iter_loop(self, dir=None, gen=None):
197
+ """
198
+ Initializes the iteration loop.
199
+
200
+ :param dir: directory containing 'image.npy' file that contains reconstructed object, if the reconstruction is continuation.
201
+ It defaults to None.
202
+ :param gen: generation number, only used when running GA algorithm.
203
+ It defaults to None.
204
+ :return: 0 if successful, -1 otherwise. In debug mode will re-raise exception instead of returning -1.
205
+ """
206
+ if self.ds_image is not None:
207
+ first_run = False
208
+ elif dir is None or not os.path.isfile(ut.join(dir, 'image.npy')):
209
+ self.ds_image = devlib.random(self.dims, dtype=self.data.dtype)
210
+ first_run = True
211
+ else:
212
+ self.ds_image = devlib.load(ut.join(dir, 'image.npy'))
213
+ first_run = False
214
+
215
+ # When running GA the lowpass filter, phc, and twin triggers should be active only during first
216
+ # generation. The code below inactivates the triggers in subsequent generations.
217
+ # This will be removed in the future when each generation will have own configuration.
218
+ if not first_run:
219
+ self.params.pop('lowpass_filter_trigger', None)
220
+ self.params.pop('phc_trigger', None)
221
+ self.params.pop('twin_trigger', None)
222
+
223
+ self.flow_items_list = [f.__name__ for f in self.iter_functions]
224
+
225
+ try:
226
+ self.is_pc, flow, feats = of.get_flow_arr(self.params, self.flow_items_list, gen)
227
+ except Exception as e:
228
+ if self.debug:
229
+ raise
230
+ print(e)
231
+ return -1
232
+
233
+ self.flow = []
234
+ (op_no, self.iter_no) = flow.shape
235
+ for i in range(self.iter_no):
236
+ for j in range(op_no):
237
+ if flow[j, i] > 0:
238
+ self.flow.append(self.iter_functions[j])
239
+
240
+ self.aver = None
241
+ self.iter = -1
242
+ self.errs = []
243
+ self.prev_dir = dir
244
+
245
+ # create or get initial support
246
+ if dir is None or not os.path.isfile(ut.join(dir, 'support.npy')):
247
+ init_support = [int(self.params['initial_support_area'][i] * self.dims[i]) for i in range(len(self.dims))]
248
+ center = devlib.full(init_support, 1)
249
+ self.support = dvut.pad_around(center, self.dims, 0)
250
+ else:
251
+ self.support = devlib.load(ut.join(dir, 'support.npy'))
252
+
253
+ if self.is_pc:
254
+ self.pc_obj = ft.Pcdi(self.params, self.data, dir)
255
+
256
+ # create the trgger/sub-trigger objects
257
+ try:
258
+ if 'shrink_wrap_trigger' in self.params:
259
+ self.shrink_wrap_obj = ft.create('shrink_wrap', self.params, feats)
260
+ if 'phc_trigger' in self.params:
261
+ self.phc_obj = ft.create('phc', self.params, feats)
262
+ if 'lowpass_filter_trigger' in self.params:
263
+ self.lowpass_filter_obj = ft.create('lowpass_filter', self.params, feats)
264
+ except Exception as e:
265
+ if self.debug:
266
+ raise
267
+ print(e)
268
+ return -1
269
+
270
+ # for the fast GA the data needs to be saved, as it would be changed by each lr generation
271
+ # for non-fast GA the Rec object is created in each generation with the initial data
272
+ if self.saved_data is not None:
273
+ if self.params['low_resolution_generations'] > gen:
274
+ self.data = devlib.gaussian_filter(self.saved_data, self.params['ga_lpf_sigmas'][gen])
275
+ else:
276
+ self.data = self.saved_data
277
+ else:
278
+ if gen is not None and self.params['low_resolution_generations'] > gen:
279
+ self.data = devlib.gaussian_filter(self.data, self.params['ga_lpf_sigmas'][gen])
280
+
281
+ if 'lowpass_filter_range' not in self.params or not first_run:
282
+ self.iter_data = self.data
283
+ else:
284
+ self.iter_data = devlib.copy(self.data)
285
+
286
+ if (first_run):
287
+ max_data = devlib.amax(self.data)
288
+ self.ds_image *= dvut.get_norm(self.ds_image) * max_data
289
+
290
+ # the line below are for testing to set the initial guess to support
291
+ # self.ds_image = devlib.full(self.dims, 1.0) + 1j * devlib.full(self.dims, 1.0)
292
+ # self.ds_image = devlib.full(self.dims, 1.0) + 1j * devlib.full(self.dims, 0.0)
293
+
294
+ self.ds_image *= self.support
295
+ return 0
296
+
297
+
298
+ def iterate(self):
299
+ """
300
+ It iterates over function order that was determined during loop initialization.
301
+
302
+ During iteration execution an exception can happen. The exception is handled in non debug mode and thrown otherwise.
303
+
304
+ :return: 0 if successful, -1 otherwise. In debug mode will throw exception instead of returning -1.
305
+ """
306
+ self.iter = -1
307
+ start_t = time.time()
308
+ try:
309
+ for f in self.flow:
310
+ f()
311
+ except Exception as error:
312
+ if self.debug:
313
+ raise
314
+ print(error)
315
+ return -1
316
+
317
+ print('iterate took ', (time.time() - start_t), ' sec')
318
+
319
+ if devlib.hasnan(self.ds_image):
320
+ print('reconstruction resulted in NaN')
321
+ return -1
322
+
323
+ if self.aver is not None:
324
+ ratio = self.get_ratio(devlib.from_numpy(self.aver), devlib.absolute(self.ds_image))
325
+ self.ds_image *= ratio / self.aver_iter
326
+
327
+ if self.params.get("live_trigger", None) is not None:
328
+ plt.show()
329
+
330
+ return 0
331
+
332
+
333
+ def save_res(self, save_dir, only_image=False):
334
+ """
335
+ Saves reconstruction results.
336
+
337
+ It centers the maximum of image array and saves this array, support array, coherence if present, and errors.
338
+ This function is typically called after iterations.
339
+
340
+ :param save_dir: directory where results will be saved
341
+ :param only_image: will save only image if True, otherwise all the results are saved. By default all results are saved.
342
+ :return:
343
+ """
344
+ mx = devlib.amax(devlib.absolute(self.ds_image))
345
+ self.ds_image = self.ds_image / mx
346
+
347
+ # center image's center_of_mass and sync support
348
+ self.ds_image, self.support = dvut.center_sync(self.ds_image, self.support)
349
+
350
+ from array import array
351
+
352
+ if not os.path.exists(save_dir):
353
+ os.makedirs(save_dir)
354
+ devlib.save(ut.join(save_dir, 'image'), self.ds_image)
355
+ ut.save_tif(devlib.to_numpy(self.ds_image), ut.join(save_dir, 'image.tif'))
356
+
357
+ if only_image:
358
+ return 0
359
+
360
+ devlib.save(ut.join(save_dir, 'support'), self.support)
361
+ if self.is_pc:
362
+ devlib.save(ut.join(save_dir, 'coherence'), self.pc_obj.kernel)
363
+ errs = array('f', self.errs)
364
+
365
+ with open(ut.join(save_dir, 'errors.txt'), 'w+') as err_f:
366
+ err_f.write('\n'.join(map(str, errs)))
367
+
368
+ devlib.save(ut.join(save_dir, 'errors'), errs)
369
+
370
+ metric = dvut.all_metrics(self.ds_image, self.errs)
371
+ with open(ut.join(save_dir, 'metrics.txt'), 'w+') as f:
372
+ f.write(str(metric))
373
+
374
+ return 0
375
+
376
+ def get_metric(self):
377
+ """
378
+ Returns metrics such as: chi (the error after last iteration), summed phase, area, sharpness of the ds_image array that holds reconstructed image.
379
+ """
380
+ return dvut.all_metrics(self.ds_image, self.errs)
381
+
382
+ def next(self):
383
+ self.iter = self.iter + 1
384
+
385
+ def lowpass_filter_operation(self):
386
+ args = (self.data, self.iter, self.ds_image)
387
+ (self.iter_data, self.support) = self.lowpass_filter_obj.apply_trigger(*args)
388
+
389
+ def reset_resolution(self):
390
+ self.iter_data = self.data
391
+
392
+ def shrink_wrap_operation(self):
393
+ args = (self.ds_image,)
394
+ self.support = self.shrink_wrap_obj.apply_trigger(*args)
395
+
396
+ def phc_operation(self):
397
+ args = (self.ds_image,)
398
+ self.support *= self.phc_obj.apply_trigger(*args)
399
+
400
+ def to_reciprocal_space(self):
401
+ self.rs_amplitudes = devlib.ifft(self.ds_image)
402
+
403
+ def new_func_operation(self):
404
+ self.params['new_param'] = 1
405
+ print(f'in new_func_trigger, new_param {self.params["new_param"]}')
406
+
407
+ def pc_operation(self):
408
+ self.pc_obj.update_partial_coherence(devlib.absolute(self.rs_amplitudes))
409
+
410
+ def pc_modulus(self):
411
+ abs_amplitudes = devlib.absolute(self.rs_amplitudes)
412
+ converged = self.pc_obj.apply_partial_coherence(abs_amplitudes)
413
+ ratio = self.get_ratio(self.iter_data, devlib.absolute(converged))
414
+ error = dvut.get_norm(
415
+ devlib.where(devlib.absolute(converged) != 0.0, devlib.absolute(converged) - self.iter_data, 0.0)) / dvut.get_norm(self.iter_data)
416
+ self.errs.append(float(error))
417
+ self.rs_amplitudes *= ratio
418
+
419
+ def modulus(self):
420
+ ratio = self.get_ratio(self.iter_data, devlib.absolute(self.rs_amplitudes))
421
+ error = dvut.get_norm(devlib.where((self.rs_amplitudes != 0), (devlib.absolute(self.rs_amplitudes) - self.iter_data),
422
+ 0)) / dvut.get_norm(self.iter_data)
423
+ self.errs.append(float(error))
424
+ self.rs_amplitudes *= ratio
425
+
426
+ def set_prev_pc(self):
427
+ self.pc_obj.set_previous(devlib.absolute(self.rs_amplitudes))
428
+
429
+ def to_direct_space(self):
430
+ self.ds_image_proj = devlib.fft(self.rs_amplitudes)
431
+
432
+ def er(self):
433
+ self.ds_image = self.ds_image_proj * self.support
434
+
435
+ def hio(self):
436
+ combined_image = self.ds_image - self.ds_image_proj * self.params['hio_beta']
437
+ self.ds_image = devlib.where((self.support > 0), self.ds_image_proj, combined_image)
438
+
439
+ def sf(self):
440
+ # solvent flipping
441
+ self.ds_image = 2.0 * (self.ds_image_proj * self.support) - self.ds_image_proj
442
+
443
+ def raar(self):
444
+ # Relaxed averaged alternating reflectors
445
+ self.ds_image = self.params['raar_beta'] * (self.support * self.ds_image_proj + self.ds_image) +\
446
+ (1 - 2 * self.params['raar_beta']) * self.ds_image_proj
447
+
448
+ def twin_operation(self):
449
+ # TODO this will work only for 3D array, but will the twin be used for 1D or 2D?
450
+ # com = devlib.center_of_mass(devlib.absolute(self.ds_image))
451
+ # sft = [int(self.dims[i] / 2 - com[i]) for i in range(len(self.dims))]
452
+ # self.ds_image = devlib.shift(self.ds_image, sft)
453
+ dims = devlib.dims(self.ds_image)
454
+ half_x = int((dims[0] + 1) / 2)
455
+ half_y = int((dims[1] + 1) / 2)
456
+ if self.params['twin_halves'][0] == 0:
457
+ self.ds_image[half_x:, :, :] = 0
458
+ else:
459
+ self.ds_image[: half_x, :, :] = 0
460
+ if self.params['twin_halves'][1] == 0:
461
+ self.ds_image[:, half_y:, :] = 0
462
+ else:
463
+ self.ds_image[:, : half_y, :] = 0
464
+
465
+ def average_operation(self):
466
+ if self.aver is None:
467
+ self.aver = devlib.to_numpy(devlib.absolute(self.ds_image))
468
+ self.aver_iter = 1
469
+ else:
470
+ self.aver = self.aver + devlib.to_numpy(devlib.absolute(self.ds_image))
471
+ self.aver_iter += 1
472
+
473
+ def progress_operation(self):
474
+ print(f'------iter {self.iter} error {self.errs[-1]}')
475
+
476
+ def live_operation(self):
477
+ self.shift_to_center()
478
+ half = self.dims[0] // 2
479
+ qtr = self.dims[0] // 4
480
+ plt.suptitle(
481
+ f"iteration: {self.iter}\n"
482
+ f"error: {self.errs[-1]}\n"
483
+ )
484
+ [[ax.clear() for ax in row] for row in self.axs]
485
+ img = self.ds_image[qtr:-qtr, qtr:-qtr, half]
486
+ self.axs[0][0].set(title="Amplitude", xticks=[], yticks=[])
487
+ self.axs[0][0].imshow(devlib.absolute(img).get(), cmap="gray")
488
+ self.axs[0][1].set(title="Phase", xticks=[], yticks=[])
489
+ self.axs[0][1].imshow(devlib.angle(img).get(), cmap="hsv", interpolation_stage="rgba")
490
+
491
+ self.axs[1][0].set(title="Error", xlim=(0,self.iter_no), xlabel="Iteration", yscale="log")
492
+ self.axs[1][0].plot(self.errs[1:])
493
+ self.axs[1][1].set(title="Support", xticks=[], yticks=[])
494
+ self.axs[1][1].imshow(self.support[qtr:-qtr, qtr:-qtr, half].get(), cmap="gray")
495
+
496
+ plt.draw()
497
+ plt.pause(0.15)
498
+
499
+ def get_ratio(self, divident, divisor):
500
+ ratio = devlib.where((divisor > 1e-9), divident / divisor, 0.0)
501
+ return ratio
502
+
503
+ def shift_to_center(self):
504
+ ind = devlib.center_of_mass(self.support.astype('int32'))
505
+ shift_dist = (self.dims[0]//2) - devlib.round(devlib.array(ind))
506
+ shift_dist = devlib.to_numpy(shift_dist).tolist()
507
+ axis = tuple(range(len(self.ds_image.shape)))
508
+ self.ds_image = devlib.roll(self.ds_image, shift_dist, axis=axis)
509
+ self.support = devlib.roll(self.support, shift_dist, axis=axis)
510
+
511
+ def get_image(self):
512
+ """
513
+ Returns image array.
514
+ """
515
+ return self.ds_image
516
+
517
+ def get_support(self):
518
+ """
519
+ Returns support array.
520
+ """
521
+ return self.support
522
+
523
+ def get_coherence(self):
524
+ """
525
+ returns coherence array, if exists.
526
+ """
527
+ if self.is_pc:
528
+ return self.pc_obj.kernel
529
+ else:
530
+ return None
531
+
532
+
533
+ class Peak:
534
+ """
535
+ Holds parameters related to a peak.
536
+ """
537
+
538
+ def __init__(self, peak_dir):
539
+ geometry = ut.read_config(f"{peak_dir}/geometry")
540
+ self.hkl = geometry["peak_hkl"]
541
+ self.order = max([abs(x) for x in self.hkl])
542
+ self.weight = 1.0
543
+ self.conf_hist = []
544
+ self.conf_iter = []
545
+ self.weight_iter = 0
546
+ print(f"Loading peak {self.hkl}")
547
+
548
+ # Geometry parameters
549
+ try:
550
+ a, b, c, alpha, beta, gamma = geometry["lattice"]
551
+ alpha *= np.pi / 180
552
+ beta *= np.pi / 180
553
+ gamma *= np.pi / 180
554
+ except TypeError:
555
+ # If only a single value is given, assume a cubic lattice
556
+ a = b = c = geometry["lattice"]
557
+ alpha = beta = gamma = pi/2
558
+ # The next part gets a little messy, so I'm going to predefine some things:
559
+ cosa, cosb, sing, cosg = np.cos(alpha), np.cos(beta), np.sin(gamma), np.cos(gamma)
560
+
561
+ # Convert the (possibly nonorthogonal) basis into cartesian coordinates
562
+ # a1 is defined to be along the x-axis
563
+ a1 = a * devlib.array([1, 0, 0])
564
+ # a2 is defined to be in the xy-plane
565
+ a2 = b * devlib.array([cosg, sing, 0])
566
+ # a3 is defined by the following system of equations:
567
+ # a1.a3 = a * c * cos(beta)
568
+ # a2.a3 = b * c * cos(alpha)
569
+ # a3.a3 = |c|^2
570
+ # which can be solved to give:
571
+ a3 = c * devlib.array([
572
+ cosb,
573
+ (cosa - cosb*cosg)/sing,
574
+ np.sqrt(2*cosa*cosb*cosg + sing**2 - cosa**2 - cosb**2)/sing
575
+ ])
576
+
577
+ # Now convert the direct lattice vectors (a1, a2, a3) into reciprocal lattice vectors (b1, b2, b3)
578
+ b1 = 2*pi*devlib.cross(a2, a3) / devlib.dot(a1, devlib.cross(a2, a3))
579
+ b2 = 2*pi*devlib.cross(a3, a1) / devlib.dot(a1, devlib.cross(a2, a3))
580
+ b3 = 2*pi*devlib.cross(a1, a2) / devlib.dot(a1, devlib.cross(a2, a3))
581
+
582
+ self.g_vec = self.hkl[0]*b1 + self.hkl[1]*b2 + self.hkl[2]*b3
583
+ # print(self.g_vec.get())
584
+ self.gdotg = devlib.array(devlib.dot(self.g_vec, self.g_vec))
585
+ self.size = geometry["final_size"]
586
+ self.rs_lab_to_det = np.array(geometry["rmatrix"]) / geometry["rs_voxel_size"]
587
+ # self.rs_lab_to_det = np.identity(3) # FIXME
588
+ self.rs_det_to_lab = np.linalg.inv(self.rs_lab_to_det)
589
+ self.ds_lab_to_det = self.rs_det_to_lab.T
590
+ self.ds_det_to_lab = self.rs_lab_to_det.T
591
+
592
+ datafile = (Path(peak_dir) / "phasing_data/data.tif").as_posix()
593
+ self.full_data = devlib.absolute(devlib.from_numpy(tf.imread(datafile)))
594
+ self.full_data = devlib.moveaxis(self.full_data, 0, 2)
595
+ self.full_data = devlib.moveaxis(self.full_data, 0, 1)
596
+ self.full_size = np.max(self.full_data.shape)
597
+ self.full_data = dvut.pad_to_cube(self.full_data, self.full_size)
598
+ self.data = dvut.pad_to_cube(self.full_data, self.size)
599
+ self.mask = devlib.zeros(self.data.shape)
600
+
601
+ # Uncomment when phasing non-centered data
602
+ # ind = devlib.center_of_mass(self.full_data)
603
+ # shift_dist = (self.size // 2) - devlib.round(devlib.array(ind))
604
+ # shift_dist = devlib.to_numpy(shift_dist).tolist()
605
+ # self.full_data = devlib.roll(self.full_data, shift_dist, axis=(0, 1, 2))
606
+
607
+ # Resample the diffraction patterns into the lab reference frame.
608
+ self.res_data = dvut.resample(self.full_data, self.rs_det_to_lab)
609
+ if self.size is not None:
610
+ self.res_data = dvut.pad_to_cube(self.res_data, self.size)
611
+
612
+ tf.imwrite((Path(peak_dir) / "phasing_data/data_resampled.tif").as_posix(), devlib.to_numpy(self.res_data))
613
+
614
+ # Do the fftshift on all the arrays
615
+ self.full_data = devlib.fftshift(self.full_data)
616
+ self.data = devlib.fftshift(self.data)
617
+ self.res_data = devlib.fftshift(self.res_data)
618
+ self.total = devlib.sum(self.res_data**2)
619
+ self.max_lk = devlib.sum(devlib.xlogy(self.res_data**2, self.res_data**2) - self.res_data**2)
620
+
621
+ def normalize(self, norm):
622
+ factor = norm / self.total
623
+ self.full_data *= devlib.sqrt(factor)
624
+ self.data *= devlib.sqrt(factor)
625
+ self.res_data *= devlib.sqrt(factor)
626
+ self.total = devlib.sum(self.res_data**2)
627
+ self.max_lk = devlib.mean(devlib.xlogy(self.res_data**2, self.res_data**2) - self.res_data**2)
628
+
629
+ def unlikelihood(self, proj):
630
+ """Returns the difference between the maximum and current log-likelihood"""
631
+ proj = devlib.absolute(proj)**2
632
+ lk = devlib.mean(devlib.xlogy(self.res_data**2, proj) - proj)
633
+ return self.max_lk - lk
634
+
635
+ def chi_square(self, proj):
636
+ error = devlib.where((self.res_data != 0), (devlib.absolute(proj) - self.res_data), 0)
637
+ return dvut.get_norm(error) / dvut.get_norm(self.res_data)
638
+
639
+ def get_error(self, proj):
640
+ pass
641
+
642
+
643
+ class CoupledRec(Rec):
644
+ """
645
+ Performs a coupled reconstruction of multiple Bragg peaks using iterative phase retrieval. It alternates between a
646
+ shared object with a density and atomic displacement field and a working object with an amplitude and phase. The
647
+ general outline of this process is as follows:
648
+ 1. Initialize the shared object with random values.
649
+ 2. Randomly select a diffraction pattern and corresponding reciprocal lattice vector G from the collected data.
650
+ 3. Set the working object to the projection of the shared object onto G.
651
+ 4. Apply standard phase retrieval techniques to the working object for a set number of iterations.
652
+ 5. Update the G-projection of the shared object to be a weighted average of its current value with the working
653
+ object.
654
+ 6. Repeat steps 2-5.
655
+
656
+ params : dict
657
+ parameters used in reconstruction. Refer to x for parameters description
658
+ data_file : str
659
+ name of file containing data for each peak to be reconstructed
660
+
661
+ """
662
+ __author__ = "Nick Porter"
663
+ __all__ = []
664
+
665
+ def __init__(self, params, peak_dirs, pkg, **kwargs):
666
+ super().__init__(params, None, pkg, **kwargs)
667
+
668
+ self.iter_functions = [self.adapt_operation] + self.iter_functions + [self.switch_peak_operation]
669
+
670
+ self.params["switch_peak_trigger"] = self.params.get("switch_peak_trigger", [0, 5])
671
+ self.params["adapt_trigger"] = self.params.get("adapt_trigger", [])
672
+ self.params["calc_strain"] = self.params.get("calc_strain", False)
673
+
674
+ self.peak_dirs = peak_dirs
675
+ self.er_iter = False # Indicates whether the last iteration done was ER
676
+
677
+ def init_dev(self, device_id):
678
+ os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
679
+ if device_id != -1:
680
+ self.dev = device_id
681
+ if device_id != -1:
682
+ try:
683
+ devlib.set_device(device_id)
684
+ except Exception as e:
685
+ if self.debug:
686
+ raise
687
+ print(e)
688
+ print('may need to restart GUI')
689
+ return -1
690
+
691
+ # Allows for a control peak to be left out of the reconstruction for comparison
692
+ all_peaks = [Peak(d) for d in self.peak_dirs]
693
+ norm = max([p.total for p in all_peaks])
694
+ for p in all_peaks:
695
+ p.normalize(norm)
696
+ # for pk in all_peaks:
697
+ # plt.figure()
698
+ # plt.imshow(np.log(devlib.fftshift(pk.res_data)[90].get() + 1))
699
+ # plt.show()
700
+ if "control_peak" in self.params:
701
+ control_peak = self.params["control_peak"]
702
+ self.peak_objs = [p for p in all_peaks if p.hkl != control_peak]
703
+ try:
704
+ self.ctrl_peak = next(p for p in all_peaks if p.hkl == control_peak)
705
+ self.ctrl_error = []
706
+ except StopIteration:
707
+ self.ctrl_peak = None
708
+ self.ctrl_error = None
709
+ else:
710
+ self.peak_objs = all_peaks
711
+ self.ctrl_peak = None
712
+ self.ctrl_error = None
713
+ self.peak_confidence = [1.0 for _ in self.peak_objs]
714
+
715
+ # Fast resampling means using the resampled data to reconstruct the object in a single common basis
716
+ # When this is set to False, the reconstruction will need to be resampled each time the peak is switched
717
+ self.fast_resample = True
718
+ self.lab_frame = True
719
+
720
+ self.num_peaks = len(self.peak_objs)
721
+ self.pk = 0 # index in list of current peak being reconstructed
722
+ self.data = self.peak_objs[self.pk].res_data
723
+ self.iter_data = self.data
724
+ self.dims = self.data.shape
725
+ self.n_voxels = self.dims[0]*self.dims[1]*self.dims[2]
726
+
727
+ if self.params.get("live_trigger", None) is not None:
728
+ self.fig, self.axs = plt.subplots(2, 2, figsize=(12, 13), layout="constrained")
729
+ plt.show(block=False)
730
+ else:
731
+ self.fig = None
732
+ self.axs = None
733
+
734
+ if self.need_save_data:
735
+ self.saved_data = devlib.copy(self.data)
736
+ self.need_save_data = False
737
+
738
+ return 0
739
+
740
+ def init_iter_loop(self, img_dir=None, gen=None):
741
+ if super().init_iter_loop(img_dir, gen) == -1:
742
+ return -1
743
+
744
+ # Define the shared image
745
+ self.rho_image = devlib.absolute(self.ds_image)
746
+ self.u_image = devlib.absolute(self.ds_image[:, :, :, None]) * devlib.array([0, 0, 0])
747
+
748
+ # Define the multipeak projection weighting and tapering
749
+ self.proj_weight = devlib.array([self.params["weight_init"] for _ in range(self.iter_no)])
750
+ for i, w in zip(self.params["weight_iters"], self.params["weight_vals"]):
751
+ self.proj_weight[i:] = w
752
+
753
+ self.adapt_on = False
754
+ self.peak_threshold = devlib.array([self.params["adapt_threshold_init"] for _ in range(self.iter_no)])
755
+ for i, w in zip(self.params["adapt_threshold_iters"], self.params["adapt_threshold_vals"]):
756
+ self.peak_threshold[i:] = w
757
+ self.peak_weights = []
758
+ self.iter_weights = []
759
+ return 0
760
+
761
+ def save_res(self, save_dir):
762
+ from array import array
763
+ tight_support = devlib.binary_erosion(self.support)
764
+ self.rho_image = self.rho_image * tight_support
765
+ self.u_image = self.u_image * tight_support[:, :, :, None]
766
+ # for i in range(3):
767
+ # self.u_image[:, :, :, i] = devlib.median_filter(self.u_image[:, :, :, i], 3)
768
+ self.shift_to_center()
769
+
770
+ crop = self.dims[0] / 4
771
+ sup = self.support[crop:-crop, crop:-crop, crop:-crop]
772
+ rho = self.rho_image[crop:-crop, crop:-crop, crop:-crop] * sup
773
+ u_x = self.u_image[crop:-crop, crop:-crop, crop:-crop, 0] * sup
774
+ u_y = self.u_image[crop:-crop, crop:-crop, crop:-crop, 1] * sup
775
+ u_z = self.u_image[crop:-crop, crop:-crop, crop:-crop, 2] * sup
776
+
777
+ if self.params["calc_strain"]:
778
+ J = self.calc_jacobian()[crop:-crop, crop:-crop, crop:-crop]
779
+ s_xx = J[:,:,:,0,0]
780
+ s_yy = J[:,:,:,1,1]
781
+ s_zz = J[:,:,:,2,2]
782
+ s_xy = ((J[:,:,:,0,1] + J[:,:,:,1,0]) / 2)
783
+ s_yz = ((J[:,:,:,1,2] + J[:,:,:,2,1]) / 2)
784
+ s_zx = ((J[:,:,:,2,0] + J[:,:,:,0,2]) / 2)
785
+ else:
786
+ s_xx = s_yy = s_zz = s_xy = s_yz = s_zx = devlib.zeros(sup.shape)
787
+
788
+ final_rec = devlib.stack((rho, u_x, u_y, u_z, s_xx, s_yy, s_zz, s_xy, s_yz, s_zx, sup))
789
+
790
+ if not os.path.exists(save_dir):
791
+ os.makedirs(save_dir)
792
+ devlib.save(save_dir + "/reconstruction", final_rec)
793
+ devlib.save(save_dir + "/image_nostrain", devlib.stack((rho, u_x, u_y, u_z)))
794
+ devlib.save(save_dir + "/shared_density", rho)
795
+ devlib.save(save_dir + "/shared_u1", u_x)
796
+ devlib.save(save_dir + "/shared_u2", u_y)
797
+ devlib.save(save_dir + "/shared_u3", u_z)
798
+ devlib.save(save_dir + '/support', sup)
799
+
800
+ errs = array('f', self.errs)
801
+ with open(ut.join(save_dir, 'errors.txt'), 'w+') as err_f:
802
+ err_f.write('\n'.join(map(str, errs)))
803
+ devlib.save(ut.join(save_dir, 'errors'), errs)
804
+
805
+ metric = dvut.all_metrics(self.ds_image, self.errs)
806
+ with open(ut.join(save_dir, 'metrics.txt'), 'w+') as f:
807
+ f.write(str(metric))
808
+
809
+ for pk in self.peak_objs:
810
+ np.savetxt(f"{save_dir}/conf_hist_{pk.hkl[0]}{pk.hkl[1]}{pk.hkl[2]}.txt", pk.conf_hist)
811
+ np.savetxt(f"{save_dir}/conf_iter_{pk.hkl[0]}{pk.hkl[1]}{pk.hkl[2]}.txt", pk.conf_iter)
812
+
813
+ if self.ctrl_error is not None:
814
+ ctrl_error = np.array(self.ctrl_error)
815
+ np.save(save_dir + '/ctrl_error', ctrl_error)
816
+ np.savetxt(save_dir + '/ctrl_error.txt', ctrl_error)
817
+ return 0
818
+
819
+ def make_binary(self):
820
+ self.support = devlib.absolute(self.support)
821
+ self.support = devlib.where(self.support >= 0.9 * devlib.amax(self.support), 1, 0).astype("?")
822
+
823
+ def get_phase_gradient(self):
824
+ """Calculate the phase gradient for a given peak"""
825
+ # Project onto the peak
826
+ if self.fast_resample:
827
+ self.iter_data = self.peak_objs[self.pk].res_data
828
+ else:
829
+ self.iter_data = self.peak_objs[self.pk].data
830
+
831
+ self.to_working_image()
832
+
833
+ # Calculate the continuous phase gradient using Hofmann's method
834
+ # (https://doi.org/10.1103/PhysRevMaterials.4.013801)
835
+ gradient = []
836
+ voxel_size = self.params["ds_voxel_size"]
837
+ dx0, dy0, dz0 = devlib.gradient(devlib.angle(self.ds_image), voxel_size)
838
+ dx1, dy1, dz1 = devlib.gradient(devlib.angle(self.ds_image * devlib.exp(1j*pi/2)), voxel_size)
839
+ dx2, dy2, dz2 = devlib.gradient(devlib.angle(self.ds_image * devlib.exp(-1j*pi/2)), voxel_size)
840
+ for stack in ([dx0, dx1, dx2], [dy0, dy1, dy2], [dz0, dz1, dz2]):
841
+ stack = devlib.array(stack)
842
+ index = devlib.argmin(stack**2, axis=0)
843
+ gradient.append(devlib.take_along_axis(stack, index[None, :, :, :], axis=0).squeeze(axis=0))
844
+ return gradient
845
+
846
+ def calc_jacobian(self):
847
+ grad_phi = []
848
+ for i, peak in enumerate(self.peak_objs):
849
+ self.prev_pk = self.pk
850
+ self.pk = i
851
+ grad_phi.append(self.get_phase_gradient())
852
+ grad_phi = devlib.array(grad_phi)
853
+ G = devlib.array([peak.g_vec for peak in self.peak_objs])
854
+ grad_phi = devlib.moveaxis(devlib.moveaxis(grad_phi, 0, -1), 0, -1)
855
+ cond = devlib.where(self.support, True, False)
856
+ final_shape = (grad_phi.shape[0], grad_phi.shape[1], grad_phi.shape[2], 3, 3)
857
+ ind = devlib.moveaxis(devlib.indices(cond.shape), 0, -1).reshape((-1, 3))[cond.ravel()].get()
858
+ jacobian = devlib.zeros(final_shape)
859
+ print("Calculating strain...")
860
+ for i, j, k in tqdm.tqdm(ind):
861
+ jacobian[i, j, k] = devlib.lstsq(G, grad_phi[i, j, k])[0]
862
+ return jacobian
863
+
864
+ def iterate(self):
865
+ self.iter = -1
866
+ start_t = time.time()
867
+
868
+ try:
869
+ for f in self.flow:
870
+ f()
871
+ except Exception as error:
872
+ if self.debug:
873
+ raise
874
+ print('error',error)
875
+ return -1
876
+
877
+ print('iterate took ', (time.time() - start_t), ' sec')
878
+
879
+ if self.params.get("live_trigger", None) is not None:
880
+ plt.show()
881
+
882
+ if devlib.hasnan(self.ds_image):
883
+ print('reconstruction resulted in NaN')
884
+ return -1
885
+
886
+ if self.aver is not None:
887
+ ratio = self.get_ratio(devlib.from_numpy(self.aver), devlib.absolute(self.ds_image))
888
+ self.ds_image *= ratio / self.aver_iter
889
+
890
+ mx = devlib.amax(devlib.absolute(self.ds_image))
891
+ self.ds_image = self.ds_image / mx
892
+
893
+ return 0
894
+
895
+ def switch_peak_operation(self):
896
+ self.calc_confidence()
897
+ self.to_shared_image()
898
+ self.get_control_error()
899
+
900
+ if self.adapt_on:
901
+ print("Adapting weights")
902
+ self.update_weights()
903
+
904
+ if self.params.get("live_view", False):
905
+ self.update_live()
906
+
907
+ # Use the peak weights as probabilities for projecting to that peak. High-confidence = more likely
908
+ p_weights = [self.peak_objs[x].weight for x in range(self.num_peaks)]
909
+ p_weights[self.pk] = 0 # Don't project back onto the same peak we just used
910
+ self.peak_weights.append(p_weights / np.sum(p_weights))
911
+ self.iter_weights.append(self.iter)
912
+ self.pk = random.choices([x for x in range(self.num_peaks)], p_weights)[0]
913
+
914
+ self.to_working_image()
915
+
916
+ def to_shared_image(self):
917
+ pk = self.peak_objs[self.pk] # shorthand
918
+
919
+ if not self.fast_resample:
920
+ # Resample the object
921
+ if self.lab_frame:
922
+ self.lab_frame = False
923
+ else:
924
+ self.shift_to_center()
925
+ self.ds_image = dvut.resample(self.ds_image, self.peak_objs[self.pk].ds_det_to_lab)
926
+ self.support = dvut.resample(self.support, self.peak_objs[self.pk].ds_det_to_lab,
927
+ plot=True)
928
+ if self.dims is not None:
929
+ self.ds_image = dvut.pad_to_cube(self.ds_image, self.dims[0])
930
+ self.support = dvut.pad_to_cube(self.support, self.dims[0])
931
+
932
+ self.make_binary()
933
+
934
+ # The weighting is determined by the peak weight and the global weight. I'm leaving the option to give the
935
+ # density and displacement their own weights, but currently they're just the same.
936
+ wt_rho = pk.weight * self.proj_weight[self.iter]
937
+ wt_u = pk.weight * self.proj_weight[self.iter]
938
+
939
+ # Update density with a weighted average of the shared and working objects
940
+ self.rho_image = (1-wt_rho) * self.rho_image + wt_rho * devlib.absolute(self.ds_image)
941
+
942
+ # Update displacement with a weighted average.
943
+ old_u = (devlib.dot(self.u_image, pk.g_vec) / pk.gdotg)[:, :, :, None] * pk.g_vec
944
+ new_u = (devlib.angle(self.ds_image) / pk.gdotg)[:, :, :, None] * pk.g_vec
945
+ self.u_image = self.u_image + wt_u * (new_u - old_u)
946
+
947
+ if self.er_iter:
948
+ # No shrinkwrap during ER blocks. Instead, the shared object is given an extra-tight support constraint,
949
+ # and the density is given a 3-pixel smoothover.
950
+ tight_support = devlib.binary_erosion(self.support)
951
+ self.rho_image = devlib.median_filter(self.rho_image, 3)
952
+ self.rho_image = self.rho_image * tight_support
953
+ self.u_image = self.u_image * tight_support[:, :, :, None]
954
+ self.shift_to_center()
955
+
956
+ # Shift the displacement field so that the center of the image is at ux=uy=uz=0
957
+ ctr = self.dims[0] / 2
958
+ self.u_image = self.u_image[:, :, :] - self.u_image[ctr, ctr, ctr]
959
+
960
+ def to_working_image(self):
961
+ pk = self.peak_objs[self.pk] # Shorthand for convenience
962
+
963
+ # Define the exit wave for this peak based on the shared density/displacement
964
+ self.ds_image = self.rho_image * devlib.exp(1j * devlib.dot(self.u_image, pk.g_vec))
965
+
966
+ if self.fast_resample:
967
+ # Use the resampled data
968
+ self.iter_data = pk.res_data
969
+ else:
970
+ # Use the original sampling
971
+ self.iter_data = pk.data
972
+
973
+ if self.iter > self.params["adapt_alien_start"]:
974
+ # Calculate the diffraction amplitude from the current exit wave (which is based ONLY on shared object).
975
+ proj = devlib.absolute(devlib.ifft(self.ds_image))
976
+
977
+ # Blur the projected and measured diffraction amplitudes by one pixel (to mitigate HF noise)
978
+ proj_blurred = devlib.gaussian_filter(proj, 1)
979
+ meas_blurred = devlib.gaussian_filter(self.iter_data, 1)
980
+
981
+ # Map the absolute difference between the two blurred images.
982
+ # Normalizing to the projected image makes bright artifacts in the measurement stand out:
983
+ # proj | meas | diff_map
984
+ # --------|--------|----------
985
+ # high | high | low
986
+ # low | low | low
987
+ # high | low | low
988
+ # low | high | HIGH
989
+ diff_map = devlib.absolute(meas_blurred - proj_blurred) / proj_blurred
990
+
991
+ # Mask voxels where the difference map is exceptionally high compared to its median. If there are no
992
+ # outliers, the difference map will be tightly clustered around the median.
993
+ pk.mask = diff_map > devlib.median(diff_map) * self.params["adapt_alien_threshold"]
994
+
995
+ # For phasing, use the projected amplitude for masked voxels and the measurement for unmasked voxels.
996
+ self.iter_data = devlib.where(pk.mask, proj, proj + pk.weight*(self.iter_data - proj))
997
+
998
+ if not self.fast_resample:
999
+ # Resample the object and support
1000
+ self.ds_image = dvut.resample(self.ds_image, pk.ds_lab_to_det)
1001
+ self.support = dvut.resample(self.support, pk.ds_lab_to_det)
1002
+ if self.dims is not None:
1003
+ self.ds_image = dvut.pad_to_cube(self.ds_image, self.dims[0])
1004
+ self.support = dvut.pad_to_cube(self.support, self.dims[0])
1005
+ self.make_binary()
1006
+
1007
+ def calc_confidence(self):
1008
+ pk = self.peak_objs[self.pk] # shorthand
1009
+
1010
+ # Calculate the amplitude of the exit wave after phasing.
1011
+ rho = devlib.absolute(self.ds_image)
1012
+ cond = self.support > 0
1013
+
1014
+ # Compare the exit wave amplitude before and after phasing (only within the support region)
1015
+ # conf = 1 / dvut.calc_ehd(self.rho_image[cond], rho[cond], log=False).get()
1016
+ conf = dvut.calc_nmi(self.rho_image[cond], rho[cond], log=False).get() - 1
1017
+
1018
+ pk.conf_hist.append(conf)
1019
+ pk.conf_iter.append(self.iter)
1020
+
1021
+ def adapt_operation(self):
1022
+ self.adapt_on = True
1023
+
1024
+ def update_weights(self):
1025
+ # Grab the 75th %ile confidence for each peak. If a peak has not been phased, then its confidence history will
1026
+ # be empty, in which case it just gets a -1 and skips the weighting.
1027
+ confidences = [
1028
+ sorted(p.conf_hist, reverse=True)[len(p.conf_hist) // 4]
1029
+ if len(p.conf_hist) > 0 else -1
1030
+ for p in self.peak_objs
1031
+ ]
1032
+ for pk, confidence in zip(self.peak_objs, confidences):
1033
+ if confidence == -1:
1034
+ continue
1035
+ # Assign the weights based on the RELATIVE confidence raised to a power (currently hard-coded at 2). The
1036
+ # power determines how harshly bad peaks are punished.
1037
+ pk.weight = (confidence / max(confidences)) ** self.params["adapt_power"]
1038
+ print(f"New weights: {[round(p.weight, 2) for p in self.peak_objs]}")
1039
+ self.adapt_on = False
1040
+
1041
+ def to_reciprocal_space(self):
1042
+ self.rs_amplitudes = devlib.ifft(self.ds_image)
1043
+
1044
+ def to_direct_space(self):
1045
+ self.ds_image_proj = devlib.fft(self.rs_amplitudes)
1046
+
1047
+ def modulus(self):
1048
+ ratio = self.get_ratio(self.iter_data, devlib.absolute(self.rs_amplitudes))
1049
+ error = dvut.get_norm(devlib.where((self.rs_amplitudes != 0), (devlib.absolute(self.rs_amplitudes) - self.iter_data),
1050
+ 0)) / dvut.get_norm(self.iter_data)
1051
+ self.errs.append(float(error))
1052
+ self.rs_amplitudes *= ratio
1053
+
1054
+ def er(self):
1055
+ self.er_iter = True
1056
+ self.ds_image = self.ds_image_proj * self.support
1057
+
1058
+ def hio(self):
1059
+ self.er_iter = False
1060
+ combined_image = self.ds_image - self.ds_image_proj * self.params['hio_beta']
1061
+ support = self.support
1062
+ self.ds_image = devlib.where((support > 0), self.ds_image_proj, combined_image)
1063
+
1064
+ def shrink_wrap_operation(self):
1065
+ if self.er_iter or self.peak_objs[self.pk].weight < self.peak_threshold[self.iter]:
1066
+ return
1067
+ super().shrink_wrap_operation()
1068
+
1069
+ def get_control_error(self):
1070
+ pk = self.peak_objs[self.pk]
1071
+ if self.ctrl_peak is None:
1072
+ return
1073
+ phi = devlib.dot(self.u_image, pk.g_vec)
1074
+ rho = self.rho_image
1075
+ img = devlib.absolute(devlib.ifft(rho * devlib.exp(1j * phi)))
1076
+
1077
+ lin_hist = devlib.histogram2d(self.ctrl_peak.res_data, img, log=False)
1078
+ nmi = dvut.calc_nmi(lin_hist).get()
1079
+ ehd = dvut.calc_ehd(lin_hist).get()
1080
+
1081
+ log_hist = devlib.histogram2d(self.ctrl_peak.res_data, img, log=True)
1082
+ lnmi = dvut.calc_nmi(log_hist).get()
1083
+ lehd = dvut.calc_ehd(log_hist).get()
1084
+
1085
+ self.ctrl_error.append([nmi, lnmi, ehd, lehd])
1086
+
1087
+ def progress_operation(self):
1088
+ ornt = self.peak_objs[self.pk].hkl
1089
+ prg = f'| iter {self.iter:>4} ' \
1090
+ f'| peak {self.pk} [{ornt[0]:>2}, {ornt[1]:>2}, {ornt[2]:>2}] ' \
1091
+ f'| err {self.errs[-1]:0.6f} ' \
1092
+ f'| sup {devlib.sum(self.support):>8} '
1093
+ if self.ctrl_error is not None:
1094
+ prg += f"| NMI {self.ctrl_error[-1][0]:0.6f} "
1095
+ prg += f"| LNMI {self.ctrl_error[-1][1]:0.6f} "
1096
+ prg += f"| EHD {self.ctrl_error[-1][2]:0.6f} "
1097
+ prg += f"| LEHD {self.ctrl_error[-1][3]:0.6f} "
1098
+ print(prg)
1099
+
1100
+ def live_operation(self):
1101
+ half = self.dims[0] // 2
1102
+ qtr = self.dims[0] // 4
1103
+ plt.suptitle(
1104
+ f"iteration: {self.iter}\n"
1105
+ f"peak: {self.peak_objs[self.pk].hkl}\n"
1106
+ f"global weight: {self.proj_weight[self.iter]}\n"
1107
+ f"peak weight: {self.peak_objs[self.pk].weight:0.3f}\n"
1108
+ f"confidence threshold: {self.peak_threshold[self.iter]}\n"
1109
+ )
1110
+ [[ax.clear() for ax in row] for row in self.axs]
1111
+ self.axs[0][0].set_title("XY amplitude")
1112
+ self.axs[0][0].imshow(devlib.absolute(self.ds_image[qtr:-qtr, qtr:-qtr, half]).get(), cmap="gray")
1113
+ self.axs[0][1].set_title("XY phase")
1114
+ self.axs[0][1].imshow(devlib.angle(self.ds_image[qtr:-qtr, half, qtr:-qtr]).get(), cmap="hsv",
1115
+ interpolation_stage="rgba")
1116
+
1117
+ self.axs[1][0].set_title("Measurement")
1118
+ meas = devlib.sum(devlib.ifftshift(self.peak_objs[self.pk].res_data), axis=0)
1119
+ self.axs[1][0].imshow(devlib.sqrt(meas).get(), cmap="magma")
1120
+ self.axs[1][1].set_title("Fourier Constraint")
1121
+ data = devlib.sum(devlib.ifftshift(self.iter_data), axis=0)
1122
+ self.axs[1][1].imshow(devlib.sqrt(data).get(), cmap="magma")
1123
+ plt.setp(self.fig.get_axes(), xticks=[], yticks=[])
1124
+
1125
+ plt.draw()
1126
+ plt.pause(0.15)
1127
+
1128
+ def switch_resampling_operation(self):
1129
+ self.fast_resample = False
1130
+
1131
+ def get_density(self):
1132
+ return self.rho_image
1133
+
1134
+ def get_distortion(self):
1135
+ return self.u_image.swapaxes(3, 2).swapaxes(2, 1).swapaxes(1, 0)
1136
+
1137
+ def flip(self):
1138
+ self.rho_image = devlib.flip(self.rho_image, axis=(0, 1, 2))
1139
+ self.u_image = -1 * devlib.flip(self.u_image, axis=(0, 1, 2))
1140
+ self.support = devlib.flip(self.support, axis=(0, 1, 2))
1141
+
1142
+ def shift_to_center(self):
1143
+ ind = devlib.center_of_mass(self.rho_image)
1144
+ shift_dist = (self.dims[0]//2) - devlib.round(devlib.array(ind))
1145
+ shift_dist = devlib.to_numpy(shift_dist).tolist()
1146
+ axis = tuple(range(len(self.rho_image.shape)))
1147
+ self.rho_image = devlib.roll(self.rho_image, shift_dist, axis=axis)
1148
+ self.u_image = devlib.roll(self.u_image, shift_dist, axis=axis)
1149
+ self.ds_image = devlib.roll(self.ds_image, shift_dist, axis=axis)
1150
+ self.support = devlib.roll(self.support, shift_dist, axis=axis)
1151
+
1152
+
1153
+ class TeRec(Rec):
1154
+ """
1155
+ Coherent diffractive imaging of time-evolving samples with improved temporal resolution
1156
+
1157
+ params : dict
1158
+ parameters used in reconstruction. Refer to x for parameters description
1159
+ data_file : str
1160
+ name of file containing data
1161
+
1162
+ """
1163
+
1164
+ def __init__(self, params, data_file, pkg, comm):
1165
+ super().__init__(params, data_file, pkg)
1166
+
1167
+ self.comm = comm
1168
+ self.size = comm.Get_size()
1169
+ self.rank = comm.Get_rank()
1170
+ self.weight = params['weight']
1171
+
1172
+
1173
+ def exchange_data_info(self):
1174
+ # The data with fewer frames comparing to full data
1175
+ # has the missing frames filled with -1.
1176
+ # Since data collected by detector is greater than 0,
1177
+ # the data that does not have any negative values is full data,
1178
+ # and partial data otherwise.
1179
+ self.is_full_data = (self.data < 0).sum() == 0
1180
+ # send to previous if full_data
1181
+ if self.rank != 0:
1182
+ self.comm.send(self.is_full_data, dest=self.rank - 1)
1183
+ if self.rank != self.size - 1:
1184
+ next_full_data = self.comm.recv(source=self.rank+1)
1185
+ # send to next if full_data
1186
+ if self.rank != self.size - 1:
1187
+ self.comm.send(self.is_full_data, dest=self.rank + 1)
1188
+ if self.rank != 0:
1189
+ prev_full_data = self.comm.recv(source=self.rank-1)
1190
+
1191
+ # figure out if rank needs to send prev/next
1192
+ self.send_to_prev = (self.rank > 0) and (not prev_full_data)
1193
+ self.send_to_next = (self.rank < self.size - 1) and (not next_full_data)
1194
+
1195
+
1196
+ def er(self):
1197
+ if self.send_to_prev:
1198
+ self.comm.send(self.ds_image, dest=self.rank - 1)
1199
+ if not self.is_full_data:
1200
+ ds_image_next = self.comm.recv(source=self.rank + 1)
1201
+ if self.send_to_next:
1202
+ self.comm.send(self.ds_image, dest=self.rank + 1)
1203
+ if not self.is_full_data:
1204
+ ds_image_prev = self.comm.recv(source=self.rank - 1)
1205
+
1206
+ if self.is_full_data:
1207
+ # run the super er
1208
+ self.ds_image = self.ds_image_proj * self.support
1209
+
1210
+ else:
1211
+ # use previous and next to run modified er
1212
+ self.ds_image = (1/(1+2*self.weight)) * self.support * (self.ds_image_proj +
1213
+ self.weight * (ds_image_prev + ds_image_next))
1214
+
1215
+
1216
+ def hio(self):
1217
+ if self.send_to_prev:
1218
+ self.comm.send(self.ds_image, dest=self.rank - 1)
1219
+ if not self.is_full_data:
1220
+ ds_image_next = self.comm.recv(source=self.rank + 1)
1221
+ if self.send_to_next:
1222
+ self.comm.send(self.ds_image, dest=self.rank + 1)
1223
+ if not self.is_full_data:
1224
+ ds_image_prev = self.comm.recv(source=self.rank - 1)
1225
+
1226
+ if self.is_full_data:
1227
+ # run the super hio
1228
+ combined_image = self.ds_image - self.ds_image_proj * self.params['hio_beta']
1229
+ self.ds_image = devlib.where((self.support > 0), self.ds_image_proj, combined_image)
1230
+ else:
1231
+ # use previous and next to run modified hio
1232
+ combined_image = self.ds_image - self.ds_image_proj * self.params['hio_beta']
1233
+ corr = self.weight * self.support * (2 * (self.ds_image) - (ds_image_prev + ds_image_next))
1234
+ self.ds_image = devlib.where((self.support > 0), self.ds_image_proj, combined_image) - corr
1235
+
1236
+ def modulus(self):
1237
+ ratio = self.get_ratio(self.iter_data, devlib.absolute(self.rs_amplitudes))
1238
+ error = dvut.get_norm(devlib.where((self.rs_amplitudes != 0), (devlib.absolute(self.rs_amplitudes) - self.iter_data),
1239
+ 0)) / dvut.get_norm(self.iter_data)
1240
+ self.errs.append(float(error))
1241
+ # do not change the frames with -1 value.
1242
+ # This value is marking frames that were not collected, and the reconstruction
1243
+ # is taking neighboring results (in hio and er)
1244
+ self.rs_amplitudes[self.iter_data != -1.0] *= ratio[self.iter_data != -1.0]
1245
+
1246
+
1247
+ def create_rec(params, datainfo, pkg, dev, **kwargs):
1248
+ """
1249
+ Factory for creating Rec object.
1250
+
1251
+ If the rec_type is "mp", it will create CoupledRec object used for multipeak
1252
+ reconstruction, otherwise base Rec object.
1253
+ After the object is instantiated it will be set to a given device. This operation
1254
+ can fail, in which case no object is returned.
1255
+ The function continues with initialization of iteration loop. If successful, the
1256
+ Rec object is returned, otherwise None.
1257
+
1258
+ :param params: dict, contains reconstruction parameters
1259
+ :param datainfo:
1260
+ for 'basic' datainfo is data file name,
1261
+ and for 'mp' reconstruction it is a list of peak directories
1262
+ :param pkg:
1263
+ python package that will be used to run the reconstruction:
1264
+ 'cp' for cupy, 'np' for numpy, 'torch' for torch
1265
+ :param dev: GPU device id or -1
1266
+ :param kwargs:
1267
+ var parameters:
1268
+ rec_type: 'mp' for multipeak,
1269
+ debug : if True the exceptions are not handled
1270
+ :return: created and initialized object if success, None if failure
1271
+
1272
+ """
1273
+
1274
+ rec_type = kwargs.pop('rec_type', 'basic')
1275
+ if rec_type == 'mp':
1276
+ worker = CoupledRec(params, datainfo, pkg, **kwargs)
1277
+ else:
1278
+ worker = Rec(params, datainfo, pkg, **kwargs)
1279
+
1280
+ if worker.init_dev(dev) < 0:
1281
+ del worker
1282
+ return None
1283
+
1284
+ continue_dir = params.get('continue_dir')
1285
+ ret_code = worker.init_iter_loop(continue_dir)
1286
+ if ret_code < 0:
1287
+ del worker
1288
+ return None
1289
+
1290
+ return worker