/
signal.py
3286 lines (2870 loc) · 124 KB
/
signal.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 2007-2011 The Hyperspy developers
#
# This file is part of Hyperspy.
#
# Hyperspy 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.
#
# Hyperspy 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 Hyperspy. If not, see <http://www.gnu.org/licenses/>.
import copy
import os.path
import numpy as np
import numpy.ma as ma
import scipy as sp
from matplotlib import pyplot as plt
from hyperspy import messages
from hyperspy.axes import AxesManager
from hyperspy import io
from hyperspy.drawing import mpl_hie, mpl_hse
from hyperspy.misc import utils
from hyperspy.learn.mva import MVA, LearningResults
from hyperspy.misc.utils import DictionaryBrowser
from hyperspy.drawing import signal as sigdraw
from hyperspy.decorators import auto_replot
from hyperspy.defaults_parser import preferences
from hyperspy.misc.io.tools import ensure_directory
from hyperspy.misc.progressbar import progressbar
from hyperspy.gui.tools import (
SpectrumCalibration,
SmoothingSavitzkyGolay,
SmoothingLowess,
SmoothingTV,
ButterworthFilter)
from hyperspy.gui.egerton_quantification import BackgroundRemoval
from hyperspy.decorators import only_interactive
from hyperspy.decorators import interactive_range_selector
from scipy.ndimage.filters import gaussian_filter1d
from hyperspy.misc.spectrum_tools import find_peaks_ohaver
from hyperspy.misc.image_tools import (shift_image, estimate_image_shift)
from hyperspy.misc.math_tools import symmetrize, antisymmetrize
from hyperspy.exceptions import SignalDimensionError
from hyperspy.misc import array_tools
from hyperspy.misc import spectrum_tools
class Signal2DTools(object):
def estimate_shift2D(self, reference='current',
correlation_threshold=None,
chunk_size=30,
roi=None,
normalize_corr=False,
sobel=True,
medfilter=True,
hanning=True,
plot=False,
dtype='float',):
"""Estimate the shifts in a image using phase correlation
This method can only estimate the shift by comparing
bidimensional features that should not change position
between frames. To decrease the memory usage, the time of
computation and the accuracy of the results it is convenient
to select a region of interest by setting the roi keyword.
Parameters
----------
reference : {'current', 'cascade' ,'stat'}
If 'current' (default) the image at the current
coordinates is taken as reference. If 'cascade' each image
is aligned with the previous one. If 'stat' the translation
of every image with all the rest is estimated and by
performing statistical analysis on the result the
translation is estimated.
correlation_threshold : {None, 'auto', float}
This parameter is only relevant when `reference` is 'stat'.
If float, the shift estimations with a maximum correlation
value lower than the given value are not used to compute
the estimated shifts. If 'auto' the threshold is calculated
automatically as the minimum maximum correlation value
of the automatically selected reference image.
chunk_size: {None, int}
If int and `reference`=='stat' the number of images used
as reference are limited to the given value.
roi : tuple of ints (top, bottom, left, right)
Define the region of interest
sobel : bool
apply a sobel filter for edge enhancement
medfilter : bool
apply a median filter for noise reduction
hanning : bool
Apply a 2d hanning filter
plot : bool
If True plots the images after applying the filters and
the phase correlation
dtype : str or dtype
Typecode or data-type in which the calculations must be
performed.
Returns
-------
list of applied shifts
Notes
-----
The statistical analysis approach to the translation estimation
when using `reference`='stat' roughly follows [1]_ . If you use
it please cite their article.
References
----------
.. [1] Schaffer, Bernhard, Werner Grogger, and Gerald
Kothleitner. “Automated Spatial Drift Correction for EFTEM
Image Series.”
Ultramicroscopy 102, no. 1 (December 2004): 27–36.
"""
self._check_signal_dimension_equals_two()
ref = None if reference == 'cascade' else \
self.__call__().copy()
shifts = []
nrows = None
images_number = self.axes_manager._max_index + 1
if reference == 'stat':
nrows = images_number if chunk_size is None else \
min(images_number, chunk_size)
pcarray = ma.zeros((nrows, self.axes_manager._max_index + 1,
),
dtype=np.dtype([('max_value', np.float),
('shift', np.int32,
(2,))]))
nshift, max_value = estimate_image_shift(
self(),
self(),
roi=roi,
sobel=sobel,
medfilter=medfilter,
hanning=hanning,
normalize_corr=normalize_corr,
plot=plot,
dtype=dtype)
np.fill_diagonal(pcarray['max_value'], max_value)
pbar = progressbar(maxval=nrows*images_number).start()
else:
pbar = progressbar(maxval=images_number).start()
# Main iteration loop. Fills the rows of pcarray when reference
# is stat
for i1, im in enumerate(self._iterate_signal()):
if reference in ['current', 'cascade']:
if ref is None:
ref = im.copy()
shift = np.array([0,0])
nshift, max_val = estimate_image_shift(ref,
im,
roi=roi,
sobel=sobel,
medfilter=medfilter,
hanning=hanning,
plot=plot,
normalize_corr=normalize_corr,
dtype=dtype)
if reference == 'cascade':
shift += nshift
ref = im.copy()
else:
shift = nshift
shifts.append(shift.copy())
pbar.update(i1+1)
elif reference == 'stat':
if i1 == nrows:
break
# Iterate to fill the columns of pcarray
for i2, im2 in enumerate(
self._iterate_signal()):
if i2 > i1:
nshift, max_value = estimate_image_shift(
im,
im2,
roi=roi,
sobel=sobel,
medfilter=medfilter,
hanning=hanning,
normalize_corr=normalize_corr,
plot=plot,
dtype=dtype)
pcarray[i1,i2] = max_value, nshift
del im2
pbar.update(i2 + images_number*i1 + 1)
del im
if reference == 'stat':
# Select the reference image as the one that has the
# higher max_value in the row
sqpcarr = pcarray[:,:nrows]
sqpcarr['max_value'][:] = symmetrize(sqpcarr['max_value'])
sqpcarr['shift'][:] = antisymmetrize(sqpcarr['shift'])
ref_index = np.argmax(pcarray['max_value'].min(1))
self.ref_index = ref_index
shifts = (pcarray['shift'] +
pcarray['shift'][ref_index,:nrows][:,np.newaxis])
if correlation_threshold is not None:
if correlation_threshold == 'auto':
correlation_threshold = \
(pcarray['max_value'].min(0)).max()
print("Correlation threshold = %1.2f" %
correlation_threshold)
shifts[pcarray['max_value'] < \
correlation_threshold] = ma.masked
shifts.mask[ref_index,:] = False
shifts = shifts.mean(0)
else:
shifts = np.array(shifts)
del ref
return shifts
def align2D(self, crop=True, fill_value=np.nan, shifts=None,
roi=None,
sobel=True,
medfilter=True,
hanning=True,
plot=False,
normalize_corr=False,
reference='current',
dtype='float',
correlation_threshold=None,
chunk_size=30):
"""Align the images in place using user provided shifts or by
estimating the shifts.
Please, see `estimate_shift2D` docstring for details
on the rest of the parameters not documented in the following
section
Parameters
----------
crop : bool
If True, the data will be cropped not to include regions
with missing data
fill_value : int, float, nan
The areas with missing data are filled with the given value.
Default is nan.
shifts : None or list of tuples
If None the shifts are estimated using
`estimate_shift2D`.
Returns
-------
shifts : np.array
The shifts are returned only if `shifts` is None
Notes
-----
The statistical analysis approach to the translation estimation
when using `reference`='stat' roughly follows [1]_ . If you use
it please cite their article.
References
----------
.. [1] Schaffer, Bernhard, Werner Grogger, and Gerald
Kothleitner. “Automated Spatial Drift Correction for EFTEM
Image Series.”
Ultramicroscopy 102, no. 1 (December 2004): 27–36.
"""
self._check_signal_dimension_equals_two()
if shifts is None:
shifts = self.estimate_shift2D(
roi=roi,sobel=sobel, medfilter=medfilter,
hanning=hanning, plot=plot,reference=reference,
dtype=dtype, correlation_threshold=
correlation_threshold,
normalize_corr=normalize_corr,
chunk_size=chunk_size)
return_shifts = True
else:
return_shifts = False
# Translate with sub-pixel precision if necesary
for im, shift in zip(self._iterate_signal(),
shifts):
if np.any(shift):
shift_image(im, -shift,
fill_value=fill_value)
del im
# Crop the image to the valid size
if crop is True:
shifts = -shifts
bottom, top = (int(np.floor(shifts[:,0].min())) if
shifts[:,0].min() < 0 else None,
int(np.ceil(shifts[:,0].max())) if
shifts[:,0].max() > 0 else 0)
right, left = (int(np.floor(shifts[:,1].min())) if
shifts[:,1].min() < 0 else None,
int(np.ceil(shifts[:,1].max())) if
shifts[:,1].max() > 0 else 0)
self.crop_image(top, bottom, left, right)
shifts = -shifts
if return_shifts:
return shifts
def crop_image(self,top=None, bottom=None,
left=None, right=None):
"""Crops an image in place.
top, bottom, left, right : int or float
If int the values are taken as indices. If float the values are
converted to indices.
See also:
---------
crop
"""
self._check_signal_dimension_equals_two()
self.crop(self.axes_manager.signal_axes[1].index_in_axes_manager,
top,
bottom)
self.crop(self.axes_manager.signal_axes[0].index_in_axes_manager,
left,
right)
class Signal1DTools(object):
def shift1D(self,
shift_array,
interpolation_method='linear',
crop=True,
fill_value=np.nan):
"""Shift the data in place over the signal axis by the amount specified
by an array.
Parameters
----------
shift_array : numpy array
An array containing the shifting amount. It must have
`axes_manager._navigation_shape_in_array` shape.
interpolation_method : str or int
Specifies the kind of interpolation as a string ('linear',
'nearest', 'zero', 'slinear', 'quadratic, 'cubic') or as an
integer specifying the order of the spline interpolator to
use.
crop : bool
If True automatically crop the signal axis at both ends if
needed.
fill_value : float
If crop is False fill the data outside of the original
interval with the given value where needed.
Raises
------
SignalDimensionError if the signal dimension is not 1.
"""
self._check_signal_dimension_equals_one()
axis = self.axes_manager.signal_axes[0]
offset = axis.offset
original_axis = axis.axis.copy()
pbar = progressbar(
maxval=self.axes_manager.navigation_size)
for i, (dat, shift) in enumerate(zip(
self._iterate_signal(),
shift_array.ravel(()))):
si = sp.interpolate.interp1d(original_axis,
dat,
bounds_error=False,
fill_value=fill_value,
kind=interpolation_method)
axis.offset = float(offset - shift)
dat[:] = si(axis.axis)
pbar.update(i + 1)
axis.offset = offset
if crop is True:
mini, maxi = shift_array.min(), shift_array.max()
if mini < 0:
self.crop(axis.index_in_axes_manager,
None,
axis.axis[-1] + mini + axis.scale)
if maxi > 0:
self.crop(axis.index_in_axes_manager,
float(offset + maxi))
def interpolate_in_between(self, start, end, delta=3, **kwargs):
"""Replace the data in a given range by interpolation.
The operation is performed in place.
Parameters
----------
start, end : {int | float}
The limits of the interval. If int they are taken as the
axis index. If float they are taken as the axis value.
All extra keyword arguments are passed to
scipy.interpolate.interp1d. See the function documentation
for details.
Raises
------
SignalDimensionError if the signal dimension is not 1.
"""
self._check_signal_dimension_equals_one()
axis = self.axes_manager.signal_axes[0]
i1 = axis._get_index(start)
i2 = axis._get_index(end)
i0 = int(np.clip(i1 - delta, 0, np.inf))
i3 = int(np.clip(i2 + delta, 0, axis.size))
pbar = progressbar(
maxval=self.axes_manager.navigation_size)
for i, dat in enumerate(self._iterate_signal()):
dat_int = sp.interpolate.interp1d(
range(i0,i1) + range(i2,i3),
dat[i0:i1].tolist() + dat[i2:i3].tolist(),
**kwargs)
dat[i1:i2] = dat_int(range(i1,i2))
pbar.update(i + 1)
def estimate_shift1D(self,
start=None,
end=None,
reference_indices=None,
max_shift=None,
interpolate=True,
number_of_interpolation_points=5):
"""Estimate the shifts in the current signal axis using
cross-correlation.
This method can only estimate the shift by comparing
unidimensional features that should not change the position in
the signal axis. To decrease the memory usage, the time of
computation and the accuracy of the results it is convenient to
select the feature of interest providing sensible values for
`start` and `end`. By default interpolation is used to obtain
subpixel precision.
Parameters
----------
start, end : {int | float | None}
The limits of the interval. If int they are taken as the
axis index. If float they are taken as the axis value.
reference_indices : tuple of ints or None
Defines the coordinates of the spectrum that will be used
as eference. If None the spectrum at the current
coordinates is used for this purpose.
max_shift : int
"Saturation limit" for the shift.
interpolate : bool
If True, interpolation is used to provide sub-pixel
accuracy.
number_of_interpolation_points : int
Number of interpolation points. Warning: making this number
too big can saturate the memory
Return
------
An array with the result of the estimation in the axis units.
Raises
------
SignalDimensionError if the signal dimension is not 1.
"""
self._check_signal_dimension_equals_one()
ip = number_of_interpolation_points + 1
axis = self.axes_manager.signal_axes[0]
if reference_indices is None:
reference_indices = self.axes_manager.indices
i1, i2 = axis._get_index(start), axis._get_index(end)
shift_array = np.zeros(self.axes_manager._navigation_shape_in_array)
ref = self.navigation_indexer[reference_indices].data[i1:i2]
if interpolate is True:
ref = spectrum_tools.interpolate1D(ip, ref)
pbar = progressbar(
maxval=self.axes_manager.navigation_size)
for i, (dat, indices) in enumerate(zip(
self._iterate_signal(),
self.axes_manager._array_indices_generator())):
dat = dat[i1:i2]
if interpolate is True:
dat = spectrum_tools.interpolate1D(ip, dat)
shift_array[indices] = np.argmax(
np.correlate(ref, dat,'full')) - len(ref) + 1
pbar.update(i + 1)
pbar.finish()
if max_shift is not None:
if interpolate is True:
max_shift *= ip
shift_array.clip(a_min=-max_shift, a_max=max_shift)
if interpolate is True:
shift_array /= ip
shift_array *= axis.scale
return shift_array
def align1D(self,
start=None,
end=None,
reference_indices=None,
max_shift=None,
interpolate=True,
number_of_interpolation_points=5,
interpolation_method='linear',
crop=True,
fill_value=np.nan,
also_align=None):
"""Estimate the shifts in the signal axis using
cross-correlation and use the estimation to align the data in place.
This method can only estimate the shift by comparing
unidimensional
features that should not change the position.
To decrease memory usage, time of computation and improve
accuracy it is convenient to select the feature of interest
setting the `start` and `end` keywords. By default interpolation is
used to obtain subpixel precision.
Parameters
----------
start, end : {int | float | None}
The limits of the interval. If int they are taken as the
axis index. If float they are taken as the axis value.
reference_indices : tuple of ints or None
Defines the coordinates of the spectrum that will be used
as eference. If None the spectrum at the current
coordinates is used for this purpose.
max_shift : int
"Saturation limit" for the shift.
interpolate : bool
If True, interpolation is used to provide sub-pixel
accuracy.
number_of_interpolation_points : int
Number of interpolation points. Warning: making this number
too big can saturate the memory
interpolation_method : str or int
Specifies the kind of interpolation as a string ('linear',
'nearest', 'zero', 'slinear', 'quadratic, 'cubic') or as an
integer specifying the order of the spline interpolator to
use.
crop : bool
If True automatically crop the signal axis at both ends if
needed.
fill_value : float
If crop is False fill the data outside of the original
interval with the given value where needed.
also_align : list of signals
A list of Signal instances that has exactly the same
dimensions
as this one and that will be aligned using the shift map
estimated using the this signal.
Return
------
An array with the result of the estimation. The shift will be
Raises
------
SignalDimensionError if the signal dimension is not 1.
See also
--------
estimate_shift1D
"""
self._check_signal_dimension_equals_one()
shift_array = self.estimate_shift1D(
start=start,
end=end,
reference_indices=reference_indices,
max_shift=max_shift,
interpolate=interpolate,
number_of_interpolation_points=
number_of_interpolation_points)
if also_align is None:
also_align = list()
also_align.append(self)
for signal in also_align:
signal.shift1D(shift_array=shift_array,
interpolation_method=interpolation_method,
crop=crop,
fill_value=fill_value)
@only_interactive
def calibrate(self):
"""Calibrate the spectral dimension using a gui.
It displays a window where the new calibration can be set by:
* Setting the offset, units and scale directly
* Selection a range by dragging the mouse on the spectrum figure
and
setting the new values for the given range limits
Notes
-----
For this method to work the output_dimension must be 1. Set the
view
accordingly
Raises
------
SignalDimensionError if the signal dimension is not 1.
"""
self._check_signal_dimension_equals_one()
calibration = SpectrumCalibration(self)
calibration.edit_traits()
def smooth_savitzky_golay(self, polynomial_order=None,
number_of_points=None, differential_order=0):
"""Savitzky-Golay data smoothing in place.
"""
self._check_signal_dimension_equals_one()
if (polynomial_order is not None and
number_of_points is not None):
for spectrum in self:
spectrum.data[:] = spectrum_tools.sg(self(),
number_of_points,
polynomial_order,
differential_order)
else:
smoother = SmoothingSavitzkyGolay(self)
smoother.differential_order = differential_order
if polynomial_order is not None:
smoother.polynomial_order = polynomial_order
if number_of_points is not None:
smoother.number_of_points = number_of_points
smoother.edit_traits()
def smooth_lowess(self, smoothing_parameter=None,
number_of_iterations=None, differential_order=0):
"""Lowess data smoothing in place.
Raises
------
SignalDimensionError if the signal dimension is not 1.
"""
self._check_signal_dimension_equals_one()
smoother = SmoothingLowess(self)
smoother.differential_order = differential_order
if smoothing_parameter is not None:
smoother.smoothing_parameter = smoothing_parameter
if number_of_iterations is not None:
smoother.number_of_iterations = number_of_iterations
if smoothing_parameter is None or smoothing_parameter is None:
smoother.edit_traits()
else:
smoother.apply()
def smooth_tv(self, smoothing_parameter=None, differential_order=0):
"""Total variation data smoothing in place.
Raises
------
SignalDimensionError if the signal dimension is not 1.
"""
self._check_signal_dimension_equals_one()
smoother = SmoothingTV(self)
smoother.differential_order = differential_order
if smoothing_parameter is not None:
smoother.smoothing_parameter = smoothing_parameter
if smoothing_parameter is None:
smoother.edit_traits()
else:
smoother.apply()
def filter_butterworth(self,
cutoff_frequency_ratio=None,
type='low',
order=2):
"""Butterworth filter in place.
Raises
------
SignalDimensionError if the signal dimension is not 1.
"""
self._check_signal_dimension_equals_one()
smoother = ButterworthFilter(self)
if cutoff_frequency_ratio is not None:
smoother.cutoff_frequency_ratio = cutoff_frequency_ratio
smoother.apply()
else:
smoother.edit_traits()
@only_interactive
def remove_background(self):
"""Remove the background in place using a gui.
Raises
------
SignalDimensionError if the signal dimension is not 1.
"""
self._check_signal_dimension_equals_one()
br = BackgroundRemoval(self)
br.edit_traits()
@interactive_range_selector
def crop_spectrum(self, left_value=None, right_value=None,):
"""Crop in place the spectral dimension.
Parameters
----------
left_value, righ_value: {int | float | None}
If int the values are taken as indices. If float they are
converted to indices using the spectral axis calibration.
If left_value is None crops from the beginning of the axis.
If right_value is None crops up to the end of the axis. If
both are
None the interactive cropping interface is activated
enabling
cropping the spectrum using a span selector in the signal
plot.
Raises
------
SignalDimensionError if the signal dimension is not 1.
"""
self._check_signal_dimension_equals_one()
self.crop(
axis=self.axes_manager.signal_axes[0].index_in_axes_manager,
start=left_value, end=right_value)
@auto_replot
def gaussian_filter(self, FWHM):
"""Applies a Gaussian filter in the spectral dimension in place.
Parameters
----------
FWHM : float
The Full Width at Half Maximum of the gaussian in the
spectral axis units
Raises
------
ValueError if FWHM is equal or less than zero.
SignalDimensionError if the signal dimension is not 1.
"""
self._check_signal_dimension_equals_one()
if FWHM <= 0:
raise ValueError(
"FWHM must be greater than zero")
axis = self.axes_manager.signal_axes[0]
FWHM *= 1/axis.scale
self.data = gaussian_filter1d(
self.data,
axis=axis.index_in_array,
sigma=FWHM/2.35482)
@auto_replot
def hanning_taper(self, side='both', channels=None, offset=0):
"""Apply a hanning taper to the data in place.
Parameters
----------
side : {'left', 'right', 'both'}
channels : {None, int}
The number of channels to taper. If None 5% of the total
number of channels are tapered.
offset : int
Returns
-------
channels
Raises
------
SignalDimensionError if the signal dimension is not 1.
"""
# TODO: generalize it
self._check_signal_dimension_equals_one()
if channels is None:
channels = int(round(len(self()) * 0.02))
if channels < 20:
channels = 20
dc = self.data
if side == 'left' or side == 'both':
dc[..., offset:channels+offset] *= (
np.hanning(2*channels)[:channels])
dc[...,:offset] *= 0.
if side== 'right' or side == 'both':
if offset == 0:
rl = None
else:
rl = -offset
dc[..., -channels-offset:rl] *= (
np.hanning(2*channels)[-channels:])
if offset != 0:
dc[..., -offset:] *= 0.
return channels
def find_peaks1D_ohaver(self, xdim=None,slope_thresh=0, amp_thresh=None,
subchannel=True, medfilt_radius=5, maxpeakn=30000,
peakgroup=10):
"""Find peaks along a 1D line (peaks in spectrum/spectra).
Function to locate the positive peaks in a noisy x-y data set.
Detects peaks by looking for downward zero-crossings in the
first
derivative that exceed 'slope_thresh'.
Returns an array containing position, height, and width of each
peak.
'slope_thresh' and 'amp_thresh', control sensitivity: higher
values will
neglect smaller features.
peakgroup is the number of points around the top peak to search
around
Parameters
---------
slope_thresh : float (optional)
1st derivative threshold to count the peak
default is set to 0.5
higher values will neglect smaller features.
amp_thresh : float (optional)
intensity threshold above which
default is set to 10% of max(y)
higher values will neglect smaller features.
medfilt_radius : int (optional)
median filter window to apply to smooth the data
(see scipy.signal.medfilt)
if 0, no filter will be applied.
default is set to 5
peakgroup : int (optional)
number of points around the "top part" of the peak
default is set to 10
maxpeakn : int (optional)
number of maximum detectable peaks
default is set to 5000
subpix : bool (optional)
default is set to True
Returns
-------
peaks : structured array of shape _navigation_shape_in_array in which
each cell contains an array that contains as many structured arrays as
peaks where found at that location and which fields: position, width,
height contains position, height, and width of each peak.
Raises
------
SignalDimensionError if the signal dimension is not 1.
"""
# TODO: add scipy.signal.find_peaks_cwt
self._check_signal_dimension_equals_one()
axis = self.axes_manager.signal_axes[0].axis
arr_shape = (self.axes_manager._navigation_shape_in_array
if self.axes_manager.navigation_size > 0
else [1,])
peaks = np.zeros(arr_shape, dtype=object)
for y, indices in zip(self._iterate_signal(),
self.axes_manager._array_indices_generator()):
peaks[indices] = find_peaks_ohaver(
y,
axis,
slope_thresh=slope_thresh,
amp_thresh=amp_thresh,
medfilt_radius=medfilt_radius,
maxpeakn=maxpeakn,
peakgroup=peakgroup,
subchannel=subchannel)
return peaks
class MVATools(object):
# TODO: All of the plotting methods here should move to drawing
def _plot_factors_or_pchars(self, factors, comp_ids=None,
calibrate=True, avg_char=False,
same_window=None, comp_label='PC',
img_data=None,
plot_shifts=True, plot_char=4,
cmap=plt.cm.gray, quiver_color='white',
vector_scale=1,
per_row=3,ax=None):
"""Plot components from PCA or ICA, or peak characteristics
Parameters
----------
comp_ids : None, int, or list of ints
if None, returns maps of all components.
if int, returns maps of components with ids from 0 to given
int.
if list of ints, returns maps of components with ids in
given list.
calibrate : bool
if True, plots are calibrated according to the data in the
axes
manager.
same_window : bool
if True, plots each factor to the same window. They are
not scaled.
comp_label : string, the label that is either the plot title
(if plotting in
separate windows) or the label in the legend (if plotting
in the
same window)
cmap : a matplotlib colormap
The colormap used for factor images or
any peak characteristic scatter map
overlay.
Parameters only valid for peak characteristics (or pk char factors):
--------------------------------------------------------------------
img_data - 2D numpy array,
The array to overlay peak characteristics onto. If None,
defaults to the average image of your stack.
plot_shifts - bool, default is True
If true, plots a quiver (arrow) plot showing the shifts for
each
peak present in the component being plotted.
plot_char - None or int
If int, the id of the characteristic to plot as the colored
scatter plot.
Possible components are:
4: peak height
5: peak orientation
6: peak eccentricity
quiver_color : any color recognized by matplotlib
Determines the color of vectors drawn for
plotting peak shifts.
vector_scale : integer or None
Scales the quiver plot arrows. The vector
is defined as one data unit along the X axis.
If shifts are small, set vector_scale so
that when they are multiplied by vector_scale,
they are on the scale of the image plot.
If None, uses matplotlib's autoscaling.
"""
if same_window is None:
same_window = preferences.MachineLearning.same_window
if comp_ids is None:
comp_ids=xrange(factors.shape[1])
elif not hasattr(comp_ids,'__iter__'):
comp_ids=xrange(comp_ids)
n=len(comp_ids)
if same_window:
rows=int(np.ceil(n/float(per_row)))
fig_list=[]
if n<per_row: per_row=n
if same_window and self.axes_manager.signal_dimension==2:
f=plt.figure(figsize=(4*per_row,3*rows))
else:
f=plt.figure()
for i in xrange(len(comp_ids)):
if self.axes_manager.signal_dimension==1:
if same_window: