cohere-core 4.2.2__tar.gz → 4.4.0__tar.gz

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.
Files changed (36) hide show
  1. cohere_core-4.4.0/PKG-INFO +70 -0
  2. {cohere_core-4.2.2 → cohere_core-4.4.0}/README.md +2 -2
  3. cohere_core-4.4.0/pyproject.toml +46 -0
  4. {cohere_core-4.2.2 → cohere_core-4.4.0/src}/cohere_core/controller/AI_guess.py +5 -3
  5. {cohere_core-4.2.2 → cohere_core-4.4.0/src}/cohere_core/controller/features.py +22 -53
  6. {cohere_core-4.2.2 → cohere_core-4.4.0/src}/cohere_core/controller/op_flow.py +16 -16
  7. {cohere_core-4.2.2 → cohere_core-4.4.0/src}/cohere_core/controller/phasing.py +33 -16
  8. {cohere_core-4.2.2 → cohere_core-4.4.0/src}/cohere_core/data/standard_preprocess.py +12 -2
  9. {cohere_core-4.2.2 → cohere_core-4.4.0/src}/cohere_core/lib/cohlib.py +9 -9
  10. {cohere_core-4.2.2 → cohere_core-4.4.0/src}/cohere_core/lib/cplib.py +11 -10
  11. {cohere_core-4.2.2 → cohere_core-4.4.0/src}/cohere_core/lib/nplib.py +6 -6
  12. {cohere_core-4.2.2 → cohere_core-4.4.0/src}/cohere_core/lib/torchlib.py +12 -23
  13. {cohere_core-4.2.2 → cohere_core-4.4.0/src}/cohere_core/utilities/config_errors_dict.py +12 -5
  14. {cohere_core-4.2.2 → cohere_core-4.4.0/src}/cohere_core/utilities/config_verifier.py +78 -62
  15. {cohere_core-4.2.2 → cohere_core-4.4.0/src}/cohere_core/utilities/dvc_utils.py +26 -20
  16. {cohere_core-4.2.2 → cohere_core-4.4.0/src}/cohere_core/utilities/utils.py +18 -26
  17. cohere_core-4.4.0/src/cohere_core.egg-info/PKG-INFO +70 -0
  18. cohere_core-4.4.0/src/cohere_core.egg-info/SOURCES.txt +28 -0
  19. {cohere_core-4.2.2 → cohere_core-4.4.0/src}/cohere_core.egg-info/requires.txt +3 -0
  20. cohere_core-4.2.2/PKG-INFO +0 -22
  21. cohere_core-4.2.2/cohere_core/__init__.py +0 -1
  22. cohere_core-4.2.2/cohere_core/lib/aflib.py +0 -393
  23. cohere_core-4.2.2/cohere_core.egg-info/PKG-INFO +0 -22
  24. cohere_core-4.2.2/cohere_core.egg-info/SOURCES.txt +0 -30
  25. cohere_core-4.2.2/setup.py +0 -24
  26. {cohere_core-4.2.2 → cohere_core-4.4.0}/LICENSE +0 -0
  27. {cohere_core-4.2.2 → cohere_core-4.4.0}/setup.cfg +0 -0
  28. {cohere_core-4.2.2 → cohere_core-4.4.0/src}/cohere_core/controller/__init__.py +0 -0
  29. {cohere_core-4.2.2 → cohere_core-4.4.0/src}/cohere_core/data/__init__.py +0 -0
  30. {cohere_core-4.2.2 → cohere_core-4.4.0/src}/cohere_core/data/alien_tools.py +0 -0
  31. {cohere_core-4.2.2 → cohere_core-4.4.0/src}/cohere_core/lib/__init__.py +0 -0
  32. {cohere_core-4.2.2 → cohere_core-4.4.0/src}/cohere_core/lib/check_libs.py +0 -0
  33. {cohere_core-4.2.2 → cohere_core-4.4.0/src}/cohere_core/utilities/__init__.py +0 -0
  34. {cohere_core-4.2.2 → cohere_core-4.4.0/src}/cohere_core/utilities/ga_utils.py +0 -0
  35. {cohere_core-4.2.2 → cohere_core-4.4.0/src}/cohere_core.egg-info/dependency_links.txt +0 -0
  36. {cohere_core-4.2.2 → cohere_core-4.4.0/src}/cohere_core.egg-info/top_level.txt +0 -0
