-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
ica.py
2915 lines (2508 loc) · 120 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
# -*- coding: utf-8 -*-
#
# Authors: Denis A. Engemann <denis.engemann@gmail.com>
# Alexandre Gramfort <alexandre.gramfort@inria.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
from time import time
from dataclasses import dataclass
from typing import Optional, List
import math
import os
import json
import numpy as np
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,
_picks_to_idx, _get_channel_types, _DATA_CH_TYPES_SPLIT)
from ..io.proj import make_projector
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 FIFF
from ..io.base import BaseRaw
from ..io.eeglab.eeglab import _get_info, _check_load_mat
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.topomap import _plot_corrmap
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, _check_fname, verbose,
_reject_data_segments, check_random_state, _validate_type,
compute_corr, _get_inst_data, _ensure_int,
copy_function_doc_to_method_doc, _pl, warn, Bunch,
_check_preload, _check_compensation_grade, fill_doc,
_check_option, _PCA, int_like,
_check_all_same_channel_names, deprecated)
from ..fixes import _get_args, _safe_svd
from ..filter import filter_data
from .bads import _find_outliers
from .ctps_ import ctps
from ..io.pick import pick_channels_regexp, _picks_by_type
from ..data.html_templates import ica_template
__all__ = ('ICA', 'ica_find_ecg_events', 'ica_find_eog_events',
'get_score_funcs', 'read_ica', 'read_ica_eeglab')
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
# Violate our assumption that the output is 1D so can't be used.
# Could eventually be added but probably not worth the effort unless someone
# requests it.
_BLOCKLIST = {'somersd'}
# makes score funcs attr accessible for users
def get_score_funcs():
"""Get the score functions.
Returns
-------
score_funcs : dict
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('_') and
n not in _BLOCKLIST]
xy_arg_stats_funcs = [(n, f) for n, f in vars(stats).items()
if isfunction(f) and not n.startswith('_') and
n not in _BLOCKLIST]
score_funcs.update({n: _make_xy_sfunc(f)
for n, f in xy_arg_dist_funcs
if _get_args(f) == ['u', 'v']})
score_funcs.update({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, allow_ref_meg=False):
"""Check for channels in picks that are not considered valid channels.
Accepted channels are the data channels
('seeg', 'dbs', 'ecog', 'eeg', 'hbo', 'hbr', 'mag', and 'grad'), 'eog'
and 'ref_meg'.
This prevents the program from crashing without
feedback when a bad channel is provided to ICA whitening.
"""
types = _DATA_CH_TYPES_SPLIT + ('eog',)
types += ('ref_meg',) if allow_ref_meg else ()
chs = _get_channel_types(info, picks, unique=True, only_data_chs=False)
check = all([ch in types for ch in chs])
if not check:
raise ValueError('Invalid channel type%s passed for ICA: %s.'
'Only the following types are supported: %s'
% (_pl(chs), chs, types))
_KNOWN_ICA_METHODS = ('fastica', 'infomax', 'picard')
@fill_doc
class ICA(ContainsMixin):
u"""Data decomposition using Independent Component Analysis (ICA).
This object estimates independent components from :class:`mne.io.Raw`,
:class:`mne.Epochs`, or :class:`mne.Evoked` objects. Components can
optionally be removed (for artifact repair) prior to signal reconstruction.
.. warning:: ICA is sensitive to low-frequency drifts and therefore
requires the data to be high-pass filtered prior to fitting.
Typically, a cutoff frequency of 1 Hz is recommended.
Parameters
----------
n_components : int | float | None
Number of principal components (from the pre-whitening PCA step) that
are passed to the ICA algorithm during fitting:
- :class:`int`
Must be greater than 1 and less than or equal to the number of
channels.
- :class:`float` between 0 and 1 (exclusive)
Will select the smallest number of components required to explain
the cumulative variance of the data greater than ``n_components``.
Consider this hypothetical example: we have 3 components, the first
explaining 70%%, the second 20%%, and the third the remaining 10%%
of the variance. Passing 0.8 here (corresponding to 80%% of
explained variance) would yield the first two components,
explaining 90%% of the variance: only by using both components the
requested threshold of 80%% explained variance can be exceeded. The
third component, on the other hand, would be excluded.
- ``None``
``0.999999`` will be used. This is done to avoid numerical
stability problems when whitening, particularly when working with
rank-deficient data.
Defaults to ``None``. The actual number used when executing the
:meth:`ICA.fit` method will be stored in the attribute
``n_components_`` (note the trailing underscore).
.. versionchanged:: 0.22
For a :class:`python:float`, the number of components will account
for *greater than* the given variance level instead of *less than or
equal to* it. The default (None) will also take into account the
rank deficiency of the data.
noise_cov : None | instance of Covariance
Noise covariance used for pre-whitening. If None (default), channels
are scaled to unit variance ("z-standardized") as a group by channel
type prior to the whitening by PCA.
%(random_state)s
method : 'fastica' | 'infomax' | 'picard'
The ICA method to use in the fit method. Use the ``fit_params`` argument
to set additional parameters. Specifically, if you want Extended
Infomax, set ``method='infomax'`` and ``fit_params=dict(extended=True)``
(this also works for ``method='picard'``). Defaults to ``'fastica'``.
For reference, see :footcite:`Hyvarinen1999,BellSejnowski1995,LeeEtAl1999,AblinEtAl2018`.
fit_params : dict | None
Additional parameters passed to the ICA estimator as specified by
``method``. Allowed entries are determined by the various algorithm
implementations: see :class:`~sklearn.decomposition.FastICA`,
:func:`~picard.picard`, :func:`~mne.preprocessing.infomax`.
max_iter : int | 'auto'
Maximum number of iterations during fit. If ``'auto'``, it
will set maximum iterations to ``1000`` for ``'fastica'``
and to ``500`` for ``'infomax'`` or ``'picard'``. The actual number of
iterations it took :meth:`ICA.fit` to complete will be stored in the
``n_iter_`` attribute.
allow_ref_meg : bool
Allow ICA on MEG reference channels. Defaults to False.
.. versionadded:: 0.18
%(verbose)s
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.
n_components_ : int
If fit, the actual number of PCA components used for ICA decomposition.
pre_whitener_ : ndarray, shape (n_channels, 1) or (n_channels, n_channels)
If fit, array used to pre-whiten the data prior to PCA.
pca_components_ : ndarray, shape ``(n_channels, n_channels)``
If fit, the PCA components.
pca_mean_ : ndarray, shape (n_channels,)
If fit, the mean vector used to center the data before doing the PCA.
pca_explained_variance_ : ndarray, shape ``(n_channels,)``
If fit, the variance explained by each PCA component.
mixing_matrix_ : ndarray, shape ``(n_components_, n_components_)``
If fit, the whitened mixing matrix to go back from ICA space to PCA
space.
It is, in combination with the ``pca_components_``, used by
:meth:`ICA.apply` and :meth:`ICA.get_components` to re-mix/project
a subset of the ICA components into the observed channel space.
The former method also removes the pre-whitening (z-scaling) and the
de-meaning.
unmixing_matrix_ : ndarray, shape ``(n_components_, n_components_)``
If fit, the whitened matrix to go from PCA space to ICA space.
Used, in combination with the ``pca_components_``, by the methods
:meth:`ICA.get_sources` and :meth:`ICA.apply` to unmix the observed
data.
exclude : array-like of int
List or np.array of sources indices to exclude when re-mixing the data
in the :meth:`ICA.apply` method, i.e. artifactual ICA components.
The components identified manually and by the various automatic
artifact detection methods should be (manually) appended
(e.g. ``ica.exclude.extend(eog_inds)``).
(There is also an ``exclude`` parameter in the :meth:`ICA.apply`
method.) To scrap all marked components, set this attribute to an empty
list.
%(info)s
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.
n_iter_ : int
If fit, the number of iterations required to complete ICA.
Notes
-----
.. versionchanged:: 0.23
Version 0.23 introduced the ``max_iter='auto'`` settings for maximum
iterations. With version 0.24 ``'auto'`` will be the new
default, replacing the current ``max_iter=200``.
.. versionchanged:: 0.23
Warn if `~mne.Epochs` were baseline-corrected.
.. note:: If you intend to fit ICA on `~mne.Epochs`, it is recommended to
high-pass filter, but **not** baseline correct the data for good
ICA performance. A warning will be emitted otherwise.
A trailing ``_`` in an attribute name signifies that the attribute was
added to the object during fitting, consistent with standard scikit-learn
practice.
ICA :meth:`fit` in MNE proceeds in two steps:
1. :term:`Whitening <whitening>` the data by means of a pre-whitening step
(using ``noise_cov`` if provided, or the standard deviation of each
channel type) and then principal component analysis (PCA).
2. Passing the ``n_components`` largest-variance components to the ICA
algorithm to obtain the unmixing matrix (and by pseudoinversion, the
mixing matrix).
ICA :meth:`apply` then:
1. Unmixes the data with the ``unmixing_matrix_``.
2. Includes ICA components based on ``ica.include`` and ``ica.exclude``.
3. Re-mixes the data with ``mixing_matrix_``.
4. Restores any data not passed to the ICA algorithm, i.e., the PCA
components between ``n_components`` and ``n_pca_components``.
``n_pca_components`` determines how many PCA components will be kept when
reconstructing the data when calling :meth:`apply`. This parameter can be
used for dimensionality reduction of the data, or dealing with low-rank
data (such as those with projections, or MEG data processed by SSS). It is
important to remove any numerically-zero-variance components in the data,
otherwise numerical instability causes problems when computing the mixing
matrix. Alternatively, using ``n_components`` as a float will also avoid
numerical stability problems.
The ``n_components`` parameter determines how many components out of
the ``n_channels`` PCA components the ICA algorithm will actually fit.
This is not typically used for EEG data, but for MEG data, it's common to
use ``n_components < n_channels``. For example, full-rank
306-channel MEG data might use ``n_components=40`` to find (and
later exclude) only large, dominating artifacts in the data, but still
reconstruct the data using all 306 PCA components. Setting
``n_pca_components=40``, on the other hand, would actually reduce the
rank of the reconstructed data to 40, which is typically undesirable.
If you are migrating from EEGLAB and intend to reduce dimensionality via
PCA, similarly to EEGLAB's ``runica(..., 'pca', n)`` functionality,
pass ``n_components=n`` during initialization and then
``n_pca_components=n`` during :meth:`apply`. The resulting reconstructed
data after :meth:`apply` will have rank ``n``.
.. note:: Commonly used for reasons of i) computational efficiency and
ii) additional noise reduction, it is a matter of current debate
whether pre-ICA dimensionality reduction could decrease the
reliability and stability of the ICA, at least for EEG data and
especially during preprocessing :footcite:`ArtoniEtAl2018`.
(But see also :footcite:`Montoya-MartinezEtAl2017` for a
possibly confounding effect of the different whitening/sphering
methods used in this paper (ZCA vs. PCA).)
On the other hand, for rank-deficient data such as EEG data after
average reference or interpolation, it is recommended to reduce
the dimensionality (by 1 for average reference and 1 for each
interpolated channel) for optimal ICA performance (see the
`EEGLAB wiki <eeglab_wiki_>`_).
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 ICA, for example::
>> projs, raw.info['projs'] = raw.info['projs'], []
>> ica.fit(raw)
>> raw.info['projs'] = projs
Methods currently implemented are FastICA (default), Infomax, and Picard.
Standard Infomax can be quite sensitive to differences in floating point
arithmetic. Extended Infomax seems to be more stable in this respect,
enhancing reproducibility and stability of results; use Extended Infomax
via ``method='infomax', fit_params=dict(extended=True)``. Allowed entries
in ``fit_params`` are determined by the various algorithm implementations:
see :class:`~sklearn.decomposition.FastICA`, :func:`~picard.picard`,
:func:`~mne.preprocessing.infomax`.
.. note:: Picard can be used to solve the same problems as FastICA,
Infomax, and extended Infomax, but typically converges faster
than either of those methods. To make use of Picard's speed while
still obtaining the same solution as with other algorithms, you
need to specify ``method='picard'`` and ``fit_params`` as a
dictionary with the following combination of keys:
- ``dict(ortho=False, extended=False)`` for Infomax
- ``dict(ortho=False, extended=True)`` for extended Infomax
- ``dict(ortho=True, extended=True)`` for FastICA
Reducing the tolerance (set in ``fit_params``) speeds up estimation at the
cost of consistency of the obtained results. It is difficult to directly
compare tolerance levels between Infomax and Picard, but for Picard and
FastICA a good rule of thumb is ``tol_fastica == tol_picard ** 2``.
.. _eeglab_wiki: https://eeglab.org/tutorials/06_RejectArtifacts/RunICA.html#how-to-deal-with-corrupted-ica-decompositions
References
----------
.. footbibliography::
""" # noqa: E501
@verbose
def __init__(self, n_components=None, *, noise_cov=None,
random_state=None, method='fastica', fit_params=None,
max_iter='auto', allow_ref_meg=False,
verbose=None): # noqa: D102
_validate_type(method, str, 'method')
_validate_type(n_components, (float, 'int-like', None))
if method != 'imported_eeglab': # internal use only
_check_option('method', method, _KNOWN_ICA_METHODS)
if method == 'fastica' and not check_version('sklearn'):
raise ImportError(
'The scikit-learn package is required for method="fastica".')
if method == 'picard' and not check_version('picard'):
raise ImportError(
'The python-picard package is required for method="picard".')
self.noise_cov = noise_cov
for (kind, val) in [('n_components', n_components)]:
if isinstance(val, float) and not 0 < val < 1:
raise ValueError('Selecting ICA components by explained '
'variance needs values between 0.0 and 1.0 '
f'(exclusive), got {kind}={val}')
if isinstance(val, int_like) and val == 1:
raise ValueError(
f'Selecting one component with {kind}={val} is not '
'supported')
self.current_fit = 'unfitted'
self.verbose = verbose
self.n_components = n_components
# In newer ICAs this should always be None, but keep it for
# backward compat with older versions of MNE that used it
self._max_pca_components = None
self.n_pca_components = None
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 method == 'fastica':
update = {'algorithm': 'parallel', 'fun': 'logcosh',
'fun_args': None}
fit_params.update({k: v for k, v in update.items() if k
not in fit_params})
elif method == 'infomax':
# extended=True is default in underlying function, but we want
# default False here unless user specified True:
fit_params.setdefault('extended', False)
_validate_type(max_iter, (str, 'int-like'), 'max_iter')
if isinstance(max_iter, str):
_check_option('max_iter', max_iter, ('auto',), 'when str')
if method == 'fastica':
max_iter = 1000
elif method in ['infomax', 'picard']:
max_iter = 500
fit_params.setdefault('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()
self.allow_ref_meg = allow_ref_meg
def _get_infos_for_repr(self):
@dataclass
class _InfosForRepr:
# XXX replace with Optional[Literal['raw data', 'epochs'] once we
# drop support for Py 3.7
fit_on: Optional[str]
# XXX replace with fit_method: Literal['fastica', 'infomax',
# 'extended-infomax', 'picard'] once we drop support for Py 3.7
fit_method: str
fit_n_iter: Optional[int]
fit_n_samples: Optional[int]
fit_n_components: Optional[int]
fit_n_pca_components: Optional[int]
fit_explained_variance: Optional[float]
ch_types: List[str]
excludes: List[str]
if self.current_fit == 'unfitted':
fit_on = None
elif self.current_fit == 'raw':
fit_on = 'raw data'
else:
fit_on = 'epochs'
fit_method = self.method
fit_n_iter = getattr(self, 'n_iter_', None)
fit_n_samples = getattr(self, 'n_samples_', None)
fit_n_components = getattr(self, 'n_components_', None)
fit_n_pca_components = getattr(self, 'pca_components_', None)
if fit_n_pca_components is not None:
fit_n_pca_components = len(self.pca_components_)
fit_explained_variance = getattr(self, 'pca_explained_variance_', None)
if fit_explained_variance is not None:
abs_vars = self.pca_explained_variance_
rel_vars = abs_vars / abs_vars.sum()
fit_explained_variance = rel_vars[:fit_n_components].sum()
if self.info is not None:
ch_types = [c for c in _DATA_CH_TYPES_SPLIT if c in self]
else:
ch_types = []
if self.exclude:
excludes = [self._ica_names[i] for i in self.exclude]
else:
excludes = []
infos_for_repr = _InfosForRepr(
fit_on=fit_on,
fit_method=fit_method,
fit_n_iter=fit_n_iter,
fit_n_samples=fit_n_samples,
fit_n_components=fit_n_components,
fit_n_pca_components=fit_n_pca_components,
fit_explained_variance=fit_explained_variance,
ch_types=ch_types,
excludes=excludes
)
return infos_for_repr
def __repr__(self):
"""ICA fit information."""
infos = self._get_infos_for_repr()
s = (f'{infos.fit_on or "no"} decomposition, '
f'method: {infos.fit_method}')
if infos.fit_on is not None:
s += (
f' (fit in {infos.fit_n_iter} iterations on '
f'{infos.fit_n_samples} samples), '
f'{infos.fit_n_components} ICA components '
f'explaining {round(infos.fit_explained_variance * 100, 1)} % '
f'of variance '
f'({infos.fit_n_pca_components} PCA components available), '
f'channel types: {", ".join(infos.ch_types)}, '
f'{len(infos.excludes) or "no"} sources marked for exclusion'
)
return f'<ICA | {s}>'
def _repr_html_(self):
infos = self._get_infos_for_repr()
html = ica_template.substitute(
fit_on=infos.fit_on,
method=infos.fit_method,
n_iter=infos.fit_n_iter,
n_samples=infos.fit_n_samples,
n_components=infos.fit_n_components,
n_pca_components=infos.fit_n_pca_components,
explained_variance=infos.fit_explained_variance,
ch_types=infos.ch_types,
excludes=infos.excludes
)
return html
@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 or Epochs
The data to be decomposed.
%(picks_good_data_noref)s
This selection remains throughout the initialized ICA solution.
start, stop : int | float | None
First and last sample to include. If float, data will be
interpreted as time in seconds. If ``None``, data will be used from
the first sample and to the last sample, respectively.
.. note:: These parameters only have an effect if ``inst`` is
`~mne.io.Raw` data.
decim : int | None
Increment for selecting only each n-th sampling point. If ``None``,
all samples between ``start`` and ``stop`` (inclusive) are used.
reject, flat : dict | None
Rejection parameters based on peak-to-peak amplitude (PTP)
in the continuous data. Signal periods exceeding the thresholds
in ``reject`` or less than the thresholds in ``flat`` will be
removed before fitting the ICA.
.. note:: These parameters only have an effect if ``inst`` is
`~mne.io.Raw` data. For `~mne.Epochs`, perform PTP
rejection via :meth:`~mne.Epochs.drop_bad`.
Valid keys are all channel types present in the data. Values must
be integers or floats.
If ``None``, no PTP-based rejection will be performed. 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)
)
flat = None # no rejection based on flatness
tstep : float
Length of data chunks for artifact rejection in seconds.
.. note:: This parameter only has an effect if ``inst`` is
`~mne.io.Raw` data.
%(reject_by_annotation_raw)s
.. versionadded:: 0.14.0
%(verbose_meth)s
Returns
-------
self : instance of ICA
Returns the modified instance.
"""
_validate_type(inst, (BaseRaw, BaseEpochs), 'inst', 'Raw or Epochs')
if np.isclose(inst.info['highpass'], 0.):
warn('The data has not been high-pass filtered. For good ICA '
'performance, it should be high-pass filtered (e.g., with a '
'1.0 Hz lower bound) before fitting ICA.')
if isinstance(inst, BaseEpochs) and inst.baseline is not None:
warn('The epochs you passed to ICA.fit() were baseline-corrected. '
'However, we suggest to fit ICA only on data that has been '
'high-pass filtered, but NOT baseline-corrected.')
if not isinstance(inst, BaseRaw):
ignored_params = [
param_name for param_name, param_val in zip(
('start', 'stop', 'reject', 'flat'),
(start, stop, reject, flat)
)
if param_val is not None
]
if ignored_params:
warn(f'The following parameters passed to ICA.fit() will be '
f'ignored, as they only affect raw data (and it appears '
f'you passed epochs): {", ".join(ignored_params)}')
picks = _picks_to_idx(inst.info, picks, allow_empty=False,
with_ref_meg=self.allow_ref_meg)
_check_for_unsupported_ica_channels(
picks, inst.info, allow_ref_meg=self.allow_ref_meg)
# Actually start fitting
t_start = time()
if self.current_fit != 'unfitted':
self._reset()
logger.info('Fitting ICA to data using %i channels '
'(please be patient, this may take a while)' % len(picks))
# n_components could be float 0 < x < 1, but that's okay here
if self.n_components is not None and self.n_components > len(picks):
raise ValueError(
f'ica.n_components ({self.n_components}) cannot '
f'be greater than len(picks) ({len(picks)})')
# filter out all the channels the raw wouldn't have initialized
self.info = pick_info(inst.info, picks)
if self.info['comps']:
with self.info._unlock():
self.info['comps'] = []
self.ch_names = self.info['ch_names']
if isinstance(inst, BaseRaw):
self._fit_raw(inst, picks, start, stop, decim, reject, flat,
tstep, reject_by_annotation, verbose)
else:
assert isinstance(inst, BaseEpochs)
self._fit_epochs(inst, picks, decim, verbose)
# sort ICA components by explained variance
var = _ica_explained_variance(self, inst)
var_ord = var.argsort()[::-1]
_sort_components(self, var_ord, copy=False)
t_stop = time()
logger.info("Fitting ICA took {:.1f}s.".format(t_stop - t_start))
return self
def _reset(self):
"""Aux method."""
for key in ('pre_whitener_', 'unmixing_matrix_', 'mixing_matrix_',
'n_components_', 'n_samples_', 'pca_components_',
'pca_explained_variance_',
'pca_mean_', 'n_iter_', 'drop_inds_', 'reject_'):
if hasattr(self, key):
delattr(self, key)
def _fit_raw(self, raw, picks, start, stop, decim, reject, flat, tstep,
reject_by_annotation, verbose):
"""Aux method."""
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):
self.reject_ = reject
data, self.drop_inds_ = _reject_data_segments(data, reject, flat,
decim, self.info,
tstep)
self.n_samples_ = data.shape[1]
self._fit(data, 'raw')
return self
def _fit_epochs(self, epochs, picks, decim, verbose):
"""Aux method."""
if epochs.events.size == 0:
raise RuntimeError('Tried to fit ICA with epochs, but none were '
'found: epochs.events is "{}".'
.format(epochs.events))
# 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_ = data.shape[0] * data.shape[2]
# This will make at least one copy (one from hstack, maybe one
# more from _pre_whiten)
data = np.hstack(data)
self._fit(data, 'epochs')
return self
def _compute_pre_whitener(self, data):
"""Aux function."""
data = self._do_proj(data, log_suffix='(pre-whitener computation)')
if self.noise_cov is None:
# use standardization as whitener
# Scale (z-score) the data by channel type
info = self.info
pre_whitener = np.empty([len(data), 1])
for _, picks_ in _picks_by_type(info, ref_meg=False, exclude=[]):
pre_whitener[picks_] = np.std(data[picks_])
if _contains_ch_type(info, "ref_meg"):
picks_ = pick_types(info, ref_meg=True, exclude=[])
pre_whitener[picks_] = np.std(data[picks_])
if _contains_ch_type(info, "eog"):
picks_ = pick_types(info, eog=True, exclude=[])
pre_whitener[picks_] = np.std(data[picks_])
else:
pre_whitener, _ = compute_whitener(
self.noise_cov, self.info, picks=self.info.ch_names)
assert data.shape[0] == pre_whitener.shape[1]
self.pre_whitener_ = pre_whitener
def _do_proj(self, data, log_suffix=''):
if self.info is not None and self.info['projs']:
proj, nproj, _ = make_projector(
[p for p in self.info['projs'] if p['active']],
self.info['ch_names'], include_active=True)
if nproj:
logger.info(
f' Applying projection operator with {nproj} '
f'vector{_pl(nproj)}'
f'{" " if log_suffix else ""}{log_suffix}')
if self.noise_cov is None: # otherwise it's in pre_whitener_
data = proj @ data
return data
def _pre_whiten(self, data):
data = self._do_proj(data, log_suffix='(pre-whitener application)')
if self.noise_cov is None:
data /= self.pre_whitener_
else:
data = self.pre_whitener_ @ data
return data
def _fit(self, data, fit_type):
"""Aux function."""
random_state = check_random_state(self.random_state)
n_channels, n_samples = data.shape
self._compute_pre_whitener(data)
data = self._pre_whiten(data)
pca = _PCA(n_components=self._max_pca_components, whiten=True)
data = pca.fit_transform(data.T)
use_ev = pca.explained_variance_ratio_
n_pca = self.n_pca_components
if isinstance(n_pca, float):
n_pca = int(_exp_var_ncomp(use_ev, n_pca)[0])
elif n_pca is None:
n_pca = len(use_ev)
assert isinstance(n_pca, (int, np.int_))
# If user passed a float, select the PCA components explaining the
# given cumulative variance. This information will later be used to
# only submit the corresponding parts of the data to ICA.
if self.n_components is None:
# None case: check if n_pca_components or 0.999999 yields smaller
msg = 'Selecting by non-zero PCA components'
self.n_components_ = min(
n_pca, _exp_var_ncomp(use_ev, 0.999999)[0])
elif isinstance(self.n_components, float):
self.n_components_, ev = _exp_var_ncomp(use_ev, self.n_components)
if self.n_components_ == 1:
raise RuntimeError(
'One PCA component captures most of the '
f'explained variance ({100 * ev}%), your threshold '
'results in 1 component. You should select '
'a higher value.')
msg = 'Selecting by explained variance'
else:
msg = 'Selecting by number'
self.n_components_ = _ensure_int(self.n_components)
# check to make sure something okay happened
if self.n_components_ > n_pca:
ev = np.cumsum(use_ev)
ev /= ev[-1]
evs = 100 * ev[[self.n_components_ - 1, n_pca - 1]]
raise RuntimeError(
f'n_components={self.n_components} requires '
f'{self.n_components_} PCA values (EV={evs[0]:0.1f}%) but '
f'n_pca_components ({self.n_pca_components}) results in '
f'only {n_pca} components (EV={evs[1]:0.1f}%)')
logger.info('%s: %s components' % (msg, self.n_components_))
# the things to store for PCA
self.pca_mean_ = pca.mean_
self.pca_components_ = pca.components_
self.pca_explained_variance_ = pca.explained_variance_
del pca
# update number of components
self._update_ica_names()
if self.n_pca_components is not None and \
self.n_pca_components > len(self.pca_components_):
raise ValueError(
f'n_pca_components ({self.n_pca_components}) is greater than '
f'the number of PCA components ({len(self.pca_components_)})')
# take care of ICA
sel = slice(0, self.n_components_)
if self.method == 'fastica':
from sklearn.decomposition import FastICA
ica = FastICA(
whiten=False, random_state=random_state, **self.fit_params)
ica.fit(data[:, sel])
self.unmixing_matrix_ = ica.components_
self.n_iter_ = ica.n_iter_
elif self.method in ('infomax', 'extended-infomax'):
unmixing_matrix, n_iter = infomax(
data[:, sel], random_state=random_state, return_n_iter=True,
**self.fit_params)
self.unmixing_matrix_ = unmixing_matrix
self.n_iter_ = n_iter
del unmixing_matrix, n_iter
elif self.method == 'picard':
from picard import picard
_, W, _, n_iter = picard(
data[:, sel].T, whiten=False, return_n_iter=True,
random_state=random_state, **self.fit_params)
self.unmixing_matrix_ = W
self.n_iter_ = n_iter + 1 # picard() starts counting at 0
del _, n_iter
assert self.unmixing_matrix_.shape == (self.n_components_,) * 2
norms = self.pca_explained_variance_
stable = norms / norms[0] > 1e-6 # to be stable during pinv
norms = norms[:self.n_components_]
if not stable[self.n_components_ - 1]:
max_int = np.where(stable)[0][-1] + 1
warn(f'Using n_components={self.n_components} (resulting in '
f'n_components_={self.n_components_}) may lead to an '
f'unstable mixing matrix estimation because the ratio '
f'between the largest ({norms[0]:0.2g}) and smallest '
f'({norms[-1]:0.2g}) variances is too large (> 1e6); '
f'consider setting n_components=0.999999 or an '
f'integer <= {max_int}')
norms = np.sqrt(norms)
norms[norms == 0] = 1.
self.unmixing_matrix_ /= norms # whitening
self._update_mixing_matrix()
self.current_fit = fit_type
def _update_mixing_matrix(self):
from scipy import linalg
self.mixing_matrix_ = linalg.pinv(self.unmixing_matrix_)
def _update_ica_names(self):
"""Update ICA names when n_components_ is set."""
self._ica_names = ['ICA%03d' % ii for ii in range(self.n_components_)]
def _transform(self, data):
"""Compute sources from data (operates inplace)."""
data = self._pre_whiten(data)
if self.pca_mean_ is not None:
data -= self.pca_mean_[:, None]
# Apply unmixing
pca_data = np.dot(self.unmixing_matrix_,
self.pca_components_[:self.n_components_])
# Apply PCA
sources = np.dot(pca_data, 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 = self._get_picks(raw)
reject = 'omit' if reject_by_annotation else None
data = raw.get_data(picks, start, stop, reject)
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 = self._get_picks(epochs)
data = np.hstack(epochs.get_data()[:, 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 fit ICA.')
picks = self._get_picks(evoked)
return self._transform(evoked.data[picks])
def _get_picks(self, inst):
"""Pick logic for _transform method."""
picks = _picks_to_idx(
inst.info, self.ch_names, exclude=[], allow_empty=True)
if len(picks) != len(self.ch_names):
if isinstance(inst, BaseRaw):
kind, do = 'Raw', "doesn't"
elif isinstance(inst, BaseEpochs):
kind, do = 'Epochs', "don't"
elif isinstance(inst, Evoked):
kind, do = 'Evoked', "doesn't"
else:
raise ValueError('Data input must be of Raw, Epochs or Evoked '
'type')
raise RuntimeError("%s %s match fitted data: %i channels "
"fitted but %i channels supplied. \nPlease "
"provide %s compatible with ica.ch_names"
% (kind, do, len(self.ch_names), len(picks),
kind))
return picks
def get_components(self):
"""Get ICA topomap for components as numpy arrays.
Returns
-------
components : array, shape (n_channels, n_components)
The ICA components (maps).
"""
return np.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 <mne.io.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):
_check_compensation_grade(self.info, inst.info, 'ICA', 'Raw',
ch_names=self.ch_names)
sources = self._sources_as_raw(inst, add_channels, start, stop)
elif isinstance(inst, BaseEpochs):
_check_compensation_grade(self.info, inst.info, 'ICA', 'Epochs',
ch_names=self.ch_names)
sources = self._sources_as_epochs(inst, add_channels, False)
elif isinstance(inst, Evoked):
_check_compensation_grade(self.info, inst.info, 'ICA', 'Evoked',
ch_names=self.ch_names)
sources = self._sources_as_evoked(inst, add_channels)