Ejemplo n.º 1
0
def main():
    """Run sliding estimator."""
    if not config.contrasts:
        msg = 'No contrasts specified; not performing decoding.'
        logger.info(**gen_log_kwargs(message=msg))
        return

    if not config.decode:
        msg = 'No decoding requested by user.'
        logger.info(**gen_log_kwargs(message=msg))
        return

    # Here we go parallel inside the :class:`mne.decoding.SlidingEstimator`
    # so we don't dispatch manually to multiple jobs.
    parallel, run_func, _ = parallel_func(run_time_decoding, n_jobs=1)
    logs = parallel(
        run_func(cfg=get_config(),
                 subject=subject,
                 condition1=cond_1,
                 condition2=cond_2,
                 session=session)
        for subject, session, (cond_1, cond_2) in itertools.product(
            config.get_subjects(), config.get_sessions(), config.contrasts))

    config.save_logs(logs)
Ejemplo n.º 2
0
def make_ecg_epochs(*,
                    cfg,
                    raw: mne.io.BaseRaw,
                    subject: str,
                    session: str,
                    run: Optional[str] = None) -> Optional[mne.BaseEpochs]:
    # ECG either needs an ecg channel, or avg of the mags (i.e. MEG data)
    if ('ecg' in raw.get_channel_types() or 'meg' in cfg.ch_types
            or 'mag' in cfg.ch_types):
        msg = 'Creating ECG epochs …'
        logger.info(**gen_log_kwargs(
            message=msg, subject=subject, session=session, run=run))

        ecg_epochs = create_ecg_epochs(raw,
                                       baseline=(None, -0.2),
                                       tmin=-0.5,
                                       tmax=0.5)

        if len(ecg_epochs) == 0:
            msg = ('No ECG events could be found. Not running ECG artifact '
                   'detection.')
            logger.info(**gen_log_kwargs(
                message=msg, subject=subject, session=session, run=run))
            ecg_epochs = None
    else:
        msg = ('No ECG or magnetometer channels are present. Cannot '
               'automate artifact detection for ECG')
        logger.info(**gen_log_kwargs(
            message=msg, subject=subject, session=session, run=run))
        ecg_epochs = None

    return ecg_epochs
Ejemplo n.º 3
0
def make_scalp_surface(*, cfg, subject):
    fs_subject = cfg.fs_subject
    bem_dir = Path(cfg.fs_subjects_dir) / fs_subject / 'bem'

    generate_surface = cfg.recreate_scalp_surface

    # Even if the user didn't ask for re-creation of the surface, we check if
    # the required file exist; if it doesn't, we create it
    surface_fname = bem_dir / f'sub-{subject}-head-dense.fif'
    if not generate_surface and not surface_fname.exists():
        generate_surface = True

    if not generate_surface:
        # Seems everything is in place, so we can safely skip surface creation
        msg = 'Not generating high-resolution scalp surface.'
        logger.info(**gen_log_kwargs(message=msg, subject=subject))
        return

    msg = 'Generating high-resolution scalp surface for coregistration.'
    logger.info(**gen_log_kwargs(message=msg, subject=subject))

    mne.bem.make_scalp_surfaces(subject=fs_subject,
                                subjects_dir=cfg.fs_subjects_dir,
                                no_decimate=True,
                                force=True,
                                overwrite=True)
Ejemplo n.º 4
0
def detect_bad_components(*, cfg, which: Literal['eog', 'ecg'],
                          epochs: mne.BaseEpochs, ica: mne.preprocessing.ICA,
                          subject: str,
                          session: str) -> Tuple[List[int], np.ndarray]:
    artifact = which.upper()
    msg = f'Performing automated {artifact} artifact detection …'
    logger.info(
        **gen_log_kwargs(message=msg, subject=subject, session=session))

    if which == 'eog':
        inds, scores = ica.find_bads_eog(epochs,
                                         threshold=cfg.ica_eog_threshold)
    else:
        inds, scores = ica.find_bads_ecg(epochs,
                                         method='ctps',
                                         threshold=cfg.ica_ctps_ecg_threshold)

    if not inds:
        adjust_setting = ('ica_eog_threshold'
                          if which == 'eog' else 'ica_ctps_ecg_threshold')
        warn = (f'No {artifact}-related ICs detected, this is highly '
                f'suspicious. A manual check is suggested. You may wish to '
                f'lower "{adjust_setting}".')
        logger.warning(
            **gen_log_kwargs(message=warn, subject=subject, session=session))
    else:
        msg = (f'Detected {len(inds)} {artifact}-related ICs in '
               f'{len(epochs)} {artifact} epochs.')
        logger.info(
            **gen_log_kwargs(message=msg, subject=subject, session=session))

    return inds, scores
