stemdiff 5.2.10__py3-none-any.whl → 5.2.12__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.
STEMDIFF/__init__.py CHANGED
@@ -30,7 +30,7 @@ STEMDIFF auxiliary package IDIFF and its modules:
30
30
  - idiff.ncore = noise correction/reduction
31
31
  - idiff.psf = estimate of PSF function
32
32
  '''
33
- __version__ = "5.2.10"
33
+ __version__ = "5.2.12"
34
34
 
35
35
 
36
36
  # Import modules of stemdiff package
STEMDIFF/dbase.py CHANGED
@@ -56,11 +56,11 @@ def calc_database(SDATA, DIFFIMAGES):
56
56
  # (the center must be determined for rescaled/upscaled array
57
57
  if DIFFIMAGES.ctype == 2:
58
58
  xc,yc = stemdiff.io.Arrays.find_center(
59
- stemdiff.io.Arrays.rescale(arr, R, order=3), # rescaled array
59
+ stemdiff.io.Arrays.rescale_fast(arr, R, inter=2), # rescaled array
60
60
  DIFFIMAGES.csquare*R, DIFFIMAGES.cintensity) # central region
61
61
  elif (DIFFIMAGES.ctype == 1) and (xc == None):
62
- xc,yc = stemdiff.io.Array.find_center(
63
- stemdiff.io.Arrays.rescale(arr, R, order=3), # rescaled array
62
+ xc,yc = stemdiff.io.Arrays.find_center(
63
+ stemdiff.io.Arrays.rescale_fast(arr, R, inter=2), # rescaled array
64
64
  DIFFIMAGES.csquare*R, DIFFIMAGES.cintensity) # central region
65
65
  elif (DIFFIMAGES.ctype == 0) and (xc == None):
66
66
  geometric_center = round(SDATA.detector.detector_size*R/2)
STEMDIFF/io.py CHANGED
@@ -50,6 +50,8 @@ import matplotlib.pyplot as plt
50
50
  from mpl_toolkits import axes_grid1 # to add nice colorbars
51
51
  from PIL import Image
52
52
  from skimage import transform, measure, morphology
53
+ from scipy.ndimage import shift
54
+ import cv2
53
55
 
54
56
 
55
57
  def set_plot_parameters(size=(12,9), dpi=75, fontsize=10, my_rcParams=None):
@@ -636,7 +638,114 @@ class Arrays:
636
638
  arr = arr/np.max(arr) * arr_max
637
639
  # Return the rescaled array.
638
640
  return(arr)
641
+
642
+ def rescale_fast(arr, R, inter=1):
643
+ '''
644
+ Rescale 2D numpy array (which represents an image).
645
+ Uses resize function from cv2, which is fater than skimage rescale.
646
+
647
+ Parameters
648
+ ----------
649
+ arr : 2D numpy array
650
+ Numpy array representing DAT-file/image.
651
+ R : integer
652
+ Rescale parameter: new_size_of the array = original_size * R
653
+ inter : integer
654
+ Interpolation mode:
655
+ * 0 = nearest
656
+ * 1 = linear
657
+ * 2 = cubic
658
+
659
+ Returns
660
+ -------
661
+ arr : 2D numpy array
662
+ The array has `new_size = original_size * R`.
663
+ '''
664
+ # Map inter to cv enum
665
+ inters = [
666
+ cv2.INTER_NEAREST,
667
+ cv2.INTER_LINEAR,
668
+ cv2.INTER_CUBIC
669
+ ]
670
+ # Keep original value of array maximum.
671
+ arr_max = np.max(arr)
672
+ # Rescale the array.
673
+ # dsize is required, (0, 0) means use fx and fy
674
+ arr = cv2.resize(arr, (0, 0), fx=R, fy=R, interpolation=inters[inter])
675
+ # Restore the original value of array maximum.
676
+ arr = arr/np.max(arr) * arr_max
677
+ # Avoid negative values
678
+ arr = np.clip(arr, 0, None)
679
+ # Return the rescaled array.
680
+ return arr
681
+
682
+ def zero_spatial_edges(arr, border_width=10):
683
+ '''
684
+ Zeros the edges of an array with shape (..., H, W).
685
+ This allows processing N images at once - shape (N, H, W).
686
+ Also works for a single image with shape (H, W).
687
+
688
+ Important - this operation happens inplace (the zeros are written
689
+ to the input array).
639
690
 
691
+ Parameters
692
+ ----------
693
+ arr : numpy array
694
+ Numpy array representing DAT-file/image.
695
+ border_width : int, optional, default is 10
696
+ Width of the
697
+
698
+ Returns
699
+ -------
700
+ numpy array
701
+ Array with zeroed edges.
702
+ '''
703
+ w = border_width
704
+
705
+ # Zero Top and Bottom
706
+ arr[..., :w, :] = 0 # first 'w' rows
707
+ arr[..., -w:, :] = 0 # last 'w' rows
708
+
709
+ # Zero Left and Right
710
+ arr[..., :, :w] = 0 # first 'w' columns
711
+ arr[..., :, -w:] = 0 # last 'w' columns
712
+
713
+ return arr
714
+
715
+ def recenter(arr, center_x, center_y):
716
+ '''
717
+ Recenters the image by shifting (center_x, center_y) to the array
718
+ center.
719
+ Empty edges are filled with zeros.
720
+
721
+ Parameters
722
+ ----------
723
+ arr : 2D numpy array
724
+ Numpy array representing DAT-file/image.
725
+ center_x : int
726
+ X coordinate of the center.
727
+ center_y : int
728
+ Y coordinate of the center.
729
+
730
+ Returns
731
+ -------
732
+ 2D numpy array
733
+ Centered array.
734
+ '''
735
+ h, w = arr.shape
736
+
737
+ # Calculate the required displacement
738
+ # shift_y = target_y - current_y
739
+ shift_y = (h // 2) - center_y
740
+ shift_x = (w // 2) - center_x
741
+
742
+ # mode='constant' fills the boundary with cval (default is 0.0)
743
+ # order=0 uses nearest-neighbor (keeps pixel values exact)
744
+ # order=1 uses bilinear interpolation (smoother, better for sub-pixel)
745
+ shifted_img = shift(arr, shift=[shift_x, shift_y], mode='constant',
746
+ cval=0, order=0)
747
+
748
+ return shifted_img
640
749
 
641
750
  def remove_edges(arr,rsize,xc,yc):
642
751
  '''
STEMDIFF/sum.py CHANGED
@@ -8,83 +8,158 @@ The summation of 4D-STEM datafiles to create one 2D powder diffraction file.
8
8
 
9
9
  To perform the summation, we just call function sum_datafiles:
10
10
 
11
- * serial : stemdiff.sum.sum_datafiles(SDATA, DIFFIMAGES, df, deconv, ...)
12
- * parallel : stemdiff.summ.sum_datafiles(SDATA, DIFFIMAGES, df, deconv, ...)
11
+ * serial : stemdiff.sum.sum_datafiles(SDATA, DIFFIMAGES, df, ...)
12
+ * parallel : stemdiff.summ.sum_datafiles(SDATA, DIFFIMAGES, df, ...)
13
13
 
14
14
  The initial arguments are:
15
15
 
16
16
  * SDATA = stemdiff.gvars.SourceData object = description of source data
17
17
  * DIFFIMAGES = stemdiff.gvars.DiffImages object = description of diffractograms
18
- * df = pre-calculated database of datafiles/diffratograms to sum
18
+ * df_sum = pre-calculated database of datafiles/diffratograms to sum
19
19
 
