-
Notifications
You must be signed in to change notification settings - Fork 84
/
diffraction2d.py
2472 lines (2154 loc) · 86.7 KB
/
diffraction2d.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
# Copyright 2016-2024 The pyXem developers
#
# This file is part of pyXem.
#
# pyXem is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# pyXem is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with pyXem. If not, see <http://www.gnu.org/licenses/>.
import numpy as np
from scipy.ndimage import rotate
from skimage import morphology
import dask.array as da
from dask.diagnostics import ProgressBar
from tqdm import tqdm
import warnings
import hyperspy.api as hs
from hyperspy.signals import Signal2D, BaseSignal
from hyperspy._signals.lazy import LazySignal
from hyperspy.misc.utils import isiterable
from importlib import import_module
from hyperspy.axes import UniformDataAxis
from pyxem.signals import (
CommonDiffraction,
)
from pyxem.utils.pyfai_utils import (
get_azimuthal_integrator,
_get_radial_extent,
_get_setup,
)
from pyxem.utils.diffraction import (
azimuthal_integrate1d,
azimuthal_integrate2d,
gain_normalise,
remove_bad_pixels,
circular_mask,
find_beam_offset_cross_correlation,
normalize_template_match,
convert_affine_to_transform,
apply_transformation,
find_beam_center_blur,
find_beam_center_interpolate,
find_hot_pixels,
integrate_radially,
medfilt_1d,
sigma_clip,
center_of_mass,
)
from pyxem.utils._azimuthal_integrations import (
_slice_radial_integrate,
_slice_radial_integrate1d,
)
from pyxem.utils._dask import (
_get_dask_array,
_get_signal_dimension_host_chunk_slice,
_align_single_frame,
)
from pyxem.utils._signals import (
_select_method_from_method_dict,
_to_hyperspy_index,
)
import pyxem.utils._pixelated_stem_tools as pst
import pyxem.utils._dask as dt
import pyxem.utils.ransac_ellipse_tools as ret
from pyxem.utils._deprecated import deprecated, deprecated_argument
from pyxem.utils._background_subtraction import (
_subtract_median,
_subtract_dog,
_subtract_hdome,
_subtract_radial_median,
)
from pyxem.utils.calibration import Calibration
from pyxem import CUPY_INSTALLED
if CUPY_INSTALLED:
import cupy as cp
class Diffraction2D(CommonDiffraction, Signal2D):
"""Signal class for two-dimensional diffraction data in Cartesian coordinates.
Parameters
----------
*args
See :class:`~hyperspy._signals.signal2d.Signal2D`.
**kwargs
See :class:`~hyperspy._signals.signal2d.Signal2D`
"""
_signal_type = "diffraction"
""" Methods that make geometrical changes to a diffraction pattern """
def __init__(self, *args, **kwargs):
"""
Create a Diffraction2D object from numpy.ndarray.
Parameters
----------
*args :
Passed to the __init__ of Signal2D. The first arg should be
numpy.ndarray
**kwargs :
Passed to the __init__ of Signal2D
"""
super().__init__(*args, **kwargs)
self.calibration = Calibration(self)
def apply_affine_transformation(
self, D, order=1, keep_dtype=False, inplace=True, *args, **kwargs
):
"""Correct geometric distortion by applying an affine transformation.
Parameters
----------
D : array or Signal2D of arrays
3x3 np.array (or Signal2D thereof) specifying the affine transform
to be applied.
order : 1,2,3,4 or 5
The order of interpolation on the transform. Default is 1.
keep_dtype : bool
If True dtype of returned ElectronDiffraction2D Signal is that of
the input, if False, casting to higher precision may occur.
inplace : bool
If True (default), this signal is overwritten. Otherwise, returns a
new signal.
*args:
Arguments to be passed to :meth:`hyperspy.api.signals.BaseSignal.map`.
**kwargs:
Keyword arguments to be passed to :meth:`hyperspy.api.signals.BaseSignal.map`.
Returns
-------
ElectronDiffraction2D Signal containing the affine Transformed
diffraction patterns.
"""
shape = self.axes_manager.signal_shape
if isinstance(D, np.ndarray):
transformation = convert_affine_to_transform(D, shape)
else:
transformation = D.map(
convert_affine_to_transform, shape=shape, inplace=False
)
if not keep_dtype:
out_dtype = float
else:
out_dtype = self.data.dtype
return self.map(
apply_transformation,
transformation=transformation,
output_dtype=out_dtype,
order=order,
keep_dtype=keep_dtype,
inplace=inplace,
*args,
**kwargs,
)
def shift_diffraction(
self,
shift_x,
shift_y,
interpolation_order=1,
inplace=False,
show_progressbar=True,
):
"""Shift the diffraction patterns in a pixelated STEM signal.
The points outside the boundaries are set to zero.
Parameters
----------
shift_x, shift_y : int or NumPy array
If given as int, all the diffraction patterns will have the same
shifts. Each diffraction pattern can also have different shifts,
by passing a NumPy array with the same dimensions as the navigation
axes.
interpolation_order : int
When shifting, a spline interpolation is used. This parameter
sets the order of this spline. Must be between 0 and 5.
Note that in some low-signal and high noise datasets, using a
non-zero order might lead to artifacts. See the docstring in
scipy.ndimage.shift for more information. Default 1.
inplace : bool
If True (default), the data is replaced by the result. Useful when
working with very large datasets, as this avoids doubling the
amount of memory needed. If False, a new signal with the results
is returned.
show_progressbar : bool
Default True.
Returns
-------
shifted_signal : Diffraction2D signal
Examples
--------
>>> s = pxm.data.dummy_data.get_disk_shift_simple_test_signal()
>>> s_c = s.center_of_mass(threshold=3., show_progressbar=False)
>>> s_c -= 25 # To shift the center disk to the middle (25, 25)
>>> s_shift = s.shift_diffraction(
... s_c.inav[0].data, s_c.inav[1].data,
... show_progressbar=False)
>>> s_shift.plot()
Using a different interpolation order
>>> s_shift = s.shift_diffraction(
... s_c.inav[0].data, s_c.inav[1].data, interpolation_order=3,
... show_progressbar=False)
"""
if (not isiterable(shift_x)) or (not isiterable(shift_y)):
shift_x, shift_y = pst._make_centre_array_from_signal(
self, x=shift_x, y=shift_y
)
s_shift_x = BaseSignal(shift_x).T
s_shift_y = BaseSignal(shift_y).T
s_shift = self.map(
pst._shift_single_frame,
inplace=inplace,
ragged=False,
show_progressbar=show_progressbar,
interpolation_order=interpolation_order,
shift_x=s_shift_x,
shift_y=s_shift_y,
)
if not inplace:
return s_shift
def rotate_diffraction(self, angle, show_progressbar=True):
"""
Rotate the diffraction dimensions.
Parameters
----------
angle : scalar
Clockwise rotation in degrees.
show_progressbar : bool
Default True
Returns
-------
rotated_signal : Diffraction2D class
Examples
--------
>>> s = pxm.data.dummy_data.get_holz_simple_test_signal()
>>> s_rot = s.rotate_diffraction(30, show_progressbar=False)
"""
s_rotated = self.map(
rotate,
ragged=False,
angle=-angle,
reshape=False,
inplace=False,
show_progressbar=show_progressbar,
)
if self._lazy:
s_rotated.compute(show_progressbar=show_progressbar)
return s_rotated
def flip_diffraction_x(self):
"""Flip the dataset along the diffraction x-axis.
The function returns a new signal, but the data itself
is a view of the original signal. So changing the returned signal
will also change the original signal (and visa versa). To avoid
changing the original signal, use the deepcopy method afterwards,
but note that this requires double the amount of memory.
See below for an example of this.
Returns
-------
flipped_signal : Diffraction2D signal
Example
-------
>>> s = pxm.data.dummy_data.get_holz_simple_test_signal()
>>> s_flip = s.flip_diffraction_x()
To avoid changing the original object afterwards
>>> s_flip = s.flip_diffraction_x().deepcopy()
"""
s_out = self.copy()
s_out.axes_manager = self.axes_manager.deepcopy()
s_out.data = np.flip(self.data, axis=-1)
return s_out
def flip_diffraction_y(self):
"""Flip the dataset along the diffraction y-axis.
The function returns a new signal, but the data itself
is a view of the original signal. So changing the returned signal
will also change the original signal (and visa versa). To avoid
changing the original signal, use the deepcopy method afterwards,
but note that this requires double the amount of memory.
See below for an example of this.
Returns
-------
flipped_signal : Diffraction2D signal
Example
-------
>>> s = pxm.data.dummy_data.get_holz_simple_test_signal()
>>> s_flip = s.flip_diffraction_y()
To avoid changing the original object afterwards
>>> s_flip = s.flip_diffraction_y().deepcopy()
"""
s_out = self.copy()
s_out.axes_manager = self.axes_manager.deepcopy()
s_out.data = np.flip(self.data, axis=-2)
return s_out
""" Masking and other non-geometrical 'correction' to patterns """
def get_direct_beam_mask(self, radius):
"""Generate a signal mask for the direct beam.
Parameters
----------
radius : float
Radius for the circular mask in pixel units.
Return
------
numpy.ndarray
The mask of the direct beam
"""
shape = self.axes_manager.signal_shape
center = (shape[1] - 1) / 2, (shape[0] - 1) / 2
signal_mask = Signal2D(circular_mask(shape=shape, radius=radius, center=center))
return signal_mask
def apply_gain_normalisation(
self, dark_reference, bright_reference, inplace=True, *args, **kwargs
):
"""Apply gain normalization to experimentally acquired electron
diffraction patterns.
Parameters
----------
dark_reference : pyxem.signals.ElectronDiffraction2D
Dark reference image.
bright_reference : pyxem.signals.Diffraction2D
Bright reference image.
inplace : bool
If True (default), this signal is overwritten. Otherwise, returns a
new signal.
*args:
Arguments to be passed to :meth:`hyperspy.api.signals.BaseSignal.map`.
**kwargs:
Keyword arguments to be passed to :meth:`hyperspy.api.signal.BaseSignal.map`.
"""
return self.map(
gain_normalise,
dref=dark_reference,
bref=bright_reference,
inplace=inplace,
*args,
**kwargs,
)
@deprecated_argument(
name="lazy_result", alternative="lazy_output", since="0.15.0", removal="1.0.0"
)
def subtract_diffraction_background(
self, method="median kernel", inplace=False, **kwargs
):
"""Background subtraction of the diffraction data.
Parameters
----------
method : str, optional
'difference of gaussians', 'median kernel', 'radial median', 'h-dome'
Default 'median kernel'.
For `difference of gaussians` the parameters min_sigma (default:1) and
max_sigma(default:55) control the size of the gaussian kernels used.
For `median kernel` the footprint(default:19) parameter detemines the
footprint used to determine the median.
For `radial median` the parameters center_x(default:128), center_y(default:128) are
used to detmine the center of the pattern to use to determine the median.
For `h-dome` the parameter h detemines the relative height of local peaks that
are supressed.
**kwargs :
To be passed to the method chosen: min_sigma/max_sigma, footprint,
centre_x,centre_y / h
Returns
-------
s : pyxem.signals.Diffraction2D
Examples
--------
>>> s = pxm.data.dummy_data.get_cbed_signal()
>>> s_r = s.subtract_diffraction_background(method='median kernel',
... footprint=20, lazy_output=False, show_progressbar=False)
>>> s_r.plot()
"""
method_dict = {
"difference of gaussians": _subtract_dog,
"median kernel": _subtract_median,
"radial median": _subtract_radial_median,
"h-dome": _subtract_hdome,
}
if method not in method_dict:
raise NotImplementedError(
f"The method specified, '{method}',"
f" is not implemented. The different methods are:"
f" 'difference of gaussians','median kernel',"
f"'radial median' or 'h-dome'."
)
subtraction_function = method_dict[method]
return self.map(subtraction_function, inplace=inplace, **kwargs)
@deprecated_argument(
name="mask_array", since="0.15.0", removal="1.0.0", alternative="mask"
)
def find_dead_pixels(
self,
dead_pixel_value=0,
mask=None,
):
"""Find dead pixels in the diffraction images.
Parameters
----------
dead_pixel_value : scalar
Default 0
mask_array : Boolean Numpy array
lazy_result : bool
If True, return a lazy signal. If False, compute
the result and return a non-lazy signal. Default False.
show_progressbar : bool
Returns
-------
s_dead_pixels : HyperSpy 2D signal
With dead pixels as True, rest as False.
Examples
--------
>>> s = pxm.data.dummy_data.get_dead_pixel_signal()
>>> s_dead_pixels = s.find_dead_pixels(show_progressbar=False)
Using a mask array
>>> import numpy as np
>>> mask_array = np.zeros((128, 128), dtype=bool)
>>> mask_array[:, 100:] = True
>>> s = pxm.data.dummy_data.get_dead_pixel_signal()
>>> s_dead_pixels = s.find_dead_pixels(
... mask_array=mask_array, show_progressbar=False)
Getting a lazy signal as output
>>> s_dead_pixels = s.find_dead_pixels(
... lazy_result=True, show_progressbar=False)
See Also
--------
find_hot_pixels
correct_bad_pixels
"""
mean_signal = self.mean(axis=self.axes_manager.navigation_axes)
dead_pixels = mean_signal == dead_pixel_value
if mask is not None:
dead_pixels = dead_pixels * np.invert(mask)
return dead_pixels
@deprecated_argument(
name="mask_array", since="0.15.0", removal="1.0.0", alternative="mask"
)
@deprecated_argument(
name="lazy_result", since="0.15.0", removal="1.0.0", alternative="lazy_output"
)
def find_hot_pixels(
self, threshold_multiplier=500, mask=None, inplace=False, **kwargs
):
"""Find hot pixels in the diffraction images.
Note: this method will be default return a lazy signal, since the
size of the returned signal is the same shape as the original
signal. So for large datasets actually calculating computing
the results can use a lot of memory.
In addition, this signal is currently not very optimized with
regards to memory use, so be careful when using this method
for large datasets.
Parameters
----------
threshold_multiplier : scalar
Default 500
mask_array : Boolean NumPy array
lazy_result : bool
If True, return a lazy signal. If False, compute
the result and return a non-lazy signal. Default True.
show_progressbar : bool
Examples
--------
>>> s = pxm.data.dummy_data.get_hot_pixel_signal()
>>> s_hot_pixels = s.find_hot_pixels(show_progressbar=False)
Using a mask array
>>> import numpy as np
>>> mask_array = np.zeros((128, 128), dtype=bool)
>>> mask_array[:, 100:] = True
>>> s = pxm.data.dummy_data.get_hot_pixel_signal()
>>> s_hot_pixels = s.find_hot_pixels(
... mask_array=mask_array, show_progressbar=False)
Getting a non-lazy signal as output
>>> s_hot_pixels = s.find_hot_pixels()
See Also
--------
find_dead_pixels
correct_bad_pixels
"""
return self.map(
find_hot_pixels,
threshold_multiplier=threshold_multiplier,
mask=mask,
inplace=inplace,
**kwargs,
)
@deprecated_argument(
name="lazy_result", since="0.15.0", removal="1.0.0", alternative="lazy_output"
)
def correct_bad_pixels(
self,
bad_pixel_array,
**kwargs,
):
"""Correct bad (dead/hot) pixels by replacing their values with the mean value of neighbors.
Parameters
----------
bad_pixel_array : array-like
List of pixels to correct
show_progressbar : bool, optional
Default True
lazy_output : bool, optional
When working lazily, determines if the result is computed. Default is True (ie. no .compute)
inplace : bool, optional
When working in memory, determines if operation is performed inplace, default is True. When
working lazily the result will NOT be inplace.
*args :
passed to :meth:`hyperspy.api.signals.BaseSignal.map` if working in memory
**kwargs :
passed to :meth:`hyperspy.api.signals.BaseSignal.map` if working in memory
Returns
-------
signal_corrected: :class:`pyxem.signals.Diffraction2D` or :class:`pyxem.signals.LazyDiffraction2D`
Examples
--------
>>> s = pxm.data.dummy_data.get_hot_pixel_signal()
>>> s_hot_pixels = s.find_hot_pixels()
>>> s_corr = s.correct_bad_pixels(s_hot_pixels)
See Also
--------
find_dead_pixels
find_hot_pixels
"""
return self.map(remove_bad_pixels, bad_pixels=bad_pixel_array, **kwargs)
""" Direct beam and peak finding tools """
@deprecated_argument(
name="lazy_result", since="0.14", removal="1.0.0", alternative="lazy_output"
)
def get_direct_beam_position(
self,
method,
lazy_output=None,
signal_slice=None,
half_square_width=None,
**kwargs,
):
"""Estimate the direct beam position in each experimentally acquired
electron diffraction pattern. Returns the shifts required to center the
diffraction pattern.
Parameters
----------
method : str,
Must be one of "cross_correlate", "blur", "interpolate" or "center_of_mass".
"cross_correlate": Center finding using cross-correlation of circles of
``radius_start`` to ``radius_finish``.
"blur": Center finding by blurring each frame with a Gaussian kernel with
standard deviation ``sigma`` and finding the maximum.
"interpolate": Finding the center by summing along X/Y and finding the peak
for each axis independently. Data is blurred first using a Gaussian kernel
with standard deviation ``sigma``.
"center_of_mass": The center is found using a calculation of the center of mass.
Optionally a ``mask`` can be applied to focus on just the center of some
dataset. A threshold value can also be given to suppress contrast from
weaker diffraction features.
lazy_output : optional
If True, s_shifts will be a lazy signal. If False, a non-lazy signal.
By default, if the signal is (non-)lazy, the result will also be (non-)lazy.
signal_slice : None or tuple
A tuple defining the (low_x,high_x, low_y, high_y) to slice the data before
finding the direct beam. Equivalent to
s.isig[low_x:high_x, low_y:high_y].get_direct_beam_position()+[low_x,low_y])
half_square_width : int
Half the side length of square that captures the direct beam in all
scans. Means that the centering algorithm is stable against
diffracted spots brighter than the direct beam. Crops the diffraction
pattern to `half_square_width` pixels around th center of the diffraction
pattern. Only one of `half_square_width` or signal_slice can be defined.
**kwargs:
Additional arguments accepted by :func:`pyxem.utils.diffraction.find_beam_center_blur`,
:func:`pyxem.utils.diffraction.find_beam_center_interpolate`,
:func:`pyxem.utils.diffraction.find_beam_offset_cross_correlation`,
and :func:`pyxem.signals.diffraction2d.Diffraction2D.center_of_mass`,
Returns
-------
s_shifts : :class:`pyxem.signals.BeamShift`
Array containing the shifts for each SED pattern, with the first
signal index being the x-shift and the second the y-shift.
"""
if half_square_width is not None and signal_slice is not None:
raise ValueError(
"Only one of `signal_slice` or `half_sqare_width` " "can be defined"
)
elif half_square_width is not None:
signal_shape = self.axes_manager.signal_shape
signal_center = np.array(signal_shape) / 2
min_x = int(signal_center[0] - half_square_width)
max_x = int(signal_center[0] + half_square_width)
min_y = int(signal_center[1] - half_square_width)
max_y = int(signal_center[1] + half_square_width)
signal_slice = (min_x, max_x, min_y, max_y)
if signal_slice is not None: # Crop the data
sig_axes = self.axes_manager.signal_axes
sig_axes = np.repeat(sig_axes, 2)
low_x, high_x, low_y, high_y = [
_to_hyperspy_index(ind, ax)
for ind, ax in zip(
signal_slice,
sig_axes,
)
]
signal = self.isig[low_x:high_x, low_y:high_y]
else:
signal = self
if "lazy_result" in kwargs:
warnings.warn(
"lazy_result was replaced with lazy_output in version 0.14",
DeprecationWarning,
)
lazy_output = kwargs.pop("lazy_result")
if lazy_output is None:
lazy_output = signal._lazy
signal_shape = signal.axes_manager.signal_shape
origin_coordinates = np.array(signal_shape) / 2
method_dict = {
"cross_correlate": find_beam_offset_cross_correlation,
"blur": find_beam_center_blur,
"interpolate": find_beam_center_interpolate,
"center_of_mass": None,
}
method_function = _select_method_from_method_dict(
method, method_dict, print_help=False, **kwargs
)
if method == "cross_correlate":
shifts = signal.map(
method_function,
inplace=False,
output_signal_size=(2,),
output_dtype=np.float32,
lazy_output=lazy_output,
**kwargs,
)
elif method == "blur":
centers = signal.map(
method_function,
inplace=False,
output_signal_size=(2,),
output_dtype=np.int16,
lazy_output=lazy_output,
**kwargs,
)
shifts = -centers + origin_coordinates
elif method == "interpolate":
centers = signal.map(
method_function,
inplace=False,
output_signal_size=(2,),
output_dtype=np.float32,
lazy_output=lazy_output,
**kwargs,
)
shifts = -centers + origin_coordinates
elif method == "center_of_mass":
if "mask" in kwargs and signal_slice is not None:
x, y, r = kwargs["mask"]
x = x - signal_slice[0]
y = y - signal_slice[1]
kwargs["mask"] = (x, y, r)
centers = signal.center_of_mass(
lazy_result=lazy_output,
show_progressbar=False,
**kwargs,
)
shifts = -centers.T + origin_coordinates
if signal_slice is not None:
shifted_center = [(low_x + high_x) / 2, (low_y + high_y) / 2]
unshifted_center = np.array(self.axes_manager.signal_shape) / 2
shift = np.subtract(unshifted_center, shifted_center)
shifts = shifts + shift
shifts.set_signal_type("beam_shift")
return shifts
@deprecated_argument(
name="lazy_result", since="0.15", removal="1.0.0", alternative="lazy_output"
)
def center_direct_beam(
self,
method=None,
shifts=None,
return_shifts=False,
subpixel=True,
lazy_output=None,
align_kwargs=None,
inplace=True,
*args,
**kwargs,
):
"""Estimate the direct beam position in each experimentally acquired
electron diffraction pattern and translate it to the center of the
image square.
Parameters
----------
method : str {'cross_correlate', 'blur', 'interpolate', 'center_of_mass'}
Method used to estimate the direct beam position. The direct
beam position can also be passed directly with the shifts parameter.
shifts : Signal, optional
The position of the direct beam, which can either be passed with this
parameter (shifts), or calculated on its own.
Both shifts and the signal need to have the same navigation shape, and
shifts needs to have one signal dimension with size 2.
return_shifts : bool, default False
If True, the values of applied shifts are returned
subpixel : bool, optional
If True, the data will be interpolated, allowing for subpixel shifts of
the diffraction patterns. This can lead to changes in the total intensity
of the diffraction images, see Notes for more information. If False, the
data is not interpolated. Default True.
lazy_output : optional
If True, the result will be a lazy signal. If False, a non-lazy signal.
By default, if the signal is lazy, the result will also be lazy.
If the signal is non-lazy, the result will be non-lazy.
align_kwargs : dict
Parameters passed to the alignment function. See scipy.ndimage.shift
for more information about the parameters.
*args, **kwargs :
Additional arguments accepted by :func:`pyxem.utils.diffraction.find_beam_center_blur`,
:func:`pyxem.utils.diffraction.find_beam_center_interpolate`,
:func:`pyxem.utils.diffraction.find_beam_offset_cross_correlation`,
:func:`pyxem.signals.diffraction2d.Diffraction2D.get_direct_beam_position`,
and :func:`pyxem.signals.diffraction2d.Diffraction2D.center_of_mass`,
Example
-------
>>> s.center_direct_beam(method='blur', sigma=1)
Using the shifts parameter
>>> s_shifts = s.get_direct_beam_position(
... method="interpolate", sigma=1, upsample_factor=2, kind="nearest")
>>> s.center_direct_beam(shifts=s_shifts)
Notes
-----
If the signal has an integer dtype, and subpixel=True is used (the default)
the total intensity in the diffraction images will most likely not be preserved.
This is due to ``subpixel=True`` utilizing interpolation. To keep the total intensity
use a float dtype, which can be done by ``s.change_dtype('float32', rechunk=False)``.
"""
if (shifts is None) and (method is None):
raise ValueError("Either method or shifts parameter must be specified")
if (shifts is not None) and (method is not None):
raise ValueError(
"Only one of the shifts or method parameters should be specified, "
"not both"
)
if align_kwargs is None:
align_kwargs = {}
if shifts is None:
shifts = self.get_direct_beam_position(
method=method, lazy_output=lazy_output, **kwargs
)
if "order" not in align_kwargs:
if subpixel:
align_kwargs["order"] = 1
else:
align_kwargs["order"] = 0
aligned = self.map(
_align_single_frame,
shifts=shifts,
inplace=inplace,
lazy_output=lazy_output,
output_dtype=self.data.dtype,
output_signal_size=self.axes_manager.signal_shape[::-1],
**align_kwargs,
)
if return_shifts and inplace:
return shifts
elif return_shifts:
return shifts, aligned
else:
return aligned
def threshold_and_mask(self, threshold=None, mask=None, show_progressbar=True):
"""Get a thresholded and masked of the signal.
Useful for figuring out optimal settings for the
:meth:`pyxem.signals.Diffraction2D.center_of_mass` method.
Parameters
----------
threshold : number, optional
The thresholding will be done at mean times
this threshold value.
mask : tuple (x, y, r)
Round mask centered on x and y, with radius r.
show_progressbar : bool
Default True
Returns
-------
s_out : pyxem.signals.Diffraction2D
Examples
--------
>>> s = pxm.data.dummy_data.get_disk_shift_simple_test_signal()
>>> mask = (25, 25, 10)
>>> s_out = s.threshold_and_mask(
... mask=mask, threshold=2, show_progressbar=False)
>>> s_out.plot()
See Also
--------
center_of_mass
"""
if self._lazy:
raise NotImplementedError(
"threshold_and_mask is currently not implemented for "
"lazy signals. Use compute() first to turn signal into "
"a non-lazy signal. Note that this will load the full "
"dataset into memory, which might crash your computer."
)
if mask is not None:
x, y, r = mask
im_x, im_y = self.axes_manager.signal_shape
mask = pst._make_circular_mask(x, y, im_x, im_y, r)
s_out = self.map(
function=pst._threshold_and_mask_single_frame,
ragged=False,
inplace=False,
show_progressbar=show_progressbar,
threshold=threshold,
mask=mask,
)
return s_out
@deprecated_argument(
since="0.15.0", name="lazy_result", alternative="lazy_output", removal="1.00.0"
)
def center_of_mass(
self,
threshold=None,
mask=None,
**kwargs,
):
"""Get the centre of the STEM diffraction pattern using
center of mass. Threshold can be set to only use the most
intense parts of the pattern. A mask can be used to exclude
parts of the diffraction pattern.
Parameters
----------
threshold : number, optional
The thresholding will be done at mean times
this threshold value.
mask : tuple (x, y, r), optional
Round mask centered on x and y, with radius r. These are pixel values rather
than physical units. Default None which means no mask is used.
Returns
-------
DPCSignal
DPCSignal with beam shifts along the navigation dimension
and spatial dimensions as the signal dimension(s).
Examples
--------
With mask centered at x=105, y=120 and 30 pixel radius
>>> s = pxm.data.dummy_data.get_disk_shift_simple_test_signal()
>>> mask = (25, 25, 10)
>>> s_com = s.center_of_mass(mask=mask, show_progressbar=False)
>>> s_color = s_com.get_color_signal()
Also threshold
>>> s_com = s.center_of_mass(threshold=1.5, show_progressbar=False)
Get a lazy signal, then calculate afterwards
>>> s_com = s.center_of_mass(lazy_result=True, show_progressbar=False)
>>> s_com.compute(show_progressbar=False)
"""
if "inplace" in kwargs and kwargs["inplace"]:
raise ValueError("Inplace is not allowed for center_of_mass")
else:
kwargs["inplace"] = False
det_shape = self.axes_manager.signal_shape
if mask is not None:
x, y, r = mask
mask = pst._make_circular_mask(x, y, det_shape[0], det_shape[1], r)
ans = self.map(center_of_mass, threshold=threshold, mask=mask, **kwargs)
ans = ans.T
ans.set_signal_type("dpc")
ans.axes_manager.navigation_axes[0].name = "Beam position"
return ans
@deprecated_argument(
name="lazy_result", alternative="lazy_output", since="0.15.0", removal="1.0.0"
)
def template_match_disk(self, disk_r=4, inplace=False, **kwargs):