Ejemplo n.º 5
0
def average_evokeds(cfg, session):
    # Container for all conditions:
    all_evokeds = defaultdict(list)

    for subject in cfg.subjects:
        fname_in = BIDSPath(subject=subject,
                            session=session,
                            task=cfg.task,
                            acquisition=cfg.acq,
                            run=None,
                            recording=cfg.rec,
                            space=cfg.space,
                            suffix='ave',
                            extension='.fif',
                            datatype=cfg.datatype,
                            root=cfg.deriv_root,
                            check=False)

        msg = f'Input: {fname_in}'
        logger.info(**gen_log_kwargs(message=msg, subject=subject,
                                     session=session))

        evokeds = mne.read_evokeds(fname_in)
        for idx, evoked in enumerate(evokeds):
            all_evokeds[idx].append(evoked)  # Insert into the container

    for idx, evokeds in all_evokeds.items():
        all_evokeds[idx] = mne.grand_average(
            evokeds, interpolate_bads=cfg.interpolate_bads_grand_average
        )  # Combine subjects
        # Keep condition in comment
        all_evokeds[idx].comment = 'Grand average: ' + evokeds[0].comment

    subject = 'average'
    fname_out = BIDSPath(subject=subject,
                         session=session,
                         task=cfg.task,
                         acquisition=cfg.acq,
                         run=None,
                         processing=cfg.proc,
                         recording=cfg.rec,
                         space=cfg.space,
                         suffix='ave',
                         extension='.fif',
                         datatype=cfg.datatype,
                         root=cfg.deriv_root,
                         check=False)

    if not fname_out.fpath.parent.exists():
        os.makedirs(fname_out.fpath.parent)

    msg = f'Saving grand-averaged evoked sensor data: {fname_out}'
    logger.info(**gen_log_kwargs(message=msg, subject=subject,
                                 session=session))
    mne.write_evokeds(fname_out, list(all_evokeds.values()))
    return list(all_evokeds.values())
Ejemplo n.º 6
0
def detect_bad_components(*, cfg, which: Literal['eog', 'ecg'],
                          epochs: mne.BaseEpochs, ica: mne.preprocessing.ICA,
                          subject: str, session: str,
                          report: mne.Report) -> List[int]:
    evoked = epochs.average()

    artifact = which.upper()
    msg = f'Performing automated {artifact} artifact detection …'
    logger.info(
        **gen_log_kwargs(message=msg, subject=subject, session=session))

    if which == 'eog':
        inds, scores = ica.find_bads_eog(epochs,
                                         threshold=cfg.ica_eog_threshold)
    else:
        inds, scores = ica.find_bads_ecg(epochs,
                                         method='ctps',
                                         threshold=cfg.ica_ctps_ecg_threshold)

    if not inds:
        adjust_setting = ('ica_eog_threshold'
                          if which == 'eog' else 'ica_ctps_ecg_threshold')
        warn = (f'No {artifact}-related ICs detected, this is highly '
                f'suspicious. A manual check is suggested. You may wish to '
                f'lower "{adjust_setting}".')
        logger.warning(
            **gen_log_kwargs(message=warn, subject=subject, session=session))
    else:
        msg = (f'Detected {len(inds)} {artifact}-related ICs in '
               f'{len(epochs)} {artifact} epochs.')
        logger.info(
            **gen_log_kwargs(message=msg, subject=subject, session=session))

    # Mark the artifact-related components for removal
    ica.exclude = inds

    # Plot scores
    fig = ica.plot_scores(scores, labels=which, show=cfg.interactive)
    report.add_figs_to_section(figs=fig,
                               captions=f'Scores - {artifact}',
                               section=f'sub-{subject}')

    # Plot source time course
    fig = ica.plot_sources(evoked, show=cfg.interactive)
    report.add_figs_to_section(figs=fig,
                               captions=f'Source time course - {artifact}',
                               section=f'sub-{subject}')

    # Plot original & corrected data
    fig = ica.plot_overlay(evoked, show=cfg.interactive)
    report.add_figs_to_section(figs=fig,
                               captions=f'Corrections - {artifact}',
                               section=f'sub-{subject}')

    return inds