20
- Key argument is deconv, which determines the processing type:
21
-
22
- * deconv=0 = sum *without* deconvolution
23
- * deconv=1 = R-L deconvolution with global PSF from low-diffraction datafiles
24
- * deconv=2 = subtract background + R-L deconvolution with PSF from the center
20
+ Key arguments are `deconv` and `bkg`, which determine the processing type.
25
21
  '''
26
22
 
27
23
 
28
24
  import numpy as np
29
25
  import stemdiff.io
30
- import stemdiff.dbase
31
26
  import idiff
27
+ import ediff.center
32
28
  from skimage import restoration
33
29
  import tqdm
34
30
  import sys
35
31
 
36
32
 
37
- def sum_datafiles(SDATA, DIFFIMAGES, df, deconv=0, psf=None, iterate=10):
33
+ def sum_datafiles(SDATA, DIFFIMAGES, df_sum, df_psf=None, bkg=0, bkgp={},
34
+ deconv=0, deconvp={"num_iter": 10}, peaks=0, peaksp={},
35
+ center=None, centerp={}):
38
36
  """
39
- Sum datafiles from a 4D-STEM dataset to get 2D powder diffractogram.
40
-
41
- Parameters
42
- ----------
43
- SDATA : stemdiff.gvars.SourceData object
44
- The object describes source data (detector, data_dir, filenames).
45
- DIFFIMAGES : stemdiff.gvars.DiffImages object
46
- Object describing the diffraction images/patterns.
47
- df : pandas.DataFrame object
48
- Pre-calculated atabase with datafiles to be summed.
49
- Each row of the database contains
50
- [filename, xc, yc, MaxInt, NumPeaks, S].
51
- deconv : int, optional, default is 0
52
- Deconvolution type:
53
- 0 = no deconvolution,
54
- 1 = deconvolution based on external PSF,
55
- 2 = deconvolution based on PSF from central region,
56
- psf : 2D-numpy array or None, optional, default is None
57
- Array representing 2D-PSF function.
58
- Relevant only for deconv = 1.
59
- iterate : integer, optional, default is 10
60
- Number of iterations during the deconvolution.
61
-
62
- Returns
63
- -------
64
- final_arr : 2D numpy array
65
- The array is a sum of datafiles;
66
- if the datafiles are pre-filtered,
67
- we get the sum of filtered datafiles.
68
- Additional arguments determin the (optional) type of deconvolution.
69
-
70
- Technical notes
71
- ---------------
72
- * This function works as a signpost.
73
- * It reads the summation parameters and calls a more specific summation
74
- functions (which aren NOT called directly by the end-user).
75
- * It employs progress bar, handles possible exceptions,
76
- and returns the final array (= post-processed and normalized array).
37
+ Sum datafiles from a 4D-STEM dataset to get 2D powder diffractogram.
38
+
39
+ Serial (single-threaded) version -- processes datafiles one at a time
40
+ in a plain loop. Use this when a stable, easy-to-debug/step-through
41
+ reference implementation is preferred over speed. For the same
42
+ functionality running in parallel across multiple threads, see the
43
+ corresponding function in `stemdiff.summ`.
44
+
45
+ Parameters
46
+ ----------
47
+ SDATA : stemdiff.gvars.SourceData object
48
+ The object describes source data (detector, data_dir, filenames).
49
+
50
+ DIFFIMAGES : stemdiff.gvars.DiffImages object
51
+ Object describing the diffraction images/patterns.
52
+
53
+ df_sum : pandas.DataFrame object
54
+ Pre-calculated database with datafiles to be summed.
55
+ Each row of the database contains
56
+ ['DatafileName', 'Xcenter', 'Ycenter', 'MaxInt', 'Peaks', 'S'].
57
+
58
+ df_psf : pandas.DataFrame object, optional
59
+ Database with datafiles to calculate a single, shared PSF (same
60
+ column structure as df_sum). If None and deconv > 0, a PSF is
61
+ taken from deconvp['psf'] if given there, or otherwise computed
62
+ independently for each datafile from its own central region
63
+ (see the priority order under `deconv` below).
64
+
65
+ bkg : int, optional, default is 0
66
+ Background subtraction method, from `idiff.bkg2d`:
67
+ * 0 = no background subtraction
68
+ * 1 = rolling ball -- bkgp: {radius=20}
69
+ * 2 = tophat -- bkgp: {thr=40, area_size=5, radius=2}
70
+ * 3 = gaussian -- bkgp: {thr=20, area_size=5, sigma=2, normalize=False}
71
+ * 4 = neural network -- bkgp: {path} (required: path to an .onnx
72
+ model file; any other kwargs are passed through to
73
+ `onnxruntime.InferenceSession`)
74
+
75
+ bkgp : dict, optional, default is {}
76
+ Parameters for the chosen background-subtraction method -- see
77
+ the per-method breakdown under `bkg` above. Passed as **kwargs
78
+ directly to the corresponding `idiff.bkg2d` function/class.
79
+
80
+ deconv : int, optional, default is 0
81
+ Deconvolution method:
82
+ * 0 = no deconvolution
83
+ * 1 = Richardson-Lucy from skimage
84
+ * 2 = Richardson-Lucy from idiff -- deconvp: {num_iter=30, cuda=False}
85
+ * 3 = Richardson-Lucy from idiff with Tikhonov regularization
86
+ * 4 = Richardson-Lucy from idiff with L1 regularization
87
+
88
+ Which PSF is used is determined by this priority order:
89
+ 1. `deconvp['psf']` -- used directly (after normalization) if given
90
+ 2. `df_psf` -- used to calculate one shared PSF for every datafile,
91
+ if given
92
+ 3. otherwise -- the central region of each individual datafile
93
+ (after background subtraction, before deconvolution) is used
94
+ as that datafile's own PSF
95
+
96
+ deconvp : dict, optional, default is {"num_iter": 10}
97
+ Parameters for the chosen deconvolution method -- see `deconv`
98
+ above. `num_iter` controls iteration count for all Richardson-Lucy
99
+ variants; `psf`, if supplied here, takes priority as described above.
100
+
101
+ peaks : int, optional, default is 0
102
+ Run peak-detection on the processed pattern; every detected peak
103
+ is replaced with a single pixel carrying the summed intensity of
104
+ that peak.
105
+ * 0 = no peak detection
106
+ * 1 = `idiff.peaks.run_regions` -- peaksp: {threshold=1}
107
+ * 2 = `idiff.peaks.run_log` -- peaksp: {downsample_factor=4,
108
+ threshold_factor=3.5, peak_min_sigma=6, ...}
109
+ * 3 = `idiff.peaks.run_doh` -- peaksp: {downsample_factor=4,
110
+ threshold_factor=3.5, peak_min_sigma=6, ...}
111
+ * 4 = `idiff.peaks.run_pcbr` -- peaksp: {sigma=3.0,
112
+ lambda_thresh=0.5, response_thresh_rel=0.1, ...}
113
+
114
+ `run_regions` or `run_log` are recommended.
115
+
116
+ peaksp : dict, optional, default is {}
117
+ Parameters for the chosen peak-detection method -- see `peaks` above.
118
+
119
+ center : str or None, optional, default is None
120
+ Center-detection method, re-run independently for each datafile.
121
+ If None, use the (Xcenter, Ycenter) already stored for that file
122
+ in df_sum instead of re-detecting it. The special value
123
+ `"intensity"` routes to `ediff.center.IntensityCenter` (a
124
+ lightweight intensity-centroid method); any other string is
125
+ passed as the `detection` argument to the more general
126
+ `ediff.center.CenterLocator`.
127
+
128
+ centerp : dict, optional, default is {}
129
+ Parameters for the chosen center-detection method -- passed as
130
+ **kwargs to `IntensityCenter.center_of_intensity` (if
131
+ center="intensity") or to `CenterLocator` (otherwise).
132
+
133
+ Returns
134
+ -------
135
+ arr : 2D numpy array, dtype uint16
136
+ Sum of the (optionally background-subtracted, deconvolved,
137
+ peak-filtered) datafiles, normalized by the number of datafiles
138
+ summed and rounded to the nearest integer (see
139
+ `sum_postprocess`). Shape is (imgsize*R, imgsize*R), where R is
140
+ SDATA.detector.upscale -- i.e. the *upscaled* resolution, not
141
+ DIFFIMAGES.imgsize itself.
77
142
  """
78
143
 
79
144
  # (1) Prepare variables for summation
80
145
  R = SDATA.detector.upscale
81
146
  img_size = DIFFIMAGES.imgsize
82
- datafiles = [datafile[1] for datafile in df.iterrows()]
147
+ datafiles = [datafile[1] for datafile in df_sum.iterrows()]
83
148
  sum_arr = np.zeros((img_size * R, img_size * R), dtype=np.float32)
84
149
 
150
+ if bkg == 4:
151
+ nn = idiff.bkg2d.NeuralNetwork(**bkgp)
152
+ else:
153
+ nn = None
154
+
155
+ if df_psf is not None and "psf" not in deconvp:
156
+ psf = idiff.psf.PSFtype1.get_psf(SDATA, DIFFIMAGES, df_psf)
157
+ deconvp["psf"] = psf
158
+
85
159
  # (2) Prepare variables for tqdm
86
160
  # (to create a single progress bar for the entire process
87
161
  total_tasks = len(datafiles)
162
+ stderr_original = sys.stderr
88
163
  sys.stderr = sys.stdout
89
164
 
90
165
  # (3) Run summations
@@ -94,266 +169,231 @@ def sum_datafiles(SDATA, DIFFIMAGES, df, deconv=0, psf=None, iterate=10):
94
169
  with tqdm.tqdm(total=total_tasks, desc="Processing ") as pbar:
95
170
  try:
96
171
  # Process each image in the database
97
- for index, datafile in df.iterrows():
98
- # Deconv0 => sum datafiles without deconvolution
99
- if deconv == 0:
100
- sum_arr += dfile_without_deconvolution(
101
- SDATA, DIFFIMAGES, datafile)
102
- # Deconv1 => sum datafiles with DeconvType1
103
- elif deconv == 1:
104
- sum_arr += dfile_with_deconvolution_type1(
105
- SDATA, DIFFIMAGES, datafile, psf, iterate)
106
- # Deconv2 => sum datafiles with DeconvType2
107
- elif deconv == 2:
108
- sum_arr += dfile_with_deconvolution_type2(
109
- SDATA, DIFFIMAGES, datafile, iterate)
172
+ for index, datafile in df_sum.iterrows():
173
+ sum_arr += prepare_dfile(SDATA, DIFFIMAGES, datafile, bkg,
174
+ bkgp, deconv, deconvp, peaks, peaksp,
175
+ nn, center, centerp)
176
+
110
177
  # Update the progress bar for each processed image
111
178
  pbar.update(1)
112
179
  except Exception as e:
113
180
  print(f"Error processing a task: {str(e)}")
181
+
182
+ sys.stderr = stderr_original
114
183
 
115
184
  # (4) Move to the next line after the progress bar is complete
116
185
  print('')
117
186
 
118
187
  # (5) Post-process the summation and return the result
119
- return sum_postprocess(sum_arr, len(df))
188
+ return sum_postprocess(sum_arr, len(df_sum))
120
189
 
121
190
 
122
191
  def sum_postprocess(sum_of_arrays, n):
123
192
  """
124
193
  Normalize and convert the summed array to 16-bit unsigned integers.
125
-
194
+
126
195
  Parameters
127
196
  ----------
128
- sum_of_arrays : np.array
129
- Sum of the arrays -
130
- usually from stemdiff.sum.sum_datafiles function.
197
+ sum_of_arrays : np.array, dtype float32
198
+ Sum of the arrays -- usually from `stemdiff.sum.sum_datafiles`
199
+ (its running `sum_arr` accumulator, before normalization).
200
+
131
201
  n : int
132
- Number of summed arrays -
133
- usually from stemdiff.sum.sum_datafiles function.
134
-
202
+ Number of arrays the sum should be normalized by -- usually
203
+ `len(df_sum)`, the number of datafiles requested. Note this is
204
+ the *requested* count, not necessarily the number that actually
205
+ succeeded and were added to `sum_of_arrays` (see the technical
206
+ note in `sum_datafiles`).
207
+
135
208
  Returns
136
209
  -------
137
- arr : np.array
138
- Array representing final summation.
139
- The array is normalized and converted to unsigned 16bit integers.
210
+ arr : np.array, dtype uint16
211
+ `sum_of_arrays / n`, rounded to the nearest integer and cast to
212
+ uint16. Same shape as `sum_of_arrays`.
140
213
  """
141
214
  arr = np.round(sum_of_arrays/n).astype(np.uint16)
142
215
  return(arr)
143
216
 
144
217
 
145
- def dfile_without_deconvolution(SDATA, DIFFIMAGES, datafile):
146
- """
147
- Prepare datafile for summation without deconvolution (deconv=0).
148
-
149
- Parameters
150
- ----------
151
- SDATA : stemdiff.gvars.SourceData object
152
- The object describing source data (detector, data_dir, filenames).
153
- DIFFIMAGES : stemdiff.gvars.DiffImages object
154
- The bject describing the diffraction images/patterns.
155
- datafile : one row from the prepared database of datafiles
156
- The database of datafiles is created
157
- in stemdiff.dbase.calc_database function.
158
- Each row of the database contains
159
- [filename, xc, yc, MaxInt, NumPeaks, S].
160
-
161
- Returns
162
- -------
163
- arr : 2D numpy array
164
- The datafile in the form of the array,
165
- which is ready for summation (with DeconvType0 => see Notes below).
166
-
167
- Notes
168
- -----
169
- * The parameters are transferred from the `sum_datafiles` function.
170
- * DeconvType0 = no deconvolution,
171
- just summation of the prepared datafiles (upscaled, centered...).
218
+ def prepare_dfile(SDATA, DIFFIMAGES, datafile, bkg, bkgp, deconv, deconvp,
219
+ peaks, peaksp, nn, center_detection, centerp):
172
220
  """
173
-
174
- # (0) Prepare variables
175
- R = SDATA.detector.upscale
176
- img_size = DIFFIMAGES.imgsize
177
-
178
- # (1) Read datafile
179
- datafile_name = SDATA.data_dir.joinpath(datafile.DatafileName)
180
- arr = stemdiff.io.Datafiles.read(SDATA, datafile_name)
181
-
182
- # (2) Rescale/upscale datafile and THEN remove border region
183
- # (a) upscale datafile
184
- arr = stemdiff.io.Arrays.rescale(arr, R, order=3)
185
- # (b) get the accurate center of the upscaled datafile
186
- # (the center coordinates for each datafile are saved in the database
187
- # (note: our datafile is one row from the database => we know the coords!
188
- xc,yc = (round(datafile.Xcenter),round(datafile.Ycenter))
189
- # (c) finally, the borders can be removed with respect to the center
190
- arr = stemdiff.io.Arrays.remove_edges(arr,img_size*R,xc,yc)
191
- # (Important technical notes:
192
- # (* This 3-step procedure is necessary to center the images precisely.
193
- # ( The accurate centers from upscaled images are saved in database.
194
- # ( The centers from original/non-upscaled datafiles => wrong results.
195
- # (* Some border region should ALWAYS be cut, for two reasons:
196
- # ( (i) weak/zero diffractions at edges and (ii) detector edge artifacts
197
-
198
- # (3) Return the datafile as an array that is ready for summation
199
- return(arr)
221
+ Read, process, and center a single datafile, ready for summation.
200
222
 
201
-
202
- def dfile_with_deconvolution_type1(SDATA, DIFFIMAGES, datafile, psf, iterate):
203
- """
204
- Prepare datafile for summation with deconvolution type1 (deconv=1).
223
+ Not intended to be called directly -- use `sum_datafiles`, which
224
+ calls this once per datafile and passes all of these parameters
225
+ through from its own same-named arguments.
205
226
 
206
227
  Parameters
207
228
  ----------
208
229
  SDATA : stemdiff.gvars.SourceData object
209
230
  The object describing source data (detector, data_dir, filenames).
231
+
210
232
  DIFFIMAGES : stemdiff.gvars.DiffImages object
211
- The bject describing the diffraction images/patterns.
233
+ The object describing the diffraction images/patterns.
234
+
212
235
  datafile : one row from the prepared database of datafiles
213
- The database of datafiles is created
214
- in stemdiff.dbase.calc_database function.
215
- Each row of the database contains
216
- [filename, xc, yc, MaxInt, NumPeaks, S].
217
- psf : 2D-numpy array
218
- Array representing the 2D-PSF function.
219
- iterate : int
220
- Number of iterations during the deconvolution.
236
+ The database of datafiles is created in
237
+ `stemdiff.dbase.calc_database`. Each row contains
238
+ ['DatafileName', 'Xcenter', 'Ycenter', 'MaxInt', 'Peaks', 'S'].
221
239
 
222
- Returns
223
- -------
224
- arr : 2D numpy array
225
- The datafile in the form of the array,
226
- which is ready for summation (with DeconvType1 => see Notes below).
227
-
228
- Notes
229
- -----
230
- * The parameters are transferred from the `sum_datafiles` function.
231
- * DeconvType1 = Richardson-Lucy deconvolution using PSFtype1.
232
- * PSFtype1 = 2D-PSF estimated from files with negligible diffractions.
233
- """
234
-
235
- # (0) Prepare variables
236
- R = SDATA.detector.upscale
237
- img_size = DIFFIMAGES.imgsize
238
-
239
- # (1) Read datafile
240
- datafile_name = SDATA.data_dir.joinpath(datafile.DatafileName)
241
- arr = stemdiff.io.Datafiles.read(SDATA, datafile_name)
240
+ bkg, bkgp : int, dict
241
+ Background-subtraction method and its parameters -- see
242
+ `sum_datafiles` for the full per-method breakdown.
242
243
 
243
- # (2) Rescale/upscale datafile and THEN remove border region
244
- # (a) upscale datafile
245
- arr = stemdiff.io.Arrays.rescale(arr, R, order=3)
246
- # (b) get the accurate center of the upscaled datafile
247
- # (the center coordinates for each datafile are saved in the database
248
- # (note: our datafile is one row from the database => we know the coords!
249
- xc,yc = (round(datafile.Xcenter), round(datafile.Ycenter))
250
- # (c) finally, the borders can be removed with respect to the center
251
- arr = stemdiff.io.Arrays.remove_edges(arr, img_size*R,xc,yc)
252
- # (Important technical notes:
253
- # (* This 3-step procedure is necessary to center the images precisely.
254
- # ( The accurate centers from upscaled images are saved in database.
255
- # ( The centers from original/non-upscaled datafiles => wrong results.
256
- # (* Some border region should ALWAYS be cut, for two reasons:
257
- # ( (i) weak/zero diffractions at edges and (ii) detector edge artifacts
258
-
259
- # (3) Deconvolution: Richardson-Lucy using a global PSF
260
- # (a) save np.max, normalize
261
- # (reason: deconvolution algorithm requires normalized arrays...
262
- # (...and we save original max.intensity to re-normalize the result
263
- norm_const = np.max(arr)
264
- arr_norm = arr/np.max(arr)
265
- psf_norm = psf/np.max(psf)
266
- # (b) perform the deconvolution
267
- arr_deconv = restoration.richardson_lucy(
268
- arr_norm, psf_norm, num_iter=iterate)
269
- # (c) restore original range of intensities = re-normalize
270
- arr = arr_deconv * norm_const
271
-
272
- # (4) Return the deconvolved datafile
273
- # as an array that is ready for summation
274
- return arr
244
+ deconv, deconvp : int, dict
245
+ Deconvolution method and its parameters, and the PSF-selection
246
+ priority order -- see `sum_datafiles` for details. Note:
247
+ `deconvp` is copied internally before use, so the caller's own
248
+ dict (and any shared `psf` entry in it) is not mutated between
249
+ calls for different datafiles.
275
250
 
251
+ peaks, peaksp : int, dict
252
+ Peak-detection method and its parameters -- see `sum_datafiles`
253
+ for the full per-method breakdown.
276
254
 
277
- def dfile_with_deconvolution_type2(SDATA, DIFFIMAGES, datafile, iterate):
278
- """
279
- Prepare datafile for summation with deconvolution type2 (deconv=2).
255
+ nn : idiff.bkg2d.NeuralNetwork or None
256
+ Pre-initialized neural network background-subtraction session,
257
+ already loaded once by the caller (`sum_datafiles`) and reused
258
+ across every datafile -- avoids reloading the ONNX model on
259
+ every single call. Required (non-None) if bkg == 4; ignored
260
+ otherwise.
280
261
 
281
- Parameters
282
- ----------
283
- SDATA : stemdiff.gvars.SourceData object
284
- The object describing source data (detector, data_dir, filenames).
285
- DIFFIMAGES : stemdiff.gvars.DiffImages object
286
- The bject describing the diffraction images/patterns.
287
- datafile : one row from the prepared database of datafiles
288
- The database of datafiles is created
289
- in stemdiff.dbase.calc_database function.
290
- Each row of the database contains
291
- [filename, xc, yc, MaxInt, NumPeaks, S].
292
- iterate : int
293
- Number of iterations during the deconvolution.
262
+ center_detection : str or None
263
+ Center-detection method for this datafile. If None, use the
264
+ already-stored (Xcenter, Ycenter) from `datafile` directly
265
+ instead of re-detecting. `"intensity"` routes to
266
+ `ediff.center.IntensityCenter`; any other string is passed as
267
+ the `detection` argument to `ediff.center.CenterLocator`.
268
+
269
+ centerp : dict
270
+ Parameters for the chosen center-detection method -- passed as
271
+ **kwargs to whichever of the two center-detection paths above
272
+ is used.
294
273
 
295
274
  Returns
296
275
  -------
297
276
  arr : 2D numpy array
298
- The datafile in the form of the array,
299
- which is ready for summation (with DeconvType1 => see Notes below).
300
-
277
+ The single datafile, upscaled, background-subtracted/
278
+ deconvolved/peak-filtered as requested, and recentered -- ready
279
+ to be added directly into the running sum.
280
+
301
281
  Notes
302
282
  -----
303
- * The parameters are transferred from the `sum_datafiles` function.
304
- * DeconvType2 = Richardson-Lucy deconvolution
305
- using PSFtype2 + simple background subtraction.
306
- * PSFtype2 = 2D-PSF estimated from central region of the datafile
307
- AFTER background subtraction.
283
+ * Processing order: read -> background subtraction -> upscale ->
284
+ zero border edges -> determine center -> recenter -> (build PSF
285
+ if needed) -> deconvolution -> peak detection.
286
+ * Background subtraction happens *before* upscaling/recentering,
287
+ but deconvolution's own PSF (when derived from the datafile's own
288
+ central region, i.e. PSF priority option 3) is taken *after*
289
+ recentering -- so that per-datafile PSF is always centered
290
+ correctly regardless of where the diffraction pattern originally
291
+ sat in the raw frame.
292
+ * Centers are always taken from the *upscaled* image coordinates
293
+ (never the original/non-upscaled datafile) -- using centers
294
+ computed on non-upscaled data here would recenter incorrectly.
295
+ * Some border region is always zeroed after upscaling, for two
296
+ reasons: (i) weak/zero diffraction signal at the frame edges, and
297
+ (ii) detector edge artifacts.
308
298
  """
309
-
299
+
310
300
  # (0) Prepare variables
311
301
  R = SDATA.detector.upscale
312
302
  img_size = DIFFIMAGES.imgsize
313
303
  psf_size = DIFFIMAGES.psfsize
314
-
304
+
315
305
  # (1) Read datafile
316
306
  datafile_name = SDATA.data_dir.joinpath(datafile.DatafileName)
317
- arr = stemdiff.io.Datafiles.read(SDATA, datafile_name)
307
+ arr = stemdiff.io.Datafiles.read(SDATA, datafile_name)
308
+
309
+ # (2) Remove background
310
+ if bkg == 1:
311
+ arr = idiff.bkg2d.rolling_ball(arr, **bkgp)
312
+ elif bkg == 2:
313
+ arr = idiff.bkg2d.tophat(arr, **bkgp)
314
+ elif bkg == 3:
315
+ arr = idiff.bkg2d.gaussian(arr, **bkgp)
316
+ elif bkg == 4:
317
+ arr = nn.predict(arr)
318
318
 
319
- # (2) Rescale/upscale datafile and THEN remove border region
319
+ # (3) Rescale/upscale datafile and THEN remove border region
320
320
  # (a) upscale datafile
321
- arr = stemdiff.io.Arrays.rescale(arr, R, order=3)
321
+ arr = stemdiff.io.Arrays.rescale_fast(arr, R, inter=2)
322
+ arr = stemdiff.io.Arrays.zero_spatial_edges(arr, border_width=10)
322
323
  # (b) get the accurate center of the upscaled datafile
323
324
  # (the center coordinates for each datafile are saved in the database
324
325
  # (note: our datafile is one row from the database => we know the coords!
325
- xc,yc = (round(datafile.Xcenter),round(datafile.Ycenter))
326
- # (c) finally, the borders can be removed with respect to the center
327
- arr = stemdiff.io.Arrays.remove_edges(arr,img_size*R,xc,yc)
326
+ # optionally, if user requests, run the provided center detection
327
+ if center_detection == None:
328
+ xc, yc = (round(datafile.Xcenter),round(datafile.Ycenter))
329
+ elif center_detection == "intensity":
330
+ center_locator = ediff.center.IntensityCenter()
331
+ xc, yc = center_locator.center_of_intensity(arr, **centerp)
332
+ xc, yc = round(xc), round(yc)
333
+ else:
334
+ center = ediff.center.CenterLocator(
335
+ arr, center_detection, final_print=False, **centerp)
336
+ xc, yc = round(center.x), round(center.y)
337
+ # (c) finally, recenter the image and zero the edges
338
+ arr = stemdiff.io.Arrays.recenter(arr, xc, yc)
328
339
  # (Important technical notes:
329
340
  # (* This 3-step procedure is necessary to center the images precisely.
330
341
  # ( The accurate centers from upscaled images are saved in database.
331
342
  # ( The centers from original/non-upscaled datafiles => wrong results.
332
343
  # (* Some border region should ALWAYS be cut, for two reasons:
333
344
  # ( (i) weak/zero diffractions at edges and (ii) detector edge artifacts
334
-
335
- # (3) Remove background
336
- arr = idiff.bcorr.rolling_ball(arr, radius=20)
337
-
338
- # (4) Prepare PSF from the center of given array
345
+
346
+ # (4) Prepare PSF from the center of given array, if not given as parameter
339
347
  # (recommended parameters:
340
348
  # (psf_size => to be specified in the calling script ~ 30
341
349
  # (circular => always True - square PSF causes certain artifacts
342
- psf = idiff.psf.PSFtype2.get_psf(arr, psf_size, circular=True)
350
+ if deconv > 0 and "psf" not in deconvp:
351
+ psf = idiff.psf.PSFtype2.get_psf(arr, psf_size, circular=True)
352
+ elif deconv > 0:
353
+ psf = deconvp["psf"] # get psf for the next step
343
354
 
355
+
344
356
  # (5) Deconvolution
345
- # (a) save np.max, normalize
346
- # (reason: deconvolution algorithm requires normalized arrays...
347
- # (...and we save original max.intensity to re-normalize the result
348
- norm_const = np.max(arr)
349
- arr_norm = arr/np.max(arr)
350
- psf_norm = psf/np.max(psf)
357
+ if deconv > 0:
358
+ # (a) save np.max, normalize
359
+ # (reason: deconvolution algorithm requires normalized arrays...
360
+ # (...and we save original max.intensity to re-normalize the result
361
+ norm_const = np.max(arr)
362
+ arr_norm = arr/norm_const
363
+
364
+ # PSF sould sum to 1
365
+ psf_norm = psf/np.sum(psf)
366
+
367
+ deconvp = deconvp.copy() # avoid alteration for next iterations
368
+ deconvp.pop("psf", None) # remove psf from deconvp
369
+
351
370
  # (b) perform the deconvolution
352
- arr_deconv = restoration.richardson_lucy(
353
- arr_norm, psf_norm, num_iter=iterate)
371
+ if deconv == 1:
372
+ deconvp["psf"] = psf_norm # add normalized psf to the arguments
373
+ arr_deconv = restoration.richardson_lucy(arr_norm, **deconvp)
374
+ elif deconv == 2:
375
+ rl = idiff.deconv.RichardsonLucy(**deconvp)
376
+ arr_deconv = rl.deconvRL(arr_norm, psf_norm)
377
+ elif deconv == 3:
378
+ rl = idiff.deconv.RichardsonLucy(**deconvp)
379
+ arr_deconv = rl.deconvRLTM(arr_norm, psf_norm)
380
+ elif deconv == 4:
381
+ rl = idiff.deconv.RichardsonLucy(**deconvp)
382
+ arr_deconv = rl.deconvRLTV(arr_norm, psf_norm)
383
+
354
384
  # (c) restore original range of intensities = re-normalize
355
- arr = arr_deconv * norm_const
385
+ if deconv > 0:
386
+ arr = arr_deconv * norm_const
356
387
 
357
- # (6) Return the deconvolved datafile
358
- # as an array that is ready for summation
359
- return(arr)
388
+ # (6) Detect peaks
389
+ if peaks == 1:
390
+ arr = idiff.peaks.run_regions(arr, **peaksp)
391
+ elif peaks == 2:
392
+ arr = idiff.peaks.run_log(arr, **peaksp)
393
+ elif peaks == 3:
394
+ arr = idiff.peaks.run_doh(arr, **peaksp)
395
+ elif peaks == 4:
396
+ arr = idiff.peaks.run_pcbr(arr, **peaksp)
397
+
398
+ # (7) Return the datafile as an array that is ready for summation
399
+ return arr
STEMDIFF/summ.py CHANGED
@@ -4,7 +4,7 @@ Module: stemdiff.summ
4
4
  The summation of 4D-STEM datafiles to create one 2D powder diffraction file.
5
5
 
6
6
  * The summation runs on all available cores (parallel processing).
7
- * This module takes functions from semdiff.sum, but runs them parallelly.
7
+ * This module takes functions from semdiff.sum, but runs them in parallel.
8
8
 
9
9
  The key function of the module (for a user) = stemdiff.summ.sum_datafiles:
10
10
 
@@ -13,15 +13,14 @@ The key function of the module (for a user) = stemdiff.summ.sum_datafiles:
13
13
 
14
14
  How it works:
15
15
 
16
- * This module contains just two functions:
17
- - `summ.sum_datafiles` - wrapper for the next function
18
- - `summ.multicore_sum` - runs the summation on multiple cores
16
+ * This module contains just one function:
17
+ - `summ.sum_datafiles` - runs the summation on multiple cores
19
18
  * The rest is done with the functions of sister module *stemdiff.sum*.
20
19
  - i.e. the summ.multicore_sum calls functions from stemdiff.sum
21
20
  - but the functions run within this module, using multiple cores
22
21
  * Summary:
23
22
  - `sum.sum_datafiles` - runs on a single core (docs in stemdiff.sum)
24
- - `summ.sum_datafiles` - runs on multiple cores, aguments are identical
23
+ - `summ.sum_datafiles` - runs on multiple cores, arguments are identical
25
24
  '''
