Exemplo n.º 1
0
def mne_ransac_bad_channels(raw, overwrite=False):
    bids_chan_file = tb.fileparts(raw.filenames[0], '_channels.tsv', -4)
    ransacfile = tb.fileparts(raw.filenames[0], '_channels_ransac.tsv')
    if not pathlib.Path.is_file(pathlib.Path(ransacfile)) or overwrite:
        epochs = mne_epoch(raw).drop_bad()
        epochs.load_data()
        ransac = Ransac(random_state=999)
        ransac.fit(epochs)
        raw.info['bads'] = ransac.bad_chs_
        chans = pd.read_csv(bids_chan_file, delimiter='\t')
        chans.loc[chans.name.isin(ransac.bad_chs_), 'status'] = 'bad'
        pd.DataFrame.to_csv(chans, ransacfile, sep='\t')
    else:
        chans = pd.read_csv(ransacfile, delimiter='\t')
        raw.info['bads'] = list(chans.loc[chans['status'] == 'bad', 'name'])
    return raw
    raw.filter(preprocess_options['ica_highpass'], None,
               skip_by_annotation=['boundary'])
    raw.filter(None, 40, picks=['eog'])
    raw.notch_filter([60, 120], picks=['eog'])

    # Make ICA Epochs
    epochs = mne.Epochs(raw, events, event_id=event_id,
                        tmin=preprocess_options['tmin'],
                        tmax=preprocess_options['tmax'],
                        baseline=(None, None), reject=None, preload=True)
    epochs.set_montage(bv_montage)

    # Autodetect bad channels
    ransac = Ransac(verbose=False, n_jobs=4,
                    min_corr=.60, unbroken_time=.6)
    ransac.fit(epochs.copy().filter(None, 40))
    if len(ransac.bad_chs_):
        for chan in ransac.bad_chs_:
            epochs.info['bads'].append(chan)
    print(f'RANSAC Bad Channels: {ransac.bad_chs_}')

    # Save RANSAC
    ransac_file = deriv_path / f'{sub}_task-{task}_ref_FCz_ransac.pkl'
    with open(ransac_file, 'wb') as f:
        pickle.dump(ransac, f)

    # Make RANSAC json
    json_info = {
        'Description': 'RANSAC object computed from epoched data',
        'parameteres': {
            'unbroken_time': .6,
Exemplo n.º 3
0
def test_ransac():
    """Some basic tests for ransac."""
    event_id = {'Visual/Left': 3}
    tmin, tmax = -0.2, 0.5

    events = mne.find_events(raw)
    epochs = mne.Epochs(raw,
                        events,
                        event_id,
                        tmin,
                        tmax,
                        baseline=(None, 0),
                        decim=8,
                        reject=None,
                        preload=True)
    # normal case
    picks = mne.pick_types(epochs.info,
                           meg='mag',
                           eeg=False,
                           stim=False,
                           eog=False,
                           exclude=[])
    ransac = Ransac(picks=picks, random_state=np.random.RandomState(42))
    epochs_clean = ransac.fit_transform(epochs)
    assert len(epochs_clean) == len(epochs)

    # Pass string instead of array of idx
    picks = 'eeg'
    ransac = Ransac(picks=picks)
    ransac.fit(epochs[:2])
    expected = mne.pick_types(epochs.info,
                              meg=False,
                              eeg=True,
                              stim=False,
                              eog=False,
                              exclude='bads')
    assert (expected == ransac.picks).all()

    # Pass numpy instead of epochs
    X = epochs.get_data()
    pytest.raises(AttributeError, ransac.fit, X)

    # should not contain both channel types
    picks = mne.pick_types(epochs.info,
                           meg=True,
                           eeg=False,
                           stim=False,
                           eog=False,
                           exclude=[])
    ransac = Ransac(picks=picks)
    pytest.raises(ValueError, ransac.fit, epochs)

    # should not contain other channel types.
    picks = mne.pick_types(raw.info,
                           meg=False,
                           eeg=True,
                           stim=True,
                           eog=False,
                           exclude=[])
    ransac = Ransac(picks=picks)
    pytest.raises(ValueError, ransac.fit, epochs)