Ejemplo n.º 7
0
def main():
    """Initialize the output directories."""
    msg = 'Running: Initializing output directories.'
    logger.info(**gen_log_kwargs(message=msg))

    init_dataset(cfg=get_config())
    parallel, run_func, _ = parallel_func(init_subject_dirs,
                                          n_jobs=config.get_n_jobs())
    parallel(
        run_func(cfg=get_config(), subject=subject, session=session)
        for subject, session in itertools.product(config.get_subjects(),
                                                  config.get_sessions()))

    msg = 'Completed: Initializing output directories.'
    logger.info(**gen_log_kwargs(message=msg))
Ejemplo n.º 8
0
def fit_ica(
    *,
    cfg,
    epochs: mne.BaseEpochs,
    subject: str,
    session: str,
) -> mne.preprocessing.ICA:
    algorithm = cfg.ica_algorithm
    fit_params = None

    if algorithm == 'picard':
        fit_params = dict(fastica_it=5)
    elif algorithm == 'extended_infomax':
        algorithm = 'infomax'
        fit_params = dict(extended=True)

    ica = ICA(method=algorithm,
              random_state=cfg.random_state,
              n_components=cfg.ica_n_components,
              fit_params=fit_params,
              max_iter=cfg.ica_max_iterations)

    ica.fit(epochs, decim=cfg.ica_decim)

    explained_var = (ica.pca_explained_variance_[:ica.n_components_].sum() /
                     ica.pca_explained_variance_.sum())
    msg = (f'Fit {ica.n_components_} components (explaining '
           f'{round(explained_var * 100, 1)}% of the variance) in '
           f'{ica.n_iter_} iterations.')
    logger.info(
        **gen_log_kwargs(message=msg, subject=subject, session=session))
    return ica
Ejemplo n.º 9
0
def main():
    """Make reports."""
    parallel, run_func, _ = parallel_func(run_report,
                                          n_jobs=config.get_n_jobs())
    logs = parallel(
        run_func(
            cfg=get_config(subject=subject), subject=subject, session=session)
        for subject, session in itertools.product(config.get_subjects(),
                                                  config.get_sessions()))

    config.save_logs(logs)

    sessions = config.get_sessions()
    if not sessions:
        sessions = [None]

    if (config.get_task() is not None and config.get_task().lower() == 'rest'):
        msg = '    … skipping "average" report for "rest" task.'
        logger.info(**gen_log_kwargs(message=msg))
        return

    for session in sessions:
        run_report_average(cfg=get_config(subject='average'),
                           subject='average',
                           session=session)
Ejemplo n.º 10
0
def run_forward(*, cfg, subject, session=None):
    bids_path = BIDSPath(subject=subject,
                         session=session,
                         task=cfg.task,
                         acquisition=cfg.acq,
                         run=None,
                         recording=cfg.rec,
                         space=cfg.space,
                         extension='.fif',
                         datatype=cfg.datatype,
                         root=cfg.deriv_root,
                         check=False)

    fname_info = bids_path.copy().update(**cfg.source_info_path_update)
    fname_trans = bids_path.copy().update(suffix='trans')
    fname_fwd = bids_path.copy().update(suffix='fwd')

    if cfg.use_template_mri:
        src, trans, bem_sol = _prepare_forward_fsaverage(cfg)
    else:
        src, trans, bem_sol = _prepare_forward(cfg, bids_path, fname_trans)

    # Finally, calculate and save the forward solution.
    msg = 'Calculating forward solution'
    logger.info(
        **gen_log_kwargs(message=msg, subject=subject, session=session))
    info = mne.io.read_info(fname_info)
    fwd = mne.make_forward_solution(info,
                                    trans=trans,
                                    src=src,
                                    bem=bem_sol,
                                    mindist=cfg.mindist)

    mne.write_trans(fname_trans, fwd['mri_head_t'], overwrite=True)
    mne.write_forward_solution(fname_fwd, fwd, overwrite=True)