26
25
 
27
26
  import os
@@ -29,138 +28,135 @@ import sys
29
28
  import tqdm
30
29
  import stemdiff.sum
31
30
  import concurrent.futures as future
31
+ import idiff
32
+ import numpy as np
32
33
 
33
-
34
- def sum_datafiles(
35
- SDATA, DIFFIMAGES,
36
- df, deconv=0, psf=None, iterate=10):
34
+ def sum_datafiles(SDATA, DIFFIMAGES, df_sum, df_psf=None, bkg=0, bkgp={},
35
+ deconv=0, deconvp={"num_iter": 10}, peaks=0, peaksp={},
36
+ center=None, centerp={}):
37
37
  '''
38
38
  Sum datafiles from a 4D-STEM dataset to get 2D powder diffractogram.
39
-
39
+
40
40
  Parameters
41
41
  ----------
42
42
  SDATA : stemdiff.gvars.SourceData object
43
43
  The object describes source data (detector, data_dir, filenames).
44
+
44
45
  DIFFIMAGES : stemdiff.gvars.DiffImages object
45
46
  Object describing the diffraction images/patterns.
46
- df : pandas.DataFrame object
47
- Database with datafile names and characteristics.
47
+
48
+ df_sum : pandas.DataFrame object
49
+ Pre-calculated database with datafiles to be summed.
50
+ Each row of the database contains
51
+ ['DatafileName', 'Xcenter', 'Ycenter', 'MaxInt', 'Peaks', 'S'].
52
+
53
+ df_psf : pandas.DataFrame object, optional
54
+ Database with datafiles to calculate PSF (same column structure as
55
+ df_sum). If None, PSF is used from deconvp['psf'] if given, or
56
+ otherwise calculated independently from the central region of each
57
+ individual datafile (see the priority order under `deconv` below).
58
+
59
+ bkg : int, optional, default is 0
60
+ Background subtraction method, from `idiff.bkg2d`:
61
+ * 0 = no background subtraction
62
+ * 1 = rolling ball -- bkgp: {radius=20}
63
+ * 2 = tophat -- bkgp: {thr=40, area_size=5, radius=2}
64
+ * 3 = gaussian -- bkgp: {thr=20, area_size=5, sigma=2, normalize=False}
65
+ * 4 = neural network -- bkgp: {path} (required: path to an .onnx
66
+ model file; any other kwargs are passed through to
67
+ `onnxruntime.InferenceSession`)
68
+
69
+ bkgp : dict, optional, default is {}
70
+ Parameters for the chosen background-subtraction method -- see the
71
+ per-method breakdown under `bkg` above. Passed as **kwargs directly
72
+ to the corresponding `idiff.bkg2d` function/class.
73
+
48
74
  deconv : int, optional, default is 0
49
- Deconvolution type:
50
- 0 = no deconvolution,
51
- 1 = deconvolution based on external PSF,
52
- 2 = deconvolution based on PSF from central region,
53
- psf : 2D-numpy array or None, optional, default is None
54
- Array representing 2D-PSF function.
55
- Relevant only for deconv = 1.
56
- iterate : integer, optional, default is 10
57
- Number of iterations during the deconvolution.
58
-
59
- Returns
60
- -------
61
- final_arr : 2D numpy array
62
- The array is a sum of datafiles;
63
- if the datafiles are pre-filtered, we get the sum of filtered datafiles,
64
- if PSF is given, we get the sum of datafiles with PSF deconvolution.
65
-
66
- Technical notes
67
- ---------------
68
- * This function is a wrapper.
69
- * It calls stemdiff.summ.multicore_sum with correct arguments:
70
- - all relevant original arguments
71
- - one additional argument: the *function for summation*
72
- - the *function for summation* depends on the deconvolution type
73
- '''
74
-
75
- if deconv == 0:
76
- arr = multicore_sum(
77
- SDATA, DIFFIMAGES, df, psf, iterate,
78
- func = stemdiff.sum.dfile_without_deconvolution)
79
- elif deconv == 1:
80
- arr = multicore_sum(
81
- SDATA, DIFFIMAGES, df, psf, iterate,
82
- func = stemdiff.sum.dfile_with_deconvolution_type1)
83
- elif deconv == 2:
84
- arr = multicore_sum(
85
- SDATA, DIFFIMAGES, df, psf, iterate,
86
- func = stemdiff.sum.dfile_with_deconvolution_type2)
87
- else:
88
- print(f'Unknown deconvolution type: deconv={deconv}')
89
- print('Nothing to do.')
90
- return None
91
- return arr
75
+ Deconvolution method:
76
+ * 0 = no deconvolution
77
+ * 1 = Richardson-Lucy from skimage
78
+ * 2 = Richardson-Lucy from idiff -- deconvp: {num_iter=30, cuda=False}
79
+ * 3 = Richardson-Lucy from idiff with Tikhonov regularization
80
+ * 4 = Richardson-Lucy from idiff with L1 regularization
92
81
 
