cohere-core 4.3__0-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,303 @@
1
+ # #########################################################################
2
+ # Copyright (c) , UChicago Argonne, LLC. All rights reserved. #
3
+ # #
4
+ # See LICENSE file. #
5
+ # #########################################################################
6
+
7
+ import numpy as np
8
+ import os
9
+ import cohere_core.utilities.utils as ut
10
+ import math
11
+ from typing import Union
12
+ import tensorflow as tf
13
+ from tensorflow.keras import backend as K
14
+ from tensorflow.keras.models import Model, load_model
15
+ from tensorflow.keras.activations import sigmoid, tanh
16
+
17
+
18
+ class Mymodel:
19
+ __model = None
20
+ __amp_layer_model = None
21
+ __ph_layer_model = None
22
+
23
+ @staticmethod
24
+ def get_model(model_file):
25
+ """ Static access method. """
26
+ if Mymodel.__model == None:
27
+ Mymodel(model_file)
28
+ return Mymodel.__amp_layer_model, Mymodel.__ph_layer_model
29
+
30
+ def __init__(self, model_file):
31
+ """ Virtually private constructor. """
32
+ if Mymodel.__model != None:
33
+ raise Exception("This class is a singleton!")
34
+ else:
35
+ # load trained network
36
+ Mymodel.__model = load_model(
37
+ model_file,
38
+ custom_objects={
39
+ 'tf': tf,
40
+ 'loss_comb2_scale': loss_comb2_scale,
41
+ 'sigmoid': sigmoid,
42
+ 'tanh': tanh,
43
+ 'math': math,
44
+ 'combine_complex': combine_complex,
45
+ 'get_mask': get_mask,
46
+ 'ff_propagation': ff_propagation
47
+ })
48
+ model = Mymodel.__model
49
+ # get the outputs from amplitude and phase layers
50
+ Mymodel.__amp_layer_model = Model(inputs=model.input,
51
+ outputs=model.get_layer('amp').output)
52
+ Mymodel.__ph_layer_model = Model(inputs=model.input,
53
+ outputs=model.get_layer('phi').output)
54
+
55
+
56
+ def match_oversample_diff(
57
+ diff: np.ndarray,
58
+ fr: Union[list, np.ndarray, None] = None,
59
+ to: Union[list, np.ndarray, None] = None,
60
+ shape: Union[list, np.ndarray, None] = [64, 64, 64],
61
+ ):
62
+ """ resize diff to match oversample ratios
63
+ diff = diffraction pattern
64
+ fr = from oversample ratio
65
+ to = to oversample ratio
66
+ shape = output shape
67
+ """
68
+ # adjustment needed to match oversample ratio
69
+ change = [np.round(f / t).astype('int32') for f, t in zip(fr, to)]
70
+ change = [np.max([1, c]) for c in change]
71
+ diff = ut.binning(diff, change)
72
+ # crop diff to match output shape
73
+ shape_arr = np.array(shape)
74
+ diff_shape_arr = np.array(diff.shape)
75
+ pad_value1 = shape_arr // 2 - diff_shape_arr // 2
76
+ pad_value2 = shape_arr - diff_shape_arr -pad_value1
77
+ pad = [[pad_value1[0], pad_value2[0]], [pad_value1[1], pad_value2[1]],
78
+ [pad_value1[2], pad_value2[2]]]
79
+
80
+ output = ut.adjust_dimensions(diff, pad, next_fast_len=False)
81
+ return output, diff.shape
82
+
83
+
84
+ def shift_com(amp, phi):
85
+ from scipy.ndimage.measurements import center_of_mass as com
86
+ from scipy.ndimage.interpolation import shift
87
+
88
+ h, w, t = 64, 64, 64
89
+ coms = com(amp)
90
+ deltas = (int(round(h / 2 - coms[0])), int(round(w / 2 - coms[1])),
91
+ int(round(t / 2 - coms[2])))
92
+ amp_shift = shift(amp, shift=deltas, mode='wrap')
93
+ phi_shift = shift(phi, shift=deltas, mode='wrap')
94
+ return amp_shift, phi_shift
95
+
96
+
97
+ def post_process(amp, phi, th=0.1, uw=0):
98
+ if uw == 1:
99
+ phi = np.unwrap(np.unwrap(np.unwrap(phi,0),1),2)
100
+
101
+ mask = np.where(amp > th, 1, 0)
102
+ amp_out = mask * amp
103
+ phi_out = mask * phi
104
+
105
+ mean_phi = np.sum(phi_out) / np.sum(mask)
106
+ phi_out = phi_out - mean_phi
107
+
108
+ amp_out, phi_out = shift_com(amp_out, phi_out)
109
+
110
+ mask = np.where(amp_out > th, 1, 0)
111
+ amp_out = mask * amp_out
112
+ phi_out = mask * phi_out
113
+ return amp_out, phi_out
114
+
115
+
116
+ # funcions needed in tensorflow model
117
+ @tf.function
118
+ def combine_complex(amp, phi):
119
+ import tensorflow as tf
120
+ output = tf.cast(amp, tf.complex64) * tf.exp(
121
+ 1j * tf.cast(phi, tf.complex64))
122
+ return output
123
+
124
+
125
+ @tf.function
126
+ def get_mask(input):
127
+ import tensorflow as tf
128
+
129
+ mask = tf.where(input >= 0.1, tf.ones_like(input), tf.zeros_like(input))
130
+ return mask
131
+
132
+
133
+ @tf.function
134
+ def loss_comb2_scale(Y_true, Y_pred):
135
+ Y_pred = Y_pred / (
136
+ tf.math.reduce_max(Y_pred, axis=(1, 2, 3), keepdims=True) +
137
+ 1e-6) * tf.math.reduce_max(Y_true, axis=(1, 2, 3), keepdims=True)
138
+ loss_1 = tf.math.sqrt(loss_sq(Y_true, Y_pred))
139
+ loss_2 = loss_pcc(Y_true, Y_pred)
140
+ a1 = 1
141
+ a2 = 1
142
+ loss_value = (a1 * loss_1 + a2 * loss_2) / (a1 + a2)
143
+ return loss_value
144
+
145
+
146
+ @tf.function
147
+ def loss_sq(Y_true, Y_pred):
148
+ top = tf.reduce_sum(tf.math.square(Y_pred - Y_true))
149
+ bottom = tf.reduce_sum(tf.math.square(Y_true))
150
+ loss_value = tf.sqrt(top / bottom)
151
+ return loss_value
152
+
153
+
154
+ @tf.function
155
+ def loss_pcc(Y_true, Y_pred):
156
+ pred = Y_pred - tf.reduce_mean(Y_pred)
157
+ true = Y_true - tf.reduce_mean(Y_true)
158
+
159
+ top = tf.reduce_sum(pred * true)
160
+ bottom = tf.math.sqrt(tf.reduce_sum(pred**2) * tf.reduce_sum(true**2))
161
+ loss_value = 1 - top / bottom
162
+ return loss_value
163
+
164
+
165
+ @tf.function
166
+ def ff_propagation(data):
167
+ '''
168
+ diffraction. Assume same x and y lengthss and uniform sampling
169
+ data: source plane field
170
+
171
+ '''
172
+ diff = _fourier_transform(data)
173
+
174
+ # far-field amplitude
175
+ intensity = tf.math.abs(diff)
176
+ intensity = tf.cast(intensity, tf.float32)
177
+ return intensity
178
+
179
+
180
+ @tf.function
181
+ # 3D fourier transform
182
+ def _fourier_transform(input):
183
+ import tensorflow as tf
184
+ # fft3d transform with channel unequal to 1
185
+ perm_input = K.permute_dimensions(input, pattern=[4, 0, 1, 2, 3])
186
+ perm_Fr = tf.signal.fftshift(tf.signal.fft3d(
187
+ tf.signal.ifftshift(tf.cast(perm_input, tf.complex64),
188
+ axes=[-3, -2, -1])),
189
+ axes=[-3, -2, -1])
190
+ Fr = K.permute_dimensions(perm_Fr, pattern=[1, 2, 3, 4, 0])
191
+ return Fr
192
+
193
+
194
+ def run_AI(data, model_file, dir):
195
+ """
196
+ Runs AI process.
197
+
198
+ Parameters
199
+ ----------
200
+ data : ndarray
201
+ data array
202
+
203
+ model_file : str
204
+ file name containing training model
205
+
206
+ dir : str
207
+ a parent directory that holds the reconstructions. It can be experiment directory or scan directory.
208
+ Result of AI will be saved in dir/results_AI.
209
+
210
+ Returns
211
+ -------
212
+ nothing
213
+ """
214
+ print('AI guess')
215
+
216
+ # prepare data to make the oversampling ratio ~3
217
+ wos = 3.0
218
+ orig_os = ut.get_oversample_ratio(data)
219
+ # match oversampling to wos
220
+ wanted_os = [wos, wos, wos]
221
+ # match diff os
222
+ new_data, inshape = match_oversample_diff(data, orig_os, wanted_os)
223
+ new_data = new_data[np.newaxis]
224
+
225
+ amp_layer_model, ph_layer_model = Mymodel.get_model(model_file)
226
+
227
+ preds_amp = amp_layer_model.predict(new_data, verbose=1)
228
+
229
+ preds_phi = ph_layer_model.predict(new_data, verbose=1)
230
+
231
+ preds_amp, preds_phi = post_process(preds_amp[0, ..., 0],
232
+ preds_phi[0, ..., 0],
233
+ th=0.1,
234
+ uw=0)
235
+
236
+ pred_obj = preds_amp * np.exp(1j * preds_phi)
237
+
238
+ # match object size with the input data
239
+ pred_obj = ut.resample(pred_obj, inshape)
240
+
241
+ pad_value = np.array(data.shape) // 2 - np.array(pred_obj.shape) // 2
242
+ pad = [[pad_value[0], pad_value[0]], [pad_value[1], pad_value[1]],
243
+ [pad_value[2], pad_value[2]]]
244
+ # not passing in 'next_fst_len' switch, so the dimensions will not be adjusted for fast processing of
245
+ # Fourier transforms
246
+ guess = ut.adjust_dimensions(pred_obj, pad, next_fast_len=False)
247
+
248
+ np.save(ut.join(dir, 'image.npy'), guess)
249
+
250
+
251
+ def start_AI(pars, datafile, dir):
252
+ """
253
+ Starts AI process if all conditionas are met.
254
+
255
+ Parameters
256
+ ----------
257
+ pars : dict
258
+ parameters for reconstruction
259
+
260
+ datafile : str
261
+ file name containing data for reconstruction
262
+
263
+ dir : str
264
+ a parent directory that holds the reconstructions. It can be experiment directory or scan directory.
265
+ Result of AI will be saved in dir/results_AI.
266
+
267
+ Returns
268
+ -------
269
+ ai_dir : str
270
+ directory where results were saved
271
+ """
272
+ if 'AI_trained_model' not in pars:
273
+ print ('no AI_trained_model in config')
274
+ return None
275
+ if not os.path.isfile(pars['AI_trained_model']):
276
+ print(f'there is no file {pars["AI_trained_model"]}')
277
+ return None
278
+
279
+ if datafile.endswith('tif') or datafile.endswith('tiff'):
280
+ try:
281
+ data = ut.read_tif(datafile)
282
+ except:
283
+ print('could not load data file', datafile)
284
+ return None
285
+ elif datafile.endswith('npy'):
286
+ try:
287
+ data = np.load(datafile)
288
+ except:
289
+ print('could not load data file', datafile)
290
+ return None
291
+ else:
292
+ print('no data file found')
293
+ return None
294
+
295
+ # The results will be stored in the directory <experiment_dir>/AI_guess
296
+ ai_dir = ut.join(dir, 'results_AI')
297
+ if os.path.exists(ai_dir):
298
+ pass
299
+ else:
300
+ os.makedirs(ai_dir)
301
+
302
+ run_AI(data, pars['AI_trained_model'], ai_dir)
303
+ return ai_dir
@@ -0,0 +1 @@
1
+ from .phasing import *
@@ -0,0 +1,341 @@
1
+ # #########################################################################
2
+ # Copyright (c) , UChicago Argonne, LLC. All rights reserved. #
3
+ # #
4
+ # See LICENSE file. #
5
+ # #########################################################################
6
+
7
+ import cohere_core.utilities.utils as ut
8
+ import cohere_core.utilities.dvc_utils as dvut
9
+ from abc import ABC, abstractmethod
10
+
11
+ __author__ = "Barbara Frosik"
12
+ __copyright__ = "Copyright (c) 2016, UChicago Argonne, LLC."
13
+ __docformat__ = 'restructuredtext en'
14
+ __all__ = ['Pcdi',
15
+ 'TriggeredOp',
16
+ 'ShrinkWrap',
17
+ 'PhaseConstrain',
18
+ 'LowPassFilter']
19
+
20
+
21
+ def set_lib(dlib):
22
+ global devlib
23
+ devlib = dlib
24
+
25
+
26
+ class Pcdi:
27
+ def __init__(self, params, data, dir=None):
28
+ self.type = params.get('pc_type', 'LUCY')
29
+ if 'pc_LUCY_iterations' in params:
30
+ self.iterations = params['pc_LUCY_iterations']
31
+ else:
32
+ msg = 'pc_LUCY_iterations parameter not defined'
33
+ raise ValueError(msg)
34
+ self.normalize = params.get('pc_normalize', True)
35
+ if 'pc_LUCY_kernel' in params:
36
+ self.kernel_area = params['pc_LUCY_kernel']
37
+ else:
38
+ msg = 'pc_LUCY_kernel parameter not defined'
39
+ raise ValueError(msg)
40
+ if dir is None:
41
+ self.kernel = None
42
+ else:
43
+ try:
44
+ self.kernel = devlib.load(ut.join(dir, 'coherence.npy'))
45
+ except:
46
+ self.kernel = None
47
+
48
+ self.dims = devlib.dims(data)
49
+ self.roi_data = ut.crop_center(devlib.fftshift(data), self.kernel_area)
50
+ if self.normalize:
51
+ self.sum_roi_data = devlib.sum(devlib.square(self.roi_data))
52
+ if self.kernel is None:
53
+ self.kernel = devlib.full(self.kernel_area, 0.5, dtype=devlib.dtype(data))
54
+
55
+ def set_previous(self, abs_amplitudes):
56
+ self.roi_amplitudes_prev = ut.crop_center(devlib.fftshift(abs_amplitudes), self.kernel_area)
57
+
58
+ def apply_partial_coherence(self, abs_amplitudes):
59
+ abs_amplitudes_2 = devlib.square(abs_amplitudes)
60
+ converged_2 = devlib.fftconvolve(abs_amplitudes_2, self.kernel)
61
+ converged = devlib.sqrt(converged_2)
62
+ return converged
63
+
64
+ def update_partial_coherence(self, abs_amplitudes):
65
+ roi_amplitudes = ut.crop_center(devlib.fftshift(abs_amplitudes), self.kernel_area)
66
+ roi_combined_amp = 2 * roi_amplitudes - self.roi_amplitudes_prev
67
+ if self.normalize:
68
+ amplitudes_2 = devlib.square(roi_combined_amp)
69
+ sum_ampl = devlib.sum(amplitudes_2)
70
+ ratio = self.sum_roi_data / sum_ampl
71
+ amplitudes = devlib.sqrt(amplitudes_2 * ratio)
72
+ else:
73
+ amplitudes = roi_combined_amp
74
+
75
+ if self.type == "LUCY":
76
+ self.kernel = dvut.lucy_deconvolution(devlib.square(amplitudes), devlib.square(self.roi_data),
77
+ self.kernel, self.iterations)
78
+
79
+
80
+ class LowPassFilter():
81
+ def __init__(self, params):
82
+ iter_range = [params['lowpass_filter_trigger'][0], params['lowpass_filter_trigger'][2]]
83
+ iter_diff = params['lowpass_filter_trigger'][2] - params['lowpass_filter_trigger'][0]
84
+ if len(params['lowpass_filter_range']) == 1:
85
+ end_sigma = 1.0
86
+ else:
87
+ end_sigma = params['lowpass_filter_range'][1]
88
+ sigma_diff = end_sigma - params['lowpass_filter_range'][0]
89
+ self.filter_sigmas = [sigma_diff / iter_diff * iter + params['lowpass_filter_range'][0]
90
+ for iter in range(iter_range[0], iter_range[1])]
91
+
92
+
93
+ def apply_trigger(self, *args):
94
+ # The filter is applied on data
95
+ data = args[0]
96
+ iter = args[1]
97
+
98
+ filter_sigma = self.filter_sigmas[iter]
99
+ return devlib.gaussian_filter(data, filter_sigma)
100
+
101
+
102
+ class TriggeredOp(ABC):
103
+ """
104
+ Base class for Triggered operation. This class creates feature objects and manages the trigger or subtrigger depending on
105
+ configuration.
106
+ """
107
+ def __init__(self, trig_op_name):
108
+ # the self.objs will hold either one concrete feature object if configuration is for general trigger,
109
+ # i.e. spanning across all iterations,
110
+ # or it will hold a list of objects, each being a concrete sub-feature, appearing in order that will be
111
+ # executed during each trigger
112
+ self.objs = None
113
+
114
+ # the self.f points to either self.apply_trigger_obj function if configuration is for general trigger,
115
+ # or to self.apply_trigger_seq if sub-triggers are configured
116
+ self.f = None
117
+
118
+ self.trig_op_name = trig_op_name # ex: 'shrink_wrap_trigger'
119
+
120
+
121
+ def apply_trigger_obj(self, *args):
122
+ """
123
+ This function is called when general trigger is used. In this case there is only one instance of the concrete
124
+ feature. The trigger is then executed on this instance.
125
+ :param args: variable parameters depending on the concrete feature
126
+ :return: depends on the concrete feature
127
+ """
128
+ return self.objs.apply_trigger(*args)
129
+
130
+ def apply_trigger_seq(self, *args):
131
+ """
132
+ This function is called when sub-triggers are used. the self.objs is a list for this case. Every time a trigger
133
+ is applied the first object is removed from this list and the trigger is executed on this instance.
134
+ :param args: variable parameters depending on the concrete feature
135
+ :return: depends on the concrete feature
136
+ """
137
+ sub_obj = self.objs.pop(0)
138
+ return sub_obj.apply_trigger(*args)
139
+
140
+ def apply_trigger(self, *args):
141
+ """
142
+ Thhis function is called by a trigger. It then directs the trigger by calling the self.f function.
143
+ :param args: variable parameters depending on the concrete feature
144
+ :return: depends on the concrete feature
145
+ """
146
+ # the f is either update_amp_seq function or update_amp_seq
147
+ # The f is set in constructor depending on whether the trigger
148
+ # was defined for the entire span of iterations or multiple
149
+ # subtriggers were defined in algorithm sequence
150
+ return self.f(*args)
151
+
152
+ @abstractmethod
153
+ def create_obj(self, *args):
154
+ """
155
+ This class must be overriden by subclass. It creates a feature object.
156
+ :param args: variable parameters depending on the concrete feature
157
+ :return: an instance of the subclass
158
+ """
159
+ pass
160
+
161
+ def create_objs(self, params, sub_rows_trigs):
162
+ """
163
+ The params map contains value of the feature trigger. If the trigger is configured as a general one,
164
+ i.e. a single trigger, the self.objs is set to the created instance of the feature, and the self.f
165
+ pointer is set accordingly, i.e. to the self.apply_trigger_obj function.
166
+ If the trigger contains several sub-triggers, the sub_row_trigs contain info about the sequence the
167
+ subtrigger should be executed. Based on this info the unique instances are created and are added to the
168
+ in the order the triggers should be called. The self.f function is set to the self.apply_trigger_seq
169
+ function.
170
+ :param sub_rows_trigs: sub-triggers info if sub-triggers are configured
171
+ :param params: configuration parameters
172
+ :return:
173
+ """
174
+ trigger_name = f'{self.trig_op_name}_trigger'
175
+
176
+ if trigger_name in sub_rows_trigs.keys():
177
+ row = sub_rows_trigs[trigger_name][0]
178
+ sub_trigs = sub_rows_trigs[trigger_name][1]
179
+ sub_objs = {}
180
+ for sub_t in sub_trigs:
181
+ (beg, end, idx) = sub_t
182
+ index = int(idx)
183
+ if index not in sub_objs.keys():
184
+ sub_objs[index] = self.create_obj(params, index=index, beg=beg, end=end)
185
+ trigs = [i-1 for i in row.tolist() if i != 0]
186
+ # the operation of creating object might fail
187
+ # if conditions are not met, ex: the sw_type is not supported
188
+ # This should be already verified by a verifier, so no checking here
189
+ self.objs = [sub_objs[idx] for idx in trigs]
190
+ self.f = self.apply_trigger_seq
191
+ else:
192
+ if trigger_name in params:
193
+ self.objs = self.create_obj(params)
194
+ self.f = self.apply_trigger_obj
195
+
196
+
197
+ class ShrinkWrap(TriggeredOp):
198
+ def __init__(self, trig_op):
199
+ super().__init__(trig_op)
200
+
201
+ class GaussSW:
202
+ def __init__(self, gauss_sigma, threshold):
203
+ self.gauss_sigma = gauss_sigma
204
+ self.threshold = threshold
205
+
206
+ def apply_trigger(self, *args):
207
+ ds_image = args[0]
208
+ return dvut.shrink_wrap(ds_image, self.threshold, self.gauss_sigma)
209
+
210
+
211
+ class Gauss1SW:
212
+ def __init__(self, gauss_sigma, threshold):
213
+ self.gauss_sigma = gauss_sigma
214
+ self.threshold = threshold
215
+
216
+ def apply_trigger(self, *args):
217
+ ds_image = args[0]
218
+ return dvut.shrink_wrap(ds_image, self.threshold + .01, self.gauss_sigma)
219
+
220
+
221
+ def create_obj(self, params, index=None, beg=None, end=None):
222
+ def check_Gauss_type():
223
+ # for now cohere supports only Gauss type, so the following parameters are mandatory
224
+ if 'shrink_wrap_gauss_sigma' not in params:
225
+ msg = 'shrink_wrap_gauss_sigma parameter not defined'
226
+ raise ValueError(msg)
227
+ if 'shrink_wrap_threshold' not in params:
228
+ msg = 'shrink_wrap_threshold parameter not defined'
229
+ raise ValueError(msg)
230
+
231
+ def check_Gauss1_type():
232
+ # for now cohere supports only Gauss type, so the following parameters are mandatory
233
+ if 'shrink_wrap_gauss_sigma' not in params:
234
+ msg = 'shrink_wrap_gauss_sigma parameter not defined'
235
+ raise ValueError(msg)
236
+ if 'shrink_wrap_threshold' not in params:
237
+ msg = 'shrink_wrap_threshold parameter not defined'
238
+ raise ValueError(msg)
239
+
240
+ if 'shrink_wrap_type' not in params:
241
+ msg = 'shrink_wrap_type parameter not defined'
242
+ raise ValueError(msg)
243
+
244
+ if index is None:
245
+ sw_type = params['shrink_wrap_type']
246
+ if sw_type == 'GAUSS':
247
+ check_Gauss_type()
248
+ sigma = params['shrink_wrap_gauss_sigma']
249
+ threshold = params['shrink_wrap_threshold']
250
+ return self.GaussSW(sigma, threshold)
251
+ elif sw_type == 'GAUSS1':
252
+ check_Gauss1_type()
253
+ sigma = params['shrink_wrap_gauss_sigma']
254
+ threshold = params['shrink_wrap_threshold']
255
+ return self.Gauss1SW(sigma, threshold)
256
+ else:
257
+ msg = f'{sw_type} shrink wrap type is not supported'
258
+ raise ValueError(msg)
259
+ else:
260
+ if len(params['shrink_wrap_type']) - 1 < index:
261
+ msg = f'shrink_wrap_type not defined for sub-trigger {index}'
262
+ raise ValueError(msg)
263
+ sw_type = params['shrink_wrap_type'][index]
264
+ if sw_type == 'GAUSS':
265
+ check_Gauss_type()
266
+ if len(params['shrink_wrap_gauss_sigma']) - 1 < index:
267
+ msg = f'shrink_wrap_gauss_sigma not defined for sub-trigger {index}'
268
+ raise ValueError(msg)
269
+ sigma = params['shrink_wrap_gauss_sigma'][index]
270
+ if len(params['shrink_wrap_threshold']) - 1 < index:
271
+ msg = f'shrink_wrap_threshold not defined for sub-trigger {index}'
272
+ raise ValueError(msg)
273
+ threshold = params['shrink_wrap_threshold'][index]
274
+ return self.GaussSW(sigma, threshold)
275
+ elif sw_type == 'GAUSS1':
276
+ check_Gauss1_type()
277
+ if len(params['shrink_wrap_gauss_sigma']) - 1 < index:
278
+ msg = f'shrink_wrap_gauss_sigma not defined for sub-trigger {index}'
279
+ raise ValueError(msg)
280
+ sigma = params['shrink_wrap_gauss_sigma'][index]
281
+ if len(params['shrink_wrap_threshold']) - 1 < index:
282
+ msg = f'shrink_wrap_threshold not defined for sub-trigger {index}'
283
+ raise ValueError(msg)
284
+ threshold = params['shrink_wrap_threshold'][index]
285
+ return self.Gauss1SW(sigma, threshold)
286
+ else:
287
+ msg = f'{sw_type} shrink wrap type is not supported'
288
+ raise ValueError(msg)
289
+
290
+
291
+ class PhaseConstrain(TriggeredOp):
292
+ def __init__(self, trig_op):
293
+ super().__init__(trig_op)
294
+
295
+ class PhasePHC:
296
+ def __init__(self, phc_phase_min, phc_phase_max):
297
+ self.phc_phase_min = phc_phase_min
298
+ self.phc_phase_max = phc_phase_max
299
+
300
+ def apply_trigger(self, *args):
301
+ ds_image = args[0]
302
+ phase = devlib.angle(ds_image)
303
+ return (phase > self.phc_phase_min) & (phase < self.phc_phase_max)
304
+
305
+
306
+ def create_obj(self, params, index=None, beg=None, end=None):
307
+ if 'phc_phase_min' not in params:
308
+ msg = 'phc_phase_min parameter not defined'
309
+ raise ValueError(msg)
310
+ if 'phc_phase_max' not in params:
311
+ msg = 'phc_phase_max parameter not defined'
312
+ raise ValueError(msg)
313
+ if index is None:
314
+ phase_min = params['phc_phase_min']
315
+ phase_max = params['phc_phase_max']
316
+ else:
317
+ if len(params['phc_phase_min']) - 1 < index:
318
+ msg = f'phc_phase_min not defined for sub-trigger {index}'
319
+ raise ValueError(msg)
320
+ phase_min = params['phc_phase_min'][index]
321
+ if len(params['phc_phase_max']) - 1 < index:
322
+ msg = f'phc_phase_max not defined for sub-trigger {index}'
323
+ raise ValueError(msg)
324
+ phase_max = params['phc_phase_max'][index]
325
+ return self.PhasePHC(phase_min, phase_max)
326
+
327
+
328
+ def create(trig_op, params, trig_op_info):
329
+ if trig_op == 'shrink_wrap':
330
+ to = ShrinkWrap(trig_op)
331
+ if trig_op == 'phc':
332
+ to = PhaseConstrain(trig_op)
333
+
334
+ # this function sets self.objs and self.f and creates all objects
335
+ # It may throw exception
336
+ to.create_objs(params, trig_op_info)
337
+ return to
338
+
339
+
340
+
341
+