Ejemplo n.º 11
0
def compute_cov_from_epochs(cfg, subject, session, tmin, tmax):
    bids_path = BIDSPath(subject=subject,
                         session=session,
                         task=cfg.task,
                         acquisition=cfg.acq,
                         run=None,
                         processing=cfg.proc,
                         recording=cfg.rec,
                         space=cfg.space,
                         extension='.fif',
                         datatype=cfg.datatype,
                         root=cfg.deriv_root,
                         check=False)

    processing = None
    if cfg.spatial_filter is not None:
        processing = 'clean'

    epo_fname = bids_path.copy().update(processing=processing, suffix='epo')
    cov_fname = bids_path.copy().update(suffix='cov')

    msg = (f"Computing regularized covariance based on epochs' baseline "
           f"periods. Input: {epo_fname}, Output: {cov_fname}")
    logger.info(
        **gen_log_kwargs(message=msg, subject=subject, session=session))

    epochs = mne.read_epochs(epo_fname, preload=True)
    cov = mne.compute_covariance(epochs,
                                 tmin=tmin,
                                 tmax=tmax,
                                 method='shrunk',
                                 rank='info')
    cov.save(cov_fname)
def run_group_average_source(*, cfg, subject='average'):
    """Run group average in source space"""
    if not config.run_source_estimation:
        msg = '    … skipping: run_source_estimation is set to False.'
        logger.info(**gen_log_kwargs(message=msg))
        return

    mne.datasets.fetch_fsaverage(subjects_dir=config.get_fs_subjects_dir())

    parallel, run_func, _ = parallel_func(morph_stc,
                                          n_jobs=config.get_n_jobs())
    all_morphed_stcs = parallel(
        run_func(cfg=cfg,
                 subject=subject,
                 fs_subject=config.get_fs_subject(subject),
                 session=session) for subject, session in itertools.product(
                     config.get_subjects(), config.get_sessions()))
    mean_morphed_stcs = np.array(all_morphed_stcs).mean(axis=0)

    # XXX to fix
    sessions = config.get_sessions()
    if sessions:
        session = sessions[0]
    else:
        session = None

    run_average(cfg=cfg, session=session, mean_morphed_stcs=mean_morphed_stcs)
Ejemplo n.º 13
0
def compute_cov_from_empty_room(cfg, subject, session):
    bids_path = BIDSPath(subject=subject,
                         session=session,
                         task=cfg.task,
                         acquisition=cfg.acq,
                         run=None,
                         recording=cfg.rec,
                         space=cfg.space,
                         extension='.fif',
                         datatype=cfg.datatype,
                         root=cfg.deriv_root,
                         check=False)

    raw_er_fname = bids_path.copy().update(processing='filt',
                                           task='noise',
                                           suffix='raw')
    cov_fname = bids_path.copy().update(suffix='cov')

    msg = (f'Computing regularized covariance based on empty-room recording. '
           f'Input: {raw_er_fname}, Output: {cov_fname}')
    logger.info(
        **gen_log_kwargs(message=msg, subject=subject, session=session))

    raw_er = mne.io.read_raw_fif(raw_er_fname, preload=True)
    cov = mne.compute_raw_covariance(raw_er, method='shrunk', rank='info')
    cov.save(cov_fname)