82
+ Which PSF is used is determined by this priority order:
83
+ 1. `deconvp['psf']` -- used directly (after normalization) if given
84
+ 2. `df_psf` -- used to calculate a single shared PSF, if given
85
+ 3. otherwise -- the central region of each array (after background
86
+ subtraction) is used as that array's own individual PSF
93
87
 
94
- def multicore_sum(SDATA, DIFFIMAGES, df, psf, iterate, func):
95
- '''
96
- Execute concurrent data processing using a thread pool.
88
+ deconvp : dict, optional, default is {"num_iter": 10}
89
+ Parameters for the chosen deconvolution method -- see `deconv`
90
+ above. `num_iter` controls iteration count for all Richardson-Lucy
91
+ variants; `psf`, if supplied here, takes priority as described above.
97
92
 
98
- This function processes a list of datafiles using a thread pool
99
- for parallel execution. The number of concurrent workers is determined
100
- by subtracting 1 from the available CPU cores.
93
+ peaks : int, optional, default is 0
94
+ Peak-detection method to run on the processed pattern; every
95
+ detected peak is replaced with a single pixel carrying the summed
96
+ intensity of that peak. `run_regions` or `run_log` are recommended
97
+ (more robust to the typically low peak counts/high noise of
98
+ individual 4D-STEM frames than `run_doh`/`run_pcbr`).
99
+ * 0 = no peak detection
100
+ * 1 = `idiff.peaks.run_regions` -- peaksp: {threshold=1}
101
+ * 2 = `idiff.peaks.run_log` -- peaksp: {downsample_factor=4,
102
+ threshold_factor=3.5, peak_min_sigma=6, ...}
103
+ * 3 = `idiff.peaks.run_doh` -- peaksp: {downsample_factor=4,
104
+ threshold_factor=3.5, peak_min_sigma=6, ...}
105
+ * 4 = `idiff.peaks.run_pcbr` -- peaksp: {sigma=3.0,
106
+ lambda_thresh=0.5, response_thresh_rel=0.1, ...}
107
+
108
+ peaksp : dict, optional, default is {}
109
+ Parameters for the chosen peak-detection method -- see `peaks` above.
110
+
111
+ center : str or None, optional, default is None
112
+ Detection method for `ediff.center.CenterLocator`'s `detection`
113
+ argument, run independently for each image. If None, use the
114
+ (xc, yc) center already stored in df_sum instead of re-detecting it.
115
+
116
+ centerp : dict, optional, default is {}
117
+ Parameters for the chosen center-detection method -- see `ediff.
118
+ center.CenterLocator` for the full set of options per method.
101
119
 
102
- Parameters
103
- ----------
104
- SDATA : stemdiff.gvars.SourceData object
105
- The object describes source data (detector, data_dir, filenames).
106
- DIFFIMAGES : stemdiff.gvars.DiffImages object
107
- Object describing the diffraction images/patterns.
108
- df : pandas.DataFrame object
109
- Database with datafile names and characteristics.
110
- psf : 2D-numpy array or None, optional, default is None
111
- Array representing 2D-PSF function.
112
- Relevant only for deconv = 1.
113
- iterate : integer, optional, default is 10
114
- Number of iterations during the deconvolution.
115
- func : a function from stemdiff.sum module to be used for summation
116
- A function from sister module stemdiff.sum,
117
- which will be used for summation on multiple cores.
118
- This argument is (almost always) passed from the calling function
119
- stemdiff.summ.sum_datafiles so that it corresponded to
120
- the user-selected deconvolution type.
121
-
122
120
  Returns
123
121
  -------
124
- final_arr : 2D numpy array
125
- The array is a sum of datafiles;
126
- if the datafiles are pre-filtered, we get sum of filtered datafiles,
127
- if PSF is given, we get sum of datafiles with PSF deconvolution.
128
-
129
- Technical notes
130
- ---------------
131
- * This function is NOT to be called directly.
132
- * It is called by wrapper function stemdiff.summ.sum_datafiles.
133
- * The two functions work as follows:
134
- - calling function = stemdiff.summ.sum_datafiles
135
- - passes all relevant arguments including function for summation
136
- - this function = stemdiff.summ.multicore_sum
137
- - runs the summation on multiple cores and returns the result
122
+ final_arr : 2D numpy array, dtype float32
123
+ Sum of the (optionally background-subtracted, deconvolved,
124
+ peak-filtered) datafiles. Shape is (imgsize*R, imgsize*R), where R
125
+ is SDATA.detector.upscale -- i.e. the *upscaled* resolution, not
126
+ DIFFIMAGES.imgsize itself.
127
+
138
128
  '''
