Example #1
0
def test_lcmv_fieldtrip(_get_bf_data, bf_type, weight_norm, pick_ori, pwr):
    """Test LCMV vs fieldtrip output."""
    evoked, data_cov, fwd = _get_bf_data

    # run the MNE-Python beamformer
    filters = make_lcmv(evoked.info,
                        fwd,
                        data_cov=data_cov,
                        noise_cov=None,
                        pick_ori=pick_ori,
                        reg=0.05,
                        weight_norm=weight_norm)
    if pwr:
        stc_mne = apply_lcmv_cov(data_cov, filters)
    else:
        stc_mne = apply_lcmv(evoked, filters)

    # load the FieldTrip output
    ft_fname = op.join(ft_data_path, 'ft_source_' + bf_type + '-vol.mat')
    stc_ft_data = read_mat(ft_fname)['stc']
    if stc_ft_data.ndim == 1:
        stc_ft_data.shape = (stc_ft_data.size, 1)

    if stc_mne.data.ndim == 2:
        signs = np.sign((stc_mne.data * stc_ft_data).sum(-1, keepdims=True))
        if pwr:
            assert_array_equal(signs, 1.)
        stc_mne.data *= signs
    assert stc_ft_data.shape == stc_mne.data.shape
    if pick_ori == 'vector':
        # compare norms first
        assert_allclose(np.linalg.norm(stc_mne.data, axis=1),
                        np.linalg.norm(stc_ft_data, axis=1),
                        rtol=1e-6)
    assert_allclose(stc_mne.data, stc_ft_data, rtol=1e-6)
Example #2
0
def get_cfg_local(system):
    """Return cfg_local field for the system."""
    from mne.externals.pymatreader import read_mat
    cfg_local = read_mat(os.path.join(get_data_paths(system), 'raw_v7.mat'),
                         ['cfg_local'])['cfg_local']

    return cfg_local
Example #3
0
def get_cfg_local(system):
    """Return cfg_local field for the system."""
    from mne.externals.pymatreader import read_mat
    cfg_local = read_mat(os.path.join(get_data_paths(system), 'raw_v7.mat'),
                         ['cfg_local'])['cfg_local']

    return cfg_local
Example #4
0
def test_lcmv_fieldtrip(_get_bf_data, bf_type, weight_norm, pick_ori, pwr):
    """Test LCMV vs fieldtrip output."""
    evoked, data_cov, fwd = _get_bf_data

    # run the MNE-Python beamformer
    filters = make_lcmv(evoked.info,
                        fwd,
                        data_cov=data_cov,
                        noise_cov=None,
                        pick_ori=pick_ori,
                        reg=0.05,
                        weight_norm=weight_norm)
    if pwr is True:
        stc_mne = apply_lcmv_cov(data_cov, filters)
    else:
        stc_mne = apply_lcmv(evoked, filters)
        # take the absolute value, since orientation can be flipped
        stc_mne.data[:, :] = np.abs(stc_mne.data)

    # load the FieldTrip output
    ft_fname = op.join(ft_data_path, 'ft_source_' + bf_type + '-vol.mat')
    stc_ft_data = read_mat(ft_fname)['stc']
    if stc_ft_data.ndim == 3:
        stc_ft_data = np.linalg.norm(stc_ft_data, axis=1)
    else:
        stc_ft_data = np.abs(stc_ft_data)

    # calculate the Pearson correlation between the source solutions:
    pearson = np.corrcoef(stc_mne.data.ravel(), stc_ft_data.ravel())[0, 1]
    assert pearson >= 0.99
def get_source_model(template, source_model, subjects_dir=None):
    path = "/home/christian/synchedin/infants_atlas_modeling/fieldtrip/single_subject_analysis/"
    source_model_dict = read_mat(path + "sourcemodel_{}_{}.mat".format(source_model, template))["sourcemodel"]

    kdtree, vox2ras_tkr, vox2ras, epi_img_data = get_atlas_info(template, subjects_dir=subjects_dir)
    source_model_dict["pos"] += (vox2ras_tkr - vox2ras)[:3, 3]

    return source_model_dict