def filter(raw: mne.io.BaseRaw, subject: str, session: Optional[str],
           run: Optional[str], l_freq: Optional[float],
           h_freq: Optional[float],
           l_trans_bandwidth: Optional[Union[float, Literal['auto']]],
           h_trans_bandwidth: Optional[Union[float, Literal['auto']]]) -> None:
    """Filter data channels (MEG and EEG)."""

    data_type = 'empty-room' if subject == 'emptyroom' else 'experimental'

    if l_freq is not None and h_freq is None:
        msg = (f'High-pass filtering {data_type} data; lower bound: '
               f'{l_freq} Hz')
    elif l_freq is None and h_freq is not None:
        msg = (f'Low-pass filtering {data_type} data; upper bound: '
               f'{h_freq} Hz')
    elif l_freq is not None and h_freq is not None:
        msg = (f'Band-pass filtering {data_type} data; range: '
               f'{l_freq} – {h_freq} Hz')
    else:
        msg = (f'Not applying frequency filtering to {data_type} data.')

    logger.info(**gen_log_kwargs(
        message=msg, subject=subject, session=session, run=run))

    if l_freq is None and h_freq is None:
        return

    raw.filter(l_freq=l_freq,
               h_freq=h_freq,
               l_trans_bandwidth=l_trans_bandwidth,
               h_trans_bandwidth=h_trans_bandwidth,
               filter_length='auto',
               phase='zero',
               fir_window='hamming',
               fir_design='firwin')
Ejemplo n.º 15
0
def filter_for_ica(*,
                   cfg,
                   raw: mne.io.BaseRaw,
                   subject: str,
                   session: str,
                   run: Optional[str] = None) -> None:
    """Apply a high-pass filter if needed."""
    if cfg.ica_l_freq is None:
        msg = (f'Not applying high-pass filter (data is already filtered, '
               f'cutoff: {raw.info["highpass"]} Hz).')
        logger.info(**gen_log_kwargs(
            message=msg, subject=subject, session=session, run=run))
    else:
        msg = f'Applying high-pass filter with {cfg.ica_l_freq} Hz cutoff …'
        logger.info(**gen_log_kwargs(
            message=msg, subject=subject, session=session, run=run))
        raw.filter(l_freq=cfg.ica_l_freq, h_freq=None)
def main():
    if not config.run_source_estimation:
        msg = '    … skipping: run_source_estimation is set to False.'
        logger.info(**gen_log_kwargs(message=msg))
        return

    log = run_group_average_source(cfg=get_config())
    config.save_logs([log])
Ejemplo n.º 17
0
def make_ecg_epochs(*,
                    cfg,
                    raw_path: BIDSPath,
                    subject: str,
                    session: str,
                    run: Optional[str] = None,
                    n_runs: int) -> Optional[mne.BaseEpochs]:
    # ECG either needs an ecg channel, or avg of the mags (i.e. MEG data)
    raw = mne.io.read_raw(raw_path, preload=False)

    if ('ecg' in raw.get_channel_types() or 'meg' in cfg.ch_types
            or 'mag' in cfg.ch_types):
        msg = 'Creating ECG epochs …'
        logger.info(**gen_log_kwargs(
            message=msg, subject=subject, session=session, run=run))

        # We want to extract a total of 5 min of data for ECG epochs generation
        # (across all runs)
        total_ecg_dur = 5 * 60
        ecg_dur_per_run = total_ecg_dur / n_runs
        t_mid = (raw.times[-1] + raw.times[0]) / 2
        raw = raw.crop(tmin=max(t_mid - 1 / 2 * ecg_dur_per_run, 0),
                       tmax=min(t_mid + 1 / 2 * ecg_dur_per_run,
                                raw.times[-1])).load_data()

        ecg_epochs = create_ecg_epochs(raw,
                                       baseline=(None, -0.2),
                                       tmin=-0.5,
                                       tmax=0.5)
        del raw  # Free memory

        if len(ecg_epochs) == 0:
            msg = ('No ECG events could be found. Not running ECG artifact '
                   'detection.')
            logger.info(**gen_log_kwargs(
                message=msg, subject=subject, session=session, run=run))
            ecg_epochs = None
    else:
        msg = ('No ECG or magnetometer channels are present. Cannot '
               'automate artifact detection for ECG')
        logger.info(**gen_log_kwargs(
            message=msg, subject=subject, session=session, run=run))
        ecg_epochs = None

    return ecg_epochs
