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.
- cohere_core/controller/AI_guess.py +303 -0
- cohere_core/controller/__init__.py +1 -0
- cohere_core/controller/features.py +372 -0
- cohere_core/controller/op_flow.py +318 -0
- cohere_core/controller/phasing.py +1290 -0
- cohere_core/data/__init__.py +1 -0
- cohere_core/data/alien_tools.py +417 -0
- cohere_core/data/standard_preprocess.py +187 -0
- cohere_core/lib/__init__.py +0 -0
- cohere_core/lib/aflib.py +393 -0
- cohere_core/lib/check_libs.py +50 -0
- cohere_core/lib/cohlib.py +594 -0
- cohere_core/lib/cplib.py +388 -0
- cohere_core/lib/nplib.py +361 -0
- cohere_core/lib/torchlib.py +478 -0
- cohere_core/utilities/__init__.py +4 -0
- cohere_core/utilities/config_errors_dict.py +155 -0
- cohere_core/utilities/config_verifier.py +1088 -0
- cohere_core/utilities/dvc_utils.py +780 -0
- cohere_core/utilities/ga_utils.py +217 -0
- cohere_core/utilities/utils.py +502 -0
- cohere_core-4.3.dist-info/METADATA +68 -0
- cohere_core-4.3.dist-info/RECORD +26 -0
- cohere_core-4.3.dist-info/WHEEL +5 -0
- cohere_core-4.3.dist-info/licenses/LICENSE +18 -0
- cohere_core-4.3.dist-info/top_level.txt +1 -0
|
@@ -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,372 @@
|
|
|
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 TriggeredOp(ABC):
|
|
81
|
+
"""
|
|
82
|
+
Base class for Triggered operation. This class creates feature objects and manages the trigger or subtrigger depending on
|
|
83
|
+
configuration.
|
|
84
|
+
"""
|
|
85
|
+
def __init__(self, trig_op_name):
|
|
86
|
+
# the self.objs will hold either one concrete feature object if configuration is for general trigger,
|
|
87
|
+
# i.e. spanning across all iterations,
|
|
88
|
+
# or it will hold a list of objects, each being a concrete sub-feature, appearing in order that will be
|
|
89
|
+
# executed during each trigger
|
|
90
|
+
self.objs = None
|
|
91
|
+
|
|
92
|
+
# the self.f points to either self.apply_trigger_obj function if configuration is for general trigger,
|
|
93
|
+
# or to self.apply_trigger_seq if sub-triggers are configured
|
|
94
|
+
self.f = None
|
|
95
|
+
|
|
96
|
+
self.trig_op_name = trig_op_name # ex: 'shrink_wrap_trigger'
|
|
97
|
+
|
|
98
|
+
|
|
99
|
+
def apply_trigger_obj(self, *args):
|
|
100
|
+
"""
|
|
101
|
+
This function is called when general trigger is used. In this case there is only one instance of the concrete
|
|
102
|
+
feature. The trigger is then executed on this instance.
|
|
103
|
+
:param args: variable parameters depending on the concrete feature
|
|
104
|
+
:return: depends on the concrete feature
|
|
105
|
+
"""
|
|
106
|
+
return self.objs.apply_trigger(*args)
|
|
107
|
+
|
|
108
|
+
def apply_trigger_seq(self, *args):
|
|
109
|
+
"""
|
|
110
|
+
This function is called when sub-triggers are used. the self.objs is a list for this case. Every time a trigger
|
|
111
|
+
is applied the first object is removed from this list and the trigger is executed on this instance.
|
|
112
|
+
:param args: variable parameters depending on the concrete feature
|
|
113
|
+
:return: depends on the concrete feature
|
|
114
|
+
"""
|
|
115
|
+
sub_obj = self.objs.pop(0)
|
|
116
|
+
return sub_obj.apply_trigger(*args)
|
|
117
|
+
|
|
118
|
+
def apply_trigger(self, *args):
|
|
119
|
+
"""
|
|
120
|
+
Thhis function is called by a trigger. It then directs the trigger by calling the self.f function.
|
|
121
|
+
:param args: variable parameters depending on the concrete feature
|
|
122
|
+
:return: depends on the concrete feature
|
|
123
|
+
"""
|
|
124
|
+
# the f is either update_amp_seq function or update_amp_seq
|
|
125
|
+
# The f is set in constructor depending on whether the trigger
|
|
126
|
+
# was defined for the entire span of iterations or multiple
|
|
127
|
+
# subtriggers were defined in algorithm sequence
|
|
128
|
+
return self.f(*args)
|
|
129
|
+
|
|
130
|
+
@abstractmethod
|
|
131
|
+
def create_obj(self, *args):
|
|
132
|
+
"""
|
|
133
|
+
This class must be overriden by subclass. It creates a feature object.
|
|
134
|
+
:param args: variable parameters depending on the concrete feature
|
|
135
|
+
:return: an instance of the subclass
|
|
136
|
+
"""
|
|
137
|
+
pass
|
|
138
|
+
|
|
139
|
+
def create_objs(self, params, sub_rows_trigs):
|
|
140
|
+
"""
|
|
141
|
+
The params map contains value of the feature trigger. If the trigger is configured as a general one,
|
|
142
|
+
i.e. a single trigger, the self.objs is set to the created instance of the feature, and the self.f
|
|
143
|
+
pointer is set accordingly, i.e. to the self.apply_trigger_obj function.
|
|
144
|
+
If the trigger contains several sub-triggers, the sub_row_trigs contain info about the sequence the
|
|
145
|
+
subtrigger should be executed. Based on this info the unique instances are created and are added to the
|
|
146
|
+
in the order the triggers should be called. The self.f function is set to the self.apply_trigger_seq
|
|
147
|
+
function.
|
|
148
|
+
:param sub_rows_trigs: sub-triggers info if sub-triggers are configured
|
|
149
|
+
:param params: configuration parameters
|
|
150
|
+
:return:
|
|
151
|
+
"""
|
|
152
|
+
trigger_name = f'{self.trig_op_name}_trigger'
|
|
153
|
+
|
|
154
|
+
if trigger_name in sub_rows_trigs.keys():
|
|
155
|
+
row = sub_rows_trigs[trigger_name][0]
|
|
156
|
+
sub_trigs = sub_rows_trigs[trigger_name][1]
|
|
157
|
+
sub_objs = {}
|
|
158
|
+
for sub_t in sub_trigs:
|
|
159
|
+
(beg, end, idx) = sub_t
|
|
160
|
+
index = int(idx)
|
|
161
|
+
if index not in sub_objs.keys():
|
|
162
|
+
sub_objs[index] = self.create_obj(params, index=index, beg=beg, end=end)
|
|
163
|
+
trigs = [i-1 for i in row.tolist() if i != 0]
|
|
164
|
+
# the operation of creating object might fail
|
|
165
|
+
# if conditions are not met, ex: the sw_type is not supported
|
|
166
|
+
# This should be already verified by a verifier, so no checking here
|
|
167
|
+
self.objs = [sub_objs[idx] for idx in trigs]
|
|
168
|
+
self.f = self.apply_trigger_seq
|
|
169
|
+
else:
|
|
170
|
+
if trigger_name in params:
|
|
171
|
+
self.objs = self.create_obj(params)
|
|
172
|
+
self.f = self.apply_trigger_obj
|
|
173
|
+
|
|
174
|
+
|
|
175
|
+
class ShrinkWrap(TriggeredOp):
|
|
176
|
+
def __init__(self, trig_op):
|
|
177
|
+
super().__init__(trig_op)
|
|
178
|
+
|
|
179
|
+
class GaussSW:
|
|
180
|
+
def __init__(self, gauss_sigma, threshold):
|
|
181
|
+
self.gauss_sigma = gauss_sigma
|
|
182
|
+
self.threshold = threshold
|
|
183
|
+
|
|
184
|
+
def apply_trigger(self, *args):
|
|
185
|
+
ds_image = args[0]
|
|
186
|
+
return dvut.shrink_wrap(ds_image, self.threshold, self.gauss_sigma)
|
|
187
|
+
|
|
188
|
+
|
|
189
|
+
class Gauss1SW:
|
|
190
|
+
def __init__(self, gauss_sigma, threshold):
|
|
191
|
+
self.gauss_sigma = gauss_sigma
|
|
192
|
+
self.threshold = threshold
|
|
193
|
+
|
|
194
|
+
def apply_trigger(self, *args):
|
|
195
|
+
ds_image = args[0]
|
|
196
|
+
return dvut.shrink_wrap(ds_image, self.threshold + .01, self.gauss_sigma)
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def create_obj(self, params, index=None, beg=None, end=None):
|
|
200
|
+
def check_Gauss_type():
|
|
201
|
+
# for now cohere supports only Gauss type, so the following parameters are mandatory
|
|
202
|
+
if 'shrink_wrap_gauss_sigma' not in params:
|
|
203
|
+
msg = 'shrink_wrap_gauss_sigma parameter not defined'
|
|
204
|
+
raise ValueError(msg)
|
|
205
|
+
if 'shrink_wrap_threshold' not in params:
|
|
206
|
+
msg = 'shrink_wrap_threshold parameter not defined'
|
|
207
|
+
raise ValueError(msg)
|
|
208
|
+
|
|
209
|
+
def check_Gauss1_type():
|
|
210
|
+
# for now cohere supports only Gauss type, so the following parameters are mandatory
|
|
211
|
+
if 'shrink_wrap_gauss_sigma' not in params:
|
|
212
|
+
msg = 'shrink_wrap_gauss_sigma parameter not defined'
|
|
213
|
+
raise ValueError(msg)
|
|
214
|
+
if 'shrink_wrap_threshold' not in params:
|
|
215
|
+
msg = 'shrink_wrap_threshold parameter not defined'
|
|
216
|
+
raise ValueError(msg)
|
|
217
|
+
|
|
218
|
+
if 'shrink_wrap_type' not in params:
|
|
219
|
+
msg = 'shrink_wrap_type parameter not defined'
|
|
220
|
+
raise ValueError(msg)
|
|
221
|
+
|
|
222
|
+
if index is None:
|
|
223
|
+
sw_type = params['shrink_wrap_type']
|
|
224
|
+
if sw_type == 'GAUSS':
|
|
225
|
+
check_Gauss_type()
|
|
226
|
+
sigma = params['shrink_wrap_gauss_sigma']
|
|
227
|
+
threshold = params['shrink_wrap_threshold']
|
|
228
|
+
return self.GaussSW(sigma, threshold)
|
|
229
|
+
elif sw_type == 'GAUSS1':
|
|
230
|
+
check_Gauss1_type()
|
|
231
|
+
sigma = params['shrink_wrap_gauss_sigma']
|
|
232
|
+
threshold = params['shrink_wrap_threshold']
|
|
233
|
+
return self.Gauss1SW(sigma, threshold)
|
|
234
|
+
else:
|
|
235
|
+
msg = f'{sw_type} shrink wrap type is not supported'
|
|
236
|
+
raise ValueError(msg)
|
|
237
|
+
else:
|
|
238
|
+
if len(params['shrink_wrap_type']) - 1 < index:
|
|
239
|
+
msg = f'shrink_wrap_type not defined for sub-trigger {index}'
|
|
240
|
+
raise ValueError(msg)
|
|
241
|
+
sw_type = params['shrink_wrap_type'][index]
|
|
242
|
+
if sw_type == 'GAUSS':
|
|
243
|
+
check_Gauss_type()
|
|
244
|
+
if len(params['shrink_wrap_gauss_sigma']) - 1 < index:
|
|
245
|
+
msg = f'shrink_wrap_gauss_sigma not defined for sub-trigger {index}'
|
|
246
|
+
raise ValueError(msg)
|
|
247
|
+
sigma = params['shrink_wrap_gauss_sigma'][index]
|
|
248
|
+
if len(params['shrink_wrap_threshold']) - 1 < index:
|
|
249
|
+
msg = f'shrink_wrap_threshold not defined for sub-trigger {index}'
|
|
250
|
+
raise ValueError(msg)
|
|
251
|
+
threshold = params['shrink_wrap_threshold'][index]
|
|
252
|
+
return self.GaussSW(sigma, threshold)
|
|
253
|
+
elif sw_type == 'GAUSS1':
|
|
254
|
+
check_Gauss1_type()
|
|
255
|
+
if len(params['shrink_wrap_gauss_sigma']) - 1 < index:
|
|
256
|
+
msg = f'shrink_wrap_gauss_sigma not defined for sub-trigger {index}'
|
|
257
|
+
raise ValueError(msg)
|
|
258
|
+
sigma = params['shrink_wrap_gauss_sigma'][index]
|
|
259
|
+
if len(params['shrink_wrap_threshold']) - 1 < index:
|
|
260
|
+
msg = f'shrink_wrap_threshold not defined for sub-trigger {index}'
|
|
261
|
+
raise ValueError(msg)
|
|
262
|
+
threshold = params['shrink_wrap_threshold'][index]
|
|
263
|
+
return self.Gauss1SW(sigma, threshold)
|
|
264
|
+
else:
|
|
265
|
+
msg = f'{sw_type} shrink wrap type is not supported'
|
|
266
|
+
raise ValueError(msg)
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
class PhaseConstrain(TriggeredOp):
|
|
271
|
+
def __init__(self, trig_op):
|
|
272
|
+
super().__init__(trig_op)
|
|
273
|
+
|
|
274
|
+
class PhasePHC:
|
|
275
|
+
def __init__(self, phc_phase_min, phc_phase_max):
|
|
276
|
+
self.phc_phase_min = phc_phase_min
|
|
277
|
+
self.phc_phase_max = phc_phase_max
|
|
278
|
+
|
|
279
|
+
def apply_trigger(self, *args):
|
|
280
|
+
ds_image = args[0]
|
|
281
|
+
phase = devlib.angle(ds_image)
|
|
282
|
+
return (phase > self.phc_phase_min) & (phase < self.phc_phase_max)
|
|
283
|
+
|
|
284
|
+
|
|
285
|
+
def create_obj(self, params, index=None, beg=None, end=None):
|
|
286
|
+
if 'phc_phase_min' not in params:
|
|
287
|
+
msg = 'phc_phase_min parameter not defined'
|
|
288
|
+
raise ValueError(msg)
|
|
289
|
+
if 'phc_phase_max' not in params:
|
|
290
|
+
msg = 'phc_phase_max parameter not defined'
|
|
291
|
+
raise ValueError(msg)
|
|
292
|
+
if index is None:
|
|
293
|
+
phase_min = params['phc_phase_min']
|
|
294
|
+
phase_max = params['phc_phase_max']
|
|
295
|
+
else:
|
|
296
|
+
if len(params['phc_phase_min']) - 1 < index:
|
|
297
|
+
msg = f'phc_phase_min not defined for sub-trigger {index}'
|
|
298
|
+
raise ValueError(msg)
|
|
299
|
+
phase_min = params['phc_phase_min'][index]
|
|
300
|
+
if len(params['phc_phase_max']) - 1 < index:
|
|
301
|
+
msg = f'phc_phase_max not defined for sub-trigger {index}'
|
|
302
|
+
raise ValueError(msg)
|
|
303
|
+
phase_max = params['phc_phase_max'][index]
|
|
304
|
+
return self.PhasePHC(phase_min, phase_max)
|
|
305
|
+
|
|
306
|
+
|
|
307
|
+
class LowPassFilter(TriggeredOp):
|
|
308
|
+
def __init__(self, trig_op):
|
|
309
|
+
super().__init__(trig_op)
|
|
310
|
+
|
|
311
|
+
class Filter:
|
|
312
|
+
def __init__(self, filter_range, iter_range, threshold):
|
|
313
|
+
self.iter_offset = iter_range[0]
|
|
314
|
+
self.filter_sigmas = [(filter_range[1] - filter_range[0]) / (iter_range[1] - iter_range[0]) *
|
|
315
|
+
(iter - self.iter_offset) + filter_range[0]
|
|
316
|
+
for iter in range(iter_range[0], iter_range[1])]
|
|
317
|
+
self.threshold = threshold
|
|
318
|
+
|
|
319
|
+
def apply_trigger(self, *args):
|
|
320
|
+
# The filter is applied on data
|
|
321
|
+
# simultaneously the sigma used in shrink wrap is changing to be reverse of the filter_sigma
|
|
322
|
+
data = args[0]
|
|
323
|
+
iter = args[1]
|
|
324
|
+
ds_image = args[2]
|
|
325
|
+
filter_sigma = self.filter_sigmas[iter - self.iter_offset]
|
|
326
|
+
return (devlib.gaussian_filter(data, filter_sigma), dvut.shrink_wrap(ds_image, self.threshold, 1/filter_sigma))
|
|
327
|
+
|
|
328
|
+
|
|
329
|
+
def create_obj(self, params, index=None, beg=None, end=None):
|
|
330
|
+
if 'lowpass_filter_sw_threshold' not in params:
|
|
331
|
+
msg = 'lowpass_filter_sw_threshold parameter not defined'
|
|
332
|
+
raise ValueError(msg)
|
|
333
|
+
if 'lowpass_filter_range' not in params:
|
|
334
|
+
msg = 'lowpass_filter_range parameter not defined'
|
|
335
|
+
raise ValueError(msg)
|
|
336
|
+
# in case of a all_iteration configuration the lowpass filter
|
|
337
|
+
# iteration can be read from lowpass_filter_trigger
|
|
338
|
+
if index is None:
|
|
339
|
+
iter_range = (params['lowpass_filter_trigger'][0], params['lowpass_filter_trigger'][2])
|
|
340
|
+
filter_range = params['lowpass_filter_range']
|
|
341
|
+
threshold = params['lowpass_filter_sw_threshold']
|
|
342
|
+
# otherwise the iterations to apply this instance are given as arguments
|
|
343
|
+
else:
|
|
344
|
+
iter_range = (beg, end)
|
|
345
|
+
if len(params['lowpass_filter_range']) - 1 < index:
|
|
346
|
+
msg = f'lowpass_filter_range not defined for sub-trigger {index}'
|
|
347
|
+
raise ValueError(msg)
|
|
348
|
+
filter_range = params['lowpass_filter_range'][index]
|
|
349
|
+
if len(params['lowpass_filter_sw_threshold']) - 1 < index:
|
|
350
|
+
msg = f'lowpass_filter_sw_threshold not defined for sub-trigger {index}'
|
|
351
|
+
raise ValueError(msg)
|
|
352
|
+
threshold = params['lowpass_filter_sw_threshold'][index]
|
|
353
|
+
if len(filter_range) == 1:
|
|
354
|
+
filter_range.append(1.0)
|
|
355
|
+
return self.Filter(filter_range, iter_range, threshold)
|
|
356
|
+
|
|
357
|
+
def create(trig_op, params, trig_op_info):
|
|
358
|
+
if trig_op == 'shrink_wrap':
|
|
359
|
+
to = ShrinkWrap(trig_op)
|
|
360
|
+
if trig_op == 'phc':
|
|
361
|
+
to = PhaseConstrain(trig_op)
|
|
362
|
+
if trig_op == 'lowpass_filter':
|
|
363
|
+
to = LowPassFilter(trig_op)
|
|
364
|
+
|
|
365
|
+
# this function sets self.objs and self.f and creates all objects
|
|
366
|
+
# It may throw exception
|
|
367
|
+
to.create_objs(params, trig_op_info)
|
|
368
|
+
return to
|
|
369
|
+
|
|
370
|
+
|
|
371
|
+
|
|
372
|
+
|