Example #6
0
def test_get_montage_info_with_ch_type():
    """Test that the channel types are properly returned."""
    mat = read_mat(raw_fname_onefile_mat, uint16_codec=None)
    n = len(mat['EEG']['chanlocs']['labels'])
    mat['EEG']['chanlocs']['type'] = ['eeg'] * (n - 2) + ['eog'] + ['stim']
    mat['EEG']['chanlocs'] = _dol_to_lod(mat['EEG']['chanlocs'])
    mat['EEG'] = Bunch(**mat['EEG'])
    ch_names, ch_types, montage = _get_montage_information(mat['EEG'], False)
    assert len(ch_names) == len(ch_types) == n
    assert ch_types == ['eeg'] * (n - 2) + ['eog'] + ['stim']
    assert montage is None

    # test unknown type warning
    mat = read_mat(raw_fname_onefile_mat, uint16_codec=None)
    n = len(mat['EEG']['chanlocs']['labels'])
    mat['EEG']['chanlocs']['type'] = ['eeg'] * (n - 2) + ['eog'] + ['unknown']
    mat['EEG']['chanlocs'] = _dol_to_lod(mat['EEG']['chanlocs'])
    mat['EEG'] = Bunch(**mat['EEG'])
    with pytest.warns(RuntimeWarning, match='Unknown types found'):
        ch_names, ch_types, montage = \
            _get_montage_information(mat['EEG'], False)
Example #7
0
def read_prepare(filename):
    raw = read_mat(filename)
    fs = 250
    trig = raw['trig']
    data = raw['y']
    filtered = data.copy()
    for i in range(filtered.shape[1]):
        filtered[:, i] = butter_bandpass_filter(data[:, i], 0.5, 30, fs)
        filtered[:, i] = np.convolve(filtered[:, i], 7, 'same')
    filtered = (filtered - filtered.mean(0)[None]) / filtered.std(0)[None]
    # pca = PCA(8)
    # filtered = pca.fit_transform(filtered)
    # print(pca.explained_variance_ratio_)
    return filtered, trig
Example #8
0
def main():
    config_dir = os.path.join(*[CDIR, ex.observers[0].basedir, '1'])
    images_dir = os.path.join(*[CDIR, ex.observers[0].basedir, 'images'])
    models_dir = os.path.join(
        *[CDIR, ex.observers[0].basedir, 'trained_models'])

    file_name = '../data/Subject1_Run1.mat'
    mat_data = read_mat(file_name)
    data = mat_data['eegData'].T
    fs = mat_data['fs']
    montage = mne.channels.make_standard_montage('biosemi128')
    info = mne.create_info(ch_names=montage.ch_names, sfreq=fs,
                           ch_types='eeg').set_montage(montage)

    raw = mne.io.RawArray(data, info)
    # plot = raw.plot(n_channels=128, title='Data from arrays',
    #         show=True, block=True)

    data, times = raw[:]

    pos_3d = montage._get_ch_pos()
    pos_2d = np.array([v[:2] for _, v in pos_3d.items()])

    print('max eeg: ', np.max(np.abs(pos_2d)))

    mne.viz.plot_topomap(data[:, 2], pos_2d)
    plt.savefig(os.path.join(*[images_dir, 'eeg.png']))

    # for referencing, add 2 channels this way
    # https://mne.tools/dev/auto_examples/preprocessing/plot_find_ref_artifacts.html#sphx-glr-auto-examples-preprocessing-plot-find-ref-artifacts-py

    ref_info = mne.create_info(['LPA', 'RPA'], raw.info['sfreq'], 'stim')
    ref_raw = mne.io.RawArray(mat_data['mastoids'].T, ref_info)
    raw.add_channels([ref_raw], force_update_info=True)

    # and then this way
    # https://mne.tools/stable/auto_tutorials/preprocessing/plot_55_setting_eeg_reference.html

    raw.set_eeg_reference(ref_channels=['LPA', 'RPA'])

    data, times = raw[:]
    pos_2d = np.concatenate(
        [pos_2d, np.array([[-79.32e-3, 0], [79.32e-3, 0]])])
    mne.viz.plot_topomap(data[:, 2], pos_2d)

    print(pos_2d)