Ejemplo n.º 18
0
def main():
    """Run BEM surface extraction."""
    if not config.run_source_estimation:
        msg = '    … skipping: run_source_estimation is set to False.'
        logger.info(**gen_log_kwargs(message=msg))
        return

    if config.use_template_mri:
        msg = '    … skipping BEM computating when using MRI template.'
        logger.info(**gen_log_kwargs(message=msg))
        return

    parallel, run_func, _ = parallel_func(make_bem_and_scalp_surface,
                                          n_jobs=config.get_n_jobs())
    logs = parallel(
        run_func(cfg=get_config(subject=subject), subject=subject)
        for subject in config.get_subjects())

    config.save_logs(logs)
Ejemplo n.º 19
0
def make_bem(*, cfg, subject):
    fs_subject = cfg.fs_subject
    mri_dir = Path(cfg.fs_subjects_dir) / fs_subject / 'mri'
    bem_dir = Path(cfg.fs_subjects_dir) / fs_subject / 'bem'
    watershed_bem_dir = bem_dir / 'watershed'
    flash_bem_dir = bem_dir / 'flash'
    flash_dir = mri_dir / 'flash' / 'parameter_maps'
    show = True if cfg.interactive else False

    if cfg.bem_mri_images == 'FLASH' and not flash_dir.exists():
        raise RuntimeError('Cannot locate FLASH MRI images.')
    elif cfg.bem_mri_images == 'FLASH':
        mri_images = 'FLASH'
    elif cfg.bem_mri_images == 'auto' and flash_dir.exists():
        mri_images = 'FLASH'
    else:
        mri_images = 'T1'

    if ((mri_images == 'FLASH' and flash_bem_dir.exists())
            or (mri_images == 'T1' and watershed_bem_dir.exists())):
        msg = 'Found existing BEM surfaces. '
        if cfg.recreate_bem:
            msg += 'Overwriting as requested in configuration.'
            logger.info(**gen_log_kwargs(message=msg, subject=subject))
        else:
            msg = 'Skipping surface extraction as requested in configuration.'
            logger.info(**gen_log_kwargs(message=msg, subject=subject))
            return

    if mri_images == 'FLASH':
        msg = 'Creating BEM surfaces from FLASH MRI images'
        bem_func = mne.bem.make_flash_bem
    else:
        msg = ('Creating BEM surfaces from T1-weighted MRI images using '
               'watershed algorithm')
        bem_func = mne.bem.make_watershed_bem

    logger.info(**gen_log_kwargs(message=msg, subject=subject))
    bem_func(subject=fs_subject,
             subjects_dir=cfg.fs_subjects_dir,
             copy=True,
             overwrite=True,
             show=show)
Ejemplo n.º 20
0
def main():
    """Run cov."""
    if not config.run_source_estimation:
        msg = '    … skipping: run_source_estimation is set to False.'
        logger.info(**gen_log_kwargs(message=msg))
        return

    if config.noise_cov == "ad-hoc":
        msg = '    … skipping: using ad-hoc diagonal covariance.'
        logger.info(**gen_log_kwargs(message=msg))
        return

    with config.get_parallel_backend():
        parallel, run_func, _ = parallel_func(run_covariance,
                                              n_jobs=config.get_n_jobs())
        logs = parallel(
            run_func(cfg=get_config(), subject=subject, session=session)
            for subject, session in itertools.product(config.get_subjects(),
                                                      config.get_sessions()))

        config.save_logs(logs)
