cohere-core 4.3__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 (31) hide show
  1. {cohere_core-4.3/src/cohere_core.egg-info → cohere_core-4.4.0}/PKG-INFO +3 -1
  2. {cohere_core-4.3 → cohere_core-4.4.0}/pyproject.toml +3 -1
  3. {cohere_core-4.3 → cohere_core-4.4.0}/src/cohere_core/controller/features.py +22 -53
  4. {cohere_core-4.3 → cohere_core-4.4.0}/src/cohere_core/controller/op_flow.py +16 -16
  5. {cohere_core-4.3 → cohere_core-4.4.0}/src/cohere_core/controller/phasing.py +33 -16
  6. {cohere_core-4.3 → cohere_core-4.4.0}/src/cohere_core/lib/cohlib.py +2 -9
  7. {cohere_core-4.3 → cohere_core-4.4.0}/src/cohere_core/lib/cplib.py +2 -6
  8. {cohere_core-4.3 → cohere_core-4.4.0}/src/cohere_core/lib/nplib.py +2 -6
  9. {cohere_core-4.3 → cohere_core-4.4.0}/src/cohere_core/lib/torchlib.py +7 -23
  10. {cohere_core-4.3 → cohere_core-4.4.0}/src/cohere_core/utilities/config_errors_dict.py +2 -5
  11. {cohere_core-4.3 → cohere_core-4.4.0}/src/cohere_core/utilities/config_verifier.py +26 -61
  12. {cohere_core-4.3 → cohere_core-4.4.0}/src/cohere_core/utilities/dvc_utils.py +26 -20
  13. {cohere_core-4.3 → cohere_core-4.4.0/src/cohere_core.egg-info}/PKG-INFO +3 -1
  14. {cohere_core-4.3 → cohere_core-4.4.0}/src/cohere_core.egg-info/SOURCES.txt +0 -1
  15. cohere_core-4.3/src/cohere_core/lib/aflib.py +0 -393
  16. {cohere_core-4.3 → cohere_core-4.4.0}/LICENSE +0 -0
  17. {cohere_core-4.3 → cohere_core-4.4.0}/README.md +0 -0
  18. {cohere_core-4.3 → cohere_core-4.4.0}/setup.cfg +0 -0
  19. {cohere_core-4.3 → cohere_core-4.4.0}/src/cohere_core/controller/AI_guess.py +0 -0
  20. {cohere_core-4.3 → cohere_core-4.4.0}/src/cohere_core/controller/__init__.py +0 -0
  21. {cohere_core-4.3 → cohere_core-4.4.0}/src/cohere_core/data/__init__.py +0 -0
  22. {cohere_core-4.3 → cohere_core-4.4.0}/src/cohere_core/data/alien_tools.py +0 -0
  23. {cohere_core-4.3 → cohere_core-4.4.0}/src/cohere_core/data/standard_preprocess.py +0 -0
  24. {cohere_core-4.3 → cohere_core-4.4.0}/src/cohere_core/lib/__init__.py +0 -0
  25. {cohere_core-4.3 → cohere_core-4.4.0}/src/cohere_core/lib/check_libs.py +0 -0
  26. {cohere_core-4.3 → cohere_core-4.4.0}/src/cohere_core/utilities/__init__.py +0 -0
  27. {cohere_core-4.3 → cohere_core-4.4.0}/src/cohere_core/utilities/ga_utils.py +0 -0
  28. {cohere_core-4.3 → cohere_core-4.4.0}/src/cohere_core/utilities/utils.py +0 -0
  29. {cohere_core-4.3 → cohere_core-4.4.0}/src/cohere_core.egg-info/dependency_links.txt +0 -0
  30. {cohere_core-4.3 → cohere_core-4.4.0}/src/cohere_core.egg-info/requires.txt +0 -0
  31. {cohere_core-4.3 → cohere_core-4.4.0}/src/cohere_core.egg-info/top_level.txt +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: cohere_core
3
- Version: 4.3
3
+ Version: 4.4.0
4
4
  Summary: cohere reconstruction tools
5
5
  Author-email: Barbara Frosik <bfrosik@anl.gov>, Ross Harder <rharder@anl.gov>
6
6
  License: Copyright © 2019, UChicago Argonne, LLC
@@ -22,6 +22,8 @@ License: Copyright © 2019, UChicago Argonne, LLC
22
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
23
  ***************************************************************************************************
24
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
25
27
  Classifier: Programming Language :: Python :: 3
26
28
  Classifier: Operating System :: OS Independent