139
129
 
140
130
  # (0) Initialize
141
131
  num_workers = os.cpu_count() # Number of concurrent workers
142
- datafiles = [datafile[1] for datafile in df.iterrows()]
132
+ datafiles = [datafile[1] for datafile in df_sum.iterrows()]
133
+ R = SDATA.detector.upscale
134
+ img_size = DIFFIMAGES.imgsize
135
+ sum_arr = np.zeros((img_size * R, img_size * R), dtype=np.float32)
136
+ n_arr_summed = 0
137
+
138
+ if bkg == 4:
139
+ nn = idiff.bkg2d.NeuralNetwork(**bkgp)
140
+ else:
141
+ nn = None
142
+
143
+ if df_psf is not None and "psf" not in deconvp:
144
+ psf = idiff.psf.PSFtype1.get_psf(SDATA, DIFFIMAGES, df_psf)
145
+ deconvp["psf"] = psf
143
146
 
144
- # (1) Use ThreadPool to perform multicore summation
147
+ # (1) Use ThreadPool to perform multicore summation
145
148
  with future.ThreadPoolExecutor(max_workers=num_workers) as executor:
146
149
  # (a) Prepare variables
147
- futures = []
150
+ futures = set()
148
151
  total_tasks = len(datafiles)
149
152
  # (b) Submit tasks to the executor