@@ -0,0 +1,70 @@
1
+ Metadata-Version: 2.4
2
+ Name: cohere_core
3
+ Version: 4.4.0
4
+ Summary: cohere reconstruction tools
5
+ Author-email: Barbara Frosik <bfrosik@anl.gov>, Ross Harder <rharder@anl.gov>
6
+ License: Copyright © 2019, UChicago Argonne, LLC
7
+ All Rights Reserved
8
+ Software Name: CDI Reconstruction (cohere)
9
+ By: Argonne National Laboratory
10
+ OPEN SOURCE LICENSE
11
+
12
+ Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
13
+
14
+ 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
15
+ 2. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
16
+ 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
17
+
18
+
19
+ ******************************************************************************************************
20
+ DISCLAIMER
21
+
22
+ THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
23
+ ***************************************************************************************************
24
+ Project-URL: Homepage, https://github.com/AdvancedPhotonSource/cohere
25
+ Project-URL: Documentation, https://readthedocs.org
26
+ Project-URL: Repository, https://github.com//AdvancedPhotonSource/cohere.git
27
+ Classifier: Programming Language :: Python :: 3
28
+ Classifier: Operating System :: OS Independent
29
+ Requires-Python: >=3.11
30
+ Description-Content-Type: text/markdown
31
+ License-File: LICENSE
32
+ Requires-Dist: numpy<2
33
+ Requires-Dist: scikit-learn
34
+ Requires-Dist: tifffile
35
+ Requires-Dist: psutil
36
+ Requires-Dist: tqdm
37
+ Requires-Dist: matplotlib
38
+ Requires-Dist: scipy==1.14.1
39
+ Requires-Dist: sphinx
40
+ Requires-Dist: sphinx-pyproject
41
+ Dynamic: license-file
42
+
43
+ [![Documentation Status](https://readthedocs.org/projects/cohere/badge/?version=latest)](http://cohere.readthedocs.io/en/latest/?badge=latest)
44
+
45
+ Project home page: [https://cohere.readthedocs.io/](https://cohere.readthedocs.io/)
46
+
47
+ The cohere package provides tools for reconstruction of image of a nanoscale structures from data obtained using Bragg Coherent Diffraction Imaging technique.
48
+
49
+ The reconstruction has very good performance, in particular when utilizing GPU. User has a choice to run on cpu or GPU by selecting Python library. Supported libraries: numpy, cupy, torch. The libraries cupy or torch are installed by user. The solution offers concurrent processing for fast reconstruction of multiple starting points.
50
+
51
+ Important features:
52
+ - Genetic Algorithm (GA) - powerful feature that can deliver good reconstruction result by using GA principles. Based on research "Three-dimensional imaging of dislocation propagation during crystal growth and dissolution, Supplementary Information" by Jesse N. Clark et. al.
53
+ - Artificial Intelligence initial guess for reconstruction - uses AI to find reconstructed object that is subsequently used as input to further reconstruction. The work is built on the research by Yudong Yao, et. al: "AutoPhaseNN: Unsupervised Physics-aware Deep Learning of 3D Nanoscale Bragg Coherent Diffraction Imaging".
54
+ A trained model must be provided when using this feature. User can download trained model by clicking the following link
55
+ https://g-29c18.fd635.8443.data.globus.org/cherukara/cohere-trained_model.hdf5
56
+ - AutoAlien1 algorithm - a method to remove aliens by automatic means during standard data preprocessing. Based on work "Removal of spurious data in Bragg coherent diffraction imaging: an algorithm for automated data preprocessing" by Kenley Pelzer et. al.
57
+ - Multipeak - support for an experiment where data is collected for adjacent peaks simultaneously and reconstructing this multipeak scenario. The research is in experimental stage. Implemented by Jason (Nick) Porter.
58
+ - chrono CDI - allows the oversampling requirement at each time step to be reduced. The increased time resolution will allow imaging of faster dynamics and of radiation-dose-sensitive samples. Based on work "Coherent diffractive imaging of time-evolving samples with improved temporal resolution" by A. Ulvestat et. al.
59
+
60
+ The tools offers a full solution for reading beamline specific experiment data, formatting the data, reconstruction, and visualization. Each of the components can be utilized independently. The project was implemented for the Advanced Photon Source beamline 34-ID-C.
61
+
62
+ Author(s)
63
+
64
+ Barbara Frosik - Principal Software Engineer at Argonne National Laboratory
65
+
66
+ Ross Harder - Scientist at Argonne National Laboratory
67
+
68
+ License
69
+
70
+ Copyright (c) UChicago Argonne, LLC. All rights reserved. See LICENSE file.
@@ -1,6 +1,6 @@
1
- [![Documentation Status](https://readthedocs.org/projects/cohere-dev/badge/?version=latest)](http://cohere-dev.readthedocs.io/en/latest/?badge=latest)
1
+ [![Documentation Status](https://readthedocs.org/projects/cohere/badge/?version=latest)](http://cohere.readthedocs.io/en/latest/?badge=latest)
2
2
 
3
- Project home page: [https://cohere-dev.readthedocs.io/](https://cohere-dev.readthedocs.io/)
3
+ Project home page: [https://cohere.readthedocs.io/](https://cohere.readthedocs.io/)
4
4
 
5
5
  The cohere package provides tools for reconstruction of image of a nanoscale structures from data obtained using Bragg Coherent Diffraction Imaging technique.
6
6
 
@@ -0,0 +1,46 @@
1
+ [build-system]
2
+ requires = ["setuptools >= 77.0.3"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "cohere_core"
7
+ version = "4.4.0"
8
+ authors = [
9
+ { name="Barbara Frosik", email="bfrosik@anl.gov" },
10
+ { name="Ross Harder", email="rharder@anl.gov" }
11
+ ]
12
+ description = "cohere reconstruction tools"
13
+ readme = "README.md"
14
+ requires-python = ">=3.11"
15
+ classifiers = [
16
+ "Programming Language :: Python :: 3",
17
+ "Operating System :: OS Independent",
18
+ ]
19
+ license = { file = "LICENSE" }
20
+
21
+ dependencies = [
22
+ 'numpy<2',
23
+ 'scikit-learn',
24
+ 'tifffile',
25
+ 'psutil',
26
+ 'tqdm',
27
+ 'matplotlib',
28
+ 'scipy==1.14.1',
29
+ 'sphinx',
30
+ 'sphinx-pyproject'
31
+ ]
32
+
33
+ [tool.setuptools.packages.find]
34
+ where = ["src"]
35
+
36
+ [project.urls]
37
+ Homepage = "https://github.com/AdvancedPhotonSource/cohere"
38
+ Documentation = "https://readthedocs.org"
39
+ Repository = "https://github.com//AdvancedPhotonSource/cohere.git"
40
+
41
+ [tool.sphinx-pyproject]
42
+ extensions = [
43
+ "sphinx.ext.autodoc",
44
+ "sphinx.ext.napoleon",
45
+ 'sphinx.ext.intersphinx',
46
+ ]
@@ -77,7 +77,7 @@ def match_oversample_diff(
77
77
  pad = [[pad_value1[0], pad_value2[0]], [pad_value1[1], pad_value2[1]],
78
78
  [pad_value1[2], pad_value2[2]]]
79
79
 
80
- output = ut.adjust_dimensions(diff, pad)
80
+ output = ut.adjust_dimensions(diff, pad, next_fast_len=False)
81
81
  return output, diff.shape
82
82
 
83
83
 
@@ -236,12 +236,14 @@ def run_AI(data, model_file, dir):
236
236
  pred_obj = preds_amp * np.exp(1j * preds_phi)
237
237
 
238
238
  # match object size with the input data
239
- pred_obj = ut.Resize(pred_obj, inshape)
239
+ pred_obj = ut.resample(pred_obj, inshape)
240
240
 
241
241
  pad_value = np.array(data.shape) // 2 - np.array(pred_obj.shape) // 2
242
242
  pad = [[pad_value[0], pad_value[0]], [pad_value[1], pad_value[1]],
243
243
  [pad_value[2], pad_value[2]]]
244
- guess = ut.adjust_dimensions(pred_obj, pad)
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)
245
247
 
246
248
  np.save(ut.join(dir, 'image.npy'), guess)
247
249
 
@@ -77,6 +77,28 @@ class Pcdi:
77
77
  self.kernel, self.iterations)
78
78
 
79
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
+
80
102
  class TriggeredOp(ABC):
81
103
  """
82
104
  Base class for Triggered operation. This class creates feature objects and manages the trigger or subtrigger depending on
@@ -266,7 +288,6 @@ class ShrinkWrap(TriggeredOp):
266
288
  raise ValueError(msg)
267
289
 
268
290
 
269
-
270
291
  class PhaseConstrain(TriggeredOp):
271
292
  def __init__(self, trig_op):
272
293
  super().__init__(trig_op)
@@ -304,63 +325,11 @@ class PhaseConstrain(TriggeredOp):
304
325
  return self.PhasePHC(phase_min, phase_max)
305
326
 
306
327
 
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
328
  def create(trig_op, params, trig_op_info):
358
329
  if trig_op == 'shrink_wrap':
359
330
  to = ShrinkWrap(trig_op)
360
331
  if trig_op == 'phc':
361
332
  to = PhaseConstrain(trig_op)
362
- if trig_op == 'lowpass_filter':
363
- to = LowPassFilter(trig_op)
364
333
 
365
334
  # this function sets self.objs and self.f and creates all objects
366
335
  # It may throw exception
@@ -22,8 +22,7 @@ algs = {'ER': ('to_reciprocal_space', 'modulus', 'to_direct_space', 'er'),
22
22
  # defined by preceding algorithm. The key is the trigger name and value is the mnemonic. The mnemonic is used in the
23
23
  # configuration.
24
24
  sub_triggers = {'SW' : 'shrink_wrap_trigger',
25
- 'PHC' : 'phc_trigger',
26
- 'LPF' : 'lowpass_filter_trigger'}
25
+ 'PHC' : 'phc_trigger'}
27
26
 
28
27
  # This list contains triggers that will be active at the last iteration defined by trigger, despite
29
28
  # not being a trigger calculated by the step formula.
@@ -197,7 +196,8 @@ def fill_sub_trigger_row(sub_iters, sub_trigs, iter_no, last_trig):
197
196
  # create array indicating with index which sub-triggered operation may happen in the iterations
198
197
  sub_trig_idx_row = np.zeros(iter_no, dtype=int)
199
198
  # for each defined sub iteration chunk apply corresponding sub-trigger
200
- for (b, e, idx) in sub_iters:
199
+ for i, sub_iter in enumerate(sub_iters):
200
+ (b, e, idx) = sub_iter
201
201
  index = int(idx)
202
202
  sub_trig_idx_row[b:e] = index + 1
203
203
  if len(sub_trigs) - 1 < index:
@@ -209,6 +209,8 @@ def fill_sub_trigger_row(sub_iters, sub_trigs, iter_no, last_trig):
209
209
  trigger.append(e)
210
210
  elif len(trigger) == 3:
211
211
  trigger[2] = min(e, trigger[0] + trigger[2])
212
+ # update the sub_iters
213
+ sub_iters[i] = (b, trigger[2], idx)
212
214
  sub_trig_row = fill_trigger_row(trigger, iter_no, last_trig, sub_trig_row)
213
215
 
214
216
  return sub_trig_row * sub_trig_idx_row
@@ -244,22 +246,15 @@ def get_flow_arr(params, flow_items_list, curr_gen=None):
244
246
  # do some checks to find if the sequence and configuration are runnable
245
247
  # and special cases
246
248
 
247
- # this array is a mask blocking shrink wrap when low pass filter is active
248
- apply_sw_row = np.ones(iter_no, dtype=int)
249
249
  last_lpf = None
250
250
  if 'lowpass_filter_trigger' in params:
251
- if 'lowpass_filter_trigger' in sub_iters:
252
- for b, e, i in sub_iters['lowpass_filter_trigger']:
253
- apply_sw_row[b:e] = 0
254
- last_lpf = e
255
- elif len(params['lowpass_filter_trigger']) < 2:
251
+ if len(params['lowpass_filter_trigger']) < 2:
256
252
  print('Low pass trigger misconfiguration error. This trigger should have upper bound.')
257
253
  raise
258
254
  elif params['lowpass_filter_trigger'][2] >= iter_no:
259
255
  print('Low pass trigger misconfiguration error. The upper bound should be less than total iterations.')
260
256
  raise
261
257
  else:
262
- apply_sw_row[params['lowpass_filter_trigger'][0]:params['lowpass_filter_trigger'][2]] = 0
263
258
  last_lpf = params['lowpass_filter_trigger'][2]
264
259
 
265
260
  if pc_start is not None:
@@ -297,16 +292,21 @@ def get_flow_arr(params, flow_items_list, curr_gen=None):
297
292
  if trigger_name in sub_iters.keys():
298
293
  # may throw exception
299
294
  flow_arr[i] = fill_sub_trigger_row(sub_iters[trigger_name], params[trigger_name], iter_no, last_trig)
295
+ # special case
296
+ if flow_item == 'phc_operation':
297
+ reset = [l[1] for l in list(sub_iters[trigger_name])]
298
+ flow_arr[i-1][reset] = 1
299
+
300
300
  # add entry to sub trigger operation dict with key of the trigger mnemonic
301
301
  # and the value of a list with the row and sub triggers iterations chunks
302
302
  sub_trig_op[trigger_name] = (flow_arr[i], sub_iters[trigger_name])
303
303
  else:
304
304
  flow_arr[i] = fill_trigger_row(params[trigger_name], iter_no, last_trig)
305
-
306
- # handle special cases
307
- if flow_item == 'shrink_wrap_operation':
308
- # shrink wrap is blocked by low pass filter
309
- flow_arr[i] = flow_arr[i] * apply_sw_row
305
+ # special case
306
+ if flow_item == 'phc_operation':
307
+ # Assuming phc trigger is configured with upper limit
308
+ reset_iter = min(iter_no - 1, params[trigger_name][2] + 1)
309
+ flow_arr[i-1][reset_iter] = 1
310
310
  elif flow_item == 'set_prev_pc' and pc_start is not None:
311
311
  # set_prev_pc is executed one iteration before pc_trigger
312
312
  pc_row = flow_items_list.index('pc_operation')
@@ -89,6 +89,7 @@ class Rec:
89
89
  self.lowpass_filter_operation,
90
90
  self.reset_resolution,
91
91
  self.shrink_wrap_operation,
92
+ self.reset_phc_correction,
92
93
  self.phc_operation,
93
94
  self.to_reciprocal_space,
94
95
  self.new_func_operation,
@@ -129,6 +130,8 @@ class Rec:
129
130
  self.need_save_data = False
130
131
  self.saved_data = None
131
132
  self.debug = kwargs.get('debug', False)
133
+ # only when phc feature is configured this becomes array
134
+ self.phc_correction = 1
132
135
 
133
136
 
134
137
  def init_dev(self, device_id):
@@ -253,14 +256,15 @@ class Rec:
253
256
  if self.is_pc:
254
257
  self.pc_obj = ft.Pcdi(self.params, self.data, dir)
255
258
 
259
+ if 'lowpass_filter_trigger' in self.params:
260
+ self.lowpass_filter_obj = ft.LowPassFilter( self.params)
261
+
256
262
  # create the trgger/sub-trigger objects
257
263
  try:
258
264
  if 'shrink_wrap_trigger' in self.params:
259
265
  self.shrink_wrap_obj = ft.create('shrink_wrap', self.params, feats)
260
266
  if 'phc_trigger' in self.params:
261
267
  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
268
  except Exception as e:
265
269
  if self.debug:
266
270
  raise
@@ -383,8 +387,8 @@ class Rec:
383
387
  self.iter = self.iter + 1
384
388
 
385
389
  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)
390
+ args = (self.data, self.iter)
391
+ self.iter_data = self.lowpass_filter_obj.apply_trigger(*args)
388
392
 
389
393
  def reset_resolution(self):
390
394
  self.iter_data = self.data
@@ -393,9 +397,12 @@ class Rec:
393
397
  args = (self.ds_image,)
394
398
  self.support = self.shrink_wrap_obj.apply_trigger(*args)
395
399
 
400
+ def reset_phc_correction(self):
401
+ self.phc_correction = 1
402
+
396
403
  def phc_operation(self):
397
404
  args = (self.ds_image,)
398
- self.support *= self.phc_obj.apply_trigger(*args)
405
+ self.phc_correction = self.phc_obj.apply_trigger(*args)
399
406
 
400
407
  def to_reciprocal_space(self):
401
408
  self.rs_amplitudes = devlib.ifft(self.ds_image)
@@ -430,20 +437,23 @@ class Rec:
430
437
  self.ds_image_proj = devlib.fft(self.rs_amplitudes)
431
438
 
432
439
  def er(self):
433
- self.ds_image = self.ds_image_proj * self.support
440
+ self.ds_image = self.ds_image_proj * self.support * self.phc_correction
434
441
 
435
442
  def hio(self):
436
443
  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)
444
+ self.ds_image = devlib.where((self.support * self.phc_correction > 0),
445
+ self.ds_image_proj,
446
+ combined_image)
438
447
 
439
448
  def sf(self):
440
449
  # solvent flipping
441
- self.ds_image = 2.0 * (self.ds_image_proj * self.support) - self.ds_image_proj
450
+ self.ds_image = 2.0 * (self.ds_image_proj * self.support * self.phc_correction) - self.ds_image_proj
442
451
 
443
452
  def raar(self):
444
453
  # 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
454
+ self.ds_image = (self.params['raar_beta']
455
+ * (self.support * self.phc_correction * self.ds_image_proj + self.ds_image)
456
+ + (1 - 2 * self.params['raar_beta']) * self.ds_image_proj)
447
457
 
448
458
  def twin_operation(self):
449
459
  # TODO this will work only for 3D array, but will the twin be used for 1D or 2D?
@@ -482,16 +492,23 @@ class Rec:
482
492
  f"error: {self.errs[-1]}\n"
483
493
  )
484
494
  [[ax.clear() for ax in row] for row in self.axs]
485
- img = self.ds_image[qtr:-qtr, qtr:-qtr, half]
495
+ if len(self.ds_image.shape) == 2:
496
+ img = self.ds_image
497
+ else:
498
+ img = self.ds_image[qtr:-qtr, qtr:-qtr, half]
486
499
  self.axs[0][0].set(title="Amplitude", xticks=[], yticks=[])
487
- self.axs[0][0].imshow(devlib.absolute(img).get(), cmap="gray")
500
+ self.axs[0][0].imshow(devlib.absolute(img), cmap="gray")
488
501
  self.axs[0][1].set(title="Phase", xticks=[], yticks=[])
489
- self.axs[0][1].imshow(devlib.angle(img).get(), cmap="hsv", interpolation_stage="rgba")
502
+ self.axs[0][1].imshow(devlib.angle(img), cmap="hsv", interpolation_stage="rgba")
490
503
 
504
+ if len(self.ds_image.shape) == 2:
505
+ sup = self.support
506
+ else:
507
+ sup = self.support[qtr:-qtr, qtr:-qtr, half]
491
508
  self.axs[1][0].set(title="Error", xlim=(0,self.iter_no), xlabel="Iteration", yscale="log")
492
509
  self.axs[1][0].plot(self.errs[1:])
493
510
  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")
511
+ self.axs[1][1].imshow(sup, cmap="gray")
495
512
 
496
513
  plt.draw()
497
514
  plt.pause(0.15)
@@ -501,7 +518,7 @@ class Rec:
501
518
  return ratio
502
519
 
503
520
  def shift_to_center(self):
504
- ind = devlib.center_of_mass(self.support.astype('int32'))
521
+ ind = devlib.center_of_mass(devlib.astype(self.support, 'int32'))
505
522
  shift_dist = (self.dims[0]//2) - devlib.round(devlib.array(ind))
506
523
  shift_dist = devlib.to_numpy(shift_dist).tolist()
507
524
  axis = tuple(range(len(self.ds_image.shape)))
@@ -818,7 +835,7 @@ class CoupledRec(Rec):
818
835
 
819
836
  def make_binary(self):
820
837
  self.support = devlib.absolute(self.support)
821
- self.support = devlib.where(self.support >= 0.9 * devlib.amax(self.support), 1, 0).astype("?")
838
+ self.support = devlib.where(self.support >= devlib.astype(0.9 * devlib.amax(self.support), 1, 0), ("?"))
822
839
 
823
840
  def get_phase_gradient(self):
824
841
  """Calculate the phase gradient for a given peak"""
@@ -65,8 +65,12 @@ def prep(beamline_full_datafile_name, **kwargs):
65
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
66
  binning : list
67
67
  Optional, a list that defines binning values in respective dimensions, [1,1,1] has no effect.
68
- no_center_max : False
68
+ no_center_max : boolean, defaults to False
69
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
70
74
  """
71
75
  beamline_full_datafile_name = beamline_full_datafile_name.replace(os.sep, '/')
72
76
  # The data has been transposed when saved in tif format for the ImageJ to show the right orientation
@@ -117,7 +121,13 @@ def prep(beamline_full_datafile_name, **kwargs):
117
121
  pair = crops_pads[2 * i:2 * i + 2]
118
122
  pairs.append(pair)
119
123
 
120
- data = ut.adjust_dimensions(data, pairs)
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)
121
131
  if data is None:
122
132
  print('check "crop_pad" configuration')
123
133
  return
@@ -17,8 +17,6 @@ class cohlib(metaclass=abc.ABCMeta):
17
17
  callable(subclass.cross) and
18
18
  hasattr(subclass, 'set_device') and
19
19
  callable(subclass.set_device) and
20
- hasattr(subclass, 'set_backend') and
21
- callable(subclass.set_backend) and
22
20
  hasattr(subclass, 'to_numpy') and
23
21
  callable(subclass.to_numpy) and
24
22
  hasattr(subclass, 'save') and
@@ -35,6 +33,8 @@ class cohlib(metaclass=abc.ABCMeta):
35
33
  callable(subclass.reshape) and
36
34
  hasattr(subclass, 'size') and
37
35
  callable(subclass.size) and
36
+ hasattr(subclass, 'next_fast_len') and
37
+ callable(subclass.next_fast_len) and
38
38
  hasattr(subclass, 'hasnan') and
39
39
  callable(subclass.hasnan) and
40
40
  hasattr(subclass, 'copy') and
@@ -195,11 +195,6 @@ class cohlib(metaclass=abc.ABCMeta):
195
195
  def set_device(dev_id):
196
196
  pass
197
197
 
198
- @staticmethod
199
- @abc.abstractmethod
200
- def set_backend(proc):
201
- pass
202
-
203
198
  @staticmethod
204
199
  @abc.abstractmethod
205
200
  def to_numpy(arr):
@@ -212,12 +207,12 @@ class cohlib(metaclass=abc.ABCMeta):
212
207
 
213
208
  @staticmethod
214
209
  @abc.abstractmethod
215
- def load(filename):
210
+ def load(filename, **kwargs):
216
211
  pass
217
212
 
218
213
  @staticmethod
219
214
  @abc.abstractmethod
220
- def from_numpy(arr):
215
+ def from_numpy(arr, **kwargs):
221
216
  pass
222
217
 
223
218
  @staticmethod
@@ -240,6 +235,11 @@ class cohlib(metaclass=abc.ABCMeta):
240
235
  def size(arr):
241
236
  pass
242
237
 
238
+ @staticmethod
239
+ @abc.abstractmethod
240
+ def next_fast_len(target):
241
+ pass
242
+
243
243
  @staticmethod
244
244
  @abc.abstractmethod
245
245
  def hasnan(arr):
@@ -11,6 +11,7 @@ import cupyx.scipy.stats as stats
11
11
  import cupyx.scipy.ndimage as sc
12
12
  import cupyx.scipy.special as sp
13
13
  import cupyx.scipy.signal as sig
14
+ import cupyx.scipy.fft as fft
14
15
 
15
16
 
16
17
  class cplib(cohlib):
@@ -31,16 +32,12 @@ class cplib(cohlib):
31
32
  if dev_id != -1:
32
33
  cp.cuda.Device(dev_id).use()
33
34
 
34
- @staticmethod
35
- def set_backend(proc):
36
- pass
37
-
38
35
  @staticmethod
39
36
  def to_numpy(arr):
40
37
  return cp.asnumpy(arr)
41
38
 
42
39
  @staticmethod
43
- def from_numpy(arr):
40
+ def from_numpy(arr, **kwargs):
44
41
  return cp.array(arr)
45
42
 
46
43
  @staticmethod
@@ -48,7 +45,7 @@ class cplib(cohlib):
48
45
  cp.save(filename, arr)
49
46
 
50
47
  @staticmethod
51
- def load(filename):
48
+ def load(filename, **kwargs):
52
49
  return cp.load(filename, allow_pickle=True)
53
50
 
54
51
  @staticmethod
@@ -67,6 +64,10 @@ class cplib(cohlib):
67
64
  def size(arr):
68
65
  return arr.size
69
66
 
67
+ @staticmethod
68
+ def next_fast_len(target):
69
+ return fft.next_fast_len(target)
70
+
70
71
  @staticmethod
71
72
  def hasnan(arr):
72
73
  return cp.any(cp.isnan(arr))
@@ -103,19 +104,19 @@ class cplib(cohlib):
103
104
 
104
105
  @staticmethod
105
106
  def fftshift(arr):
106
- return cp.fft.fftshift(arr)
107
+ return fft.fftshift(arr)
107
108
 
108
109
  @staticmethod
109
110
  def ifftshift(arr):
110
- return cp.fft.ifftshift(arr)
111
+ return fft.ifftshift(arr)
111
112
 
112
113
  @staticmethod
113
114
  def fft(arr, norm='forward'):
114
- return cp.fft.fftn(arr, norm=norm)
115
+ return fft.fftn(arr, norm=norm)
115
116
 
116
117
  @staticmethod
117
118
  def ifft(arr, norm='forward'):
118
- return cp.fft.ifftn(arr, norm=norm)
119
+ return fft.ifftn(arr, norm=norm)
119
120
 
120
121
  @staticmethod
121
122
  def fftconvolve(arr1, kernel):
@@ -28,20 +28,16 @@ class nplib(cohlib):
28
28
  def set_device(dev_id):
29
29
  pass
30
30
 
31
- @staticmethod
32
- def set_backend(proc):
33
- pass
34
-
35
31
  @staticmethod
36
32
  def to_numpy(arr):
37
33
  return arr
38
34
 
39
35
  @staticmethod
40
- def load(filename):
36
+ def load(filename, **kwargs):
41
37
  return np.load(filename)
42
38
 
43
39
  @staticmethod
44
- def from_numpy(arr):
40
+ def from_numpy(arr, **kwargs):
45
41
  return arr
46
42
 
47
43
  @staticmethod
@@ -64,6 +60,10 @@ class nplib(cohlib):
64
60
  def size(arr):
65
61
  return arr.size
66
62
 
63
+ @staticmethod
64
+ def next_fast_len(target):
65
+ return fft.next_fast_len(target)
66
+
67
67
  @staticmethod
68
68
  def nan_to_num(arr, **kwargs):
69
69
  return np.nan_to_num(arr, **kwargs)