forked from mne-tools/mne-python
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cov.py
1874 lines (1581 loc) · 69.1 KB
/
cov.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: Alexandre Gramfort <[email protected]>
# Matti Hamalainen <[email protected]>
# Denis A. Engemann <[email protected]>
#
# License: BSD (3-clause)
import copy as cp
import os
from math import floor, ceil, log
import itertools as itt
import warnings
import six
from distutils.version import LooseVersion
import numpy as np
from scipy import linalg
from .io.write import start_file, end_file
from .io.proj import (make_projector, _proj_equal, activate_proj,
_has_eeg_average_ref_proj)
from .io import fiff_open
from .io.pick import (pick_types, channel_indices_by_type, pick_channels_cov,
pick_channels, pick_info, _picks_by_type)
from .io.constants import FIFF
from .io.meas_info import read_bad_channels
from .io.proj import _read_proj, _write_proj
from .io.tag import find_tag
from .io.tree import dir_tree_find
from .io.write import (start_block, end_block, write_int, write_name_list,
write_double, write_float_matrix, write_string)
from .defaults import _handle_default
from .epochs import _is_good
from .utils import (check_fname, logger, verbose, estimate_rank,
_compute_row_norms, check_sklearn_version, _time_mask)
from .externals.six.moves import zip
from .externals.six import string_types
def _check_covs_algebra(cov1, cov2):
if cov1.ch_names != cov2.ch_names:
raise ValueError('Both Covariance do not have the same list of '
'channels.')
projs1 = [str(c) for c in cov1['projs']]
projs2 = [str(c) for c in cov1['projs']]
if projs1 != projs2:
raise ValueError('Both Covariance do not have the same list of '
'SSP projections.')
def _get_tslice(epochs, tmin, tmax):
"""get the slice."""
tstart, tend = None, None
mask = _time_mask(epochs.times, tmin, tmax)
tstart = np.where(mask)[0][0] if tmin is not None else None
tend = np.where(mask)[0][-1] + 1 if tmax is not None else None
tslice = slice(tstart, tend, None)
return tslice
class Covariance(dict):
"""Noise covariance matrix.
Parameters
----------
fname : string
The name of the raw file.
Attributes
----------
data : array of shape (n_channels, n_channels)
The covariance.
ch_names : list of string
List of channels' names.
nfree : int
Number of degrees of freedom i.e. number of time points used.
"""
def __init__(self, fname):
"""Init of covariance."""
if fname is None:
return
# Reading
fid, tree, _ = fiff_open(fname)
self.update(_read_cov(fid, tree, FIFF.FIFFV_MNE_NOISE_COV))
fid.close()
@property
def data(self):
"""Numpy array of Noise covariance matrix."""
return self['data']
@property
def ch_names(self):
"""Channel names."""
return self['names']
@property
def nfree(self):
"""Number of degrees of freedom."""
return self['nfree']
def save(self, fname):
"""Save covariance matrix in a FIF file.
Parameters
----------
fname : str
Output filename.
"""
check_fname(fname, 'covariance', ('-cov.fif', '-cov.fif.gz'))
fid = start_file(fname)
try:
_write_cov(fid, self)
except Exception as inst:
os.remove(fname)
raise inst
end_file(fid)
def as_diag(self, copy=True):
"""Set covariance to be processed as being diagonal.
Parameters
----------
copy : bool
If True, return a modified copy of the covarince. If False,
the covariance is modified in place.
Returns
-------
cov : dict
The covariance.
Notes
-----
This function allows creation of inverse operators
equivalent to using the old "--diagnoise" mne option.
"""
if self['diag'] is True:
return self.copy() if copy is True else self
if copy is True:
cov = cp.deepcopy(self)
else:
cov = self
cov['diag'] = True
cov['data'] = np.diag(cov['data'])
cov['eig'] = None
cov['eigvec'] = None
return cov
def __repr__(self):
if self.data.ndim == 2:
s = 'size : %s x %s' % self.data.shape
else: # ndim == 1
s = 'diagonal : %s' % self.data.size
s += ", n_samples : %s" % self.nfree
s += ", data : %s" % self.data
return "<Covariance | %s>" % s
def __add__(self, cov):
"""Add Covariance taking into account number of degrees of freedom."""
_check_covs_algebra(self, cov)
this_cov = cp.deepcopy(cov)
this_cov['data'] = (((this_cov['data'] * this_cov['nfree']) +
(self['data'] * self['nfree'])) /
(self['nfree'] + this_cov['nfree']))
this_cov['nfree'] += self['nfree']
this_cov['bads'] = list(set(this_cov['bads']).union(self['bads']))
return this_cov
def __iadd__(self, cov):
"""Add Covariance taking into account number of degrees of freedom."""
_check_covs_algebra(self, cov)
self['data'][:] = (((self['data'] * self['nfree']) +
(cov['data'] * cov['nfree'])) /
(self['nfree'] + cov['nfree']))
self['nfree'] += cov['nfree']
self['bads'] = list(set(self['bads']).union(cov['bads']))
return self
@verbose
def plot(self, info, exclude=[], colorbar=True, proj=False, show_svd=True,
show=True, verbose=None):
"""Plot Covariance data.
Parameters
----------
info: dict
Measurement info.
exclude : list of string | str
List of channels to exclude. If empty do not exclude any channel.
If 'bads', exclude info['bads'].
colorbar : bool
Show colorbar or not.
proj : bool
Apply projections or not.
show_svd : bool
Plot also singular values of the noise covariance for each sensor
type. We show square roots ie. standard deviations.
show : bool
Call pyplot.show() as the end or not.
verbose : bool, str, int, or None
If not None, override default verbose level (see mne.verbose).
Returns
-------
fig_cov : instance of matplotlib.pyplot.Figure
The covariance plot.
fig_svd : instance of matplotlib.pyplot.Figure | None
The SVD spectra plot of the covariance.
"""
from .viz.misc import plot_cov
return plot_cov(self, info, exclude, colorbar, proj, show_svd, show)
###############################################################################
# IO
@verbose
def read_cov(fname, verbose=None):
"""Read a noise covariance from a FIF file.
Parameters
----------
fname : string
The name of file containing the covariance matrix. It should end with
-cov.fif or -cov.fif.gz.
verbose : bool, str, int, or None (default None)
If not None, override default verbose level (see mne.verbose).
Returns
-------
cov : Covariance
The noise covariance matrix.
See Also
--------
write_cov, compute_covariance, compute_raw_data_covariance
"""
check_fname(fname, 'covariance', ('-cov.fif', '-cov.fif.gz'))
return Covariance(fname)
###############################################################################
# Estimate from data
@verbose
def make_ad_hoc_cov(info, verbose=None):
"""Create an ad hoc noise covariance.
Parameters
----------
info : instance of mne.io.meas_info.Info
Measurement info.
verbose : bool, str, int, or None (default None)
If not None, override default verbose level (see mne.verbose).
Returns
-------
cov : instance of Covariance
The ad hoc diagonal noise covariance for the M/EEG data channels.
Notes
-----
.. versionadded:: 0.9.0
"""
info = pick_info(info, pick_types(info, meg=True, eeg=True))
# Standard deviations to be used
grad_std = 5e-13
mag_std = 20e-15
eeg_std = 0.2e-6
logger.info('Using standard noise values '
'(MEG grad : %6.1f fT/cm MEG mag : %6.1f fT EEG : %6.1f uV)'
% (1e13 * grad_std, 1e15 * mag_std, 1e6 * eeg_std))
data = np.zeros(len(info['ch_names']))
for meg, eeg, val in zip(('grad', 'mag', False), (False, False, True),
(grad_std, mag_std, eeg_std)):
data[pick_types(info, meg=meg, eeg=eeg)] = val * val
cov = Covariance(None)
cov.update(kind=FIFF.FIFFV_MNE_NOISE_COV, diag=True, dim=len(data),
names=info['ch_names'], data=data, projs=info['projs'],
bads=info['bads'], nfree=0, eig=None, eigvec=None,
info=info)
return cov
def _check_n_samples(n_samples, n_chan):
"""Check to see if there are enough samples for reliable cov calc."""
n_samples_min = 10 * (n_chan + 1) // 2
if n_samples <= 0:
raise ValueError('No samples found to compute the covariance matrix')
if n_samples < n_samples_min:
text = ('Too few samples (required : %d got : %d), covariance '
'estimate may be unreliable' % (n_samples_min, n_samples))
warnings.warn(text)
logger.warning(text)
@verbose
def compute_raw_data_covariance(raw, tmin=None, tmax=None, tstep=0.2,
reject=None, flat=None, picks=None,
verbose=None):
"""Estimate noise covariance matrix from a continuous segment of raw data.
It is typically useful to estimate a noise covariance
from empty room data or time intervals before starting
the stimulation.
Note: To speed up the computation you should consider preloading raw data
by setting preload=True when reading the Raw data.
Parameters
----------
raw : instance of Raw
Raw data
tmin : float | None (default None)
Beginning of time interval in seconds
tmax : float | None (default None)
End of time interval in seconds
tstep : float (default 0.2)
Length of data chunks for artefact rejection in seconds.
reject : dict | None (default None)
Rejection parameters based on peak-to-peak amplitude.
Valid keys are 'grad' | 'mag' | 'eeg' | 'eog' | 'ecg'.
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, # uV (EEG channels)
eog=250e-6 # uV (EOG channels)
)
flat : dict | None (default None)
Rejection parameters based on flatness of signal.
Valid keys are 'grad' | 'mag' | 'eeg' | 'eog' | 'ecg', and values
are floats that set the minimum acceptable peak-to-peak amplitude.
If flat is None then no rejection is done.
picks : array-like of int | None (default None)
Indices of channels to include (if None, all channels
except bad channels are used).
verbose : bool | str | int | None (default None)
If not None, override default verbose level (see mne.verbose).
Returns
-------
cov : instance of Covariance
Noise covariance matrix.
See Also
--------
compute_covariance : Estimate noise covariance matrix from epochs
"""
sfreq = raw.info['sfreq']
# Convert to samples
start = 0 if tmin is None else int(floor(tmin * sfreq))
if tmax is None:
stop = int(raw.last_samp - raw.first_samp)
else:
stop = int(ceil(tmax * sfreq))
step = int(ceil(tstep * raw.info['sfreq']))
# don't exclude any bad channels, inverses expect all channels present
if picks is None:
picks = pick_types(raw.info, meg=True, eeg=True, eog=False,
ref_meg=False, exclude=[])
data = 0
n_samples = 0
mu = 0
info = cp.copy(raw.info)
info['chs'] = [info['chs'][k] for k in picks]
info['ch_names'] = [info['ch_names'][k] for k in picks]
info['nchan'] = len(picks)
idx_by_type = channel_indices_by_type(info)
# Read data in chuncks
for first in range(start, stop, step):
last = first + step
if last >= stop:
last = stop
raw_segment, times = raw[picks, first:last]
if _is_good(raw_segment, info['ch_names'], idx_by_type, reject, flat,
ignore_chs=info['bads']):
mu += raw_segment.sum(axis=1)
data += np.dot(raw_segment, raw_segment.T)
n_samples += raw_segment.shape[1]
else:
logger.info("Artefact detected in [%d, %d]" % (first, last))
_check_n_samples(n_samples, len(picks))
mu /= n_samples
data -= n_samples * mu[:, None] * mu[None, :]
data /= (n_samples - 1.0)
logger.info("Number of samples used : %d" % n_samples)
logger.info('[done]')
cov = Covariance(None)
ch_names = [raw.info['ch_names'][k] for k in picks]
# XXX : do not compute eig and eigvec now (think it's better...)
eig = None
eigvec = None
# Store structure for fif
cov.update(kind=FIFF.FIFFV_MNE_NOISE_COV, diag=False, dim=len(data),
names=ch_names, data=data,
projs=cp.deepcopy(raw.info['projs']),
bads=raw.info['bads'], nfree=n_samples, eig=eig,
eigvec=eigvec)
return cov
@verbose
def compute_covariance(epochs, keep_sample_mean=True, tmin=None, tmax=None,
projs=None, method='empirical', method_params=None,
cv=3, scalings=None, n_jobs=1, return_estimators=False,
verbose=None):
"""Estimate noise covariance matrix from epochs.
The noise covariance is typically estimated on pre-stim periods
when the stim onset is defined from events.
If the covariance is computed for multiple event types (events
with different IDs), the following two options can be used and combined.
A) either an Epochs object for each event type is created and
a list of Epochs is passed to this function.
B) an Epochs object is created for multiple events and passed
to this function.
Note: Baseline correction should be used when creating the Epochs.
Otherwise the computed covariance matrix will be inaccurate.
Note: For multiple event types, it is also possible to create a
single Epochs object with events obtained using
merge_events(). However, the resulting covariance matrix
will only be correct if keep_sample_mean is True.
Note: The covariance can be unstable if the number of samples is not
sufficient. In that case it is common to regularize a covariance
estimate. The ``method`` parameter of this function allows to
regularize the covariance in an automated way. It also allows
to select between different alternative estimation algorithms which
themselves achieve regularization. Details are described in [1].
Parameters
----------
epochs : instance of Epochs, or a list of Epochs objects
The epochs.
keep_sample_mean : bool (default true)
If False, the average response over epochs is computed for
each event type and subtracted during the covariance
computation. This is useful if the evoked response from a
previous stimulus extends into the baseline period of the next.
Note. This option is only implemented for method='empirical'.
tmin : float | None (default None)
Start time for baseline. If None start at first sample.
tmax : float | None (default None)
End time for baseline. If None end at last sample.
projs : list of Projection | None (default None)
List of projectors to use in covariance calculation, or None
to indicate that the projectors from the epochs should be
inherited. If None, then projectors from all epochs must match.
method : str | list | None (default 'empirical')
The method used for covariance estimation. If 'empirical' (default),
the sample covariance will be computed. A list can be passed to run a
set of the different methods.
If 'auto' or a list of methods, the best estimator will be determined
based on log-likelihood and cross-validation on unseen data as
described in ref. [1]. Valid methods are:
'empirical', the empirical or sample covariance,
'diagonal_fixed', a diagonal regularization as in mne.cov.regularize
(see MNE manual), 'ledoit_wolf', the Ledoit-Wolf estimator (see [2]),
'shrunk' like 'ledoit_wolf' with cross-validation for optimal alpha
(see scikit-learn documentation on covariance estimation), 'pca',
probabilistic PCA with low rank
(see [3]), and, 'factor_analysis', Factor Analysis with low rank
(see [4]). If 'auto', expands to::
['shrunk', 'diagonal_fixed', 'empirical', 'factor_analysis']
Note. 'ledoit_wolf' and 'pca' are similar to 'shrunk' and
'factor_analysis', respectively. They are not included to avoid
redundancy. In most cases 'shrunk' and 'factor_analysis' represent
more appropriate default choices.
.. versionadded:: 0.9.0
method_params : dict | None (default None)
Additional parameters to the estimation procedure. Only considered if
method is not None. Keys must correspond to the value(s) of `method`.
If None (default), expands to::
'empirical': {'store_precision': False, 'assume_centered': True},
'diagonal_fixed': {'grad': 0.01, 'mag': 0.01, 'eeg': 0.0,
'store_precision': False,
'assume_centered': True},
'ledoit_wolf': {'store_precision': False, 'assume_centered': True},
'shrunk': {'shrinkage': np.logspace(-4, 0, 30),
'store_precision': False, 'assume_centered': True},
'pca': {'iter_n_components': None},
'factor_analysis': {'iter_n_components': None}
cv : int | sklearn cross_validation object (default 3)
The cross validation method. Defaults to 3, which will
internally trigger a default 3-fold shuffle split.
scalings : dict | None (default None)
Defaults to ``dict(mag=1e15, grad=1e13, eeg=1e6)``.
These defaults will scale magnetometers and gradiometers
at the same unit.
n_jobs : int (default 1)
Number of jobs to run in parallel.
return_estimators : bool (default False)
Whether to return all estimators or the best. Only considered if
method equals 'auto' or is a list of str. Defaults to False
verbose : bool | str | int | or None (default None)
If not None, override default verbose level (see mne.verbose).
Returns
-------
cov : instance of Covariance | list
The computed covariance. If method equals 'auto' or is a list of str
and return_estimators equals True, a list of covariance estimators is
returned (sorted by log-likelihood, from high to low, i.e. from best
to worst).
See Also
--------
compute_raw_data_covariance : Estimate noise covariance from raw data
References
----------
[1] Engemann D. and Gramfort A. (2015) Automated model selection in
covariance estimation and spatial whitening of MEG and EEG signals,
vol. 108, 328-342, NeuroImage.
[2] Ledoit, O., Wolf, M., (2004). A well-conditioned estimator for
large-dimensional covariance matrices. Journal of Multivariate
Analysis 88 (2), 365 - 411.
[3] Tipping, M. E., Bishop, C. M., (1999). Probabilistic principal
component analysis. Journal of the Royal Statistical Society: Series
B (Statistical Methodology) 61 (3), 611 - 622.
[4] Barber, D., (2012). Bayesian reasoning and machine learning.
Cambridge University Press., Algorithm 21.1
"""
accepted_methods = ('auto', 'empirical', 'diagonal_fixed', 'ledoit_wolf',
'shrunk', 'pca', 'factor_analysis',)
msg = ('Invalid method ({method}). Accepted values (individually or '
'in a list) are "%s"' % '" or "'.join(accepted_methods + ('None',)))
# scale to natural unit for best stability with MEG/EEG
if isinstance(scalings, dict):
for k, v in scalings.items():
if k not in ('mag', 'grad', 'eeg'):
raise ValueError('The keys in `scalings` must be "mag" or'
'"grad" or "eeg". You gave me: %s' % k)
scalings = _handle_default('scalings', scalings)
_method_params = {
'empirical': {'store_precision': False, 'assume_centered': True},
'diagonal_fixed': {'grad': 0.01, 'mag': 0.01, 'eeg': 0.0,
'store_precision': False, 'assume_centered': True},
'ledoit_wolf': {'store_precision': False, 'assume_centered': True},
'shrunk': {'shrinkage': np.logspace(-4, 0, 30),
'store_precision': False, 'assume_centered': True},
'pca': {'iter_n_components': None},
'factor_analysis': {'iter_n_components': None}
}
if isinstance(method_params, dict):
for key, values in method_params.items():
if key not in _method_params:
raise ValueError('key (%s) must be "%s"' %
(key, '" or "'.join(_method_params)))
_method_params[key].update(method_params[key])
# for multi condition support epochs is required to refer to a list of
# epochs objects
def _unpack_epochs(epochs):
if len(epochs.event_id) > 1:
epochs = [epochs[k] for k in epochs.event_id]
else:
epochs = [epochs]
return epochs
if not isinstance(epochs, list):
epochs = _unpack_epochs(epochs)
else:
epochs = sum([_unpack_epochs(epoch) for epoch in epochs], [])
# check for baseline correction
for epochs_t in epochs:
if epochs_t.baseline is None and epochs_t.info['highpass'] < 0.5:
warnings.warn('Epochs are not baseline corrected, covariance '
'matrix may be inaccurate')
bads = epochs[0].info['bads']
if projs is None:
projs = cp.deepcopy(epochs[0].info['projs'])
# make sure Epochs are compatible
for epochs_t in epochs[1:]:
if epochs_t.proj != epochs[0].proj:
raise ValueError('Epochs must agree on the use of projections')
for proj_a, proj_b in zip(epochs_t.info['projs'], projs):
if not _proj_equal(proj_a, proj_b):
raise ValueError('Epochs must have same projectors')
else:
projs = cp.deepcopy(projs)
ch_names = epochs[0].ch_names
# make sure Epochs are compatible
for epochs_t in epochs[1:]:
if epochs_t.info['bads'] != bads:
raise ValueError('Epochs must have same bad channels')
if epochs_t.ch_names != ch_names:
raise ValueError('Epochs must have same channel names')
picks_list = _picks_by_type(epochs[0].info)
picks_meeg = np.concatenate([b for _, b in picks_list])
picks_meeg = np.sort(picks_meeg)
ch_names = [epochs[0].ch_names[k] for k in picks_meeg]
info = epochs[0].info # we will overwrite 'epochs'
if method == 'auto':
method = ['shrunk', 'diagonal_fixed', 'empirical', 'factor_analysis']
if not isinstance(method, (list, tuple)):
method = [method]
ok_sklearn = check_sklearn_version('0.15') is True
if not ok_sklearn and (len(method) != 1 or method[0] != 'empirical'):
raise ValueError('scikit-learn is not installed, `method` must be '
'`empirical`')
if keep_sample_mean is False:
if len(method) != 1 or 'empirical' not in method:
raise ValueError('`keep_sample_mean=False` is only supported'
'with `method="empirical"`')
for p, v in _method_params.items():
if v.get('assume_centered', None) is False:
raise ValueError('`assume_centered` must be True'
' if `keep_sample_mean` is False')
# prepare mean covs
n_epoch_types = len(epochs)
data_mean = list(np.zeros(n_epoch_types))
n_samples = np.zeros(n_epoch_types, dtype=np.int)
n_epochs = np.zeros(n_epoch_types, dtype=np.int)
for ii, epochs_t in enumerate(epochs):
tslice = _get_tslice(epochs_t, tmin, tmax)
for e in epochs_t:
e = e[picks_meeg, tslice]
if not keep_sample_mean:
data_mean[ii] += e
n_samples[ii] += e.shape[1]
n_epochs[ii] += 1
n_samples_epoch = n_samples // n_epochs
norm_const = np.sum(n_samples_epoch * (n_epochs - 1))
data_mean = [1.0 / n_epoch * np.dot(mean, mean.T) for n_epoch, mean
in zip(n_epochs, data_mean)]
if not all(k in accepted_methods for k in method):
raise ValueError(msg.format(method=method))
info = pick_info(info, picks_meeg)
tslice = _get_tslice(epochs[0], tmin, tmax)
epochs = [ee.get_data()[:, picks_meeg, tslice] for ee in epochs]
picks_meeg = np.arange(len(picks_meeg))
picks_list = _picks_by_type(info)
if len(epochs) > 1:
epochs = np.concatenate(epochs, 0)
else:
epochs = epochs[0]
epochs = np.hstack(epochs)
n_samples_tot = epochs.shape[-1]
_check_n_samples(n_samples_tot, len(picks_meeg))
epochs = epochs.T # sklearn | C-order
if ok_sklearn:
cov_data = _compute_covariance_auto(epochs, method=method,
method_params=_method_params,
info=info,
verbose=verbose,
cv=cv,
n_jobs=n_jobs,
# XXX expose later
stop_early=True, # if needed.
picks_list=picks_list,
scalings=scalings)
else:
if _method_params['empirical']['assume_centered'] is True:
cov = epochs.T.dot(epochs) / n_samples_tot
else:
cov = np.cov(epochs.T, bias=1)
cov_data = {'empirical': {'data': cov}}
if keep_sample_mean is False:
cov = cov_data['empirical']['data']
# undo scaling
cov *= n_samples_tot
# ... apply pre-computed class-wise normalization
for mean_cov in data_mean:
cov -= mean_cov
cov /= norm_const
covs = list()
for this_method, data in cov_data.items():
cov = Covariance(None)
cov.update(kind=1, diag=False, dim=len(data['data']), names=ch_names,
data=data.pop('data'), projs=projs, bads=info['bads'],
nfree=n_samples_tot, eig=None, eigvec=None)
logger.info('Number of samples used : %d' % n_samples_tot)
logger.info('[done]')
# add extra info
cov.update(method=this_method, **data)
covs.append(cov)
if ok_sklearn:
msg = ['log-likelihood on unseen data (descending order):']
logliks = [(c['method'], c['loglik']) for c in covs]
logliks.sort(reverse=True, key=lambda c: c[1])
for k, v in logliks:
msg.append('%s: %0.3f' % (k, v))
logger.info('\n '.join(msg))
if ok_sklearn and not return_estimators:
keys, scores = zip(*[(c['method'], c['loglik']) for c in covs])
out = covs[np.argmax(scores)]
logger.info('selecting best estimator: {0}'.format(out['method']))
elif ok_sklearn:
out = covs
out.sort(key=lambda c: c['loglik'], reverse=True)
else:
out = covs[0]
return out
def _compute_covariance_auto(data, method, info, method_params, cv,
scalings, n_jobs, stop_early, picks_list,
verbose):
"""docstring for _compute_covariance_auto."""
from sklearn.grid_search import GridSearchCV
from sklearn.covariance import (LedoitWolf, ShrunkCovariance,
EmpiricalCovariance)
# rescale to improve numerical stability
_apply_scaling_array(data.T, picks_list=picks_list, scalings=scalings)
estimator_cov_info = list()
msg = 'Estimating covariance using %s'
_RegCovariance, _ShrunkCovariance = _get_covariance_classes()
for this_method in method:
data_ = data.copy()
name = this_method.__name__ if callable(this_method) else this_method
logger.info(msg % name.upper())
if this_method == 'empirical':
est = EmpiricalCovariance(**method_params[this_method])
est.fit(data_)
_info = None
estimator_cov_info.append((est, est.covariance_, _info))
elif this_method == 'diagonal_fixed':
est = _RegCovariance(info=info, **method_params[this_method])
est.fit(data_)
_info = None
estimator_cov_info.append((est, est.covariance_, _info))
elif this_method == 'ledoit_wolf':
shrinkages = []
lw = LedoitWolf(**method_params[this_method])
for ch_type, picks in picks_list:
lw.fit(data_[:, picks])
shrinkages.append((
ch_type,
lw.shrinkage_,
picks
))
sc = _ShrunkCovariance(shrinkage=shrinkages,
**method_params[this_method])
sc.fit(data_)
_info = None
estimator_cov_info.append((sc, sc.covariance_, _info))
elif this_method == 'shrunk':
shrinkage = method_params[this_method].pop('shrinkage')
tuned_parameters = [{'shrinkage': shrinkage}]
shrinkages = []
gs = GridSearchCV(ShrunkCovariance(**method_params[this_method]),
tuned_parameters, cv=cv)
for ch_type, picks in picks_list:
gs.fit(data_[:, picks])
shrinkages.append((
ch_type,
gs.best_estimator_.shrinkage,
picks
))
shrinkages = [c[0] for c in zip(shrinkages)]
sc = _ShrunkCovariance(shrinkage=shrinkages,
**method_params[this_method])
sc.fit(data_)
_info = None
estimator_cov_info.append((sc, sc.covariance_, _info))
elif this_method == 'pca':
mp = method_params[this_method]
pca, _info = _auto_low_rank_model(data_, this_method,
n_jobs=n_jobs,
method_params=mp, cv=cv,
stop_early=stop_early)
pca.fit(data_)
estimator_cov_info.append((pca, pca.get_covariance(), _info))
elif this_method == 'factor_analysis':
mp = method_params[this_method]
fa, _info = _auto_low_rank_model(data_, this_method, n_jobs=n_jobs,
method_params=mp, cv=cv,
stop_early=stop_early)
fa.fit(data_)
estimator_cov_info.append((fa, fa.get_covariance(), _info))
else:
raise ValueError('Oh no! Your estimator does not have'
' a .fit method')
logger.info('Done.')
logger.info('Using cross-validation to select the best estimator.')
estimators, _, _ = zip(*estimator_cov_info)
logliks = np.array([_cross_val(data, e, cv, n_jobs) for e in estimators])
# undo scaling
for c in estimator_cov_info:
_undo_scaling_cov(c[1], picks_list, scalings)
out = dict()
estimators, covs, runtime_infos = zip(*estimator_cov_info)
cov_methods = [c.__name__ if callable(c) else c for c in method]
runtime_infos, covs = list(runtime_infos), list(covs)
my_zip = zip(cov_methods, runtime_infos, logliks, covs, estimators)
for this_method, runtime_info, loglik, data, est in my_zip:
out[this_method] = {'loglik': loglik, 'data': data, 'estimator': est}
if runtime_info is not None:
out[this_method].update(runtime_info)
return out
def _logdet(A):
"""Compute the log det of a symmetric matrix."""
vals = linalg.eigh(A)[0]
vals = np.abs(vals) # avoid negative values (numerical errors)
return np.sum(np.log(vals))
def _gaussian_loglik_scorer(est, X, y=None):
"""Compute the Gaussian log likelihood of X under the model in est."""
# compute empirical covariance of the test set
precision = est.get_precision()
n_samples, n_features = X.shape
log_like = np.zeros(n_samples)
log_like = -.5 * (X * (np.dot(X, precision))).sum(axis=1)
log_like -= .5 * (n_features * log(2. * np.pi) - _logdet(precision))
out = np.mean(log_like)
return out
def _cross_val(data, est, cv, n_jobs):
"""Helper to compute cross validation."""
from sklearn.cross_validation import cross_val_score
return np.mean(cross_val_score(est, data, cv=cv, n_jobs=n_jobs,
scoring=_gaussian_loglik_scorer))
def _auto_low_rank_model(data, mode, n_jobs, method_params, cv,
stop_early=True, verbose=None):
"""compute latent variable models."""
method_params = cp.deepcopy(method_params)
iter_n_components = method_params.pop('iter_n_components')
if iter_n_components is None:
iter_n_components = np.arange(5, data.shape[1], 5)
from sklearn.decomposition import PCA, FactorAnalysis
if mode == 'factor_analysis':
est = FactorAnalysis
elif mode == 'pca':
est = PCA
else:
raise ValueError('Come on, this is not a low rank estimator: %s' %
mode)
est = est(**method_params)
est.n_components = 1
scores = np.empty_like(iter_n_components, dtype=np.float64)
scores.fill(np.nan)
# make sure we don't empty the thing if it's a generator
max_n = max(list(cp.deepcopy(iter_n_components)))
if max_n > data.shape[1]:
warnings.warn('You are trying to estimate %i components on matrix '
'with %i features.' % (max_n, data.shape[1]))
for ii, n in enumerate(iter_n_components):
est.n_components = n
try: # this may fail depending on rank and split
score = _cross_val(data=data, est=est, cv=cv, n_jobs=n_jobs)
except ValueError:
score = np.inf
if np.isinf(score) or score > 0:
logger.info('... infinite values encountered. stopping estimation')
break
logger.info('... rank: %i - loglik: %0.3f' % (n, score))
if score != -np.inf:
scores[ii] = score
if (ii >= 3 and np.all(np.diff(scores[ii - 3:ii]) < 0.) and
stop_early is True):
# early stop search when loglik has been going down 3 times
logger.info('early stopping parameter search.')
break
# happens if rank is too low right form the beginning
if np.isnan(scores).all():
raise RuntimeError('Oh no! Could not estimate covariance because all '
'scores were NaN. Please contact the MNE-Python '
'developers.')
i_score = np.nanargmax(scores)
best = est.n_components = iter_n_components[i_score]
logger.info('... best model at rank = %i' % best)
runtime_info = {'ranks': np.array(iter_n_components),
'scores': scores,
'best': best,
'cv': cv}
return est, runtime_info
def _get_covariance_classes():
"""Prepare special cov estimators."""
from sklearn.covariance import (EmpiricalCovariance, shrunk_covariance,
ShrunkCovariance)
class _RegCovariance(EmpiricalCovariance):
"""Aux class."""
def __init__(self, info, grad=0.01, mag=0.01, eeg=0.0,
store_precision=False, assume_centered=False):
self.info = info
self.grad = grad
self.mag = mag
self.eeg = eeg
self.store_precision = store_precision
self.assume_centered = assume_centered
def fit(self, X):
EmpiricalCovariance.fit(self, X)
self.covariance_ = 0.5 * (self.covariance_ + self.covariance_.T)
cov_ = Covariance(None)
cov_['data'] = self.covariance_
cov_['names'] = self.info['ch_names']
cov_['nfree'] = len(self.covariance_)
cov_['bads'] = self.info['bads']
cov_['projs'] = self.info['projs']
cov_['diag'] = False
cov_ = regularize(cov_, self.info, grad=self.grad, mag=self.mag,
eeg=self.eeg, proj=False,
exclude='bads') # ~proj == important!!
self.covariance_ = cov_.data
return self
class _ShrunkCovariance(ShrunkCovariance):
"""Aux class."""
def __init__(self, store_precision, assume_centered, shrinkage=0.1):
self.store_precision = store_precision
self.assume_centered = assume_centered
self.shrinkage = shrinkage
def fit(self, X):
EmpiricalCovariance.fit(self, X)
cov = self.covariance_