We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
StratifiedKFold with shuffling in the decoding step?
Currently we create the cross-validation object in our decoding step (08) of the pipeline via:
https://github.com/mne-tools/mne-study-template/blob/b61a5ca66aaef1f631d7ce2def3b1cde5d611729/08-sliding_estimator.py#L80-L81

By default, `StratifiedKFold` does not shuffle, meaning that the passed `random_state` doesn't have any effect (it produces a warning, though).

So – should we enable shuffling? Intuitively I would say yes, but want to hear your opinion, @agramfort

--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `11-make_cov.py`
Content:
```
1 """
2 ==================================
3 08. Baseline covariance estimation
4 ==================================
5 
6 Covariance matrices are computed and saved.
7 """
8 
9 import os.path as op
10 import itertools
11 import logging
12 
13 import mne
14 from mne.parallel import parallel_func
15 from mne_bids import make_bids_basename
16 
17 from sklearn.model_selection import KFold
18 
19 import config
20 from config import gen_log_message, on_error, failsafe_run
21 
22 logger = logging.getLogger('mne-study-template')
23 
24 
25 def compute_cov_from_epochs(subject, session, tmin, tmax):
26     deriv_path = config.get_subject_deriv_path(subject=subject,
27                                                session=session,
28                                                kind=config.get_kind())
29 
30     bids_basename = make_bids_basename(subject=subject,
31                                        session=session,
32                                        task=config.get_task(),
33                                        acquisition=config.acq,
34                                        run=None,
35                                        processing=config.proc,
36                                        recording=config.rec,
37                                        space=config.space)
38 
39     if config.use_ica or config.use_ssp:
40         extension = '_cleaned-epo'
41     else:
42         extension = '-epo'
43 
44     epo_fname = op.join(deriv_path, bids_basename + '%s.fif' % extension)
45     cov_fname = op.join(deriv_path, bids_basename + '-cov.fif')
46 
47     msg = (f"Computing regularized covariance based on epochs' baseline "
48            f"periods. Input: {epo_fname}, Output: {cov_fname}")
49     logger.info(gen_log_message(message=msg, step=11, subject=subject,
50                                 session=session))
51 
52     epochs = mne.read_epochs(epo_fname, preload=True)
53 
54     # Do not shuffle the data before splitting into train and test samples.
55     # Perform a block cross-validation instead to maintain autocorrelated
56     # noise.
57     cv = KFold(3, shuffle=False)
58     cov = mne.compute_covariance(epochs, tmin=tmin, tmax=tmax, method='shrunk',
59                                  cv=cv, rank='info')
60     cov.save(cov_fname)
61 
62 
63 def compute_cov_from_empty_room(subject, session):
64     deriv_path = config.get_subject_deriv_path(subject=subject,
65                                                session=session,
66                                                kind=config.get_kind())
67 
68     bids_basename = make_bids_basename(subject=subject,
69                                        session=session,
70                                        task=config.get_task(),
71                                        acquisition=config.acq,
72                                        run=None,
73                                        processing=config.proc,
74                                        recording=config.rec,
75                                        space=config.space)
76 
77     raw_er_fname = op.join(deriv_path,
78                            bids_basename + '_emptyroom_filt_raw.fif')
79     cov_fname = op.join(deriv_path, bids_basename + '-cov.fif')
80 
81     extra_params = dict()
82     if not config.use_maxwell_filter and config.allow_maxshield:
83         extra_params['allow_maxshield'] = config.allow_maxshield
84 
85     msg = (f'Computing regularized covariance based on empty-room recording. '
86            f'Input: {raw_er_fname}, Output: {cov_fname}')
87     logger.info(gen_log_message(message=msg, step=11, subject=subject,
88                                 session=session))
89 
90     raw_er = mne.io.read_raw_fif(raw_er_fname, preload=True, **extra_params)
91 
92     # Do not shuffle the data before splitting into train and test samples.
93     # Perform a block cross-validation instead to maintain autocorrelated
94     # noise.
95     cv = KFold(3, shuffle=False)
96     cov = mne.compute_raw_covariance(raw_er, method='shrunk', cv=cv,
97                                      rank='info')
98     cov.save(cov_fname)
99 
100 
101 @failsafe_run(on_error=on_error)
102 def run_covariance(subject, session=None):
103     if config.noise_cov == 'emptyroom' and 'eeg' not in config.ch_types:
104         compute_cov_from_empty_room(subject=subject, session=session)
105     else:
106         tmin, tmax = config.noise_cov
107         compute_cov_from_epochs(subject=subject, session=session, tmin=tmin,
108                                 tmax=tmax)
109 
110 
111 def main():
112     """Run cov."""
113     msg = 'Running Step 11: Estimate noise covariance'
114     logger.info(gen_log_message(step=11, message=msg))
115 
116     parallel, run_func, _ = parallel_func(run_covariance, n_jobs=config.N_JOBS)
117     parallel(run_func(subject, session) for subject, session in
118              itertools.product(config.get_subjects(), config.get_sessions()))
119 
120     msg = 'Completed Step 11: Estimate noise covariance'
121     logger.info(gen_log_message(step=11, message=msg))
122 
123 
124 if __name__ == '__main__':
125     main()
126
```

