stemdiff 5.2.11__tar.gz → 5.2.12__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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: stemdiff
3
- Version: 5.2.11
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
@@ -36,7 +41,7 @@ STEMDIFF :: 4D-STEM dataset to 2D-diffractogram
36
41
 
37
42
  * The **STEMDIFF package** converts... <br>
38
43
  ... a 4D-STEM dataset from a SEM microscope (huge and complex) <br>
39
- ... to a 2D-powder diffraction pattern (simple and easy to work with).
44
+ ... to a 2D-powder diffraction pattern (simple and easy to process).
40
45
  * If you use EDIFF in your research, **please cite** our recent paper:
41
46
  - *Microscopy and Microanalysis* 31, 2025, ozaf045. <br>
42
47
  [https://doi.org/10.1093/mam/ozaf045](https://doi.org/10.1093/mam/ozaf045)
@@ -49,12 +54,12 @@ Principle
49
54
 
50
55
  Installation
51
56
  ------------
52
- * Requirement: Python with sci-modules = numpy, matplotlib, scipy, pandas
53
- * `pip install scikit-image` = 3rd party package for advanced image processing
54
- * `pip install tqdm` = to show progress meter during long summations
55
- * `pip install idiff` = to improve diffractograms (remove noise, background ...)
56
- * `pip install stemdiff` = STEMDIFF package itself (uses all packages above)
57
-
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`
58
63
 
59
64
  Quick start
60
65
  -----------
@@ -106,4 +111,4 @@ Acknowledgement
106
111
  ---------------
107
112
 
108
113
  The development was co-funded by TACR, program NCK,
109
- project [TN02000020](https://www.isibrno.cz/en/centre-advanced-electron-and-photonic-optics).
114
+ project [TN02000020](https://starfos.tacr.cz/en/projekty/TN02000020).
@@ -3,7 +3,7 @@ STEMDIFF :: 4D-STEM dataset to 2D-diffractogram
3
3
 
4
4
  * The **STEMDIFF package** converts... <br>
5
5
  ... a 4D-STEM dataset from a SEM microscope (huge and complex) <br>
6
- ... to a 2D-powder diffraction pattern (simple and easy to work with).
6
+ ... to a 2D-powder diffraction pattern (simple and easy to process).
7
7
  * If you use EDIFF in your research, **please cite** our recent paper:
8
8
  - *Microscopy and Microanalysis* 31, 2025, ozaf045. <br>
9
9
  [https://doi.org/10.1093/mam/ozaf045](https://doi.org/10.1093/mam/ozaf045)
@@ -16,12 +16,12 @@ Principle
16
16
 
17
17
  Installation
18
18
  ------------
19
- * Requirement: Python with sci-modules = numpy, matplotlib, scipy, pandas
20
- * `pip install scikit-image` = 3rd party package for advanced image processing
21
- * `pip install tqdm` = to show progress meter during long summations
22
- * `pip install idiff` = to improve diffractograms (remove noise, background ...)
23
- * `pip install stemdiff` = STEMDIFF package itself (uses all packages above)
24
-
19
+ * Installation of stemdiff:
20
+ - `pip install stemdiff`
21
+ * Additional packages (auto-installed with stemdiff if not present):
22
+ - Standard sci-libraries: `numpy`, `matplotlib`, `scipy`, `pandas`
23
+ - Additional libs for images: `scikit-image`, `pillow`, `opencv-python`
24
+ - Additional libs for calculations: `tqdm`, `ediff`, `idiff`
25
25
 
26
26
  Quick start
27
27
  -----------
@@ -73,4 +73,4 @@ Acknowledgement
73
73
  ---------------
74
74
 
75
75
  The development was co-funded by TACR, program NCK,
76
- project [TN02000020](https://www.isibrno.cz/en/centre-advanced-electron-and-photonic-optics).
76
+ project [TN02000020](https://starfos.tacr.cz/en/projekty/TN02000020).
@@ -32,6 +32,16 @@ setuptools.setup(
32
32
  package_dir={"":"src"},
33
33
  packages=setuptools.find_packages(where="src"),
34
34
  python_requires=">=3.6",
35
- install_requires=
36
- ["numpy", "matplotlib", "scipy", "pandas", "scikit-image"],
35
+ install_requires=[
36
+ "numpy",
37
+ "scipy", # io.py
38
+ "pandas", # dbase.py
39
+ "matplotlib", # io.py, and provides mpl_toolkits
40
+ "scikit-image", # dbase.py, io.py, sum.py
41
+ "pillow", # detectors.py, io.py
42
+ "opencv-python", # io.py: cv2.resize
43
+ "tqdm", # sum.py, summ.py
44
+ "ediff", # sum.py
45
+ "idiff", # sum.py, summ.py
46
+ ],
37
47
  include_package_data=True)
@@ -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.11"
33
+ __version__ = "5.2.12"
34
34
 
35
35
 
36
36
  # Import modules of stemdiff package
@@ -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)
@@ -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
  '''
@@ -0,0 +1,399 @@
1
+ '''
2
+ Module: stemdiff.sum
3
+ --------------------
4
+ The summation of 4D-STEM datafiles to create one 2D powder diffraction file.
5
+
6
+ * stemdiff.sum = this module, which runs on a single core (serial processing)
7
+ * stemdiff.summ = sister module running on multiple cores (parallel processing)
8
+
9
+ To perform the summation, we just call function sum_datafiles:
10
+
11
+ * serial : stemdiff.sum.sum_datafiles(SDATA, DIFFIMAGES, df, ...)
12
+ * parallel : stemdiff.summ.sum_datafiles(SDATA, DIFFIMAGES, df, ...)
13
+
14
+ The initial arguments are:
15
+
16
+ * SDATA = stemdiff.gvars.SourceData object = description of source data
17
+ * DIFFIMAGES = stemdiff.gvars.DiffImages object = description of diffractograms
18
+ * df_sum = pre-calculated database of datafiles/diffratograms to sum
19
+
20
+ Key arguments are `deconv` and `bkg`, which determine the processing type.
21
+ '''
22
+
23
+
24
+ import numpy as np
25
+ import stemdiff.io
26
+ import idiff
27
+ import ediff.center
28
+ from skimage import restoration
29
+ import tqdm
30
+ import sys
31
+
32
+
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={}):
36
+ """
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.
142
+ """
143
+
144
+ # (1) Prepare variables for summation
145
+ R = SDATA.detector.upscale
146
+ img_size = DIFFIMAGES.imgsize
147
+ datafiles = [datafile[1] for datafile in df_sum.iterrows()]
148
+ sum_arr = np.zeros((img_size * R, img_size * R), dtype=np.float32)
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
+
159
+ # (2) Prepare variables for tqdm
160
+ # (to create a single progress bar for the entire process
161
+ total_tasks = len(datafiles)
162
+ stderr_original = sys.stderr
163
+ sys.stderr = sys.stdout
164
+
165
+ # (3) Run summations
166
+ # (summations will run with tqdm
167
+ # (we will use several types of summations
168
+ # (each summations uses datafiles prepared in a different way
169
+ with tqdm.tqdm(total=total_tasks, desc="Processing ") as pbar:
170
+ try:
171
+ # Process each image in the database
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
+
177
+ # Update the progress bar for each processed image
178
+ pbar.update(1)
179
+ except Exception as e:
180
+ print(f"Error processing a task: {str(e)}")
181
+
182
+ sys.stderr = stderr_original
183
+
184
+ # (4) Move to the next line after the progress bar is complete
185
+ print('')
186
+
187
+ # (5) Post-process the summation and return the result
188
+ return sum_postprocess(sum_arr, len(df_sum))
189
+
190
+
191
+ def sum_postprocess(sum_of_arrays, n):
192
+ """
193
+ Normalize and convert the summed array to 16-bit unsigned integers.
194
+
195
+ Parameters
196
+ ----------
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
+
201
+ n : int
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
+
208
+ Returns
209
+ -------
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`.
213
+ """
214
+ arr = np.round(sum_of_arrays/n).astype(np.uint16)
215
+ return(arr)
216
+
217
+
218
+ def prepare_dfile(SDATA, DIFFIMAGES, datafile, bkg, bkgp, deconv, deconvp,
219
+ peaks, peaksp, nn, center_detection, centerp):
220
+ """
221
+ Read, process, and center a single datafile, ready for summation.
222
+
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.
226
+
227
+ Parameters
228
+ ----------
229
+ SDATA : stemdiff.gvars.SourceData object
230
+ The object describing source data (detector, data_dir, filenames).
231
+
232
+ DIFFIMAGES : stemdiff.gvars.DiffImages object
233
+ The object describing the diffraction images/patterns.
234
+
235
+ datafile : one row from the prepared database of datafiles
236
+ The database of datafiles is created in
237
+ `stemdiff.dbase.calc_database`. Each row contains
238
+ ['DatafileName', 'Xcenter', 'Ycenter', 'MaxInt', 'Peaks', 'S'].
239
+
240
+ bkg, bkgp : int, dict
241
+ Background-subtraction method and its parameters -- see
242
+ `sum_datafiles` for the full per-method breakdown.
243
+
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.
250
+
251
+ peaks, peaksp : int, dict
252
+ Peak-detection method and its parameters -- see `sum_datafiles`
253
+ for the full per-method breakdown.
254
+
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.
261
+
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.
273
+
274
+ Returns
275
+ -------
276
+ arr : 2D numpy array
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
+
281
+ Notes
282
+ -----
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.
298
+ """
299
+
300
+ # (0) Prepare variables
301
+ R = SDATA.detector.upscale
302
+ img_size = DIFFIMAGES.imgsize
303
+ psf_size = DIFFIMAGES.psfsize
304
+
305
+ # (1) Read datafile
306
+ datafile_name = SDATA.data_dir.joinpath(datafile.DatafileName)
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
+
319
+ # (3) Rescale/upscale datafile and THEN remove border region
320
+ # (a) upscale datafile
321
+ arr = stemdiff.io.Arrays.rescale_fast(arr, R, inter=2)
322
+ arr = stemdiff.io.Arrays.zero_spatial_edges(arr, border_width=10)
323
+ # (b) get the accurate center of the upscaled datafile
324
+ # (the center coordinates for each datafile are saved in the database
325
+ # (note: our datafile is one row from the database => we know the coords!
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)
339
+ # (Important technical notes:
340
+ # (* This 3-step procedure is necessary to center the images precisely.
341
+ # ( The accurate centers from upscaled images are saved in database.
342
+ # ( The centers from original/non-upscaled datafiles => wrong results.
343
+ # (* Some border region should ALWAYS be cut, for two reasons:
344
+ # ( (i) weak/zero diffractions at edges and (ii) detector edge artifacts
345
+
346
+ # (4) Prepare PSF from the center of given array, if not given as parameter
347
+ # (recommended parameters:
348
+ # (psf_size => to be specified in the calling script ~ 30
349
+ # (circular => always True - square PSF causes certain artifacts
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
354
+
355
+
356
+ # (5) Deconvolution
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
+
370
+ # (b) perform the deconvolution
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
+
384
+ # (c) restore original range of intensities = re-normalize
385
+ if deconv > 0:
386
+ arr = arr_deconv * norm_const
387
+
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