Ejemplo n.º 21
0
def run_time_frequency(*, cfg, subject, session=None):
    bids_path = BIDSPath(subject=subject,
                         session=session,
                         task=cfg.task,
                         acquisition=cfg.acq,
                         run=None,
                         recording=cfg.rec,
                         space=cfg.space,
                         datatype=cfg.datatype,
                         root=cfg.deriv_root,
                         check=False)

    processing = None
    if cfg.spatial_filter is not None:
        processing = 'clean'

    fname_in = bids_path.copy().update(suffix='epo',
                                       processing=processing,
                                       extension='.fif')

    msg = f'Input: {fname_in}'
    logger.info(
        **gen_log_kwargs(message=msg, subject=subject, session=session))

    epochs = mne.read_epochs(fname_in)
    if cfg.analyze_channels:
        # We special-case the average reference here.
        # See 02-sliding_estimator.py for more info.
        if 'eeg' in cfg.ch_types and cfg.eeg_reference == 'average':
            epochs.set_eeg_reference('average')
        else:
            epochs.apply_proj()
        epochs.pick(cfg.analyze_channels)

    freqs = np.arange(cfg.time_frequency_freq_min, cfg.time_frequency_freq_max)
    n_cycles = freqs / 3.

    for condition in cfg.time_frequency_conditions:
        this_epochs = epochs[condition]
        power, itc = mne.time_frequency.tfr_morlet(this_epochs,
                                                   freqs=freqs,
                                                   return_itc=True,
                                                   n_cycles=n_cycles)

        condition_str = sanitize_cond_name(condition)
        power_fname_out = bids_path.copy().update(
            suffix=f'power+{condition_str}+tfr', extension='.h5')
        itc_fname_out = bids_path.copy().update(
            suffix=f'itc+{condition_str}+tfr', extension='.h5')

        power.save(power_fname_out, overwrite=True)
        itc.save(itc_fname_out, overwrite=True)
Ejemplo n.º 22
0
def apply_ssp(*, cfg, subject, session=None):
    # load epochs to reject ICA components
    # compute SSP on first run of raw

    bids_path = BIDSPath(subject=subject,
                         session=session,
                         task=cfg.task,
                         acquisition=cfg.acq,
                         run=None,
                         recording=cfg.rec,
                         space=cfg.space,
                         extension='.fif',
                         datatype=cfg.datatype,
                         root=cfg.deriv_root)

    fname_in = bids_path.copy().update(suffix='epo', check=False)
    fname_out = bids_path.copy().update(processing='ssp',
                                        suffix='epo',
                                        check=False)

    epochs = mne.read_epochs(fname_in, preload=True)

    msg = f'Input: {fname_in}, Output: {fname_out}'
    logger.info(
        **gen_log_kwargs(message=msg, subject=subject, session=session))

    proj_fname_in = bids_path.copy().update(suffix='proj', check=False)

    msg = f'Reading SSP projections from : {proj_fname_in}'
    logger.info(
        **gen_log_kwargs(message=msg, subject=subject, session=session))

    projs = mne.read_proj(proj_fname_in)
    epochs_cleaned = epochs.copy().add_proj(projs).apply_proj()

    msg = 'Saving epochs with projectors.'
    logger.info(
        **gen_log_kwargs(message=msg, subject=subject, session=session))
    epochs_cleaned.save(fname_out, overwrite=True)
Ejemplo n.º 23
0
def make_eog_epochs(*,
                    raw: mne.io.BaseRaw,
                    eog_channels: Optional[Iterable[str]],
                    subject: str,
                    session: str,
                    run: Optional[str] = None) -> Optional[mne.Epochs]:
    """Create EOG epochs. No rejection thresholds will be applied.
    """
    if eog_channels:
        ch_names = eog_channels
        assert all([ch_name in raw.ch_names for ch_name in ch_names])
    else:
        ch_idx = mne.pick_types(raw.info, meg=False, eog=True)
        ch_names = [raw.ch_names[i] for i in ch_idx]
        del ch_idx

    if ch_names:
        msg = 'Creating EOG epochs …'
        logger.info(**gen_log_kwargs(
            message=msg, subject=subject, session=session, run=run))

        eog_epochs = create_eog_epochs(raw,
                                       ch_name=ch_names,
                                       baseline=(None, -0.2))

        if len(eog_epochs) == 0:
            msg = ('No EOG events could be found. Not running EOG artifact '
                   'detection.')
            logger.warning(**gen_log_kwargs(
                message=msg, subject=subject, session=session, run=run))
            eog_epochs = None
    else:
        msg = ('No EOG channel is present. Cannot automate IC detection '
               'for EOG')
        logger.info(**gen_log_kwargs(
            message=msg, subject=subject, session=session, run=run))
        eog_epochs = None

    return eog_epochs