Path: `08-sliding_estimator.py`
Content:
```
1 """
2 =================
3 Sliding estimator
4 =================
5 
6 A sliding estimator fits a logistic regression model for every time point.
7 In this example, we contrast the condition 'famous' against 'scrambled'
8 using this approach. The end result is an averaging effect across sensors.
9 The contrast across different sensors are combined into a single plot.
10 
11 """  # noqa: E501
12 
13 ###############################################################################
14 # Let us first import the libraries
15 
16 import os.path as op
17 import logging
18 
19 import numpy as np
20 from scipy.io import savemat
21 
22 import mne
23 from mne.decoding import SlidingEstimator, cross_val_multiscore
24 
25 from mne_bids import make_bids_basename
26 
27 from sklearn.preprocessing import StandardScaler
28 from sklearn.model_selection import StratifiedKFold
29 from sklearn.pipeline import make_pipeline
30 from sklearn.linear_model import LogisticRegression
31 
32 import config
33 from config import gen_log_message, on_error, failsafe_run
34 
35 logger = logging.getLogger('mne-study-template')
36 
37 
38 ###############################################################################
39 # Then we write a function to do time decoding on one subject
40 
41 @failsafe_run(on_error=on_error)
42 def run_time_decoding(subject, condition1, condition2, session=None):
43     msg = f'Contrasting conditions: {condition1} – {condition2}'
44     logger.info(gen_log_message(message=msg, step=8, subject=subject,
45                                 session=session))
46 
47     deriv_path = config.get_subject_deriv_path(subject=subject,
48                                                session=session,
49                                                kind=config.get_kind())
50 
51     bids_basename = make_bids_basename(subject=subject,
52                                        session=session,
53                                        task=config.get_task(),
54                                        acquisition=config.acq,
55                                        run=None,
56                                        processing=config.proc,
57                                        recording=config.rec,
58                                        space=config.space)
59 
60     fname_in = op.join(deriv_path, bids_basename + '-epo.fif')
61     epochs = mne.read_epochs(fname_in)
62 
63     # We define the epochs and the labels
64     epochs = mne.concatenate_epochs([epochs[condition1],
65                                      epochs[condition2]])
66     epochs.apply_baseline()
67 
68     # Get the data and labels
69     X = epochs.get_data()
70     n_cond1 = len(epochs[condition1])
71     n_cond2 = len(epochs[condition2])
72     y = np.r_[np.ones(n_cond1), np.zeros(n_cond2)]
73 
74     # Use AUC because chance level is same regardless of the class balance
75     se = SlidingEstimator(
76         make_pipeline(StandardScaler(),
77                       LogisticRegression(solver='liblinear',
78                                          random_state=config.random_state)),
79         scoring=config.decoding_metric, n_jobs=config.N_JOBS)
80     cv = StratifiedKFold(random_state=config.random_state,
81                          n_splits=config.decoding_n_splits)
82     scores = cross_val_multiscore(se, X=X, y=y, cv=cv)
83 
84     # let's save the scores now
85     a_vs_b = '%s_vs_%s' % (condition1, condition2)
86     a_vs_b = a_vs_b.replace(op.sep, '')
87     fname_td = op.join(config.bids_root, 'derivatives', config.PIPELINE_NAME,
88                        '%s_%s_%s_%s.mat' %
89                        (subject, config.study_name, a_vs_b,
90                         config.decoding_metric))
91     savemat(fname_td, {'scores': scores, 'times': epochs.times})
92 
93 
94 def main():
95     """Run sliding estimator."""
96     msg = 'Running Step 8: Sliding estimator'
97     logger.info(gen_log_message(step=8, message=msg))
98 
99     # Here we go parallel inside the :class:`mne.decoding.SlidingEstimator`
100     # so we don't dispatch manually to multiple jobs.
101     for subject in config.get_subjects():
102         for session in config.get_sessions():
103             for conditions in config.decoding_conditions:
104                 run_time_decoding(subject, *conditions, session=session)
105 
106     msg = 'Completed Step 8: Sliding estimator'
107     logger.info(gen_log_message(step=8, message=msg))
108 
109 
110 if __name__ == '__main__':
111     main()
112
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/08-sliding_estimator.py b/08-sliding_estimator.py
--- a/08-sliding_estimator.py
+++ b/08-sliding_estimator.py
@@ -77,9 +77,7 @@
                       LogisticRegression(solver='liblinear',
                                          random_state=config.random_state)),
         scoring=config.decoding_metric, n_jobs=config.N_JOBS)
-    cv = StratifiedKFold(random_state=config.random_state,
-                         n_splits=config.decoding_n_splits)
-    scores = cross_val_multiscore(se, X=X, y=y, cv=cv)
+    scores = cross_val_multiscore(se, X=X, y=y, cv=config.decoding_n_splits)
 
     # let's save the scores now
     a_vs_b = '%s_vs_%s' % (condition1, condition2)
diff --git a/11-make_cov.py b/11-make_cov.py
--- a/11-make_cov.py
+++ b/11-make_cov.py
@@ -50,13 +50,8 @@
                                 session=session))
 
     epochs = mne.read_epochs(epo_fname, preload=True)
-
-    # Do not shuffle the data before splitting into train and test samples.
-    # Perform a block cross-validation instead to maintain autocorrelated
-    # noise.
-    cv = KFold(3, shuffle=False)
     cov = mne.compute_covariance(epochs, tmin=tmin, tmax=tmax, method='shrunk',
-                                 cv=cv, rank='info')
+                                 rank='info')
     cov.save(cov_fname)
 
 
@@ -88,13 +83,7 @@
                                 session=session))
 
     raw_er = mne.io.read_raw_fif(raw_er_fname, preload=True, **extra_params)
-
-    # Do not shuffle the data before splitting into train and test samples.
-    # Perform a block cross-validation instead to maintain autocorrelated
-    # noise.
-    cv = KFold(3, shuffle=False)
-    cov = mne.compute_raw_covariance(raw_er, method='shrunk', cv=cv,
-                                     rank='info')
+    cov = mne.compute_raw_covariance(raw_er, method='shrunk', rank='info')
     cov.save(cov_fname)

{"golden_diff": "diff --git a/08-sliding_estimator.py b/08-sliding_estimator.py\n--- a/08-sliding_estimator.py\n+++ b/08-sliding_estimator.py\n@@ -77,9 +77,7 @@\n                       LogisticRegression(solver='liblinear',\n                                          random_state=config.random_state)),\n         scoring=config.decoding_metric, n_jobs=config.N_JOBS)\n-    cv = StratifiedKFold(random_state=config.random_state,\n-                         n_splits=config.decoding_n_splits)\n-    scores = cross_val_multiscore(se, X=X, y=y, cv=cv)\n+    scores = cross_val_multiscore(se, X=X, y=y, cv=config.decoding_n_splits)\n \n     # let's save the scores now\n     a_vs_b = '%s_vs_%s' % (condition1, condition2)\ndiff --git a/11-make_cov.py b/11-make_cov.py\n--- a/11-make_cov.py\n+++ b/11-make_cov.py\n@@ -50,13 +50,8 @@\n                                 session=session))\n \n     epochs = mne.read_epochs(epo_fname, preload=True)\n-\n-    # Do not shuffle the data before splitting into train and test samples.\n-    # Perform a block cross-validation instead to maintain autocorrelated\n-    # noise.\n-    cv = KFold(3, shuffle=False)\n     cov = mne.compute_covariance(epochs, tmin=tmin, tmax=tmax, method='shrunk',\n-                                 cv=cv, rank='info')\n+                                 rank='info')\n     cov.save(cov_fname)\n \n \n@@ -88,13 +83,7 @@\n                                 session=session))\n \n     raw_er = mne.io.read_raw_fif(raw_er_fname, preload=True, **extra_params)\n-\n-    # Do not shuffle the data before splitting into train and test samples.\n-    # Perform a block cross-validation instead to maintain autocorrelated\n-    # noise.\n-    cv = KFold(3, shuffle=False)\n-    cov = mne.compute_raw_covariance(raw_er, method='shrunk', cv=cv,\n-                                     rank='info')\n+    cov = mne.compute_raw_covariance(raw_er, method='shrunk', rank='info')\n     cov.save(cov_fname)\n", "issue": "StratifiedKFold with shuffling in the decoding step?\nCurrently we create the cross-validation object in our decoding step (08) of the pipeline via:\r\nhttps://github.com/mne-tools/mne-study-template/blob/b61a5ca66aaef1f631d7ce2def3b1cde5d611729/08-sliding_estimator.py#L80-L81\r\n\r\nBy default, `StratifiedKFold` does not shuffle, meaning that the passed `random_state` doesn't have any effect (it produces a warning, though).\r\n\r\nSo \u2013 should we enable shuffling? Intuitively I would say yes, but want to hear your opinion, @agramfort\n", "before_files": [{"content": "\"\"\"\n==================================\n08. Baseline covariance estimation\n==================================\n\nCovariance matrices are computed and saved.\n\"\"\"\n\nimport os.path as op\nimport itertools\nimport logging\n\nimport mne\nfrom mne.parallel import parallel_func\nfrom mne_bids import make_bids_basename\n\nfrom sklearn.model_selection import KFold\n\nimport config\nfrom config import gen_log_message, on_error, failsafe_run\n\nlogger = logging.getLogger('mne-study-template')\n\n\ndef compute_cov_from_epochs(subject, session, tmin, tmax):\n    deriv_path = config.get_subject_deriv_path(subject=subject,\n                                               session=session,\n                                               kind=config.get_kind())\n\n    bids_basename = make_bids_basename(subject=subject,\n                                       session=session,\n                                       task=config.get_task(),\n                                       acquisition=config.acq,\n                                       run=None,\n                                       processing=config.proc,\n                                       recording=config.rec,\n                                       space=config.space)\n\n    if config.use_ica or config.use_ssp:\n        extension = '_cleaned-epo'\n    else:\n        extension = '-epo'\n\n    epo_fname = op.join(deriv_path, bids_basename + '%s.fif' % extension)\n    cov_fname = op.join(deriv_path, bids_basename + '-cov.fif')\n\n    msg = (f\"Computing regularized covariance based on epochs' baseline \"\n           f\"periods. Input: {epo_fname}, Output: {cov_fname}\")\n    logger.info(gen_log_message(message=msg, step=11, subject=subject,\n                                session=session))\n\n    epochs = mne.read_epochs(epo_fname, preload=True)\n\n    # Do not shuffle the data before splitting into train and test samples.\n    # Perform a block cross-validation instead to maintain autocorrelated\n    # noise.\n    cv = KFold(3, shuffle=False)\n    cov = mne.compute_covariance(epochs, tmin=tmin, tmax=tmax, method='shrunk',\n                                 cv=cv, rank='info')\n    cov.save(cov_fname)\n\n\ndef compute_cov_from_empty_room(subject, session):\n    deriv_path = config.get_subject_deriv_path(subject=subject,\n                                               session=session,\n                                               kind=config.get_kind())\n\n    bids_basename = make_bids_basename(subject=subject,\n                                       session=session,\n                                       task=config.get_task(),\n                                       acquisition=config.acq,\n                                       run=None,\n                                       processing=config.proc,\n                                       recording=config.rec,\n                                       space=config.space)\n\n    raw_er_fname = op.join(deriv_path,\n                           bids_basename + '_emptyroom_filt_raw.fif')\n    cov_fname = op.join(deriv_path, bids_basename + '-cov.fif')\n\n    extra_params = dict()\n    if not config.use_maxwell_filter and config.allow_maxshield:\n        extra_params['allow_maxshield'] = config.allow_maxshield\n\n    msg = (f'Computing regularized covariance based on empty-room recording. '\n           f'Input: {raw_er_fname}, Output: {cov_fname}')\n    logger.info(gen_log_message(message=msg, step=11, subject=subject,\n                                session=session))\n\n    raw_er = mne.io.read_raw_fif(raw_er_fname, preload=True, **extra_params)\n\n    # Do not shuffle the data before splitting into train and test samples.\n    # Perform a block cross-validation instead to maintain autocorrelated\n    # noise.\n    cv = KFold(3, shuffle=False)\n    cov = mne.compute_raw_covariance(raw_er, method='shrunk', cv=cv,\n                                     rank='info')\n    cov.save(cov_fname)\n\n\n@failsafe_run(on_error=on_error)\ndef run_covariance(subject, session=None):\n    if config.noise_cov == 'emptyroom' and 'eeg' not in config.ch_types:\n        compute_cov_from_empty_room(subject=subject, session=session)\n    else:\n        tmin, tmax = config.noise_cov\n        compute_cov_from_epochs(subject=subject, session=session, tmin=tmin,\n                                tmax=tmax)\n\n\ndef main():\n    \"\"\"Run cov.\"\"\"\n    msg = 'Running Step 11: Estimate noise covariance'\n    logger.info(gen_log_message(step=11, message=msg))\n\n    parallel, run_func, _ = parallel_func(run_covariance, n_jobs=config.N_JOBS)\n    parallel(run_func(subject, session) for subject, session in\n             itertools.product(config.get_subjects(), config.get_sessions()))\n\n    msg = 'Completed Step 11: Estimate noise covariance'\n    logger.info(gen_log_message(step=11, message=msg))\n\n\nif __name__ == '__main__':\n    main()\n", "path": "11-make_cov.py"}, {"content": "\"\"\"\n=================\nSliding estimator\n=================\n\nA sliding estimator fits a logistic regression model for every time point.\nIn this example, we contrast the condition 'famous' against 'scrambled'\nusing this approach. The end result is an averaging effect across sensors.\nThe contrast across different sensors are combined into a single plot.\n\n\"\"\"  # noqa: E501\n\n###############################################################################\n# Let us first import the libraries\n\nimport os.path as op\nimport logging\n\nimport numpy as np\nfrom scipy.io import savemat\n\nimport mne\nfrom mne.decoding import SlidingEstimator, cross_val_multiscore\n\nfrom mne_bids import make_bids_basename\n\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.linear_model import LogisticRegression\n\nimport config\nfrom config import gen_log_message, on_error, failsafe_run\n\nlogger = logging.getLogger('mne-study-template')\n\n\n###############################################################################\n# Then we write a function to do time decoding on one subject\n\n@failsafe_run(on_error=on_error)\ndef run_time_decoding(subject, condition1, condition2, session=None):\n    msg = f'Contrasting conditions: {condition1} \u2013 {condition2}'\n    logger.info(gen_log_message(message=msg, step=8, subject=subject,\n                                session=session))\n\n    deriv_path = config.get_subject_deriv_path(subject=subject,\n                                               session=session,\n                                               kind=config.get_kind())\n\n    bids_basename = make_bids_basename(subject=subject,\n                                       session=session,\n                                       task=config.get_task(),\n                                       acquisition=config.acq,\n                                       run=None,\n                                       processing=config.proc,\n                                       recording=config.rec,\n                                       space=config.space)\n\n    fname_in = op.join(deriv_path, bids_basename + '-epo.fif')\n    epochs = mne.read_epochs(fname_in)\n\n    # We define the epochs and the labels\n    epochs = mne.concatenate_epochs([epochs[condition1],\n                                     epochs[condition2]])\n    epochs.apply_baseline()\n\n    # Get the data and labels\n    X = epochs.get_data()\n    n_cond1 = len(epochs[condition1])\n    n_cond2 = len(epochs[condition2])\n    y = np.r_[np.ones(n_cond1), np.zeros(n_cond2)]\n\n    # Use AUC because chance level is same regardless of the class balance\n    se = SlidingEstimator(\n        make_pipeline(StandardScaler(),\n                      LogisticRegression(solver='liblinear',\n                                         random_state=config.random_state)),\n        scoring=config.decoding_metric, n_jobs=config.N_JOBS)\n    cv = StratifiedKFold(random_state=config.random_state,\n                         n_splits=config.decoding_n_splits)\n    scores = cross_val_multiscore(se, X=X, y=y, cv=cv)\n\n    # let's save the scores now\n    a_vs_b = '%s_vs_%s' % (condition1, condition2)\n    a_vs_b = a_vs_b.replace(op.sep, '')\n    fname_td = op.join(config.bids_root, 'derivatives', config.PIPELINE_NAME,\n                       '%s_%s_%s_%s.mat' %\n                       (subject, config.study_name, a_vs_b,\n                        config.decoding_metric))\n    savemat(fname_td, {'scores': scores, 'times': epochs.times})\n\n\ndef main():\n    \"\"\"Run sliding estimator.\"\"\"\n    msg = 'Running Step 8: Sliding estimator'\n    logger.info(gen_log_message(step=8, message=msg))\n\n    # Here we go parallel inside the :class:`mne.decoding.SlidingEstimator`\n    # so we don't dispatch manually to multiple jobs.\n    for subject in config.get_subjects():\n        for session in config.get_sessions():\n            for conditions in config.decoding_conditions:\n                run_time_decoding(subject, *conditions, session=session)\n\n    msg = 'Completed Step 8: Sliding estimator'\n    logger.info(gen_log_message(step=8, message=msg))\n\n\nif __name__ == '__main__':\n    main()\n", "path": "08-sliding_estimator.py"}], "after_files": [{"content": "\"\"\"\n==================================\n08. Baseline covariance estimation\n==================================\n\nCovariance matrices are computed and saved.\n\"\"\"\n\nimport os.path as op\nimport itertools\nimport logging\n\nimport mne\nfrom mne.parallel import parallel_func\nfrom mne_bids import make_bids_basename\n\nfrom sklearn.model_selection import KFold\n\nimport config\nfrom config import gen_log_message, on_error, failsafe_run\n\nlogger = logging.getLogger('mne-study-template')\n\n\ndef compute_cov_from_epochs(subject, session, tmin, tmax):\n    deriv_path = config.get_subject_deriv_path(subject=subject,\n                                               session=session,\n                                               kind=config.get_kind())\n\n    bids_basename = make_bids_basename(subject=subject,\n                                       session=session,\n                                       task=config.get_task(),\n                                       acquisition=config.acq,\n                                       run=None,\n                                       processing=config.proc,\n                                       recording=config.rec,\n                                       space=config.space)\n\n    if config.use_ica or config.use_ssp:\n        extension = '_cleaned-epo'\n    else:\n        extension = '-epo'\n\n    epo_fname = op.join(deriv_path, bids_basename + '%s.fif' % extension)\n    cov_fname = op.join(deriv_path, bids_basename + '-cov.fif')\n\n    msg = (f\"Computing regularized covariance based on epochs' baseline \"\n           f\"periods. Input: {epo_fname}, Output: {cov_fname}\")\n    logger.info(gen_log_message(message=msg, step=11, subject=subject,\n                                session=session))\n\n    epochs = mne.read_epochs(epo_fname, preload=True)\n    cov = mne.compute_covariance(epochs, tmin=tmin, tmax=tmax, method='shrunk',\n                                 rank='info')\n    cov.save(cov_fname)\n\n\ndef compute_cov_from_empty_room(subject, session):\n    deriv_path = config.get_subject_deriv_path(subject=subject,\n                                               session=session,\n                                               kind=config.get_kind())\n\n    bids_basename = make_bids_basename(subject=subject,\n                                       session=session,\n                                       task=config.get_task(),\n                                       acquisition=config.acq,\n                                       run=None,\n                                       processing=config.proc,\n                                       recording=config.rec,\n                                       space=config.space)\n\n    raw_er_fname = op.join(deriv_path,\n                           bids_basename + '_emptyroom_filt_raw.fif')\n    cov_fname = op.join(deriv_path, bids_basename + '-cov.fif')\n\n    extra_params = dict()\n    if not config.use_maxwell_filter and config.allow_maxshield:\n        extra_params['allow_maxshield'] = config.allow_maxshield\n\n    msg = (f'Computing regularized covariance based on empty-room recording. '\n           f'Input: {raw_er_fname}, Output: {cov_fname}')\n    logger.info(gen_log_message(message=msg, step=11, subject=subject,\n                                session=session))\n\n    raw_er = mne.io.read_raw_fif(raw_er_fname, preload=True, **extra_params)\n    cov = mne.compute_raw_covariance(raw_er, method='shrunk', rank='info')\n    cov.save(cov_fname)\n\n\n@failsafe_run(on_error=on_error)\ndef run_covariance(subject, session=None):\n    if config.noise_cov == 'emptyroom' and 'eeg' not in config.ch_types:\n        compute_cov_from_empty_room(subject=subject, session=session)\n    else:\n        tmin, tmax = config.noise_cov\n        compute_cov_from_epochs(subject=subject, session=session, tmin=tmin,\n                                tmax=tmax)\n\n\ndef main():\n    \"\"\"Run cov.\"\"\"\n    msg = 'Running Step 11: Estimate noise covariance'\n    logger.info(gen_log_message(step=11, message=msg))\n\n    parallel, run_func, _ = parallel_func(run_covariance, n_jobs=config.N_JOBS)\n    parallel(run_func(subject, session) for subject, session in\n             itertools.product(config.get_subjects(), config.get_sessions()))\n\n    msg = 'Completed Step 11: Estimate noise covariance'\n    logger.info(gen_log_message(step=11, message=msg))\n\n\nif __name__ == '__main__':\n    main()\n", "path": "11-make_cov.py"}, {"content": "\"\"\"\n=================\nSliding estimator\n=================\n\nA sliding estimator fits a logistic regression model for every time point.\nIn this example, we contrast the condition 'famous' against 'scrambled'\nusing this approach. The end result is an averaging effect across sensors.\nThe contrast across different sensors are combined into a single plot.\n\n\"\"\"  # noqa: E501\n\n###############################################################################\n# Let us first import the libraries\n\nimport os.path as op\nimport logging\n\nimport numpy as np\nfrom scipy.io import savemat\n\nimport mne\nfrom mne.decoding import SlidingEstimator, cross_val_multiscore\n\nfrom mne_bids import make_bids_basename\n\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.linear_model import LogisticRegression\n\nimport config\nfrom config import gen_log_message, on_error, failsafe_run\n\nlogger = logging.getLogger('mne-study-template')\n\n\n###############################################################################\n# Then we write a function to do time decoding on one subject\n\n@failsafe_run(on_error=on_error)\ndef run_time_decoding(subject, condition1, condition2, session=None):\n    msg = f'Contrasting conditions: {condition1} \u2013 {condition2}'\n    logger.info(gen_log_message(message=msg, step=8, subject=subject,\n                                session=session))\n\n    deriv_path = config.get_subject_deriv_path(subject=subject,\n                                               session=session,\n                                               kind=config.get_kind())\n\n    bids_basename = make_bids_basename(subject=subject,\n                                       session=session,\n                                       task=config.get_task(),\n                                       acquisition=config.acq,\n                                       run=None,\n                                       processing=config.proc,\n                                       recording=config.rec,\n                                       space=config.space)\n\n    fname_in = op.join(deriv_path, bids_basename + '-epo.fif')\n    epochs = mne.read_epochs(fname_in)\n\n    # We define the epochs and the labels\n    epochs = mne.concatenate_epochs([epochs[condition1],\n                                     epochs[condition2]])\n    epochs.apply_baseline()\n\n    # Get the data and labels\n    X = epochs.get_data()\n    n_cond1 = len(epochs[condition1])\n    n_cond2 = len(epochs[condition2])\n    y = np.r_[np.ones(n_cond1), np.zeros(n_cond2)]\n\n    # Use AUC because chance level is same regardless of the class balance\n    se = SlidingEstimator(\n        make_pipeline(StandardScaler(),\n                      LogisticRegression(solver='liblinear',\n                                         random_state=config.random_state)),\n        scoring=config.decoding_metric, n_jobs=config.N_JOBS)\n    scores = cross_val_multiscore(se, X=X, y=y, cv=config.decoding_n_splits)\n\n    # let's save the scores now\n    a_vs_b = '%s_vs_%s' % (condition1, condition2)\n    a_vs_b = a_vs_b.replace(op.sep, '')\n    fname_td = op.join(config.bids_root, 'derivatives', config.PIPELINE_NAME,\n                       '%s_%s_%s_%s.mat' %\n                       (subject, config.study_name, a_vs_b,\n                        config.decoding_metric))\n    savemat(fname_td, {'scores': scores, 'times': epochs.times})\n\n\ndef main():\n    \"\"\"Run sliding estimator.\"\"\"\n    msg = 'Running Step 8: Sliding estimator'\n    logger.info(gen_log_message(step=8, message=msg))\n\n    # Here we go parallel inside the :class:`mne.decoding.SlidingEstimator`\n    # so we don't dispatch manually to multiple jobs.\n    for subject in config.get_subjects():\n        for session in config.get_sessions():\n            for conditions in config.decoding_conditions:\n                run_time_decoding(subject, *conditions, session=session)\n\n    msg = 'Completed Step 8: Sliding estimator'\n    logger.info(gen_log_message(step=8, message=msg))\n\n\nif __name__ == '__main__':\n    main()\n", "path": "08-sliding_estimator.py"}]}