-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
ica.py
2473 lines (2119 loc) · 102 KB
/
ica.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
# Authors: Denis A. Engemann <denis.engemann@gmail.com>
# Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr>
# Juergen Dammers <j.dammers@fz-juelich.de>
#
# License: BSD (3-clause)
from inspect import isfunction
from collections import namedtuple
from copy import deepcopy
from numbers import Integral
import os
import json
import numpy as np
from scipy import linalg
from .ecg import (qrs_detector, _get_ecg_channel_index, _make_ecg,
create_ecg_epochs)
from .eog import _find_eog_events, _get_eog_channel_index
from .infomax_ import infomax
from ..cov import compute_whitener
from .. import Covariance, Evoked
from ..io.pick import (pick_types, pick_channels, pick_info,
_pick_data_channels, _DATA_CH_TYPES_SPLIT)
from ..io.write import (write_double_matrix, write_string,
write_name_list, write_int, start_block,
end_block)
from ..io.tree import dir_tree_find
from ..io.open import fiff_open
from ..io.tag import read_tag
from ..io.meas_info import write_meas_info, read_meas_info
from ..io.constants import Bunch, FIFF
from ..io.base import BaseRaw
from ..epochs import BaseEpochs
from ..viz import (plot_ica_components, plot_ica_scores,
plot_ica_sources, plot_ica_overlay)
from ..viz.ica import plot_ica_properties
from ..viz.utils import (_prepare_trellis, tight_layout, plt_show,
_setup_vmin_vmax)
from ..viz.topomap import (_prepare_topo_plot, _check_outlines,
plot_topomap, _hide_frame)
from ..channels.channels import _contains_ch_type, ContainsMixin
from ..io.write import start_file, end_file, write_id
from ..utils import (check_version, logger, check_fname, verbose,
_reject_data_segments, check_random_state,
_get_fast_dot, compute_corr, _get_inst_data,
copy_function_doc_to_method_doc, _pl)
from ..fixes import _get_args
from ..filter import filter_data
from .bads import find_outliers
from .ctps_ import ctps
from ..externals.six import string_types, text_type
from ..io.pick import channel_type
__all__ = ('ICA', 'ica_find_ecg_events', 'ica_find_eog_events',
'get_score_funcs', 'read_ica', 'run_ica')
def _make_xy_sfunc(func, ndim_output=False):
"""Aux function."""
if ndim_output:
def sfunc(x, y):
return np.array([func(a, y.ravel()) for a in x])[:, 0]
else:
def sfunc(x, y):
return np.array([func(a, y.ravel()) for a in x])
sfunc.__name__ = '.'.join(['score_func', func.__module__, func.__name__])
sfunc.__doc__ = func.__doc__
return sfunc
# makes score funcs attr accessible for users
def get_score_funcs():
"""Get the score functions."""
from scipy import stats
from scipy.spatial import distance
score_funcs = Bunch()
xy_arg_dist_funcs = [(n, f) for n, f in vars(distance).items()
if isfunction(f) and not n.startswith('_')]
xy_arg_stats_funcs = [(n, f) for n, f in vars(stats).items()
if isfunction(f) and not n.startswith('_')]
score_funcs.update(dict((n, _make_xy_sfunc(f))
for n, f in xy_arg_dist_funcs
if _get_args(f) == ['u', 'v']))
score_funcs.update(dict((n, _make_xy_sfunc(f, ndim_output=True))
for n, f in xy_arg_stats_funcs
if _get_args(f) == ['x', 'y']))
return score_funcs
def _check_for_unsupported_ica_channels(picks, info):
"""Check for channels in picks that are not considered valid channels.
Accepted channels are the data channels
('seeg','ecog','eeg', 'hbo', 'hbr', 'mag', and 'grad') and 'eog'.
This prevents the program from crashing without
feedback when a bad channel is provided to ICA whitening.
"""
if picks is None:
return
elif len(picks) == 0:
raise ValueError('No channels provided to ICA')
types = _DATA_CH_TYPES_SPLIT + ['eog']
chs = list(set([channel_type(info, j) for j in picks]))
check = all([ch in types for ch in chs])
if not check:
raise ValueError('Invalid channel type(s) passed for ICA.\n'
'Only the following channels are supported {0}\n'
'Following types were passed {1}\n'
.format(types, chs))
class ICA(ContainsMixin):
"""M/EEG signal decomposition using Independent Component Analysis (ICA).
This object can be used to estimate ICA components and then
remove some from Raw or Epochs for data exploration or artifact
correction.
Caveat! If supplying a noise covariance keep track of the projections
available in the cov or in the raw object. For example, if you are
interested in EOG or ECG artifacts, EOG and ECG projections should be
temporally removed before fitting the ICA. You can say::
>> projs, raw.info['projs'] = raw.info['projs'], []
>> ica.fit(raw)
>> raw.info['projs'] = projs
.. note:: Methods implemented are FastICA (default), Infomax and
Extended-Infomax. Infomax can be quite sensitive to differences
in floating point arithmetic due to exponential non-linearity.
Extended-Infomax seems to be more stable in this respect
enhancing reproducibility and stability of results.
Parameters
----------
n_components : int | float | None
The number of components used for ICA decomposition. If int, it must be
smaller then max_pca_components. If None, all PCA components will be
used. If float between 0 and 1 components will be selected by the
cumulative percentage of explained variance.
max_pca_components : int | None
The number of components used for PCA decomposition. If None, no
dimension reduction will be applied and max_pca_components will equal
the number of channels supplied on decomposing data. Defaults to None.
n_pca_components : int | float
The number of PCA components used after ICA recomposition. The ensuing
attribute allows to balance noise reduction against potential loss of
features due to dimensionality reduction. If greater than
``self.n_components_``, the next ``n_pca_components`` minus
``n_components_`` PCA components will be added before restoring the
sensor space data. The attribute gets updated each time the according
parameter for in .pick_sources_raw or .pick_sources_epochs is changed.
If float, the number of components selected matches the number of
components with a cumulative explained variance below
`n_pca_components`.
noise_cov : None | instance of mne.cov.Covariance
Noise covariance used for whitening. If None, channels are just
z-scored.
random_state : None | int | instance of np.random.RandomState
np.random.RandomState to initialize the FastICA estimation.
As the estimation is non-deterministic it can be useful to
fix the seed to have reproducible results. Defaults to None.
method : {'fastica', 'infomax', 'extended-infomax'}
The ICA method to use. Defaults to 'fastica'.
fit_params : dict | None.
Additional parameters passed to the ICA estimator chosen by `method`.
max_iter : int, optional
Maximum number of iterations during fit.
verbose : bool, str, int, or None
If not None, override default verbose level (see :func:`mne.verbose`
and :ref:`Logging documentation <tut_logging>` for more).
Attributes
----------
current_fit : str
Flag informing about which data type (raw or epochs) was used for
the fit.
ch_names : list-like
Channel names resulting from initial picking.
The number of components used for ICA decomposition.
``n_components_`` : int
If fit, the actual number of components used for ICA decomposition.
n_pca_components : int
See above.
max_pca_components : int
The number of components used for PCA dimensionality reduction.
verbose : bool, str, int, or None
See above.
``pca_components_`` : ndarray
If fit, the PCA components
``pca_mean_`` : ndarray
If fit, the mean vector used to center the data before doing the PCA.
``pca_explained_variance_`` : ndarray
If fit, the variance explained by each PCA component
``mixing_matrix_`` : ndarray
If fit, the mixing matrix to restore observed data, else None.
``unmixing_matrix_`` : ndarray
If fit, the matrix to unmix observed data, else None.
exclude : list
List of sources indices to exclude, i.e. artifact components identified
throughout the ICA solution. Indices added to this list, will be
dispatched to the .pick_sources methods. Source indices passed to
the .pick_sources method via the 'exclude' argument are added to the
.exclude attribute. When saving the ICA also the indices are restored.
Hence, artifact components once identified don't have to be added
again. To dump this 'artifact memory' say: ica.exclude = []
info : None | instance of Info
The measurement info copied from the object fitted.
``n_samples_`` : int
the number of samples used on fit.
``labels_`` : dict
A dictionary of independent component indices, grouped by types of
independent components. This attribute is set by some of the artifact
detection functions.
"""
@verbose
def __init__(self, n_components=None, max_pca_components=None,
n_pca_components=None, noise_cov=None, random_state=None,
method='fastica', fit_params=None, max_iter=200,
verbose=None): # noqa: D102
methods = ('fastica', 'infomax', 'extended-infomax')
if method not in methods:
raise ValueError('`method` must be "%s". You passed: "%s"' %
('" or "'.join(methods), method))
if not check_version('sklearn', '0.12'):
raise RuntimeError('the scikit-learn package (version >= 0.12)'
'is required for ICA')
self.noise_cov = noise_cov
if (n_components is not None and
max_pca_components is not None and
n_components > max_pca_components):
raise ValueError('n_components must be smaller than '
'max_pca_components')
if isinstance(n_components, float) \
and not 0 < n_components <= 1:
raise ValueError('Selecting ICA components by explained variance '
'needs values between 0.0 and 1.0 ')
self.current_fit = 'unfitted'
self.verbose = verbose
self.n_components = n_components
self.max_pca_components = max_pca_components
self.n_pca_components = n_pca_components
self.ch_names = None
self.random_state = random_state
if fit_params is None:
fit_params = {}
fit_params = deepcopy(fit_params) # avoid side effects
if "extended" in fit_params:
raise ValueError("'extended' parameter provided. You should "
"rather use method='extended-infomax'.")
if method == 'fastica':
update = {'algorithm': 'parallel', 'fun': 'logcosh',
'fun_args': None}
fit_params.update(dict((k, v) for k, v in update.items() if k
not in fit_params))
elif method == 'infomax':
fit_params.update({'extended': False})
elif method == 'extended-infomax':
fit_params.update({'extended': True})
if 'max_iter' not in fit_params:
fit_params['max_iter'] = max_iter
self.max_iter = max_iter
self.fit_params = fit_params
self.exclude = []
self.info = None
self.method = method
self.labels_ = dict()
def __repr__(self):
"""ICA fit information."""
if self.current_fit == 'unfitted':
s = 'no'
elif self.current_fit == 'raw':
s = 'raw data'
else:
s = 'epochs'
s += ' decomposition, '
s += 'fit (%s): %s samples, ' % (self.method,
str(getattr(self, 'n_samples_', '')))
s += ('%s components' % str(self.n_components_) if
hasattr(self, 'n_components_') else
'no dimension reduction')
if self.info is not None:
ch_fit = ['"%s"' % c for c in _DATA_CH_TYPES_SPLIT if c in self]
s += ', channels used: {0}'.format('; '.join(ch_fit))
if self.exclude:
s += ', %i sources marked for exclusion' % len(self.exclude)
return '<ICA | %s>' % s
@verbose
def fit(self, inst, picks=None, start=None, stop=None, decim=None,
reject=None, flat=None, tstep=2.0, reject_by_annotation=True,
verbose=None):
"""Run the ICA decomposition on raw data.
Caveat! If supplying a noise covariance keep track of the projections
available in the cov, the raw or the epochs object. For example,
if you are interested in EOG or ECG artifacts, EOG and ECG projections
should be temporally removed before fitting the ICA.
Parameters
----------
inst : instance of Raw, Epochs or Evoked
Raw measurements to be decomposed.
picks : array-like of int
Channels to be included. This selection remains throughout the
initialized ICA solution. If None only good data channels are used.
start : int | float | None
First sample to include. If float, data will be interpreted as
time in seconds. If None, data will be used from the first sample.
stop : int | float | None
Last sample to not include. If float, data will be interpreted as
time in seconds. If None, data will be used to the last sample.
decim : int | None
Increment for selecting each nth time slice. If None, all samples
within ``start`` and ``stop`` are used.
reject : dict | None
Rejection parameters based on peak-to-peak amplitude.
Valid keys are 'grad', 'mag', 'eeg', 'seeg', 'ecog', 'eog', 'ecg',
'hbo', 'hbr'.
If reject is None then no rejection is done. Example::
reject = dict(grad=4000e-13, # T / m (gradiometers)
mag=4e-12, # T (magnetometers)
eeg=40e-6, # V (EEG channels)
eog=250e-6 # V (EOG channels)
)
It only applies if `inst` is of type Raw.
flat : dict | None
Rejection parameters based on flatness of signal.
Valid keys are 'grad', 'mag', 'eeg', 'seeg', 'ecog', 'eog', 'ecg',
'hbo', 'hbr'.
Values are floats that set the minimum acceptable peak-to-peak
amplitude. If flat is None then no rejection is done.
It only applies if `inst` is of type Raw.
tstep : float
Length of data chunks for artifact rejection in seconds.
It only applies if `inst` is of type Raw.
reject_by_annotation : bool
Whether to omit bad segments from the data before fitting. If True,
annotated segments with a description that starts with 'bad' are
omitted. Has no effect if ``inst`` is an Epochs or Evoked object.
Defaults to True.
.. versionadded:: 0.14.0
verbose : bool, str, int, or None
If not None, override default verbose level (see
:func:`mne.verbose` and :ref:`Logging documentation <tut_logging>`
for more). Defaults to self.verbose.
Returns
-------
self : instance of ICA
Returns the modified instance.
"""
if isinstance(inst, (BaseRaw, BaseEpochs)):
_check_for_unsupported_ica_channels(picks, inst.info)
if isinstance(inst, BaseRaw):
self._fit_raw(inst, picks, start, stop, decim, reject, flat,
tstep, reject_by_annotation, verbose)
elif isinstance(inst, BaseEpochs):
self._fit_epochs(inst, picks, decim, verbose)
else:
raise ValueError('Data input must be of Raw or Epochs type')
# sort ICA components by explained variance
var = _ica_explained_variance(self, inst)
var_ord = var.argsort()[::-1]
_sort_components(self, var_ord, copy=False)
return self
def _reset(self):
"""Aux method."""
del self._pre_whitener
del self.unmixing_matrix_
del self.mixing_matrix_
del self.n_components_
del self.n_samples_
del self.pca_components_
del self.pca_explained_variance_
del self.pca_mean_
if hasattr(self, 'drop_inds_'):
del self.drop_inds_
def _fit_raw(self, raw, picks, start, stop, decim, reject, flat, tstep,
reject_by_annotation, verbose):
"""Aux method."""
if self.current_fit != 'unfitted':
self._reset()
if picks is None: # just use good data channels
picks = _pick_data_channels(raw.info, exclude='bads',
with_ref_meg=False)
logger.info('Fitting ICA to data using %i channels. \n'
'Please be patient, this may take some time' % len(picks))
if self.max_pca_components is None:
self.max_pca_components = len(picks)
logger.info('Inferring max_pca_components from picks.')
self.info = pick_info(raw.info, picks)
if self.info['comps']:
self.info['comps'] = []
self.ch_names = self.info['ch_names']
start, stop = _check_start_stop(raw, start, stop)
reject_by_annotation = 'omit' if reject_by_annotation else None
# this will be a copy
data = raw.get_data(picks, start, stop, reject_by_annotation)
# this will be a view
if decim is not None:
data = data[:, ::decim]
# this will make a copy
if (reject is not None) or (flat is not None):
data, self.drop_inds_ = _reject_data_segments(data, reject, flat,
decim, self.info,
tstep)
self.n_samples_ = data.shape[1]
# this may operate inplace or make a copy
data, self._pre_whitener = self._pre_whiten(data, raw.info, picks)
self._fit(data, self.max_pca_components, 'raw')
return self
def _fit_epochs(self, epochs, picks, decim, verbose):
"""Aux method."""
if self.current_fit != 'unfitted':
self._reset()
if picks is None:
picks = _pick_data_channels(epochs.info, exclude='bads',
with_ref_meg=False)
logger.info('Fitting ICA to data using %i channels. \n'
'Please be patient, this may take some time' % len(picks))
# filter out all the channels the raw wouldn't have initialized
self.info = pick_info(epochs.info, picks)
if self.info['comps']:
self.info['comps'] = []
self.ch_names = self.info['ch_names']
if self.max_pca_components is None:
self.max_pca_components = len(picks)
logger.info('Inferring max_pca_components from picks.')
# this should be a copy (picks a list of int)
data = epochs.get_data()[:, picks]
# this will be a view
if decim is not None:
data = data[:, :, ::decim]
self.n_samples_ = np.prod(data[:, 0, :].shape)
# This will make at least one copy (one from hstack, maybe one
# more from _pre_whiten)
data, self._pre_whitener = \
self._pre_whiten(np.hstack(data), epochs.info, picks)
self._fit(data, self.max_pca_components, 'epochs')
return self
def _pre_whiten(self, data, info, picks):
"""Aux function."""
fast_dot = _get_fast_dot()
has_pre_whitener = hasattr(self, '_pre_whitener')
if not has_pre_whitener and self.noise_cov is None:
# use standardization as whitener
# Scale (z-score) the data by channel type
info = pick_info(info, picks)
pre_whitener = np.empty([len(data), 1])
for ch_type in _DATA_CH_TYPES_SPLIT + ['eog']:
if _contains_ch_type(info, ch_type):
if ch_type == 'seeg':
this_picks = pick_types(info, meg=False, seeg=True)
elif ch_type == 'ecog':
this_picks = pick_types(info, meg=False, ecog=True)
elif ch_type == 'eeg':
this_picks = pick_types(info, meg=False, eeg=True)
elif ch_type in ('mag', 'grad'):
this_picks = pick_types(info, meg=ch_type)
elif ch_type == 'eog':
this_picks = pick_types(info, meg=False, eog=True)
elif ch_type in ('hbo', 'hbr'):
this_picks = pick_types(info, meg=False, fnirs=ch_type)
else:
raise RuntimeError('Should not be reached.'
'Unsupported channel {0}'
.format(ch_type))
pre_whitener[this_picks] = np.std(data[this_picks])
data /= pre_whitener
elif not has_pre_whitener and self.noise_cov is not None:
pre_whitener, _ = compute_whitener(self.noise_cov, info, picks)
assert data.shape[0] == pre_whitener.shape[1]
data = fast_dot(pre_whitener, data)
elif has_pre_whitener and self.noise_cov is None:
data /= self._pre_whitener
pre_whitener = self._pre_whitener
else:
data = fast_dot(self._pre_whitener, data)
pre_whitener = self._pre_whitener
return data, pre_whitener
def _fit(self, data, max_pca_components, fit_type):
"""Aux function."""
random_state = check_random_state(self.random_state)
if not check_version('sklearn', '0.18'):
from sklearn.decomposition import RandomizedPCA
# XXX fix copy==True later. Bug in sklearn, see PR #2273
pca = RandomizedPCA(n_components=max_pca_components, whiten=True,
copy=True, random_state=random_state)
else:
from sklearn.decomposition import PCA
pca = PCA(n_components=max_pca_components, copy=True, whiten=True,
svd_solver='randomized', random_state=random_state)
if isinstance(self.n_components, float):
# compute full feature variance before doing PCA
full_var = np.var(data, axis=1).sum()
data = pca.fit_transform(data.T)
if isinstance(self.n_components, float):
# compute eplained variance manually, cf. sklearn bug
# fixed in #2664
explained_variance_ratio_ = pca.explained_variance_ / full_var
n_components_ = np.sum(explained_variance_ratio_.cumsum() <=
self.n_components)
if n_components_ < 1:
raise RuntimeError('One PCA component captures most of the '
'explained variance, your threshold resu'
'lts in 0 components. You should select '
'a higher value.')
logger.info('Selection by explained variance: %i components' %
n_components_)
sel = slice(n_components_)
else:
if self.n_components is not None: # normal n case
sel = slice(self.n_components)
logger.info('Selection by number: %i components' %
self.n_components)
else: # None case
logger.info('Using all PCA components: %i'
% len(pca.components_))
sel = slice(len(pca.components_))
# the things to store for PCA
self.pca_mean_ = pca.mean_
self.pca_components_ = pca.components_
self.pca_explained_variance_ = exp_var = pca.explained_variance_
if not check_version('sklearn', '0.18'):
# unwhiten pca components and put scaling in unmixing matrix later.
# RandomizedPCA applies the whitening to the components
# but not the new PCA class.
self.pca_components_ *= np.sqrt(exp_var[:, None])
del pca
# update number of components
self.n_components_ = sel.stop
if self.n_pca_components is not None:
if self.n_pca_components > len(self.pca_components_):
self.n_pca_components = len(self.pca_components_)
# Take care of ICA
if self.method == 'fastica':
from sklearn.decomposition import FastICA # to avoid strong dep.
ica = FastICA(whiten=False,
random_state=random_state, **self.fit_params)
ica.fit(data[:, sel])
# get unmixing and add scaling
self.unmixing_matrix_ = getattr(ica, 'components_',
'unmixing_matrix_')
elif self.method in ('infomax', 'extended-infomax'):
self.unmixing_matrix_ = infomax(data[:, sel],
random_state=random_state,
**self.fit_params)
self.unmixing_matrix_ /= np.sqrt(exp_var[sel])[None, :]
self.mixing_matrix_ = linalg.pinv(self.unmixing_matrix_)
self.current_fit = fit_type
def _transform(self, data):
"""Compute sources from data (operates inplace)."""
fast_dot = _get_fast_dot()
if self.pca_mean_ is not None:
data -= self.pca_mean_[:, None]
# Apply first PCA
pca_data = fast_dot(self.pca_components_[:self.n_components_], data)
# Apply unmixing to low dimension PCA
sources = fast_dot(self.unmixing_matrix_, pca_data)
return sources
def _transform_raw(self, raw, start, stop, reject_by_annotation=False):
"""Transform raw data."""
if not hasattr(self, 'mixing_matrix_'):
raise RuntimeError('No fit available. Please fit ICA.')
start, stop = _check_start_stop(raw, start, stop)
picks = pick_types(raw.info, include=self.ch_names, exclude='bads',
meg=False, ref_meg=False)
if len(picks) != len(self.ch_names):
raise RuntimeError('Raw doesn\'t match fitted data: %i channels '
'fitted but %i channels supplied. \nPlease '
'provide Raw compatible with '
'ica.ch_names' % (len(self.ch_names),
len(picks)))
if reject_by_annotation:
data = raw.get_data(picks, start, stop, 'omit')
else:
data = raw[picks, start:stop][0]
data, _ = self._pre_whiten(data, raw.info, picks)
return self._transform(data)
def _transform_epochs(self, epochs, concatenate):
"""Aux method."""
if not hasattr(self, 'mixing_matrix_'):
raise RuntimeError('No fit available. Please fit ICA')
picks = pick_types(epochs.info, include=self.ch_names, exclude='bads',
meg=False, ref_meg=False)
# special case where epochs come picked but fit was 'unpicked'.
if len(picks) != len(self.ch_names):
raise RuntimeError('Epochs don\'t match fitted data: %i channels '
'fitted but %i channels supplied. \nPlease '
'provide Epochs compatible with '
'ica.ch_names' % (len(self.ch_names),
len(picks)))
data = np.hstack(epochs.get_data()[:, picks])
data, _ = self._pre_whiten(data, epochs.info, picks)
sources = self._transform(data)
if not concatenate:
# Put the data back in 3D
sources = np.array(np.split(sources, len(epochs.events), 1))
return sources
def _transform_evoked(self, evoked):
"""Aux method."""
if not hasattr(self, 'mixing_matrix_'):
raise RuntimeError('No fit available. Please first fit ICA')
picks = pick_types(evoked.info, include=self.ch_names, exclude='bads',
meg=False, ref_meg=False)
if len(picks) != len(self.ch_names):
raise RuntimeError('Evoked doesn\'t match fitted data: %i channels'
' fitted but %i channels supplied. \nPlease '
'provide Evoked compatible with '
'ica.ch_names' % (len(self.ch_names),
len(picks)))
data, _ = self._pre_whiten(evoked.data[picks], evoked.info, picks)
sources = self._transform(data)
return sources
def get_components(self):
"""Get ICA topomap for components as numpy arrays.
Returns
-------
components : array, shape (n_channels, n_components)
The ICA components (maps).
"""
fast_dot = _get_fast_dot()
return fast_dot(self.mixing_matrix_[:, :self.n_components_].T,
self.pca_components_[:self.n_components_]).T
def get_sources(self, inst, add_channels=None, start=None, stop=None):
"""Estimate sources given the unmixing matrix.
This method will return the sources in the container format passed.
Typical usecases:
1. pass Raw object to use `raw.plot` for ICA sources
2. pass Epochs object to compute trial-based statistics in ICA space
3. pass Evoked object to investigate time-locking in ICA space
Parameters
----------
inst : instance of Raw, Epochs or Evoked
Object to compute sources from and to represent sources in.
add_channels : None | list of str
Additional channels to be added. Useful to e.g. compare sources
with some reference. Defaults to None
start : int | float | None
First sample to include. If float, data will be interpreted as
time in seconds. If None, the entire data will be used.
stop : int | float | None
Last sample to not include. If float, data will be interpreted as
time in seconds. If None, the entire data will be used.
Returns
-------
sources : instance of Raw, Epochs or Evoked
The ICA sources time series.
"""
if isinstance(inst, BaseRaw):
sources = self._sources_as_raw(inst, add_channels, start, stop)
elif isinstance(inst, BaseEpochs):
sources = self._sources_as_epochs(inst, add_channels, False)
elif isinstance(inst, Evoked):
sources = self._sources_as_evoked(inst, add_channels)
else:
raise ValueError('Data input must be of Raw, Epochs or Evoked '
'type')
return sources
def _sources_as_raw(self, raw, add_channels, start, stop):
"""Aux method."""
# merge copied instance and picked data with sources
sources = self._transform_raw(raw, start=start, stop=stop)
if raw.preload: # get data and temporarily delete
data = raw._data
del raw._data
out = raw.copy() # copy and reappend
if raw.preload:
raw._data = data
# populate copied raw.
start, stop = _check_start_stop(raw, start, stop)
if add_channels is not None:
raw_picked = raw.copy().pick_channels(add_channels)
data_, times_ = raw_picked[:, start:stop]
data_ = np.r_[sources, data_]
else:
data_ = sources
_, times_ = raw[0, start:stop]
out._data = data_
out._times = times_
out._filenames = [None]
out.preload = True
# update first and last samples
out._first_samps = np.array([raw.first_samp +
(start if start else 0)])
out._last_samps = np.array([out.first_samp + stop
if stop else raw.last_samp])
out._projector = None
self._export_info(out.info, raw, add_channels)
out._update_times()
return out
def _sources_as_epochs(self, epochs, add_channels, concatenate):
"""Aux method."""
out = epochs.copy()
sources = self._transform_epochs(epochs, concatenate)
if add_channels is not None:
picks = [epochs.ch_names.index(k) for k in add_channels]
else:
picks = []
out._data = np.concatenate([sources, epochs.get_data()[:, picks]],
axis=1) if len(picks) > 0 else sources
self._export_info(out.info, epochs, add_channels)
out.preload = True
out._raw = None
out._projector = None
return out
def _sources_as_evoked(self, evoked, add_channels):
"""Aux method."""
if add_channels is not None:
picks = [evoked.ch_names.index(k) for k in add_channels]
else:
picks = []
sources = self._transform_evoked(evoked)
if len(picks) > 1:
data = np.r_[sources, evoked.data[picks]]
else:
data = sources
out = evoked.copy()
out.data = data
self._export_info(out.info, evoked, add_channels)
return out
def _export_info(self, info, container, add_channels):
"""Aux method."""
# set channel names and info
ch_names = []
ch_info = info['chs'] = []
for ii in range(self.n_components_):
this_source = 'ICA %03d' % (ii + 1)
ch_names.append(this_source)
ch_info.append(dict(ch_name=this_source, cal=1,
logno=ii + 1, coil_type=FIFF.FIFFV_COIL_NONE,
kind=FIFF.FIFFV_MISC_CH,
coord_Frame=FIFF.FIFFV_COORD_UNKNOWN,
loc=np.array([0., 0., 0., 1.] * 3, dtype='f4'),
unit=FIFF.FIFF_UNIT_NONE,
range=1.0, scanno=ii + 1, unit_mul=0))
if add_channels is not None:
# re-append additionally picked ch_names
ch_names += add_channels
# re-append additionally picked ch_info
ch_info += [k for k in container.info['chs'] if k['ch_name'] in
add_channels]
info['bads'] = [ch_names[k] for k in self.exclude]
info['projs'] = [] # make sure projections are removed.
info._update_redundant()
info._check_consistency()
@verbose
def score_sources(self, inst, target=None, score_func='pearsonr',
start=None, stop=None, l_freq=None, h_freq=None,
reject_by_annotation=True, verbose=None):
"""Assign score to components based on statistic or metric.
Parameters
----------
inst : instance of Raw, Epochs or Evoked
The object to reconstruct the sources from.
target : array-like | ch_name | None
Signal to which the sources shall be compared. It has to be of
the same shape as the sources. If some string is supplied, a
routine will try to find a matching channel. If None, a score
function expecting only one input-array argument must be used,
for instance, scipy.stats.skew (default).
score_func : callable | str label
Callable taking as arguments either two input arrays
(e.g. Pearson correlation) or one input
array (e. g. skewness) and returns a float. For convenience the
most common score_funcs are available via string labels:
Currently, all distance metrics from scipy.spatial and All
functions from scipy.stats taking compatible input arguments are
supported. These function have been modified to support iteration
over the rows of a 2D array.
start : int | float | None
First sample to include. If float, data will be interpreted as
time in seconds. If None, data will be used from the first sample.
stop : int | float | None
Last sample to not include. If float, data will be interpreted as
time in seconds. If None, data will be used to the last sample.
l_freq : float
Low pass frequency.
h_freq : float
High pass frequency.
reject_by_annotation : bool
If True, data annotated as bad will be omitted. Defaults to True.
.. versionadded:: 0.14.0
verbose : bool, str, int, or None
If not None, override default verbose level (see
:func:`mne.verbose` and :ref:`Logging documentation <tut_logging>`
for more). Defaults to self.verbose.
Returns
-------
scores : ndarray
scores for each source as returned from score_func
"""
if isinstance(inst, BaseRaw):
sources = self._transform_raw(inst, start, stop,
reject_by_annotation)
elif isinstance(inst, BaseEpochs):
sources = self._transform_epochs(inst, concatenate=True)
elif isinstance(inst, Evoked):
sources = self._transform_evoked(inst)
else:
raise ValueError('Input must be of Raw, Epochs or Evoked type')
if target is not None: # we can have univariate metrics without target
target = self._check_target(target, inst, start, stop,
reject_by_annotation)
if sources.shape[-1] != target.shape[-1]:
raise ValueError('Sources and target do not have the same'
'number of time slices.')
# auto target selection
if verbose is None:
verbose = self.verbose
if isinstance(inst, BaseRaw):
sources, target = _band_pass_filter(self, sources, target,
l_freq, h_freq, verbose)
scores = _find_sources(sources, target, score_func)
return scores
def _check_target(self, target, inst, start, stop,
reject_by_annotation=False):
"""Aux Method."""
if isinstance(inst, BaseRaw):
reject_by_annotation = 'omit' if reject_by_annotation else None
start, stop = _check_start_stop(inst, start, stop)
if hasattr(target, 'ndim'):
if target.ndim < 2:
target = target.reshape(1, target.shape[-1])
if isinstance(target, string_types):
pick = _get_target_ch(inst, target)
target = inst.get_data(pick, start, stop, reject_by_annotation)
elif isinstance(inst, BaseEpochs):
if isinstance(target, string_types):
pick = _get_target_ch(inst, target)
target = inst.get_data()[:, pick]
if hasattr(target, 'ndim'):
if target.ndim == 3 and min(target.shape) == 1:
target = target.ravel()
elif isinstance(inst, Evoked):
if isinstance(target, string_types):
pick = _get_target_ch(inst, target)
target = inst.data[pick]
return target
@verbose
def find_bads_ecg(self, inst, ch_name=None, threshold=None, start=None,
stop=None, l_freq=8, h_freq=16, method='ctps',
reject_by_annotation=True, verbose=None):
"""Detect ECG related components using correlation.
.. note:: If no ECG channel is available, routine attempts to create
an artificial ECG based on cross-channel averaging.
Parameters
----------
inst : instance of Raw, Epochs or Evoked
Object to compute sources from.
ch_name : str
The name of the channel to use for ECG peak detection.
The argument is mandatory if the dataset contains no ECG
channels.
threshold : float
The value above which a feature is classified as outlier. If
method is 'ctps', defaults to 0.25, else defaults to 3.0.
start : int | float | None
First sample to include. If float, data will be interpreted as
time in seconds. If None, data will be used from the first sample.
stop : int | float | None
Last sample to not include. If float, data will be interpreted as
time in seconds. If None, data will be used to the last sample.
l_freq : float
Low pass frequency.
h_freq : float
High pass frequency.
method : {'ctps', 'correlation'}
The method used for detection. If 'ctps', cross-trial phase
statistics [1] are used to detect ECG related components.
Thresholding is then based on the significance value of a Kuiper
statistic.
If 'correlation', detection is based on Pearson correlation
between the filtered data and the filtered ECG channel.
Thresholding is based on iterative z-scoring. The above
threshold components will be masked and the z-score will
be recomputed until no supra-threshold component remains.
Defaults to 'ctps'.
reject_by_annotation : bool
If True, data annotated as bad will be omitted. Defaults to True.
.. versionadded:: 0.14.0
verbose : bool, str, int, or None
If not None, override default verbose level (see
:func:`mne.verbose` and :ref:`Logging documentation <tut_logging>`
for more). Defaults to self.verbose.
Returns
-------
ecg_idx : list of int
The indices of ECG related components.
scores : np.ndarray of float, shape (``n_components_``)
The correlation scores.