27
29
  Requires-Python: >=3.11
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "cohere_core"
7
- version = "4.3"
7
+ version = "4.4.0"
8
8
  authors = [
9
9
  { name="Barbara Frosik", email="bfrosik@anl.gov" },
10
10
  { name="Ross Harder", email="rharder@anl.gov" }
@@ -35,6 +35,8 @@ dependencies = [
35
35
 
36
36
  [project.urls]
37
37
  Homepage = "https://github.com/AdvancedPhotonSource/cohere"
38
+ Documentation = "https://readthedocs.org"
39
+ Repository = "https://github.com//AdvancedPhotonSource/cohere.git"
38
40
 
39
41
  [tool.sphinx-pyproject]
40
42
  extensions = [
@@ -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"""
@@ -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
@@ -197,11 +195,6 @@ class cohlib(metaclass=abc.ABCMeta):
197
195
  def set_device(dev_id):
198
196
  pass
199
197
 
200
- @staticmethod
201
- @abc.abstractmethod
202
- def set_backend(proc):
203
- pass
204
-
205
198
  @staticmethod
206
199
  @abc.abstractmethod
207
200
  def to_numpy(arr):
@@ -214,12 +207,12 @@ class cohlib(metaclass=abc.ABCMeta):
214
207
 
215
208
  @staticmethod
216
209
  @abc.abstractmethod
217
- def load(filename):
210
+ def load(filename, **kwargs):
218
211
  pass
219
212
 
220
213
  @staticmethod
221
214
  @abc.abstractmethod
222
- def from_numpy(arr):
215
+ def from_numpy(arr, **kwargs):
223
216
  pass
224
217
 
225
218
  @staticmethod
@@ -32,16 +32,12 @@ class cplib(cohlib):
32
32
  if dev_id != -1:
33
33
  cp.cuda.Device(dev_id).use()
34
34
 
35
- @staticmethod
36
- def set_backend(proc):
37
- pass
38
-
39
35
  @staticmethod
40
36
  def to_numpy(arr):
41
37
  return cp.asnumpy(arr)
42
38
 
43
39
  @staticmethod
44
- def from_numpy(arr):
40
+ def from_numpy(arr, **kwargs):
45
41
  return cp.array(arr)
46
42
 
47
43
  @staticmethod
@@ -49,7 +45,7 @@ class cplib(cohlib):
49
45
  cp.save(filename, arr)
50
46
 
51
47
  @staticmethod
52
- def load(filename):
48
+ def load(filename, **kwargs):
53
49
  return cp.load(filename, allow_pickle=True)
54
50
 
55
51
  @staticmethod
@@ -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
@@ -29,31 +29,16 @@ class torchlib(cohlib):
29
29
 
30
30
  @staticmethod
31
31
  def set_device(dev_id):
32
- if dev_id == -1 or sys.platform == 'darwin':
33
- torch.device("cpu")
34
- torchlib.device = "cpu"
35
- else:
36
- torch.device(dev_id)
37
- torchlib.device = dev_id
38
-
39
- # the pytorch does not support very needed functions such as fft, ifft for
40
- # the GPU M1 (backendMPS), so for this platform it will be set to cpu until the
41
- # functions are supported
42
- # torchlib.device = torch.device("mps")
43
-
44
- @staticmethod
45
- def set_backend(proc):
46
- # this function is not used currently
47
32
  if sys.platform == 'darwin':
48
33
  # Check that MPS is available
49
34
  if not torch.backends.mps.is_available():
50
- print("MPS not available because the current PyTorch install was not "
51
- "built with MPS enabled. Using cpu.")
35
+ print("MPS not available because the current PyTorch install was not built with MPS enabled. Using cpu.")
52
36
  torch.device("cpu")
53
37
  else:
54
38
  torch.device("mps")
55
- elif torch.backends.cuda.is_built():
56
- torch.device("cuda")
39
+ elif torch.backends.cuda.is_built() and dev_id != -1:
40
+ torch_dev = f"cuda:{str(dev_id)}"
41
+ torchlib.device = torch_dev
57
42
  else:
58
43
  torch.device("cpu")
59
44
 
@@ -74,12 +59,12 @@ class torchlib(cohlib):
74
59
  np.save(filename, arr)
75
60
 
76
61
  @staticmethod
77
- def load(filename):
62
+ def load(filename, **kwargs):
78
63
  arr = np.load(filename)
79
64
  return torch.as_tensor(arr, device=torchlib.device)
80
65
 
81
66
  @staticmethod
82
- def from_numpy(arr):
67
+ def from_numpy(arr, **kwargs):
83
68
  return torch.as_tensor(arr, device=torchlib.device)
84
69
 
85
70
  @staticmethod
@@ -122,7 +107,6 @@ class torchlib(cohlib):
122
107
  @staticmethod
123
108
  def random(shape, **kwargs):
124
109
  arr = torch.rand(shape, device=torchlib.device)
125
- print(arr.dtype)
126
110
  # return torch.rand(shape, device=torchlib.device)
127
111
  return arr
128
112
 
@@ -216,7 +200,7 @@ class torchlib(cohlib):
216
200
 
217
201
  @staticmethod
218
202
  def sum(arr, axis=None):
219
- return torch.sum(arr)
203
+ return torch.sum(arr, dim=axis)
220
204
 
221
205
  @staticmethod
222
206
  def real(arr):
@@ -129,12 +129,9 @@ config_rec_error = {'File':['No configuration file',
129
129
  'pc_normalize parameter parsing error'],
130
130
  'Pclucykernel':['pc_LUCY_kernel parameter should be a list of int',
131
131
  'pc_LUCY_kernel parameter must be configured when partial coherence feature in active'],
132
- 'lpftrigger':['Trigger should be a list of int',
133
- 'Each sub-trigger should be a list of int if multiple lowpass filters'],
134
- 'Lowpassfilterswthreshold':['lpf_sw_threshold parameter should be flot',
135
- 'lpf_sw_threshold should be a list of floats if multiple lowpass filters'],
132
+ 'Lpftrigger':['Trigger should be a list of int',
133
+ 'lawpass_filter_trigger should have upper limit'],
136
134
  'Lowpassfilterrange':['lowpass_filter_range parameter should be list of flots',
137
- 'lowpass_filter_range should be a list of int for each lowpass filter if multiple lowpass filters'
138
135
  'missing lowpass_filter_range parameter'],
139
136
  'Averagetrigger':['Trigger should be a list of int'],
140
137
  'Progresstrigger':['Trigger should be a list of int'],
@@ -259,8 +259,8 @@ def ver_config_rec(config_map):
259
259
 
260
260
 
261
261
  def verify_trigger(trigger, no_iter, trigger_name):
262
- if type(trigger) != list:
263
- return(f'{trigger_name} trigger type should be list')
262
+ if not ver_list_int(trigger_name, trigger):
263
+ return(f'{trigger_name} trigger type should be list of int')
264
264
  if len(trigger) == 0:
265
265
  return (f'empty {trigger_name} trigger {str(trigger)}')
266
266
  elif trigger[0] >= no_iter:
@@ -743,71 +743,36 @@ def ver_config_rec(config_map):
743
743
  print(error_message)
744
744
  return (error_message)
745
745
 
746
- config_parameter = 'Resolutiontrigger'
746
+ config_parameter = 'Lpftrigger'
747
747
  if 'lowpass_filter_trigger' in config_map:
748
- if '.LPF' not in config_map['algorithm_sequence']:
749
- m = verify_trigger(config_map['lowpass_filter_trigger'], iter_no, 'lowpass filter')
750
- if len(m) > 0:
751
- print(m)
752
- return(m)
753
- if not ver_list_int('lowpass_filter_trigger', config_map['lowpass_filter_trigger']):
754
- config_error = 0
755
- error_message = get_config_error_message(fname, config_map_file, config_parameter, config_error)
756
- print(error_message)
757
- return (error_message)
758
-
759
- config_parameter = 'Lowpassfilterswthreshold'
760
- if 'lowpass_filter_sw_threshold' in config_map:
761
- lowpass_filter_sw_threshold = config_map['lowpass_filter_sw_threshold']
762
- if type(lowpass_filter_sw_threshold) != float:
763
- error_message = get_config_error_message(fname, config_map_file, config_parameter, config_error)
764
- print(error_message)
765
- return (error_message)
748
+ m = verify_trigger(config_map['lowpass_filter_trigger'], iter_no, 'lowpass filter')
749
+ if len(m) > 0:
750
+ print(m)
751
+ return(m)
752
+ if not ver_list_int('lowpass_filter_trigger', config_map['lowpass_filter_trigger']):
753
+ config_error = 0
754
+ error_message = get_config_error_message(fname, config_map_file, config_parameter, config_error)
755
+ print(error_message)
756
+ return (error_message)
757
+ if len(config_map['lowpass_filter_trigger']) < 3:
758
+ config_error = 1
759
+ error_message = get_config_error_message(fname, config_map_file, config_parameter, config_error)
760
+ print(error_message)
761
+ return (error_message)
766
762
 
767
- config_parameter = 'Lowpassfilterrange'
768
- if 'lowpass_filter_range' in config_map:
769
- lowpass_filter_range = config_map['lowpass_filter_range']
770
- if not ver_list_float('lowpass_filter_range', lowpass_filter_range):
771
- config_error = 0
772
- error_message = get_config_error_message(fname, config_map_file, config_parameter, config_error)
773
- print(error_message)
774
- return (error_message)
775
- else:
776
- config_error = 2
763
+ config_parameter = 'Lowpassfilterrange'
764
+ if 'lowpass_filter_range' in config_map:
765
+ lowpass_filter_range = config_map['lowpass_filter_range']
766
+ if not ver_list_float('lowpass_filter_range', lowpass_filter_range):
767
+ config_error = 0
777
768
  error_message = get_config_error_message(fname, config_map_file, config_parameter, config_error)
778
769
  print(error_message)
779
770
  return (error_message)
780
771
  else:
781
- for t in config_map['lowpass_filter_trigger']:
782
- if not ver_list_int('lowpass_filter_trigger', t):
783
- config_error = 1
784
- error_message = get_config_error_message(fname, config_map_file, config_parameter, config_error)
785
- print(error_message)
786
- return (error_message)
787
-
788
- config_parameter = 'Lowpassfilterrange'
789
- if 'lowpass_filter_range' in config_map:
790
- for r in config_map['lowpass_filter_range']:
791
- if not ver_list_float('lowpass_filter_range', r):
792
- config_error = 1
793
- error_message = get_config_error_message(fname, config_map_file, config_parameter, config_error)
794
- print(error_message)
795
- return (error_message)
796
- else:
797
- config_error = 2
798
- error_message = get_config_error_message(fname, config_map_file, config_parameter, config_error)
799
- print(error_message)
800
- return (error_message)
801
-
802
- config_parameter = 'Lowpassfilterswthreshold'
803
- if 'lowpass_filter_sw_threshold' in config_map:
804
- lowpass_filter_sw_threshold = config_map['lowpass_filter_sw_threshold']
805
- if not ver_list_float('lowpass_filter_sw_threshold', lowpass_filter_sw_threshold):
806
- config_error = 1
807
- error_message = get_config_error_message(fname, config_map_file, config_parameter, config_error)
808
- print(error_message)
809
- return (error_message)
810
-
772
+ config_error = 2
773
+ error_message = get_config_error_message(fname, config_map_file, config_parameter, config_error)
774
+ print(error_message)
775
+ return (error_message)
811
776
 
812
777
  config_parameter = 'Averagetrigger'
813
778
  if 'average_trigger' in config_map:
@@ -17,7 +17,7 @@ import cmath
17
17
  import math
18
18
  from matplotlib import pyplot as plt
19
19
  import cohere_core.utilities.utils as ut
20
-
20
+ import numpy as np
21
21
 
22
22
  _docformat__ = 'restructuredtext en'
23
23
  __all__ = [
@@ -375,15 +375,22 @@ def dftregistration(ref_arr, arr, usfac=2):
375
375
  if usfac > 2:
376
376
  # DFT computation
377
377
  # Initial shift estimate in upsampled grid
378
- row_shift = devlib.round(row_shift * usfac) / usfac
379
- col_shift = devlib.round(col_shift * usfac) / usfac
380
- dftshift = devlib.fix(devlib.ceil(usfac * 1.5) / 2) # Center of output array at dftshift
378
+ row_shift = np.round(row_shift * usfac) / usfac
379
+ col_shift = np.round(col_shift * usfac) / usfac
380
+ dftshift = np.fix(np.ceil(usfac * 1.5) / 2) # Center of output array at dftshift
381
381
  # Matrix multiply DFT around the current shift estimate
382
- c_c = devlib.conj(
383
- dftups(arr * devlib.conj(ref_arr), int(math.ceil(usfac * 1.5)), int(math.ceil(usfac * 1.5)), usfac,
384
- int(dftshift - row_shift * usfac), int(dftshift - col_shift * usfac))) / \
382
+ # arr and ref_arr are on device
383
+ # move the input to nparray for dftups calculations and convert result to device after
384
+ combined_np = devlib.to_numpy(arr * devlib.conj(ref_arr))
385
+
386
+ ups_np = dftups(combined_np, int(math.ceil(usfac * 1.5)), int(math.ceil(usfac * 1.5)), usfac,
387
+ int(dftshift - row_shift * usfac), int(dftshift - col_shift * usfac))
388
+
389
+ ups = devlib.from_numpy(ups_np)
390
+ c_c = devlib.conj(ups) / \
385
391
  (int(math.trunc(shape[0] / 2)) * int(math.trunc(shape[1] / 2)) * usfac ^ 2)
386
392
  # Locate maximum and map back to original pixel grid
393
+
387
394
  max_coord = devlib.unravel_index(devlib.argmax(devlib.absolute(c_c)), devlib.dims(c_c))
388
395
  [rloc, cloc] = max_coord
389
396
 
@@ -408,7 +415,7 @@ def dftups(arr, nor=-1, noc=-1, usfac=2, roff=0, coff=0):
408
415
  :return: upsampled array
409
416
  """
410
417
  # arr is 2D
411
- [nr, nc] = devlib.dims(arr)
418
+ [nr, nc] = list(arr.shape)
412
419
  if nor < 0:
413
420
  nor = nr
414
421
  if noc < 0:
@@ -416,23 +423,22 @@ def dftups(arr, nor=-1, noc=-1, usfac=2, roff=0, coff=0):
416
423
 
417
424
  # Compute kernels and obtain DFT by matrix products
418
425
  yl = list(range(-int(math.floor(nc / 2)), nc - int(math.floor(nc / 2))))
419
- y = devlib.ifftshift(devlib.array(yl)) * (-2j * math.pi / (nc * usfac))
426
+ y = np.fft.ifftshift(np.array(yl)) * (-2j * math.pi / (nc * usfac))
420
427
  xl = list(range(-coff, noc - coff))
421
- x = devlib.array(xl)
422
- yt = devlib.tile(y, (len(xl), 1))
423
- xt = devlib.tile(x, (len(yl), 1))
424
- kernc = devlib.exp(yt.T * xt)
428
+ x = np.array(xl)
429
+ yt = np.tile(y, (len(xl), 1))
430
+ xt = np.tile(x, (len(yl), 1))
431
+ kernc = np.exp(yt.T * xt)
425
432
 
426
433
  yl = list(range(-roff, nor - roff))
427
- y = devlib.array(yl)
434
+ y = np.array(yl)
428
435
  xl = list(range(-int(math.floor(nr / 2)), nr - int(math.floor(nr / 2))))
429
- x = devlib.ifftshift(devlib.array(xl))
430
- yt = devlib.tile(y, (len(xl), 1))
431
- xt = devlib.tile(x, (len(yl), 1))
432
- kernr = devlib.exp(yt * xt.T * (-2j * math.pi / (nr * usfac)))
436
+ x = np.fft.ifftshift(np.array(xl))
437
+ yt = np.tile(y, (len(xl), 1))
438
+ xt = np.tile(x, (len(yl), 1))
439
+ kernr = np.exp(yt * xt.T * (-2j * math.pi / (nr * usfac)))
433
440
 
434
- # return as device array
435
- return devlib.dot(devlib.dot(kernr.T, arr), kernc)
441
+ return np.dot(np.dot(kernr.T, arr), kernc)
436
442
 
437
443
 
438
444
  # supposedly this is faster than np.roll or scipy interpolation shift.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: cohere_core
3
- Version: 4.3
3
+ Version: 4.4.0
4
4
  Summary: cohere reconstruction tools
5
5
  Author-email: Barbara Frosik <bfrosik@anl.gov>, Ross Harder <rharder@anl.gov>
6
6
  License: Copyright © 2019, UChicago Argonne, LLC
@@ -22,6 +22,8 @@ License: Copyright © 2019, UChicago Argonne, LLC
22
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
23
  ***************************************************************************************************
24
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
25
27
  Classifier: Programming Language :: Python :: 3
26
28
  Classifier: Operating System :: OS Independent
27
29
  Requires-Python: >=3.11
@@ -15,7 +15,6 @@ src/cohere_core/data/__init__.py
15
15
  src/cohere_core/data/alien_tools.py
16
16
  src/cohere_core/data/standard_preprocess.py
17
17
  src/cohere_core/lib/__init__.py
18
- src/cohere_core/lib/aflib.py
19
18
  src/cohere_core/lib/check_libs.py
20
19
  src/cohere_core/lib/cohlib.py
21
20
  src/cohere_core/lib/cplib.py
@@ -1,393 +0,0 @@
1
- # #########################################################################
2
- # Copyright (c) , UChicago Argonne, LLC. All rights reserved. #
3
- # #
4
- # See LICENSE file. #
5
- # #########################################################################
6
-
7
- from cohere_core.lib.cohlib import cohlib
8
- import arrayfire as af
9
- import math
10
- import numpy as np
11
-
12
-
13
- class aflib(cohlib):
14
- def array(obj):
15
- print('not implemented')
16
-
17
- def dot(arr1, arr2):
18
- print('not implemented')
19
-
20
- def set_device(dev_id):
21
- af.device.set_device(dev_id)
22
-
23
- def set_backend(proc):
24
- af.set_backend(proc)
25
-
26
- def to_numpy(arr):
27
- return arr.to_ndarray().T
28
-
29
- def from_numpy(arr):
30
- return af.np_to_af_array(arr.T)
31
-
32
- def save(filename, arr):
33
- np.save(filename, arr.to_ndarray().T)
34
-
35
- def load(filename):
36
- arr = np.load(filename)
37
- return af.np_to_af_array(arr.T)
38
-
39
- def dtype(arr):
40
- return arr.dtype()
41
-
42
- def size(arr):
43
- return arr.elements()
44
-
45
- def hasnan(arr):
46
- return af.any_true(af.isnan(arr))
47
-
48
- def copy(arr):
49
- return arr.copy()
50
-
51
- def random(shape, **kwargs):
52
- import time
53
- import os
54
-
55
- dims = [None, None, None, None]
56
- for i in range(len(shape)):
57
- dims[i] = shape[i]
58
-
59
- eng = af.random.Random_Engine(engine_type=af.RANDOM_ENGINE.DEFAULT,
60
- seed=int(time.time() * 1000000) * os.getpid() + os.getpid())
61
- return af.random.randn(dims[0], dims[1], dims[2], dims[3], dtype=af.Dtype.c32, engine=eng)
62
-
63
- def fftshift(arr):
64
- raise NotImplementedError
65
-
66
- def ifftshift(arr):
67
- raise NotImplementedError
68
-
69
- def shift(arr, sft):
70
- raise NotImplementedError
71
-
72
- def fft(arr):
73
- raise NotImplementedError
74
-
75
- def ifft(arr):
76
- raise NotImplementedError
77
-
78
- def fftconvolve(arr1, arr2):
79
- return af.fft_convolve(arr1, arr2)
80
-
81
- def where(cond, x, y):
82
- return af.select(cond, x, y)
83
-
84
- def dims(arr):
85
- # get array dimensions
86
- return arr.dims()
87
-
88
- def absolute(arr):
89
- return af.abs(arr)
90
-
91
- def sqrt(arr):
92
- return af.sqrt(arr)
93
-
94
- def square(arr):
95
- return af.pow(arr, 2)
96
-
97
- def sum(arr, axis=None):
98
- return af.sum(arr)
99
-
100
- def real(arr):
101
- return af.real(arr)
102
-
103
- def imag(arr):
104
- return af.imag(arr)
105
-
106
- def amax(arr):
107
- return af.max(arr)
108
-
109
- def maximum(arr1, arr2):
110
- return af.select((arr1 > arr2), arr1, arr2)
111
-
112
- def argmax(arr, axis=None):
113
- val, idx = af.imax(arr, axis)
114
- return idx
115
-
116
- def unravel_index(indices, shape):
117
- raise NotImplementedError
118
-
119
- def ceil(arr):
120
- return af.ceil(arr)
121
-
122
- def fix(arr):
123
- return af.trunc(arr)
124
-
125
- def round(val):
126
- print('not implemented')
127
-
128
- def print(arr, **kwargs):
129
- af.display(arr)
130
-
131
- def angle(arr):
132
- return af.atan2(af.imag(arr), af.real(arr))
133
-
134
- def flip(arr, axis=None):
135
- if axis is None:
136
- raise NotImplementedError
137
- else:
138
- return af.flip(arr, axis)
139
-
140
- def tile(arr, rep):
141
- print('not implemented')
142
-
143
- def full(shape, fill_value, **kwargs):
144
- dims = [None, None, None, None]
145
- for i in range(len(shape)):
146
- dims[i] = shape[i]
147
- return af.constant(fill_value, dims[0], dims[1], dims[2], dims[3])
148
-
149
- def expand_dims(arr, axis):
150
- return arr
151
-
152
- def squeeze(arr):
153
- return arr
154
-
155
- def gaussian(shape, sigmas, **kwargs):
156
- raise NotImplementedError
157
-
158
- def gaussian_flter(shape, sigma, **kwargs):
159
- raise NotImplementedError
160
-
161
- def center_of_mass(inarr):
162
- arr = af.abs(inarr)
163
- normalizer = af.sum(arr)
164
- t_dims = list(arr.dims())
165
- mod_dims = [None, None, None, None]
166
- for i in range(len(t_dims)):
167
- mod_dims[i] = 1
168
- com = []
169
-
170
- for dim in range(len(t_dims)):
171
- # swap
172
- mod_dims[dim] = t_dims[dim]
173
- t_dims[dim] = 1
174
- grid = af.iota(mod_dims[0], mod_dims[1], mod_dims[2], mod_dims[3], tile_dims=t_dims)
175
- # print(grid)
176
- com.append(af.sum(grid * arr) / normalizer)
177
- # swap back
178
- t_dims[dim] = mod_dims[dim]
179
- mod_dims[dim] = 1
180
-
181
- return com
182
-
183
- def meshgrid(*xi):
184
- print('not implemented')
185
-
186
- def exp(arr):
187
- return af.exp(arr)
188
-
189
- def cong(arr):
190
- return af.conjg(arr)
191
-
192
- def save(file, arr):
193
- arr = af.Array(arr)
194
- nparr = arr.to_ndarray().T
195
- np.save(file, nparr)
196
-
197
-
198
- class aflib1(aflib):
199
- def fftshift(arr):
200
- return af.shift(arr, math.ceil(arr.dims()[0] / 2) - 1)
201
-
202
- def ifftshift(arr):
203
- return af.shift(arr, math.ceil(arr.dims()[0] / 2))
204
-
205
- def shift(arr, sft):
206
- return af.shift(arr, math.ceil(sft[0]))
207
-
208
- def fft(arr):
209
- return af.fft(arr)
210
-
211
- def ifft(arr):
212
- return af.ifft(arr)
213
-
214
- def unravel_index(indices, shape):
215
- return [indices]
216
-
217
- def flip(arr, axis=None):
218
- if axis is None:
219
- return af.flip(arr, 0)
220
- else:
221
- return af.flip(arr, axis)
222
-
223
- def gaussian(dims, sigmas, **kwargs):
224
- alpha = 1.0
225
- grid = af.constant(1.0, dims[0])
226
- multiplier = - 0.5 * alpha / pow(sigmas[0], 2)
227
- exponent = af.pow((af.range(dims[0], dim=0) - (dims[0] - 1) / 2.0), 2) * multiplier
228
- grid = grid * af.arith.exp(exponent)
229
- return grid / af.sum(grid)
230
-
231
- def gaussian_filter(arr, sigma, **kwargs):
232
- dims = arr.dims()
233
- sigmas = [dim / (2.0 * np.pi * sigma) for dim in dims]
234
- dist = aflib2.gaussian(dims, sigmas)
235
- arr_f = aflib1.ifftshift(af.fft(aflib1.ifftshift(arr)))
236
- filter = arr_f * dist
237
- filter = aflib1.ifftshift(af.ifft(aflib1.ifftshift(filter)))
238
- filter = af.real(filter)
239
- filter = af.select(filter >= 0, filter, 0.0)
240
- return filter
241
-
242
-
243
- class aflib2(aflib):
244
- def fftshift(arr):
245
- return af.shift(arr, math.ceil(arr.dims()[0] / 2) - 1, math.ceil(arr.dims()[1] / 2) - 1)
246
-
247
- def ifftshift(arr):
248
- return af.shift(arr, math.ceil(arr.dims()[0] / 2), math.ceil(arr.dims()[1] / 2))
249
-
250
- def shift(arr, sft):
251
- return af.shift(arr, math.ceil(sft[0]), math.ceil(sft[1]))
252
-
253
- def fft(arr):
254
- return af.fft2(arr)
255
-
256
- def ifft(arr):
257
- return af.ifft2(arr)
258
-
259
- def unravel_index(indices, shape):
260
- return [indices % shape[0], int(indices / shape[0] % shape[1])]
261
-
262
- def flip(arr, axis=None):
263
- if axis is None:
264
- return af.flip(af.flip(arr, 0), 1)
265
- else:
266
- return af.flip(arr, axis)
267
-
268
- def gaussian(dims, sigmas, **kwargs):
269
- alpha = 1.0
270
- grid = af.constant(1.0, dims[0], dims[1])
271
- for i in range(len(sigmas)):
272
- multiplier = - 0.5 * alpha / pow(sigmas[i], 2)
273
- exponent = af.pow((af.range(dims[0], dims[1], dim=i) - (dims[i] - 1) / 2.0), 2) * multiplier
274
- grid = grid * af.arith.exp(exponent)
275
- return grid / af.sum(grid)
276
-
277
- def gaussian_filter(arr, sigma, **kwargs):
278
- dims = arr.dims()
279
- sigmas = [dim / (2.0 * np.pi * sigma) for dim in dims]
280
- dist = aflib2.gaussian(dims, sigmas)
281
- arr_f = aflib2.ifftshift(af.fft2(aflib2.ifftshift(arr)))
282
- filter = arr_f * dist
283
- filter = aflib2.ifftshift(af.ifft2(aflib2.ifftshift(filter)))
284
- filter = af.real(filter)
285
- filter = af.select(filter >= 0, filter, 0.0)
286
- return filter
287
-
288
-
289
- class aflib3(aflib):
290
- def fftshift(arr):
291
- return af.shift(arr, math.ceil(arr.dims()[0] / 2) - 1, math.ceil(arr.dims()[1] / 2) - 1,
292
- math.ceil(arr.dims()[2] / 2) - 1)
293
-
294
- def ifftshift(arr):
295
- return af.shift(arr, math.ceil(arr.dims()[0] / 2), math.ceil(arr.dims()[1] / 2), math.ceil(arr.dims()[2] / 2))
296
-
297
- def shift(arr, sft):
298
- return af.shift(arr, math.ceil(sft[0]), math.ceil(sft[1]), math.ceil(sft[2]))
299
-
300
- def fft(arr):
301
- return af.fft3(arr)
302
-
303
- def ifft(arr):
304
- return af.ifft3(arr)
305
-
306
- def unravel_index(indices, shape):
307
- return [indices % shape[0], int(indices / shape[0] % shape[1]), int(indices / (shape[0] * shape[1]))]
308
-
309
- def flip(arr, axis=None):
310
- if axis is None:
311
- return af.flip(af.flip(af.flip(arr, 0), 1), 2)
312
- else:
313
- return af.flip(arr, axis)
314
-
315
- def gaussian(dims, sigmas, **kwargs):
316
- alpha = 1.0
317
- grid = af.constant(1.0, dims[0], dims[1], dims[2])
318
- for i in range(len(sigmas)):
319
- multiplier = - 0.5 * alpha / pow(sigmas[i], 2)
320
- exponent = af.pow((af.range(dims[0], dims[1], dims[2], dim=i) - (dims[i] - 1) / 2.0), 2) * multiplier
321
- grid = grid * af.arith.exp(exponent)
322
- return grid / af.sum(grid)
323
-
324
- def gaussian_filter(arr, sigma, **kwargs):
325
- dims = arr.dims()
326
- if type(sigma) == int or type(sigma) == float:
327
- sigmas = [dim / (2.0 * math.pi * sigma) for dim in dims]
328
- else:
329
- sigmas = sigma
330
-
331
- dist = aflib3.gaussian(dims, sigmas)
332
-
333
- arr_sum = af.sum(arr)
334
- arr_f = aflib3.ifftshift(aflib3.fft(aflib3.ifftshift(arr)))
335
- convag = arr_f * dist
336
- convag = aflib3.ifftshift(aflib3.ifft(aflib3.ifftshift(convag)))
337
- convag = af.real(convag)
338
- convag = aflib3.where(convag > 0, convag, 0.0)
339
- correction = arr_sum / af.sum(convag)
340
- convag *= correction
341
- return convag
342
-
343
- def diff(arr, axis=None, prepend=0):
344
- raise NotImplementedError
345
-
346
- def gradient(arr, dx=1):
347
- raise NotImplementedError
348
-
349
- def argmin(arr, axis=None):
350
- raise NotImplementedError
351
-
352
- def take_along_axis(a, indices, axis):
353
- raise NotImplementedError
354
-
355
- def moveaxis(arr, source, dest):
356
- raise NotImplementedError
357
-
358
- def lstsq(A, B):
359
- raise NotImplementedError
360
-
361
- def zeros(shape):
362
- raise NotImplementedError
363
-
364
- def indices(dims):
365
- raise NotImplementedError
366
-
367
- def concatenate(tup, axis=0):
368
- raise NotImplementedError
369
-
370
- def stack(tup):
371
- raise NotImplementedError
372
-
373
- def amin(arr):
374
- raise NotImplementedError
375
-
376
- def affine_transform(arr, matrix, order=3, offset=0):
377
- raise NotImplementedError
378
-
379
- def pad(arr, padding):
380
- raise NotImplementedError
381
-
382
- def histogram2d(meas, rec, n_bins=100, log=False):
383
- raise NotImplementedError
384
-
385
- def calc_nmi(hgram):
386
- raise NotImplementedError
387
-
388
- def calc_ehd(hgram):
389
- raise NotImplementedError
390
-
391
- def clean_default_mem():
392
- pass
393
-
File without changes
File without changes
File without changes