150
153
  for i, file in enumerate(datafiles):
151
154
  try:
152
- if func == stemdiff.sum.dfile_without_deconvolution:
153
- future_obj = executor.submit(
154
- func, SDATA, DIFFIMAGES, file)
155
- elif func == stemdiff.sum.dfile_with_deconvolution_type1:
156
- future_obj = executor.submit(
157
- func, SDATA, DIFFIMAGES, file, psf, iterate)
158
- elif func == stemdiff.sum.dfile_with_deconvolution_type2:
159
- future_obj = executor.submit(
160
- func, SDATA, DIFFIMAGES, file, iterate)
161
- else:
162
- raise Exception("Uknown deconvolution function!")
163
- futures.append(future_obj)
155
+ func = stemdiff.sum.prepare_dfile
156
+ future_obj = executor.submit(func, SDATA, DIFFIMAGES, file, bkg,
157
+ bkgp, deconv, deconvp, peaks,
158
+ peaksp, nn, center, centerp)
159
+ futures.add(future_obj)
164
160
  except Exception as e:
165
161
  print(f"Error processing file {file}: {str(e)}")
166
162
  # (c) Use tqdm to create a progress bar
@@ -168,26 +164,27 @@ def multicore_sum(SDATA, DIFFIMAGES, df, psf, iterate, func):
168
164
  sys.stderr = sys.stdout
