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 @@
|
|
|
1
|
+
from .standard_preprocess import *
|
|
@@ -0,0 +1,417 @@
|
|
|
1
|
+
# #########################################################################
|
|
2
|
+
# Copyright (c) , UChicago Argonne, LLC. All rights reserved. #
|
|
3
|
+
# #
|
|
4
|
+
# See LICENSE file. #
|
|
5
|
+
# #########################################################################
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
"""
|
|
9
|
+
This tools auto eliminate aliens from CDI experiment data. It is configuration driven.
|
|
10
|
+
|
|
11
|
+
"""
|
|
12
|
+
|
|
13
|
+
import numpy as np
|
|
14
|
+
import os
|
|
15
|
+
import tifffile as tif
|
|
16
|
+
from scipy.ndimage import gaussian_filter
|
|
17
|
+
import cohere_core.utilities.utils as ut
|
|
18
|
+
|
|
19
|
+
__author__ = "Kenly Pelzer, Ross Harder"
|
|
20
|
+
__copyright__ = "Copyright (c) 2021, UChicago Argonne, LLC."
|
|
21
|
+
__docformat__ = 'restructuredtext en'
|
|
22
|
+
__all__ = ['get_asymmetry',
|
|
23
|
+
'analyze_clusters',
|
|
24
|
+
'crop_center',
|
|
25
|
+
'save_arr',
|
|
26
|
+
'save_arrays',
|
|
27
|
+
'auto_alien1',
|
|
28
|
+
'filter_aliens',
|
|
29
|
+
'remove_blocks',
|
|
30
|
+
'remove_aliens']
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def get_asymmetry(arr):
|
|
34
|
+
"""
|
|
35
|
+
Returns asymmetry of an array.
|
|
36
|
+
|
|
37
|
+
Parameters
|
|
38
|
+
----------
|
|
39
|
+
arr : ndarray
|
|
40
|
+
an array to find asymmetry
|
|
41
|
+
|
|
42
|
+
Returns
|
|
43
|
+
-------
|
|
44
|
+
ndarray
|
|
45
|
+
an array capturing asymmetry of original array
|
|
46
|
+
"""
|
|
47
|
+
|
|
48
|
+
arr_rev = arr[::-1, ::-1, ::-1]
|
|
49
|
+
denom = (arr + arr_rev) / 2.0
|
|
50
|
+
denom_nz = np.where(denom == 0, 1.0, denom)
|
|
51
|
+
asym = np.where(denom > 0.0, abs(arr - arr_rev) / denom_nz, 0.0)
|
|
52
|
+
# asym only assigned to non-zero intensity points in the passed array
|
|
53
|
+
return np.where(arr > 0, asym, 0)
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
# add output of absolute cluster size.
|
|
57
|
+
def analyze_clusters(arr, labels, nz):
|
|
58
|
+
"""
|
|
59
|
+
Analyzes clusters and returns characteristics in arrays.
|
|
60
|
+
|
|
61
|
+
Parameters
|
|
62
|
+
----------
|
|
63
|
+
arr : ndarray
|
|
64
|
+
the analyzed array
|
|
65
|
+
labels: arr
|
|
66
|
+
cluster labels for each point in the dataset given to fit(). Noisy samples are given the label -1.
|
|
67
|
+
nz : tuple
|
|
68
|
+
tuple of arrays, each array containing indices of elements in arr that are non-zero along one axis.
|
|
69
|
+
|
|
70
|
+
Returns
|
|
71
|
+
-------
|
|
72
|
+
tuple
|
|
73
|
+
tuple containing the following arrays:
|
|
74
|
+
nlabels # number of labels, i.e clusters
|
|
75
|
+
labels_arr # array with label for each non zero point
|
|
76
|
+
rel_cluster_size # array with cluster size divided by max cluster size for each
|
|
77
|
+
# non zero point
|
|
78
|
+
cluster_avg # array with cluster average for each non zero point
|
|
79
|
+
noise_arr # array with points that are non zero but not in cluster
|
|
80
|
+
no_noise # array with noise poits set to 0
|
|
81
|
+
label_counts # tuple of two arrays: First is label number, second is number of
|
|
82
|
+
# occurances of that label (size of cluster)
|
|
83
|
+
cluster_avg_asym # array with average asymmetry of a points in cluster
|
|
84
|
+
asymmetry # array of asymmetry with regard to entire array
|
|
85
|
+
cluster_size # array with cluster size for each non zero point
|
|
86
|
+
"""
|
|
87
|
+
|
|
88
|
+
labels_arr = np.zeros_like(arr)
|
|
89
|
+
noise_arr = np.zeros_like(arr)
|
|
90
|
+
cluster_size = np.zeros_like(arr)
|
|
91
|
+
cluster_avg = np.zeros_like(arr).astype(np.float32)
|
|
92
|
+
cluster_avg_asym = np.zeros_like(arr).astype(np.float32)
|
|
93
|
+
asymmetry = get_asymmetry(arr)
|
|
94
|
+
|
|
95
|
+
# label_counts is tuple of two arrays. First is label number, second is number of occurances of that label (size of cluster).
|
|
96
|
+
label_counts = np.unique(labels, return_counts=True)
|
|
97
|
+
|
|
98
|
+
# nz and labels are the same length. so the indicies given by nz will be set
|
|
99
|
+
# to their corresponding cluster number (includes noise pts).
|
|
100
|
+
labels_arr[nz] = labels
|
|
101
|
+
|
|
102
|
+
# this selects the nz indicies where labels=-1 (noise)
|
|
103
|
+
noise_pts = tuple([nz[n][labels == -1] for n in range(3)])
|
|
104
|
+
no_noise = arr
|
|
105
|
+
|
|
106
|
+
# move the points labeled noise into their own array
|
|
107
|
+
# remove the noise out of arr (no_noise is copy of arr)
|
|
108
|
+
noise_arr[noise_pts] = arr[noise_pts]
|
|
109
|
+
no_noise[noise_pts] = 0
|
|
110
|
+
nlabels = len(label_counts[0])
|
|
111
|
+
# print("processing labels")
|
|
112
|
+
# loop over the labels (clusters). label_counts[0] is the unique labels
|
|
113
|
+
for n in range(1, nlabels):
|
|
114
|
+
# the nth label from the first array of the label_counts tuple
|
|
115
|
+
n_lab = label_counts[0][n]
|
|
116
|
+
# the indicies of the points belonging to label n
|
|
117
|
+
cluspts = tuple([nz[d][labels == n_lab] for d in range(3)])
|
|
118
|
+
# the second array of the label_counts tuple is the number of points
|
|
119
|
+
# with that label. So put those into an array.
|
|
120
|
+
cluster_size[cluspts] = label_counts[1][n]
|
|
121
|
+
# compute the average intensity of each cluster and write into an array.
|
|
122
|
+
cluster_avg[cluspts] = np.sum(arr[cluspts]) / cluspts[0].size
|
|
123
|
+
# compute average asym of each cluster and store in array.
|
|
124
|
+
cluster_avg_asym[cluspts] = np.sum(asymmetry[cluspts]) / cluspts[0].size
|
|
125
|
+
# compute relative cluster sizes to largest (main) cluster.
|
|
126
|
+
rel_cluster_size = cluster_size / cluster_size.max()
|
|
127
|
+
|
|
128
|
+
# return all of these arrays
|
|
129
|
+
return (
|
|
130
|
+
nlabels, labels_arr, rel_cluster_size, cluster_avg, noise_arr, no_noise, label_counts, cluster_avg_asym,
|
|
131
|
+
asymmetry,
|
|
132
|
+
cluster_size)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
def crop_center(arr):
|
|
136
|
+
"""
|
|
137
|
+
Finds max element in array and crops the array to be symetrical with regard to this point in each direction.
|
|
138
|
+
|
|
139
|
+
Parameters
|
|
140
|
+
----------
|
|
141
|
+
arr : ndarray
|
|
142
|
+
an array
|
|
143
|
+
|
|
144
|
+
Returns
|
|
145
|
+
-------
|
|
146
|
+
centered : ndarray
|
|
147
|
+
an array symetrical in all dimensions around the max element of input array
|
|
148
|
+
"""
|
|
149
|
+
|
|
150
|
+
shape = arr.shape
|
|
151
|
+
# This tells us the point of highest intensity, which we will use as the center for inversion operations
|
|
152
|
+
center = np.unravel_index(np.argmax(arr, axis=None), shape)
|
|
153
|
+
|
|
154
|
+
# clip the largest possible cuboid putting the point of highest intensity at the center
|
|
155
|
+
principium = []
|
|
156
|
+
finis = []
|
|
157
|
+
for i in range(len(shape)):
|
|
158
|
+
half_shape = min(center[i], shape[i] - center[i] - 1)
|
|
159
|
+
principium.append(center[i] - half_shape)
|
|
160
|
+
finis.append(center[i] + half_shape + 1)
|
|
161
|
+
centered = arr[principium[0]:finis[0], principium[1]:finis[1], principium[2]:finis[2]]
|
|
162
|
+
|
|
163
|
+
return centered
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def save_arr(arr, dir, fname):
|
|
167
|
+
"""
|
|
168
|
+
Saves an array in 'tif' format file.
|
|
169
|
+
|
|
170
|
+
Parameters
|
|
171
|
+
----------
|
|
172
|
+
arr : ndarray
|
|
173
|
+
an array to save
|
|
174
|
+
dir : str
|
|
175
|
+
directory to save the file to
|
|
176
|
+
fname : str
|
|
177
|
+
file name
|
|
178
|
+
|
|
179
|
+
Returns
|
|
180
|
+
-------
|
|
181
|
+
nothing
|
|
182
|
+
"""
|
|
183
|
+
|
|
184
|
+
if dir is not None:
|
|
185
|
+
full_name = ut.join(dir, fname)
|
|
186
|
+
else:
|
|
187
|
+
full_name = fname # save in the current dir
|
|
188
|
+
tif.imwrite(full_name, arr.transpose().astype(np.float32))
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def save_arrays(arrs, iter, thresh, eps, dir):
|
|
192
|
+
"""
|
|
193
|
+
Saves multiple arrays in 'tif' format files. Determines file name from given parameters: iteration, threshold, and eps.
|
|
194
|
+
|
|
195
|
+
Parameters
|
|
196
|
+
----------
|
|
197
|
+
arr : tuple
|
|
198
|
+
a tuple of arrays to save
|
|
199
|
+
iter, thresh, eps : str, str, str
|
|
200
|
+
parameters: iteration, threshold, and eps, to deliver file name from
|
|
201
|
+
dir : str
|
|
202
|
+
directory to save the file to
|
|
203
|
+
|
|
204
|
+
Returns
|
|
205
|
+
-------
|
|
206
|
+
nothing
|
|
207
|
+
"""
|
|
208
|
+
|
|
209
|
+
save_arr(arrs[1], dir, "db%d_%3.2f_labels_arr%3.2f.tif" % (iter, thresh, eps))
|
|
210
|
+
save_arr(arrs[2], dir, "db%d_%3.2f_rel_clustersizes%3.2f.tif" % (iter, thresh, eps))
|
|
211
|
+
save_arr(arrs[3], dir, "db%d_%3.2f_clusteravg%3.2f.tif" % (iter, thresh, eps))
|
|
212
|
+
save_arr(arrs[4], dir, "db%d_%3.2f_noise%3.2f.tif" % (iter, thresh, eps))
|
|
213
|
+
save_arr(arrs[5], dir, "db%d_%3.2f_no_noise%3.2f.tif" % (iter, thresh, eps))
|
|
214
|
+
save_arr(arrs[7], dir, "db%d_%3.2f_clusteravgasym%3.2f.tif" % (iter, thresh, eps))
|
|
215
|
+
save_arr(arrs[8], dir, "db%d_%3.2f_asym%3.2f.tif" % (iter, thresh, eps))
|
|
216
|
+
save_arr(arrs[9], dir, "db%d_%3.2f_abs_clustersizes%3.2f.tif" % (iter, thresh, eps))
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
def auto_alien1(data, config, data_dir=None):
|
|
220
|
+
from sklearn.cluster import DBSCAN
|
|
221
|
+
"""
|
|
222
|
+
Removes aliens from experimental CDI data using iterative algorithm and returns the result.
|
|
223
|
+
|
|
224
|
+
The algorithm follows the steps:
|
|
225
|
+
1. Initialization:
|
|
226
|
+
- initialize variables with the configuration parameters
|
|
227
|
+
- crop the data array around maximum element to it's biggest size
|
|
228
|
+
- sets points below threshold value to 0
|
|
229
|
+
- finds non-zero elements of the data array and keeps them as tuples of indices
|
|
230
|
+
2. Iteration loop, runs until number of clasters remains unchanged
|
|
231
|
+
- runs DBSCAN algorithm on the non-zero and returns clasters labels
|
|
232
|
+
- analyzes the results to find relative clusters sizes, and clusters average asymmetry, and other characteristics
|
|
233
|
+
- removes alien clusters, i.e. the ones with relative cluster size below configured size threshold and with average asymmetry over configured asymmetry threshold
|
|
234
|
+
- go back to the loop using the non-zero elements of alien removed array to the DBSCAN
|
|
235
|
+
3. If configured, add final step to apply gaussian convolusion to the result and use it as a filter with configured sigma as threshold
|
|
236
|
+
|
|
237
|
+
Parameters
|
|
238
|
+
----------
|
|
239
|
+
data : ndarray
|
|
240
|
+
an array with experiment data
|
|
241
|
+
config : Object
|
|
242
|
+
configuration object providing access to configuration parameters
|
|
243
|
+
data_dir : str
|
|
244
|
+
a directory where 'alien_analysis' subdirectory will be created to save results of analysis if configured
|
|
245
|
+
|
|
246
|
+
Returns
|
|
247
|
+
-------
|
|
248
|
+
cuboid : ndarray
|
|
249
|
+
data array with removed aliens
|
|
250
|
+
"""
|
|
251
|
+
data_dir = data_dir.replace(os.sep, '/')
|
|
252
|
+
size_threshold = config.get('AA1_size_threshold', 0.01)
|
|
253
|
+
asym_threshold = config.get('AA1_asym_threshold', 1.75)
|
|
254
|
+
min_pts = config.get('AA1_min_pts', 5)
|
|
255
|
+
eps = config.get('AA1_eps', 1.1)
|
|
256
|
+
threshold = config.get('AA1_amp_threshold', 6)
|
|
257
|
+
if 'AA1_save_arrs' in config:
|
|
258
|
+
save_arrs = config['AA1_save_arrs']
|
|
259
|
+
if save_arrs:
|
|
260
|
+
save_dir = ut.join(data_dir, 'alien_analysis')
|
|
261
|
+
if not os.path.exists(save_dir):
|
|
262
|
+
os.makedirs(save_dir)
|
|
263
|
+
else:
|
|
264
|
+
save_arrs = False
|
|
265
|
+
|
|
266
|
+
expandcleanedsig = config.get('AA1_expandcleanedsigma', 0.0)
|
|
267
|
+
|
|
268
|
+
cuboid = crop_center(data)
|
|
269
|
+
cuboid = np.where(cuboid >= threshold, cuboid, 0)
|
|
270
|
+
if (save_arrs):
|
|
271
|
+
save_arr(cuboid, save_dir, "db%3.2f_cuboid%3.2f.tif" % (threshold, eps))
|
|
272
|
+
save_arr(cuboid[::-1, ::-1, ::-1], save_dir, "db%3.2f_cuboidrev%3.2f.tif" % (threshold, eps))
|
|
273
|
+
|
|
274
|
+
# the non_zero is a tuple of arrays, each array containing indices of elements that are non-zero along one axis.
|
|
275
|
+
non_zero = cuboid.nonzero()
|
|
276
|
+
|
|
277
|
+
# https://scikit-learn.org/stable/modules/clustering.html#dbscan
|
|
278
|
+
# labels is same size as input arr with a cluster label per point
|
|
279
|
+
iter = 0
|
|
280
|
+
nclusters = 0
|
|
281
|
+
while (True):
|
|
282
|
+
non_zero = cuboid.nonzero()
|
|
283
|
+
# print("running db", iter)
|
|
284
|
+
labels = DBSCAN(eps=eps, metric='euclidean', min_samples=min_pts, n_jobs=-1).fit_predict(
|
|
285
|
+
np.array(non_zero).transpose().astype(np.float32))
|
|
286
|
+
# print("running analyze_clusters", iter)
|
|
287
|
+
arrs = analyze_clusters(cuboid, labels, non_zero)
|
|
288
|
+
if (save_arrs):
|
|
289
|
+
save_arrays(arrs, iter, threshold, eps, save_dir)
|
|
290
|
+
if nclusters == arrs[0]:
|
|
291
|
+
break
|
|
292
|
+
nclusters = arrs[0]
|
|
293
|
+
if iter == 0: # keep values for all iterations
|
|
294
|
+
rel_cluster_size = arrs[2]
|
|
295
|
+
cluster_avg_asym = arrs[7]
|
|
296
|
+
# print("cleaning cuboid", iter)
|
|
297
|
+
cuboid = np.where(np.logical_and(rel_cluster_size < size_threshold, cluster_avg_asym > asym_threshold), 0.0,
|
|
298
|
+
cuboid)
|
|
299
|
+
# print("iter", iter, nclusters)
|
|
300
|
+
iter += 1
|
|
301
|
+
|
|
302
|
+
if (expandcleanedsig > 0):
|
|
303
|
+
cuboid = np.where(cuboid > 0, 1.0, 0.0)
|
|
304
|
+
sig = [expandcleanedsig, expandcleanedsig, 1.0]
|
|
305
|
+
cuboid = gaussian_filter(cuboid, sig)
|
|
306
|
+
no_thresh_cuboid = crop_center(data)
|
|
307
|
+
cuboid = np.where(cuboid > 0.1, no_thresh_cuboid, 0.0)
|
|
308
|
+
return cuboid
|
|
309
|
+
|
|
310
|
+
|
|
311
|
+
def remove_blocks(data, config_map):
|
|
312
|
+
"""
|
|
313
|
+
Sets to zero given alien blocks in the data array.
|
|
314
|
+
|
|
315
|
+
Parameters
|
|
316
|
+
----------
|
|
317
|
+
data : ndarray
|
|
318
|
+
an array with experiment data
|
|
319
|
+
config : Object
|
|
320
|
+
configuration object providing access to configuration parameters
|
|
321
|
+
|
|
322
|
+
Returns
|
|
323
|
+
-------
|
|
324
|
+
data : ndarray
|
|
325
|
+
data array with zeroed out aliens
|
|
326
|
+
"""
|
|
327
|
+
import ast
|
|
328
|
+
|
|
329
|
+
if 'aliens' in config_map:
|
|
330
|
+
aliens = ast.literal_eval(config_map['aliens'])
|
|
331
|
+
for alien in aliens:
|
|
332
|
+
# The ImageJ swaps the x and y axis, so the aliens coordinates needs to be swapped, since ImageJ is used
|
|
333
|
+
# to find aliens
|
|
334
|
+
data[alien[0]:alien[3], alien[1]:alien[4], alien[2]:alien[5]] = 0
|
|
335
|
+
return data
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
def filter_aliens(data, config_map):
|
|
339
|
+
"""
|
|
340
|
+
Sets to zero points in the data array defined by a file.
|
|
341
|
+
|
|
342
|
+
Parameters
|
|
343
|
+
----------
|
|
344
|
+
data : ndarray
|
|
345
|
+
an array with experiment data
|
|
346
|
+
config : Object
|
|
347
|
+
configuration object providing access to configuration parameters
|
|
348
|
+
|
|
349
|
+
Returns
|
|
350
|
+
-------
|
|
351
|
+
data : ndarray
|
|
352
|
+
data array with zeroed out aliens
|
|
353
|
+
"""
|
|
354
|
+
if 'alien_file' in config_map:
|
|
355
|
+
alien_file = config_map['alien_file']
|
|
356
|
+
if os.path.isfile(alien_file):
|
|
357
|
+
mask = np.load(alien_file)
|
|
358
|
+
for i in range(len(mask.shape)):
|
|
359
|
+
if mask.shape[i] != data.shape[i]:
|
|
360
|
+
print('exiting, mask must be of the same shape as data:', data.shape)
|
|
361
|
+
return
|
|
362
|
+
data = np.where((mask == 1), data, 0.0)
|
|
363
|
+
else:
|
|
364
|
+
print(f'alien file does not exist {alien_file}')
|
|
365
|
+
else:
|
|
366
|
+
print('alien_file parameter not configured')
|
|
367
|
+
return data
|
|
368
|
+
|
|
369
|
+
|
|
370
|
+
def remove_aliens(data, config_map, data_dir=None):
|
|
371
|
+
"""
|
|
372
|
+
Finds which algorithm is cofigured to remove the aliens and applies it to clean the data.
|
|
373
|
+
|
|
374
|
+
Parameters
|
|
375
|
+
----------
|
|
376
|
+
data : ndarray
|
|
377
|
+
an array with experiment data
|
|
378
|
+
config : Object
|
|
379
|
+
configuration object providing access to configuration parameters
|
|
380
|
+
data_dir : str
|
|
381
|
+
a directory where 'alien_analysis' subdirectory will be created to save results of analysis if configured
|
|
382
|
+
Returns
|
|
383
|
+
-------
|
|
384
|
+
data : ndarray
|
|
385
|
+
data array without aliens
|
|
386
|
+
"""
|
|
387
|
+
|
|
388
|
+
if 'alien_alg' in config_map:
|
|
389
|
+
algorithm = config_map['alien_alg']
|
|
390
|
+
if algorithm == 'block_aliens':
|
|
391
|
+
data = remove_blocks(data, config_map)
|
|
392
|
+
elif algorithm == 'alien_file':
|
|
393
|
+
data = filter_aliens(data, config_map)
|
|
394
|
+
elif algorithm == 'AutoAlien1':
|
|
395
|
+
data = auto_alien1(data, config_map, data_dir)
|
|
396
|
+
elif algorithm != 'none':
|
|
397
|
+
print('not supported alien removal algorithm', algorithm)
|
|
398
|
+
else:
|
|
399
|
+
print('alien_alg not configured')
|
|
400
|
+
|
|
401
|
+
return data
|
|
402
|
+
|
|
403
|
+
## https://stackoverflow.com/questions/51503672/decorator-for-timeit-timeit-method/51503837#51503837
|
|
404
|
+
# from functools import wraps
|
|
405
|
+
# from time import time
|
|
406
|
+
#
|
|
407
|
+
# def measure(func):
|
|
408
|
+
# @wraps(func)
|
|
409
|
+
# def _time_it(*args, **kwargs):
|
|
410
|
+
# start = int(round(time() * 1000))
|
|
411
|
+
# try:
|
|
412
|
+
# return func(*args, **kwargs)
|
|
413
|
+
# finally:
|
|
414
|
+
# end_ = int(round(time() * 1000)) - start
|
|
415
|
+
# print(f"Total execution time: {end_ if end_ > 0 else 0} ms")
|
|
416
|
+
#
|
|
417
|
+
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
# #########################################################################
|
|
2
|
+
# Copyright (c) , UChicago Argonne, LLC. All rights reserved. #
|
|
3
|
+
# #
|
|
4
|
+
# See LICENSE file. #
|
|
5
|
+
# #########################################################################
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
"""
|
|
9
|
+
Formats data for reconstruction according to configuration.
|
|
10
|
+
"""
|
|
11
|
+
|
|
12
|
+
import os
|
|
13
|
+
import numpy as np
|
|
14
|
+
import cohere_core.data.alien_tools as at
|
|
15
|
+
import cohere_core.utilities.utils as ut
|
|
16
|
+
import cohere_core.utilities.config_verifier as ver
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
__author__ = "Barbara Frosik"
|
|
20
|
+
__copyright__ = "Copyright (c) 2016, UChicago Argonne, LLC."
|
|
21
|
+
__docformat__ = 'restructuredtext en'
|
|
22
|
+
__all__ = ['prep',
|
|
23
|
+
]
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def prep(beamline_full_datafile_name, **kwargs):
|
|
27
|
+
"""
|
|
28
|
+
This function formats data for reconstruction and saves it in data.tif file. The preparation consists of the following steps:
|
|
29
|
+
- removing the aliens which is effect of interference. The removal can be done by setting regions or mask file that requires manual inspection of the data file. The removal can be automatic with the AutoAlien1 algorithm.
|
|
30
|
+
- clearing the noise, where values below an amplitude threshold are set to zero. The threshold can be set as a parameter or auto determined.
|
|
31
|
+
- amplitudes are set to sqrt
|
|
32
|
+
- cropping and padding. If the crop-pad is negative in any dimension, the array is cropped in this dimension. The cropping is followed by padding in the dimensions with positive values. After adjusting, the dimensions are adjusted further to find the smallest dimension that is supported by opencl library (multiplier of 2, 3, and 5).
|
|
33
|
+
- centering - finding the greatest amplitude and locating it at a center of array. If shift center is defined, the center will be shifted accordingly.
|
|
34
|
+
- binning - adding amplitudes of several consecutive points. Binning can be done in any dimension.
|
|
35
|
+
|
|
36
|
+
:param beamline_full_datafile_name: full path of tif file containing beamline preprocessed data
|
|
37
|
+
:param kwargs:
|
|
38
|
+
data_dir : str
|
|
39
|
+
directory where prepared data will be saved, default <experiment_dir>/phasing_data
|
|
40
|
+
alien_alg : str
|
|
41
|
+
Acronym of method used to remove aliens. Possible options are: ‘block_aliens’, ‘alien_file’, and ‘AutoAlien1’. The ‘block_aliens’ algorithm will zero out defined blocks, ‘alien_file’ method will use given file as a mask, and ‘AutoAlien1’ will use auto mechanism to remove aliens. Each of these algorithms require different parameters
|
|
42
|
+
aliens : list
|
|
43
|
+
Needed when the ‘block_aliens’ method is configured. Used when the data contains regions with intensity produced by interference. The regions needs to be zeroed out. The aliens can be defined as regions each defined by coordinates of starting point, and ending point (i.e. [[xb0,yb0,zb0,xe0,ye0,ze0],[xb1,yb1,zb1,xe1,ye1,ze1],…[xbn,ybn,zbn,xen,yen,zen]] ).
|
|
44
|
+
alien_file : str
|
|
45
|
+
Needed when the ‘alien_file’ method is configured. User can produce a file in npy format that contains table of zeros and ones, where zero means to set the pixel to zero, and one to leave it.
|
|
46
|
+
AA1_size_threshold : float
|
|
47
|
+
Used in the ‘AutoAliens1’ method. If not given it will default to 0.01. The AutoAlien1 algorithm will calculate relative sizes of all clusters with respect to the biggest cluster. The clusters with relative size smaller than the given threshold will be possibly deemed aliens. It also depends on asymmetry.
|
|
48
|
+
AA1_asym_threshold : float
|
|
49
|
+
Used in the ‘AutoAliens1’ method. If not given it will default to 1.75. The AutoAlien1 algorithm will calculate average asymmetry of all clusters. The clusters with average asymmetry greater than the given threshold will be possibly deemed aliens. It also depends on relative size.
|
|
50
|
+
AA1_min_pts : int
|
|
51
|
+
Used in the ‘AutoAliens1’ method. If not given it will default to 5. Defines minimum non zero points in neighborhood to count the area of data as cluster.
|
|
52
|
+
AA1_eps : float
|
|
53
|
+
Used in the ‘AutoAliens1’ method. If not given it will default to 1.1. Used in the clustering algorithm.
|
|
54
|
+
AA1_amp_threshold : float
|
|
55
|
+
Mandatory in the ‘AutoAliens1’ method. Used to zero data points below that threshold.
|
|
56
|
+
AA1_save_arrs : boolean
|
|
57
|
+
Used in the ‘AutoAliens1’ method, optional. If given and set to True multiple results of alien analysis will be saved in files.
|
|
58
|
+
AA1_expandcleanedsigma : float
|
|
59
|
+
Used in the ‘AutoAliens1’ method, optional. If given the algorithm will apply last step of cleaning the data using the configured sigma.
|
|
60
|
+
intensity_threshold : float
|
|
61
|
+
Mandatory, min data threshold. Intensity values below this are set to 0. The threshold is applied after removing aliens.
|
|
62
|
+
crop_pad : list
|
|
63
|
+
Optional, a list of number to adjust the size at each side of 3D data. If number is positive, the array will be padded. If negative, cropped. The parameters correspond to [x left, x right, y left, y right, z left, z right] The final dimensions will be adjusted up to the good number for the FFT which also is compatible with opencl supported dimensions powers of 2 multipled by powers of 3 multiplied by powers of5
|
|
64
|
+
shift : list
|
|
65
|
+
Optional, enter center shift list the array maximum is centered before binning, and moved according to shift, [0,0,0] has no effect
|
|
66
|
+
binning : list
|
|
67
|
+
Optional, a list that defines binning values in respective dimensions, [1,1,1] has no effect.
|
|
68
|
+
no_center_max : boolean, defaults to False
|
|
69
|
+
True if the max is not centered
|
|
70
|
+
next_fast_len : boolean, defaults to False
|
|
71
|
+
Typically True, changes dimensions to numbers that allow fast fourier transform; depends on library
|
|
72
|
+
pkg : string
|
|
73
|
+
'cp' for cupy, 'torch' for torch, 'np' for numpy
|
|
74
|
+
"""
|
|
75
|
+
beamline_full_datafile_name = beamline_full_datafile_name.replace(os.sep, '/')
|
|
76
|
+
# The data has been transposed when saved in tif format for the ImageJ to show the right orientation
|
|
77
|
+
beam_data = ut.read_tif(beamline_full_datafile_name)
|
|
78
|
+
|
|
79
|
+
prep_data_dir, beamline_datafile_name = os.path.split(beamline_full_datafile_name)
|
|
80
|
+
if 'data_dir' in kwargs:
|
|
81
|
+
data_dir = kwargs['data_dir'].replace(os.sep, '/')
|
|
82
|
+
else:
|
|
83
|
+
# assuming the directory structure and naming follows cohere-ui experiment directory structure
|
|
84
|
+
data_dir = prep_data_dir.replace(os.sep, '/').replace('preprocessed_data', 'phasing_data')
|
|
85
|
+
|
|
86
|
+
if 'alien_alg' in kwargs:
|
|
87
|
+
data = at.remove_aliens(beam_data, kwargs, data_dir)
|
|
88
|
+
else:
|
|
89
|
+
data = beam_data
|
|
90
|
+
|
|
91
|
+
auto_intensity_threshold = kwargs.get('auto_intensity_threshold', False)
|
|
92
|
+
if auto_intensity_threshold:
|
|
93
|
+
# the formula for auto threshold was found empirically, may be
|
|
94
|
+
# modified in the future if more tests are done
|
|
95
|
+
auto_threshold_value = 0.141 * beam_data[np.nonzero(beam_data)].mean().item() - 3.062
|
|
96
|
+
intensity_threshold = max(2.0, auto_threshold_value)
|
|
97
|
+
print(f'auto intensity threshold: {intensity_threshold}')
|
|
98
|
+
else:
|
|
99
|
+
intensity_threshold = kwargs.get('intensity_threshold', None)
|
|
100
|
+
if intensity_threshold is None:
|
|
101
|
+
print('define intensity threshold or set to auto, exiting.')
|
|
102
|
+
return
|
|
103
|
+
# zero out the noise
|
|
104
|
+
data = np.where(data <= intensity_threshold, 0.0, data)
|
|
105
|
+
|
|
106
|
+
# square root data
|
|
107
|
+
data = np.sqrt(data)
|
|
108
|
+
|
|
109
|
+
if 'crop_pad' in kwargs:
|
|
110
|
+
crops_pads = kwargs['crop_pad']
|
|
111
|
+
# the adjust_dimension parameter list holds adjustment in each direction. Append 0s, if shorter
|
|
112
|
+
if len(crops_pads) < 6:
|
|
113
|
+
for _ in range(6 - len(crops_pads)):
|
|
114
|
+
crops_pads.append(0)
|
|
115
|
+
else:
|
|
116
|
+
# the size still has to be adjusted to the opencl supported dimension
|
|
117
|
+
crops_pads = (0, 0, 0, 0, 0, 0)
|
|
118
|
+
# adjust the size, either pad with 0s or crop array
|
|
119
|
+
pairs = []
|
|
120
|
+
for i in range(int(len(crops_pads) / 2)):
|
|
121
|
+
pair = crops_pads[2 * i:2 * i + 2]
|
|
122
|
+
pairs.append(pair)
|
|
123
|
+
|
|
124
|
+
# next_fast_len parameter should be always True. But it needs to be included
|
|
125
|
+
# when calling adjust_dimensions functions, as depending on the pkg, the result
|
|
126
|
+
# could be different. So for the sake of flexibility, the parameter next_fast_len
|
|
127
|
+
# was added as option in kwargs.
|
|
128
|
+
next_fast_len = kwargs.get('next_fast_len', True)
|
|
129
|
+
pkg = kwargs.get('pkg', 'np')
|
|
130
|
+
data = ut.adjust_dimensions(data, pairs, next_fast_len, pkg)
|
|
131
|
+
if data is None:
|
|
132
|
+
print('check "crop_pad" configuration')
|
|
133
|
+
return
|
|
134
|
+
|
|
135
|
+
no_center_max = kwargs.get('no_center_max', False)
|
|
136
|
+
shift = [0, 0, 0]
|
|
137
|
+
if not no_center_max:
|
|
138
|
+
data, shift = ut.center_max(data)
|
|
139
|
+
|
|
140
|
+
if 'shift' in kwargs:
|
|
141
|
+
conf_shift = kwargs['shift']
|
|
142
|
+
data = np.roll(data, conf_shift, tuple(range(data.ndim)))
|
|
143
|
+
shift = [s + cs for s, cs in zip(shift, conf_shift)]
|
|
144
|
+
|
|
145
|
+
try:
|
|
146
|
+
# assuming the mask file is in directory of preprocessed data
|
|
147
|
+
mask = ut.read_tif(beamline_full_datafile_name.replace(beamline_datafile_name, 'mask.tif'))
|
|
148
|
+
mask = np.roll(mask, shift, tuple(range(mask.ndim)))
|
|
149
|
+
ut.save_tif(mask, ut.join(data_dir, 'mask.tif'))
|
|
150
|
+
except FileNotFoundError:
|
|
151
|
+
pass
|
|
152
|
+
|
|
153
|
+
# auto_binning:
|
|
154
|
+
# # prepare data to make the oversampling ratio ~3
|
|
155
|
+
# wos = 3.0
|
|
156
|
+
# orig_os = ut.get_oversample_ratio(data)
|
|
157
|
+
# # match oversampling to wos
|
|
158
|
+
# wanted_os = [wos, wos, wos]
|
|
159
|
+
# change = [np.round(f / t).astype('int32') for f, t in zip(orig_os, wanted_os)]
|
|
160
|
+
# bins = [int(max([1, c])) for c in change]
|
|
161
|
+
# print(f'auto binning size: {bins}')
|
|
162
|
+
# data = ut.binning(data, bins)
|
|
163
|
+
if 'binning' in kwargs:
|
|
164
|
+
binsizes = kwargs['binning']
|
|
165
|
+
try:
|
|
166
|
+
bins = []
|
|
167
|
+
for binsize in binsizes:
|
|
168
|
+
bins.append(binsize)
|
|
169
|
+
filler = len(data.shape) - len(bins)
|
|
170
|
+
for _ in range(filler):
|
|
171
|
+
bins.append(1)
|
|
172
|
+
data = ut.binning(data, bins)
|
|
173
|
+
kwargs['binning'] = bins
|
|
174
|
+
except:
|
|
175
|
+
print('check "binning" configuration')
|
|
176
|
+
raise
|
|
177
|
+
|
|
178
|
+
# save data
|
|
179
|
+
data_file = ut.join(data_dir, 'data.tif')
|
|
180
|
+
ut.save_tif(data, data_file)
|
|
181
|
+
print(f'data ready for reconstruction, data dims: {data.shape}')
|
|
182
|
+
|
|
183
|
+
# if auto save new config
|
|
184
|
+
if auto_intensity_threshold:
|
|
185
|
+
kwargs['intensity_threshold'] = intensity_threshold
|
|
186
|
+
|
|
187
|
+
return kwargs
|
|
File without changes
|