def test_beer_lambert_v_matlab():
    """Compare MNE results to MATLAB toolbox."""
    raw = read_raw_nirx(fname_nirx_15_0)
    raw = optical_density(raw)
    raw = beer_lambert_law(raw, ppf=0.121)
    raw._data *= 1e6  # Scale to uM for comparison to MATLAB

    matlab_fname = op.join(data_path(download=False), 'NIRx', 'validation',
                           'nirx_15_0_recording_bl.mat')
    matlab_data = read_mat(matlab_fname)

    for idx in range(raw.get_data().shape[0]):

        mean_error = np.mean(matlab_data['data'][:, idx] - raw._data[idx])
        assert mean_error < 0.1
        matlab_name = ("S" + str(int(matlab_data['sources'][idx])) + "_D" +
                       str(int(matlab_data['detectors'][idx])) + " " +
                       matlab_data['type'][idx])
        assert raw.info['ch_names'][idx] == matlab_name
Example #10
0
def main():
    images_dir = os.path.join(*[CDIR, ex.observers[0].basedir, 'images'])

    file_name = '../data/Subject1_Run1.mat'
    mat_data = read_mat(file_name)
    data = mat_data['eegData'].T
    fs = mat_data['fs']
    montage = mne.channels.make_standard_montage('biosemi128')
    info = mne.create_info(ch_names=montage.ch_names, sfreq=fs, ch_types='eeg').set_montage(montage)

    raw = mne.io.RawArray(data, info)
    # plot = raw.plot(n_channels=128, title='Data from arrays',
    #         show=True, block=True)

    data, times = raw[:]

    pos_3d = montage._get_ch_pos()
    pos_2d = np.array([v[:2] for _, v in pos_3d.items()])


    # plot 4 evenly spaced timesteps
    n_frames = 4
    frames = [int(i) for i in np.linspace(0, len(times)-2, num=n_frames)]

    fig, axes = plt.subplots(1, n_frames)
    for i, ax in zip(frames, axes):
        mne.viz.plot_topomap(data[:, i], pos_2d, show=False, axes=ax)
        t = np.round(times[i], 1)
        ax.set_title('{}s'.format(t))

    fig.savefig(os.path.join(*[images_dir, 'eeg.png']))

    # Power line noise
    print(raw)
    fig = raw.plot_psd(tmax=np.inf, fmax=64, average=True)
    # add some arrows at 60 Hz and its harmonics:
    for ax in fig.axes[:2]:
        freqs = ax.lines[-1].get_xdata()
        psds = ax.lines[-1].get_ydata()
        for freq in (60, 120, 180, 240):
            idx = np.searchsorted(freqs, freq)
            ax.arrow(x=freqs[idx], y=psds[idx] + 18, dx=0, dy=-12, color='red',
                     width=0.1, head_width=3, length_includes_head=True)
Example #11
0
def test_create_events():
    """Test 2dim trialinfo fields."""
    from mne.externals.pymatreader import read_mat

    test_data_folder_ft = get_data_paths('neuromag306')
    cur_fname = os.path.join(test_data_folder_ft, 'epoched_v7.mat')
    original_data = read_mat(cur_fname, ['data', ])

    new_data = copy.deepcopy(original_data)
    new_data['trialinfo'] = np.array([[1, 2, 3, 4],
                                      [1, 2, 3, 4],
                                      [1, 2, 3, 4]])

    with pytest.raises(ValueError):
        _create_events(new_data, -1)

    for cur_col in np.arange(4):
        evts = _create_events(new_data, cur_col)
        assert np.all(evts[:, 2] == cur_col + 1)

    with pytest.raises(ValueError):
        _create_events(new_data, 4)
Example #12
0
def test_create_events():
    """Test 2dim trialinfo fields."""
    from mne.externals.pymatreader import read_mat

    test_data_folder_ft = get_data_paths('neuromag306')
    cur_fname = os.path.join(test_data_folder_ft, 'epoched_v7.mat')
    original_data = read_mat(cur_fname, ['data', ])

    new_data = copy.deepcopy(original_data)
    new_data['trialinfo'] = np.array([[1, 2, 3, 4],
                                      [1, 2, 3, 4],
                                      [1, 2, 3, 4]])

    with pytest.raises(ValueError):
        _create_events(new_data, -1)

    for cur_col in np.arange(4):
        evts = _create_events(new_data, cur_col)
        assert np.all(evts[:, 2] == cur_col + 1)

    with pytest.raises(ValueError):
        _create_events(new_data, 4)