169
165
  with tqdm.tqdm(total=total_tasks,
170
166
  desc="Processing ") as pbar:
171
- # ...wait for all tasks to complete
167
+ # ...wait for tasks to complete
172
168
  for future_obj in future.as_completed(futures):
169
+ # (d) Obtain the processed array and add it to the result
173
170
  try:
174
- future_obj.result()
171
+ sum_arr += future_obj.result()
172
+ n_arr_summed += 1
175
173
  except Exception as e:
176
174
  print(f"Error processing a task: {str(e)}")
175
+ finally:
176
+ # Remove future from the set to free memory
177
+ futures.remove(future_obj)
178
+ # Clear the local loop variable
179
+ del future_obj
177
180
  pbar.update(1)
178
181
  sys.stderr = stderr_original
179
182
 
180
- # (2) Summation done, collect the results
181
- # (a) Print a new line to complete the progress bar
183
+ # Print a new line to complete the progress bar
182
184
  print()
183
- # (b) Collect results
184
- deconvolved_data = [f.result() for f in futures]
185
185
 
186
- # (3) Results collected, perform post-processing
187
- # (a) Sum results = the processed/deconvolved files from previous steps
188
- sum_arr = sum(deconvolved_data)
189
- # (b) Run post-processing routine = normalization,
190
- final_arr = stemdiff.sum.sum_postprocess(sum_arr,len(deconvolved_data))
186
+ # (2) Perform post-processing
187
+ final_arr = stemdiff.sum.sum_postprocess(sum_arr, n_arr_summed)
191
188
 
192
- # (4) Return final array = sum of datafiles with (optional) deconvolution
193
- return(final_arr)
189
+ # (3) Return final array = sum of datafiles with (optional) deconvolution
190
+ return final_arr
@@ -1,6 +1,6 @@
1
- Metadata-Version: 2.2
1
+ Metadata-Version: 2.4
2
2
  Name: stemdiff
3
- Version: 5.2.10
3
+ Version: 5.2.12
4
4
  Summary: Convert 4D-STEM data to 2D-powder diffraction pattern.
5
5
  Home-page: https://github.com/mirekslouf/stemdiff/
6
6
  Author: Mirek Slouf
@@ -14,10 +14,15 @@ Requires-Python: >=3.6
14
14
  Description-Content-Type: text/markdown
15
15
  License-File: LICENCE
16
16
  Requires-Dist: numpy
17
- Requires-Dist: matplotlib
18
17
  Requires-Dist: scipy
19
18
  Requires-Dist: pandas
19
+ Requires-Dist: matplotlib
20
20
  Requires-Dist: scikit-image
21
+ Requires-Dist: pillow
22
+ Requires-Dist: opencv-python
23
+ Requires-Dist: tqdm
24
+ Requires-Dist: ediff
25
+ Requires-Dist: idiff
21
26
  Dynamic: author
22
27
  Dynamic: author-email
23
28
  Dynamic: classifier
@@ -25,6 +30,7 @@ Dynamic: description
25
30
  Dynamic: description-content-type
26
31
  Dynamic: home-page
27
32
  Dynamic: license
33
+ Dynamic: license-file
28
34
  Dynamic: project-url
29
35
  Dynamic: requires-dist
30
36
  Dynamic: requires-python
@@ -35,37 +41,36 @@ STEMDIFF :: 4D-STEM dataset to 2D-diffractogram
35
41
 
36
42
  * The **STEMDIFF package** converts... <br>
37
43
  ... a 4D-STEM dataset from a SEM microscope (huge and complex) <br>