def resample(raw: mne.io.BaseRaw, subject: str, session: Optional[str],
             run: Optional[str], sfreq: Optional[float]) -> None:
    if not sfreq:
        return

    data_type = 'empty-room' if subject == 'emptyroom' else 'experimental'
    msg = f'Resampling {data_type} data to {sfreq:.1f} Hz'
    logger.info(**gen_log_kwargs(
        message=msg,
        subject=subject,
        session=session,
        run=run,
    ))
    raw.resample(sfreq, npad='auto')
Ejemplo n.º 25
0
def main():
    """Run Time-frequency decomposition."""
    if not config.time_frequency_conditions:
        msg = 'Skipping …'
        logger.info(**gen_log_kwargs(message=msg))
        return

    parallel, run_func, _ = parallel_func(run_time_frequency,
                                          n_jobs=config.get_n_jobs())
    logs = parallel(
        run_func(cfg=get_config(), subject=subject, session=session)
        for subject, session in itertools.product(config.get_subjects(),
                                                  config.get_sessions()))

    config.save_logs(logs)
Ejemplo n.º 26
0
def main():
    """Run ICA."""
    if not config.spatial_filter == 'ica':
        msg = 'Skipping …'
        logger.info(**gen_log_kwargs(message=msg))
        return

    parallel, run_func, _ = parallel_func(run_ica, n_jobs=config.get_n_jobs())
    logs = parallel(
        run_func(
            cfg=get_config(subject=subject), subject=subject, session=session)
        for subject, session in itertools.product(config.get_subjects(),
                                                  config.get_sessions()))

    config.save_logs(logs)
Ejemplo n.º 27
0
def main():
    """Run inv."""
    if not config.run_source_estimation:
        msg = '    … skipping: run_source_estimation is set to False.'
        logger.info(**gen_log_kwargs(message=msg))
        return

    parallel, run_func, _ = parallel_func(run_inverse,
                                          n_jobs=config.get_n_jobs())
    logs = parallel(
        run_func(cfg=get_config(), subject=subject, session=session)
        for subject, session in itertools.product(config.get_subjects(),
                                                  config.get_sessions()))

    config.save_logs(logs)
Ejemplo n.º 28
0
def run_group_average_sensor(*, cfg, subject='average'):
    if config.get_task().lower() == 'rest':
        msg = '    … skipping: for "rest" task.'
        logger.info(**gen_log_kwargs(message=msg))
        return

    sessions = config.get_sessions()
    if not sessions:
        sessions = [None]

    for session in sessions:
        evokeds = average_evokeds(cfg, session)
        if config.interactive:
            for evoked in evokeds:
                evoked.plot()

        if config.decode:
            average_decoding(cfg, session)
Ejemplo n.º 29
0
def main():
    """Run maxwell_filter."""
    if not config.use_maxwell_filter:
        msg = 'Skipping …'
        logger.info(**gen_log_kwargs(message=msg))
        return

    with config.get_parallel_backend():
        parallel, run_func, _ = parallel_func(run_maxwell_filter,
                                              n_jobs=config.get_n_jobs())
        logs = parallel(
            run_func(cfg=get_config(subject, session),
                     subject=subject,
                     session=session)
            for subject, session in itertools.product(config.get_subjects(),
                                                      config.get_sessions()))

        config.save_logs(logs)
Ejemplo n.º 30
0
def main():
    """Apply ssp."""
    if not config.spatial_filter == 'ssp':
        msg = 'Skipping …'
        logger.info(**gen_log_kwargs(message=msg))
        return

    with config.get_parallel_backend():
        parallel, run_func, _ = parallel_func(
            apply_ssp,
            n_jobs=config.get_n_jobs()
        )
        logs = parallel(
            run_func(cfg=get_config(), subject=subject, session=session)
            for subject, session in
            itertools.product(
                config.get_subjects(),
                config.get_sessions()
            )
        )

        config.save_logs(logs)