Example #13
0
def get_montage_lemon(subject, root_path, montage_rel_path="EEG_MPILMBB_LEMON/EEG_Localizer_BIDS_ID/",
                      parse_pattern_montage="sub-{subject}/sub-{subject}.mat"):
    path_montage = Path(root_path) / montage_rel_path
    file_name = path_montage / parse_pattern_montage.format(subject=subject)
    if file_name.exists():
        montage_mat_file = read_mat(str(file_name))

        head_points = {}
        for ch_name in np.unique(montage_mat_file["HeadPoints"]["Label"]):
            inds = np.where(np.array(montage_mat_file["HeadPoints"]["Label"]) == ch_name)[0]
            head_points[ch_name] = montage_mat_file["HeadPoints"]["Loc"][:, inds].mean(1)

        ch_names = [ch_name.split("_")[-1] for ch_name in montage_mat_file["Channel"]["Name"]]
        ch_names = [ch_name if ch_name[:2] != "FP" else "Fp" + ch_name[2:] for ch_name in ch_names]

        ch_pos = dict(zip(ch_names, montage_mat_file["Channel"]["Loc"]))

        return mne.channels.make_dig_montage(ch_pos=ch_pos,
                                             nasion=head_points["NA"],
                                             lpa=head_points["LPA"],
                                             rpa=head_points["RPA"])

    return mne.channels.make_standard_montage('standard_1020')
Example #14
0
 def modify_mat(fname, variable_names=None, ignore_fields=None):
     out = read_mat(fname, variable_names, ignore_fields)
     if 'fsample' in out['data']:
         out['data']['fsample'] = np.repeat(out['data']['fsample'], 2)
     return out
Example #15
0
def main():
    config_dir = os.path.join(*[CDIR, ex.observers[0].basedir, '1'])
    images_dir = os.path.join(*[CDIR, ex.observers[0].basedir, 'images'])
    models_dir = os.path.join(*[CDIR, ex.observers[0].basedir, 'trained_models'])

    file_name = '../data/Subject1_Run1.mat'
    mat_data = read_mat(file_name)
    data = mat_data['eegData'].T[:, :22000] * 1e-6
    #n_timesteps = data.shape[1]
    print(data)

    # remove DC
    mean_data = np.mean(data, axis=1)[:, np.newaxis]
    data = data - mean_data

    fs = mat_data['fs']
    montage = mne.channels.make_standard_montage('biosemi128')
    info = mne.create_info(ch_names=montage.ch_names, sfreq=fs, ch_types='eeg').set_montage(montage)

    raw = mne.io.RawArray(data, info)
    raw.info['bads'].append('A22')

    # cropping the raw object to just three seconds for easier plotting
    #raw.crop(tmin=0, tmax=3).load_data()
    raw.plot()

    # Preprocessing following mne tutorial
    # https://mne.tools/dev/auto_tutorials/preprocessing/plot_40_artifact_correction_ica.html#tut-artifact-ica

    # Filtering to remove slow drifts
    filt_raw = raw.copy()
    filt_raw.load_data().filter(l_freq=1., h_freq=None)

    # Fitting and plotting the ICA solution
    ica = ICA(n_components=15, random_state=0)
    ica.fit(filt_raw)

    raw.load_data()
    fig = ica.plot_sources(raw)
    fig.show()
    ica.plot_components()

    # blinks
    exclusion_list = [0, 1, 2]
    ica.plot_overlay(raw, exclude=exclusion_list, picks='eeg')
    ica.plot_properties(raw, picks=exclusion_list)

    # Selecting ICA components manually

    ica.exclude = exclusion_list

    # ica.apply() changes the Raw object in-place, so let's make a copy first:
    reconst_raw = raw.copy()
    ica.apply(reconst_raw)
    ica.apply(filt_raw)
    eeg_data_interp = filt_raw.copy().interpolate_bads(reset_bads=False)

    reconst_raw.plot()
    filt_raw.plot()
    raw.plot()
    eeg_data_interp.plot()
    ica.plot_components()