38
- ... to a 2D-powder diffraction pattern (simple and easy to work with).
39
- * The STEMDIFF package is a key part of our **4D-STEM/PNBD** method, <br>
40
- which was described (together with the package) in open-access publications:
41
- 1. *Nanomaterials* 11 (2021) 962.
42
- [https://doi.org/10.3390/nano11040962](https://doi.org/10.3390/nano11040962)
43
- 2. *Materials* 14 (2021) 7550.
44
- [https://doi.org/10.3390/ma14247550](https://doi.org/10.3390/ma14247550)
45
- * If you use STEMDIFF package, **please cite** the 2nd publication (or both :-)
44
+ ... to a 2D-powder diffraction pattern (simple and easy to process).
45
+ * If you use EDIFF in your research, **please cite** our recent paper:
46
+ - *Microscopy and Microanalysis* 31, 2025, ozaf045. <br>
47
+ [https://doi.org/10.1093/mam/ozaf045](https://doi.org/10.1093/mam/ozaf045)
46
48
 
47
49
  Principle
48
50
  ---------
49
51
 
50
52
  <img src="https://mirekslouf.github.io/stemdiff/docs/assets/principle.pptx.png" alt="STEMDIFF principle" width="500"/>
51
53
 
54
+
52
55
  Installation
53
56
  ------------
54
- * Requirement: Python with sci-modules = numpy, matplotlib, scipy, pandas
55
- * `pip install scikit-image` = 3rd party package for advanced image processing
56
- * `pip install tqdm` = to show progress meter during long summations
57
- * `pip install idiff` = to improve diffractograms (remove noise, background ...)
58
- * `pip install stemdiff` = STEMDIFF package itself (uses all packages above)
57
+ * Installation of stemdiff:
58
+ - `pip install stemdiff`
59
+ * Additional packages (auto-installed with stemdiff if not present):
60
+ - Standard sci-libraries: `numpy`, `matplotlib`, `scipy`, `pandas`
61
+ - Additional libs for images: `scikit-image`, `pillow`, `opencv-python`
62
+ - Additional libs for calculations: `tqdm`, `ediff`, `idiff`
59
63
 
60
64
  Quick start
61
65
  -----------
62
66
 
63
- * Look at the
64
- [worked example](https://www.dropbox.com/scl/fi/l5eskdgxo7976ea9x35fp/01_sdiff_au.nb.pdf?rlkey=7yd5tqtcm3zxr1uc0m0aisenl&dl=0)
65
- to see STEMDIFF in action.
66
- * Download
67
- [complete examples with data](https://www.dropbox.com/scl/fo/ccb6hs28er9dc1xufshh4/h?rlkey=omk5bqoe17jmedhj407ng9xr0&dl=0)
68
- and try STEMDIFF yourself.
67
+ * [Worked example](https://drive.google.com/file/d/1K3jWqiO1CpX-d4avcoYK0S8JfbAkZU78/view?usp=sharing)
68
+ shows the STEMDIFF package in action.
69
+ * [Help on GitHub](https://mirekslouf.github.io/stemdiff/docs/)
70
+ with complete
71
+ [package documentation](https://mirekslouf.github.io/stemdiff/docs/pdoc.html/stemdiff.html)
72
+ and
73
+ [additional examples](https://drive.google.com/drive/folders/1X4TOdnMHVGSskzQJZ12edLt6MVl3HLvm?usp=sharing).
69
74
 
70
75
  Documentation, help and examples
71
76
  --------------------------------
@@ -74,11 +79,12 @@ Documentation, help and examples
74
79
  the stable version to install.
75
80
  * [GitHub](https://github.com/mirekslouf/stemdiff) repository -
76
81
  the current version under development.
77
- * [GitHub Pages](https://mirekslouf.github.io/stemdiff)
78
- with [help](https://mirekslouf.github.io/stemdiff/docs)
79
- and [complete package documentation](https://mirekslouf.github.io/stemdiff/docs/pdoc.html/stemdiff.html).
82
+ * [GitHub Pages](https://mirekslouf.github.io/stemdiff/) -
83
+ the more user-friendly version of GitHub website.
80
84
 
81
- ## Versions of STEMDIFF
85
+
86
+ Versions of STEMDIFF
87
+ --------------------
82
88
 
83
89
  * Version 1.0 = Matlab: just a simple summation of 4D-dataset
84
90
  * Version 2.0 = like v.1.0 + post-processing in Jupyter
@@ -92,20 +98,17 @@ Documentation, help and examples
92
98
  * sum just the central region with the strongest diffractions
93
99
  &rArr; higher speed
94
100
  * 3 centering types: (0) geometry, (1) center of 1st, (2) individual centers
95
- * better definition of summation and centering parameters
96
- * better documentation strings + demo data + improved *master script*
101
+ * improved definition of summation and better documentation
97
102
  * Version 5.0 = complete rewrite of v.4.2
98
- * all key features of v.4.2 (summation, filtering, deconvolution)
99
103
  * conversion *2D-diffractogram &rarr; 1D-profile* moved to package EDIFF
100
- * several generalizations and improvements, namely:
101
- - possibility to define and use more detectors/datafile formats
102
- - better filtering (including estimated number of diffractions)
103
- - more types of deconvolution (experimental; to be finished in v.6.0)
104
+ * better filtering (including estimated number of diffractions)
105
+ * more detectors + more types of deconvolution (beta; to finish in v.6.0)
104
106
  * Version 5.1 = (beta) support for parallel processing
105
107
  * Version 5.2 = (beta) improvement of diff.patterns in sister package idiff
106
108
 
109
+
107
110
  Acknowledgement
108
111
  ---------------
109
112
 
110
113
  The development was co-funded by TACR, program NCK,
111
- project [TN02000020](https://www.isibrno.cz/en/centre-advanced-electron-and-photonic-optics).
114
+ project [TN02000020](https://starfos.tacr.cz/en/projekty/TN02000020).
@@ -0,0 +1,13 @@
1
+ STEMDIFF/__init__.py,sha256=Os1duqalPqPGB6cZep_on_phlqWnAKMsfKSXW-XvgnY,2944
2
+ STEMDIFF/__main__.py,sha256=ECOOjxFFnVPb5gHkI05h8KrVpk_vYmAI18nfrL0ZF9M,413
3
+ STEMDIFF/dbase.py,sha256=KXDZaDTmIjFF6J1whORK9KYsWgUU02Krvgzxh05b7kE,5995
4
+ STEMDIFF/detectors.py,sha256=Z5F1t3WntdFBI8fAivNbz70z4LPLzYTNDjrmtYIOl3Y,11704
5
+ STEMDIFF/gvars.py,sha256=GzKHJxUnUxin7URuNSxWJpp23bQ_kdYgI_I4s9DPko4,4669
6
+ STEMDIFF/io.py,sha256=mM7SwICdcndRC2ZdrIPbR2VvMMCQDXe8S2oxoUBIlZY,52934
7
+ STEMDIFF/sum.py,sha256=8C9zQsedUjzH02n-8vntqGAfaGHdORB1BGuTfWlSkrk,17007
8
+ STEMDIFF/summ.py,sha256=ATzP_j0WMbNac6iBs2SW_kX44aCgxj4HHJ-rVyJWVsQ,8430
9
+ stemdiff-5.2.12.dist-info/licenses/LICENCE,sha256=A0HugtkWkgCwRhYrsSqENRlIFre2Vu14xQajDnsYlqU,1340
10
+ stemdiff-5.2.12.dist-info/METADATA,sha256=v0SljGC8uNFcuqaAtPPlj832cO71bBO447h-fDJWPxc,4297
11
+ stemdiff-5.2.12.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
12
+ stemdiff-5.2.12.dist-info/top_level.txt,sha256=TEpwqMUcpSUvwCDrcH9fkjpU8fYGdR1ti2H2UsNiUIk,9
13
+ stemdiff-5.2.12.dist-info/RECORD,,
@@ -1,5 +1,5 @@
1
1
  Wheel-Version: 1.0
2
- Generator: setuptools (75.8.0)
2
+ Generator: setuptools (84.2.1)
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any
5
5
 
@@ -1,13 +0,0 @@
1
- STEMDIFF/__init__.py,sha256=Knx8ugFA4IiaYCIA6sU6_5SZAI_ILlamtjPTP7KNN5w,2944
2
- STEMDIFF/__main__.py,sha256=ECOOjxFFnVPb5gHkI05h8KrVpk_vYmAI18nfrL0ZF9M,413
3
- STEMDIFF/dbase.py,sha256=MgHPRrCy1QQdzCqgalezqdgKoTAzo1Bx-p68UBy5czA,5984
4
- STEMDIFF/detectors.py,sha256=Z5F1t3WntdFBI8fAivNbz70z4LPLzYTNDjrmtYIOl3Y,11704
5
- STEMDIFF/gvars.py,sha256=GzKHJxUnUxin7URuNSxWJpp23bQ_kdYgI_I4s9DPko4,4669
6
- STEMDIFF/io.py,sha256=T7hqWCExXgeF2Of0VCZvH6tmvTxLj3SVlsgzySuSTfE,49387
7
- STEMDIFF/sum.py,sha256=ZEHgLbdaQkooB7ZWgTxxmLJZpM5yCxCaOlK70A1rNSU,14607
8
- STEMDIFF/summ.py,sha256=LBhgfmPEvWMmCruZE2K7-XYSjA7Mh33WrziP4bTGcU4,8030
9
- stemdiff-5.2.10.dist-info/LICENCE,sha256=A0HugtkWkgCwRhYrsSqENRlIFre2Vu14xQajDnsYlqU,1340
10
- stemdiff-5.2.10.dist-info/METADATA,sha256=ZxvLS3I4cQdKgmYGC1lvhEeJsltetr0Qvrv4tU5tWC0,4740
11
- stemdiff-5.2.10.dist-info/WHEEL,sha256=In9FTNxeP60KnTkGw7wk6mJPYd_dQSjEZmXdBdMCI-8,91
12
- stemdiff-5.2.10.dist-info/top_level.txt,sha256=TEpwqMUcpSUvwCDrcH9fkjpU8fYGdR1ti2H2UsNiUIk,9
13
- stemdiff-5.2.10.dist-info/RECORD,,