Example #1
0
def test_volume_source_space():
    """Test setting up volume source spaces
    """
    fname_vol = op.join(data_path, 'subjects', 'sample', 'bem',
                        'volume-7mm-src.fif')
    src = read_source_spaces(fname_vol)
    temp_name = op.join(tempdir, 'temp-src.fif')
    try:
        # The one in the sample dataset (uses bem as bounds)
        src_new = setup_volume_source_space('sample', temp_name, pos=7.0,
                                            bem=fname_bem, mri=fname_mri,
                                            subjects_dir=subjects_dir)
        _compare_source_spaces(src, src_new, mode='approx')
        src_new = read_source_spaces(temp_name)
        _compare_source_spaces(src, src_new, mode='approx')

        # let's try the spherical one (no bem or surf supplied)
        run_subprocess(['mne_volume_source_space',
                        '--grid',  '15.0',
                        '--src', temp_name,
                        '--mri', fname_mri])
        src = read_source_spaces(temp_name)
        src_new = setup_volume_source_space('sample', temp_name, pos=15.0,
                                            mri=fname_mri,
                                            subjects_dir=subjects_dir)
        _compare_source_spaces(src, src_new, mode='approx')
    finally:
        if op.isfile(temp_name):
            os.remove(temp_name)
Example #2
0
def test_volume_source_space():
    """Test setting up volume source spaces
    """
    fname_vol = op.join(data_path, "subjects", "sample", "bem", "volume-7mm-src.fif")
    src = read_source_spaces(fname_vol)
    temp_name = op.join(tempdir, "temp-src.fif")
    try:
        # The one in the sample dataset (uses bem as bounds)
        src_new = setup_volume_source_space(
            "sample", temp_name, pos=7.0, bem=fname_bem, mri=fname_mri, subjects_dir=subjects_dir
        )
        _compare_source_spaces(src, src_new, mode="approx")
        src_new = read_source_spaces(temp_name)
        _compare_source_spaces(src, src_new, mode="approx")

        # let's try the spherical one (no bem or surf supplied)
        run_subprocess(["mne_volume_source_space", "--grid", "15.0", "--src", temp_name, "--mri", fname_mri])
        src = read_source_spaces(temp_name)
        src_new = setup_volume_source_space("sample", temp_name, pos=15.0, mri=fname_mri, subjects_dir=subjects_dir)
        _compare_source_spaces(src, src_new, mode="approx")

        # now without MRI argument, it should give an error when we try
        # to read it
        run_subprocess(["mne_volume_source_space", "--grid", "15.0", "--src", temp_name])
        assert_raises(ValueError, read_source_spaces, temp_name)
    finally:
        if op.isfile(temp_name):
            os.remove(temp_name)
def test_make_forward_solution_sphere():
    """Test making a forward solution with a sphere model"""
    temp_dir = _TempDir()
    fname_src_small = op.join(temp_dir, "sample-oct-2-src.fif")
    src = setup_source_space("sample", fname_src_small, "oct2", subjects_dir=subjects_dir, add_dist=False)
    out_name = op.join(temp_dir, "tmp-fwd.fif")
    run_subprocess(
        [
            "mne_forward_solution",
            "--meg",
            "--eeg",
            "--meas",
            fname_raw,
            "--src",
            fname_src_small,
            "--mri",
            fname_trans,
            "--fwd",
            out_name,
        ]
    )
    fwd = read_forward_solution(out_name)
    sphere = make_sphere_model(verbose=True)
    fwd_py = make_forward_solution(fname_raw, fname_trans, src, sphere, meg=True, eeg=True, verbose=True)
    _compare_forwards(fwd, fwd_py, 366, 108, meg_rtol=5e-1, meg_atol=1e-6, eeg_rtol=5e-1, eeg_atol=5e-1)
    # Since the above is pretty lax, let's check a different way
    for meg, eeg in zip([True, False], [False, True]):
        fwd_ = pick_types_forward(fwd, meg=meg, eeg=eeg)
        fwd_py_ = pick_types_forward(fwd, meg=meg, eeg=eeg)
        assert_allclose(np.corrcoef(fwd_["sol"]["data"].ravel(), fwd_py_["sol"]["data"].ravel())[0, 1], 1.0, rtol=1e-3)
Example #4
0
 def compensate_mne(fname, comp):
     """Compensate using MNE-C."""
     tmp_fname = '%s-%d-ave.fif' % (fname[:-4], comp)
     cmd = ['mne_compensate_data', '--in', fname,
            '--out', tmp_fname, '--grad', str(comp)]
     run_subprocess(cmd)
     return read_evokeds(tmp_fname)[0]
Example #5
0
def test_discrete_source_space():
    """Test setting up (and reading/writing) discrete source spaces
    """
    src = read_source_spaces(fname)
    v = src[0]["vertno"]

    # let's make a discrete version with the C code, and with ours
    temp_name = op.join(tempdir, "temp-src.fif")
    try:
        # save
        temp_pos = op.join(tempdir, "temp-pos.txt")
        np.savetxt(temp_pos, np.c_[src[0]["rr"][v], src[0]["nn"][v]])
        # let's try the spherical one (no bem or surf supplied)
        run_subprocess(["mne_volume_source_space", "--meters", "--pos", temp_pos, "--src", temp_name])
        src_c = read_source_spaces(temp_name)
        pos_dict = dict(rr=src[0]["rr"][v], nn=src[0]["nn"][v])
        src_new = setup_volume_source_space("sample", None, pos=pos_dict, subjects_dir=subjects_dir)
        _compare_source_spaces(src_c, src_new, mode="approx")
        assert_allclose(src[0]["rr"][v], src_new[0]["rr"], rtol=1e-3, atol=1e-6)
        assert_allclose(src[0]["nn"][v], src_new[0]["nn"], rtol=1e-3, atol=1e-6)

        # now do writing
        write_source_spaces(temp_name, src_c)
        src_c2 = read_source_spaces(temp_name)
        _compare_source_spaces(src_c, src_c2)

        # now do MRI
        assert_raises(ValueError, setup_volume_source_space, "sample", pos=pos_dict, mri=fname_mri)
    finally:
        if op.isfile(temp_name):
            os.remove(temp_name)
Example #6
0
def test_scale_mri():
    """Test creating fsaverage and scaling it"""
    # create fsaverage
    create_default_subject(subjects_dir=tempdir)
    is_mri = _is_mri_subject('fsaverage', tempdir)
    assert_true(is_mri, "Creating fsaverage failed")

    fid_path = os.path.join(tempdir, 'fsaverage', 'bem',
                            'fsaverage-fiducials.fif')
    os.remove(fid_path)
    create_default_subject(update=True, subjects_dir=tempdir)
    assert_true(os.path.exists(fid_path), "Updating fsaverage")

    # create source space
    path = os.path.join(tempdir, 'fsaverage', 'bem', 'fsaverage-ico-6-src.fif')
    if not os.path.exists(path):
        cmd = ['mne_setup_source_space', '--subject', 'fsaverage', '--ico',
               '6']
        env = os.environ.copy()
        env['SUBJECTS_DIR'] = tempdir
        run_subprocess(cmd, env=env)

    # scale fsaverage
    scale_mri('fsaverage', 'flachkopf', [1, .2, .8], True, subjects_dir=tempdir)
    is_mri = _is_mri_subject('flachkopf', tempdir)
    assert_true(is_mri, "Scaling fsaverage failed")
    src_path = os.path.join(tempdir, 'flachkopf', 'bem',
                            'flachkopf-ico-6-src.fif')
    assert_true(os.path.exists(src_path), "Source space was not scaled")
    scale_labels('flachkopf', subjects_dir=tempdir)

    # scale source space separately
    os.remove(src_path)
    scale_source_space('flachkopf', 'ico-6', subjects_dir=tempdir)
    assert_true(os.path.exists(src_path), "Source space was not scaled")
def test_other_volume_source_spaces():
    """Test setting up other volume source spaces"""
    # these are split off because they require the MNE tools, and
    # Travis doesn't seem to like them

    # let's try the spherical one (no bem or surf supplied)
    tempdir = _TempDir()
    temp_name = op.join(tempdir, 'temp-src.fif')
    run_subprocess(['mne_volume_source_space',
                    '--grid', '7.0',
                    '--src', temp_name,
                    '--mri', fname_mri])
    src = read_source_spaces(temp_name)
    src_new = setup_volume_source_space('sample', temp_name, pos=7.0,
                                        mri=fname_mri,
                                        subjects_dir=subjects_dir)
    _compare_source_spaces(src, src_new, mode='approx')
    del src
    del src_new
    assert_raises(ValueError, setup_volume_source_space, 'sample', temp_name,
                  pos=7.0, sphere=[1., 1.], mri=fname_mri,  # bad sphere
                  subjects_dir=subjects_dir)

    # now without MRI argument, it should give an error when we try
    # to read it
    run_subprocess(['mne_volume_source_space',
                    '--grid', '7.0',
                    '--src', temp_name])
    assert_raises(ValueError, read_source_spaces, temp_name)
Example #8
0
def test_make_forward_solution_sphere():
    """Test making a forward solution with a sphere model."""
    temp_dir = _TempDir()
    fname_src_small = op.join(temp_dir, 'sample-oct-2-src.fif')
    src = setup_source_space('sample', 'oct2', subjects_dir=subjects_dir,
                             add_dist=False)
    write_source_spaces(fname_src_small, src)  # to enable working with MNE-C
    out_name = op.join(temp_dir, 'tmp-fwd.fif')
    run_subprocess(['mne_forward_solution', '--meg', '--eeg',
                    '--meas', fname_raw, '--src', fname_src_small,
                    '--mri', fname_trans, '--fwd', out_name])
    fwd = read_forward_solution(out_name)
    sphere = make_sphere_model(verbose=True)
    fwd_py = make_forward_solution(fname_raw, fname_trans, src, sphere,
                                   meg=True, eeg=True, verbose=True)
    _compare_forwards(fwd, fwd_py, 366, 108,
                      meg_rtol=5e-1, meg_atol=1e-6,
                      eeg_rtol=5e-1, eeg_atol=5e-1)
    # Since the above is pretty lax, let's check a different way
    for meg, eeg in zip([True, False], [False, True]):
        fwd_ = pick_types_forward(fwd, meg=meg, eeg=eeg)
        fwd_py_ = pick_types_forward(fwd, meg=meg, eeg=eeg)
        assert_allclose(np.corrcoef(fwd_['sol']['data'].ravel(),
                                    fwd_py_['sol']['data'].ravel())[0, 1],
                        1.0, rtol=1e-3)
Example #9
0
def test_average_forward_solution():
    """Test averaging forward solutions
    """
    fwd = read_forward_solution(fname)
    # input not a list
    assert_raises(TypeError, average_forward_solutions, 1)
    # list is too short
    assert_raises(ValueError, average_forward_solutions, [])
    # negative weights
    assert_raises(ValueError, average_forward_solutions, [fwd, fwd], [-1, 0])
    # all zero weights
    assert_raises(ValueError, average_forward_solutions, [fwd, fwd], [0, 0])
    # weights not same length
    assert_raises(ValueError, average_forward_solutions, [fwd, fwd], [0, 0, 0])
    # list does not only have all dict()
    assert_raises(TypeError, average_forward_solutions, [1, fwd])

    # try an easy case
    fwd_copy = average_forward_solutions([fwd])
    assert_array_equal(fwd['sol']['data'], fwd_copy['sol']['data'])

    # modify a fwd solution, save it, use MNE to average with old one
    fwd_copy['sol']['data'] *= 0.5
    fname_copy = op.join(temp_dir, 'fwd.fif')
    write_forward_solution(fname_copy, fwd_copy, overwrite=True)
    cmd = ('mne_average_forward_solutions', '--fwd', fname, '--fwd',
           fname_copy, '--out', fname_copy)
    run_subprocess(cmd)

    # now let's actually do it, with one filename and one fwd
    fwd_ave = average_forward_solutions([fwd, fwd_copy])
    assert_array_equal(0.75 * fwd['sol']['data'], fwd_ave['sol']['data'])
Example #10
0
def run_freesurfer_command(command, subjects_dir):
    "Run a FreeSurfer command"
    env = os.environ.copy()
    env['SUBJECTS_DIR'] = subjects_dir

    # find FREESURFER_HOME
    fs_home = mne.get_config('FREESURFER_HOME')
    save_fs_home = False
    while True:
        problem = fs_home_problem(fs_home)
        if problem:
            save_fs_home = True
            message = "Please select the directory where FreeSurfer is installed"
            print problem
            print message
            fs_home = ui.ask_dir("Select FreeSurfer Directory", message)
            if fs_home is False:
                raise RuntimeError("Could not find FreeSurfer")
        else:
            break
    if save_fs_home:
        mne.set_config('FREESURFER_HOME', fs_home)

    # adjust environment
    env['FREESURFER_HOME'] = fs_home
    bin_path = os.path.join(fs_home, 'bin')
    if bin_path not in env['PATH']:
        env['PATH'] = ':'.join((bin_path, env['PATH']))

    # run command
    run_subprocess(command, env=env)
Example #11
0
def test_discrete_source_space():
    """Test setting up (and reading/writing) discrete source spaces
    """
    src = read_source_spaces(fname)
    v = src[0]['vertno']

    # let's make a discrete version with the C code, and with ours
    temp_name = op.join(tempdir, 'temp-src.fif')
    try:
        # save
        temp_pos = op.join(tempdir, 'temp-pos.txt')
        np.savetxt(temp_pos, np.c_[src[0]['rr'][v], src[0]['nn'][v]])
        # let's try the spherical one (no bem or surf supplied)
        run_subprocess(['mne_volume_source_space', '--meters',
                        '--pos',  temp_pos, '--src', temp_name])
        src_c = read_source_spaces(temp_name)
        src_new = setup_volume_source_space('sample', None,
                                            pos=dict(rr=src[0]['rr'][v],
                                                     nn=src[0]['nn'][v]),
                                            subjects_dir=subjects_dir)
        _compare_source_spaces(src_c, src_new, mode='approx')
        assert_allclose(src[0]['rr'][v], src_new[0]['rr'],
                        rtol=1e-3, atol=1e-6)
        assert_allclose(src[0]['nn'][v], src_new[0]['nn'],
                        rtol=1e-3, atol=1e-6)

        # now do writing
        write_source_spaces(temp_name, src_c)
        src_c2 = read_source_spaces(temp_name)
        _compare_source_spaces(src_c, src_c2)
    finally:
        if op.isfile(temp_name):
            os.remove(temp_name)
def freeview_bem_surfaces(subject, subjects_dir, method):
    """View 3-Layers BEM model with Freeview.

    Parameters
    ----------
    subject : string
        Subject name
    subjects_dir : string
        Directory containing subjects data (Freesurfer SUBJECTS_DIR)
    method : string
        Can be 'flash' or 'watershed'.
    """
    subjects_dir = get_subjects_dir(subjects_dir, raise_error=True)

    if subject is None:
        raise ValueError("subject argument is None.")

    subject_dir = op.join(subjects_dir, subject)

    if not op.isdir(subject_dir):
        raise ValueError("Wrong path: '{}'. Check subjects-dir or"
                         "subject argument.".format(subject_dir))

    env = os.environ.copy()
    env['SUBJECT'] = subject
    env['SUBJECTS_DIR'] = subjects_dir

    if 'FREESURFER_HOME' not in env:
        raise RuntimeError('The FreeSurfer environment needs to be set up.')

    mri_dir = op.join(subject_dir, 'mri')
    bem_dir = op.join(subject_dir, 'bem')
    mri = op.join(mri_dir, 'T1.mgz')

    if method == 'watershed':
        bem_dir = op.join(bem_dir, 'watershed')
        outer_skin = op.join(bem_dir, '%s_outer_skin_surface' % subject)
        outer_skull = op.join(bem_dir, '%s_outer_skull_surface' % subject)
        inner_skull = op.join(bem_dir, '%s_inner_skull_surface' % subject)
    else:
        if method == 'flash':
            bem_dir = op.join(bem_dir, 'flash')
        outer_skin = op.join(bem_dir, 'outer_skin.surf')
        outer_skull = op.join(bem_dir, 'outer_skull.surf')
        inner_skull = op.join(bem_dir, 'inner_skull.surf')

    # put together the command
    cmd = ['freeview']
    cmd += ["--volume", mri]
    cmd += ["--surface", "%s:color=red:edgecolor=red" % inner_skull]
    cmd += ["--surface", "%s:color=yellow:edgecolor=yellow" % outer_skull]
    cmd += ["--surface",
            "%s:color=255,170,127:edgecolor=255,170,127" % outer_skin]

    run_subprocess(cmd, env=env, stdout=sys.stdout)
    print("[done]")
Example #13
0
def run_freesurfer_command(command, subjects_dir):
    "Run a FreeSurfer command"
    env = os.environ.copy()
    env['SUBJECTS_DIR'] = subjects_dir
    env['FREESURFER_HOME'] = fs_home = get_fs_home()
    bin_path = os.path.join(fs_home, 'bin')
    if bin_path not in env['PATH']:
        env['PATH'] = ':'.join((bin_path, env['PATH']))

    # run command
    run_subprocess(command, env=env)
Example #14
0
def generate_commands_rst(app):
    from sphinx_gallery import sphinx_compatibility
    out_dir = op.abspath(op.join(op.dirname(__file__), '..', 'generated'))
    if not op.isdir(out_dir):
        os.mkdir(out_dir)
    out_fname = op.join(out_dir, 'commands.rst')

    command_path = op.abspath(
        op.join(os.path.dirname(__file__), '..', '..', 'mne', 'commands'))
    fnames = [op.basename(fname)
              for fname in glob.glob(op.join(command_path, 'mne_*.py'))]
    iterator = sphinx_compatibility.status_iterator(
        fnames, 'generating MNE command help ... ', length=len(fnames))
    with open(out_fname, 'w') as f:
        f.write(header)
        for fname in iterator:
            cmd_name = fname[:-3]
            run_name = op.join(command_path, fname)
            output, _ = run_subprocess([sys.executable, run_name, '--help'],
                                       stdout=subprocess.PIPE,
                                       stderr=subprocess.PIPE, verbose=False)
            f.write(command_rst % (cmd_name,
                                   cmd_name.replace('mne_', 'mne '),
                                   '-' * len(cmd_name),
                                   output))
    print('[Done]')
Example #15
0
def test_setup_source_space_spacing(tmpdir, spacing):
    """Test setting up surface source spaces using a given spacing."""
    tempdir = str(tmpdir)
    copytree(op.join(subjects_dir, 'sample'), op.join(tempdir, 'sample'))
    args = [] if spacing == 7 else ['--spacing', str(spacing)]
    with modified_env(SUBJECTS_DIR=tempdir, SUBJECT='sample'):
        run_subprocess(['mne_setup_source_space'] + args)
    src = read_source_spaces(op.join(tempdir, 'sample', 'bem',
                                     'sample-%d-src.fif' % spacing))
    src_new = setup_source_space('sample', spacing=spacing, add_dist=False,
                                 subjects_dir=subjects_dir)
    _compare_source_spaces(src, src_new, mode='approx', nearest=True)
    # Degenerate conditions
    with pytest.raises(TypeError, match='spacing must be.*got.*float.*'):
        setup_source_space('sample', 7., subjects_dir=subjects_dir)
    with pytest.raises(ValueError, match='spacing must be >= 2, got 1'):
        setup_source_space('sample', 1, subjects_dir=subjects_dir)
Example #16
0
def test_setup_source_space_spacing(tmpdir, spacing):
    """Test setting up surface source spaces using a given spacing."""
    copytree(op.join(subjects_dir, 'sample'), str(tmpdir.join('sample')))
    args = [] if spacing == 7 else ['--spacing', str(spacing)]
    with modified_env(SUBJECTS_DIR=str(tmpdir), SUBJECT='sample'):
        run_subprocess(['mne_setup_source_space'] + args)
    src = read_source_spaces(
        tmpdir.join('sample', 'bem', 'sample-%d-src.fif' % spacing))
    src_new = setup_source_space('sample',
                                 spacing=spacing,
                                 add_dist=False,
                                 subjects_dir=subjects_dir)
    _compare_source_spaces(src, src_new, mode='approx', nearest=True)
    # Degenerate conditions
    with pytest.raises(TypeError, match='spacing must be.*got.*float.*'):
        setup_source_space('sample', 7., subjects_dir=subjects_dir)
    with pytest.raises(ValueError, match='spacing must be >= 2, got 1'):
        setup_source_space('sample', 1, subjects_dir=subjects_dir)
Example #17
0
def test_snr():
    """Test SNR calculation"""
    tempdir = _TempDir()
    inv = read_inverse_operator(fname_inv)
    evoked = read_evokeds(fname_evoked, baseline=(None, 0))[0]
    snr = estimate_snr(evoked, inv)[0]
    orig_dir = os.getcwd()
    os.chdir(tempdir)
    try:
        cmd = ['mne_compute_mne', '--inv', fname_inv, '--meas', fname_evoked,
               '--snronly', '--bmin', '-200', '--bmax', '0']
        run_subprocess(cmd)
    except Exception:
        pass  # this returns 1 for some reason
    finally:
        os.chdir(orig_dir)
    snr_c = np.loadtxt(op.join(tempdir, 'SNR'))[:, 1]
    assert_allclose(snr, snr_c, atol=1e-2, rtol=1e-2)
Example #18
0
    def _mne_annot2labels(subject, subjects_dir, parc):
        """Get labels using mne_annot2lables"""
        label_dir = _TempDir()
        cwd = os.getcwd()
        try:
            os.chdir(label_dir)
            env = os.environ.copy()
            env['SUBJECTS_DIR'] = subjects_dir
            cmd = ['mne_annot2labels', '--subject', subject, '--parc', parc]
            run_subprocess(cmd, env=env)
            label_fnames = glob.glob(label_dir + '/*.label')
            label_fnames.sort()
            labels = [read_label(fname) for fname in label_fnames]
        finally:
            del label_dir
            os.chdir(cwd)

        return labels
Example #19
0
    def _mne_annot2labels(subject, subjects_dir, parc):
        """Get labels using mne_annot2lables"""
        label_dir = _TempDir()
        cwd = os.getcwd()
        try:
            os.chdir(label_dir)
            env = os.environ.copy()
            env['SUBJECTS_DIR'] = subjects_dir
            cmd = ['mne_annot2labels', '--subject', subject, '--parc', parc]
            run_subprocess(cmd, env=env)
            label_fnames = glob.glob(label_dir + '/*.label')
            label_fnames.sort()
            labels = [read_label(fname) for fname in label_fnames]
        finally:
            del label_dir
            os.chdir(cwd)

        return labels
Example #20
0
def test_setup_source_space_spacing(tmp_path, spacing, monkeypatch):
    """Test setting up surface source spaces using a given spacing."""
    copytree(op.join(subjects_dir, 'sample'), tmp_path / 'sample')
    args = [] if spacing == 7 else ['--spacing', str(spacing)]
    monkeypatch.setenv('SUBJECTS_DIR', str(tmp_path))
    monkeypatch.setenv('SUBJECT', 'sample')
    run_subprocess(['mne_setup_source_space'] + args)
    src = read_source_spaces(
        tmp_path / 'sample' / 'bem' / ('sample-%d-src.fif' % spacing)
    )
    # No need to pass subjects_dir here because we've setenv'ed it
    src_new = setup_source_space('sample', spacing=spacing, add_dist=False)
    _compare_source_spaces(src, src_new, mode='approx', nearest=True)
    # Degenerate conditions
    with pytest.raises(TypeError, match='spacing must be.*got.*float.*'):
        setup_source_space('sample', 7.)
    with pytest.raises(ValueError, match='spacing must be >= 2, got 1'):
        setup_source_space('sample', 1)
Example #21
0
def test_snr(tmpdir):
    """Test SNR calculation."""
    tempdir = str(tmpdir)
    inv = read_inverse_operator(fname_inv)
    evoked = read_evokeds(fname_evoked, baseline=(None, 0))[0]
    snr = estimate_snr(evoked, inv)[0]
    orig_dir = os.getcwd()
    os.chdir(tempdir)
    try:
        cmd = ['mne_compute_mne', '--inv', fname_inv, '--meas', fname_evoked,
               '--snronly', '--bmin', '-200', '--bmax', '0']
        run_subprocess(cmd)
    except Exception:
        pass  # this returns 1 for some reason
    finally:
        os.chdir(orig_dir)
    times, snr_c, _ = np.loadtxt(op.join(tempdir, 'SNR')).T
    assert_allclose(times / 1000., evoked.times, atol=1e-2)
    assert_allclose(snr, snr_c, atol=1e-2, rtol=1e-2)
Example #22
0
def test_kit():
    """
    Testing the functionality of the raw_to_bids conversion for KIT data.
    """
    output_path = _TempDir()
    data_path = op.join(base_path, 'kit', 'tests', 'data')
    raw_fname = op.join(data_path, 'test.sqd')
    events_fname = op.join(data_path, 'test-eve.txt')
    hpi_fname = op.join(data_path, 'test_mrk.sqd')
    electrode_fname = op.join(data_path, 'test_elp.txt')
    headshape_fname = op.join(data_path, 'test_hsp.txt')
    event_id = dict(cond=1)

    raw_to_bids(subject_id=subject_id,
                session_id=session_id,
                run=run,
                task=task,
                raw_file=raw_fname,
                events_data=events_fname,
                event_id=event_id,
                hpi=hpi_fname,
                electrode=electrode_fname,
                hsp=headshape_fname,
                output_path=output_path,
                acquisition=acq_a,
                overwrite=True)
    # run again with a different acquisiton parameter
    raw_to_bids(subject_id=subject_id,
                session_id=session_id,
                run=run,
                task=task,
                raw_file=raw_fname,
                events_data=events_fname,
                event_id=event_id,
                hpi=hpi_fname,
                electrode=electrode_fname,
                hsp=headshape_fname,
                output_path=output_path,
                acquisition=acq_b,
                overwrite=True)
    cmd = ['bids-validator', output_path]
    run_subprocess(cmd, shell=shell)
Example #23
0
def test_other_volume_source_spaces(tmpdir):
    """Test setting up other volume source spaces."""
    # these are split off because they require the MNE tools, and
    # Travis doesn't seem to like them

    # let's try the spherical one (no bem or surf supplied)
    temp_name = tmpdir.join('temp-src.fif')
    run_subprocess(['mne_volume_source_space',
                    '--grid', '7.0',
                    '--src', temp_name,
                    '--mri', fname_mri])
    src = read_source_spaces(temp_name)
    sphere = (0., 0., 0., 0.09)
    src_new = setup_volume_source_space(None, pos=7.0, mri=fname_mri,
                                        subjects_dir=subjects_dir,
                                        sphere=sphere)
    # we use a more accurate elimination criteria, so let's fix the MNE-C
    # source space
    assert len(src_new[0]['vertno']) == 7497
    assert len(src) == 1
    assert len(src_new) == 1
    good_mask = np.in1d(src[0]['vertno'], src_new[0]['vertno'])
    src[0]['inuse'][src[0]['vertno'][~good_mask]] = 0
    assert src[0]['inuse'].sum() == 7497
    src[0]['vertno'] = src[0]['vertno'][good_mask]
    assert len(src[0]['vertno']) == 7497
    src[0]['nuse'] = len(src[0]['vertno'])
    assert src[0]['nuse'] == 7497
    _compare_source_spaces(src_new, src, mode='approx')
    assert 'volume, shape' in repr(src)
    del src
    del src_new
    pytest.raises(ValueError, setup_volume_source_space, 'sample', pos=7.0,
                  sphere=[1., 1.], mri=fname_mri,  # bad sphere
                  subjects_dir=subjects_dir)

    # now without MRI argument, it should give an error when we try
    # to read it
    run_subprocess(['mne_volume_source_space',
                    '--grid', '7.0',
                    '--src', temp_name])
    pytest.raises(ValueError, read_source_spaces, temp_name)
Example #24
0
def generate_cli_rst(app=None):
    """Generate the command line interface docs."""
    from sphinx_gallery import sphinx_compatibility
    out_dir = op.abspath(op.join(op.dirname(__file__), '..', 'generated'))
    if not op.isdir(out_dir):
        os.mkdir(out_dir)
    out_fname = op.join(out_dir, 'cli.rst.new')

    cli_path = op.abspath(
        op.join(os.path.dirname(__file__), '..', '..', 'mne_bids', 'commands'))
    fnames = sorted([
        op.basename(fname)
        for fname in glob.glob(op.join(cli_path, 'mne_bids*.py'))
    ])
    iterator = sphinx_compatibility.status_iterator(
        fnames, 'generating MNE-BIDS cli help ... ', length=len(fnames))
    with open(out_fname, 'w', encoding='utf-8') as f:
        f.write(header)
        for fname in iterator:
            cmd_name = fname[:-3]
            run_name = op.join(cli_path, fname)
            output, _ = run_subprocess([sys.executable, run_name, '--help'],
                                       stdout=subprocess.PIPE,
                                       stderr=subprocess.PIPE,
                                       verbose=False)
            output = output.splitlines()

            # Swap usage and title lines
            output[0], output[2] = output[2], output[0]

            # Add header marking
            for idx in (1, 0):
                output.insert(idx, '-' * len(output[0]))

            # Add code styling for the "Usage: " line
            for li, line in enumerate(output):
                if line.startswith('Usage: mne_bids '):
                    output[li] = 'Usage: ``%s``' % line[7:]
                    break

            # Turn "Options:" into field list
            if 'Options:' in output:
                ii = output.index('Options:')
                output[ii] = 'Options'
                output.insert(ii + 1, '-------')
                output.insert(ii + 2, '')
                output.insert(ii + 3, '.. rst-class:: field-list cmd-list')
                output.insert(ii + 4, '')
            output = '\n'.join(output)
            f.write(command_rst %
                    (cmd_name, cmd_name.replace('mne_bids_', 'mne_bids '),
                     '=' * len(cmd_name), output))
    _replace_md5(out_fname)
    print('[Done]')
def test_other_volume_source_spaces():
    """Test setting up other volume source spaces."""
    # these are split off because they require the MNE tools, and
    # Travis doesn't seem to like them

    # let's try the spherical one (no bem or surf supplied)
    tempdir = _TempDir()
    temp_name = op.join(tempdir, 'temp-src.fif')
    run_subprocess(['mne_volume_source_space',
                    '--grid', '7.0',
                    '--src', temp_name,
                    '--mri', fname_mri])
    src = read_source_spaces(temp_name)
    src_new = setup_volume_source_space(None, pos=7.0, mri=fname_mri,
                                        subjects_dir=subjects_dir)
    # we use a more accurate elimination criteria, so let's fix the MNE-C
    # source space
    assert len(src_new[0]['vertno']) == 7497
    assert len(src) == 1
    assert len(src_new) == 1
    good_mask = np.in1d(src[0]['vertno'], src_new[0]['vertno'])
    src[0]['inuse'][src[0]['vertno'][~good_mask]] = 0
    assert src[0]['inuse'].sum() == 7497
    src[0]['vertno'] = src[0]['vertno'][good_mask]
    assert len(src[0]['vertno']) == 7497
    src[0]['nuse'] = len(src[0]['vertno'])
    assert src[0]['nuse'] == 7497
    _compare_source_spaces(src_new, src, mode='approx')
    assert 'volume, shape' in repr(src)
    del src
    del src_new
    pytest.raises(ValueError, setup_volume_source_space, 'sample', pos=7.0,
                  sphere=[1., 1.], mri=fname_mri,  # bad sphere
                  subjects_dir=subjects_dir)

    # now without MRI argument, it should give an error when we try
    # to read it
    run_subprocess(['mne_volume_source_space',
                    '--grid', '7.0',
                    '--src', temp_name])
    pytest.raises(ValueError, read_source_spaces, temp_name)
Example #26
0
def test_average_forward_solution():
    """Test averaging forward solutions
    """
    temp_dir = _TempDir()
    fwd = read_forward_solution(fname_meeg)
    # input not a list
    assert_raises(TypeError, average_forward_solutions, 1)
    # list is too short
    assert_raises(ValueError, average_forward_solutions, [])
    # negative weights
    assert_raises(ValueError, average_forward_solutions, [fwd, fwd], [-1, 0])
    # all zero weights
    assert_raises(ValueError, average_forward_solutions, [fwd, fwd], [0, 0])
    # weights not same length
    assert_raises(ValueError, average_forward_solutions, [fwd, fwd], [0, 0, 0])
    # list does not only have all dict()
    assert_raises(TypeError, average_forward_solutions, [1, fwd])

    # try an easy case
    fwd_copy = average_forward_solutions([fwd])
    assert_true(isinstance(fwd_copy, Forward))
    assert_array_equal(fwd['sol']['data'], fwd_copy['sol']['data'])

    # modify a fwd solution, save it, use MNE to average with old one
    fwd_copy['sol']['data'] *= 0.5
    fname_copy = op.join(temp_dir, 'copy-fwd.fif')
    write_forward_solution(fname_copy, fwd_copy, overwrite=True)
    cmd = ('mne_average_forward_solutions', '--fwd', fname_meeg, '--fwd',
           fname_copy, '--out', fname_copy)
    run_subprocess(cmd)

    # now let's actually do it, with one filename and one fwd
    fwd_ave = average_forward_solutions([fwd, fwd_copy])
    assert_array_equal(0.75 * fwd['sol']['data'], fwd_ave['sol']['data'])
    # fwd_ave_mne = read_forward_solution(fname_copy)
    # assert_array_equal(fwd_ave_mne['sol']['data'], fwd_ave['sol']['data'])

    # with gradient
    fwd = read_forward_solution(fname_meeg_grad)
    fwd_ave = average_forward_solutions([fwd, fwd])
    compare_forwards(fwd, fwd_ave)
Example #27
0
def test_discrete_source_space():
    """Test setting up (and reading/writing) discrete source spaces
    """
    src = read_source_spaces(fname)
    v = src[0]['vertno']

    # let's make a discrete version with the C code, and with ours
    temp_name = op.join(tempdir, 'temp-src.fif')
    try:
        # save
        temp_pos = op.join(tempdir, 'temp-pos.txt')
        np.savetxt(temp_pos, np.c_[src[0]['rr'][v], src[0]['nn'][v]])
        # let's try the spherical one (no bem or surf supplied)
        run_subprocess([
            'mne_volume_source_space', '--meters', '--pos', temp_pos, '--src',
            temp_name
        ])
        src_c = read_source_spaces(temp_name)
        src_new = setup_volume_source_space('sample',
                                            None,
                                            pos=dict(rr=src[0]['rr'][v],
                                                     nn=src[0]['nn'][v]),
                                            subjects_dir=subjects_dir)
        _compare_source_spaces(src_c, src_new, mode='approx')
        assert_allclose(src[0]['rr'][v],
                        src_new[0]['rr'],
                        rtol=1e-3,
                        atol=1e-6)
        assert_allclose(src[0]['nn'][v],
                        src_new[0]['nn'],
                        rtol=1e-3,
                        atol=1e-6)

        # now do writing
        write_source_spaces(temp_name, src_c)
        src_c2 = read_source_spaces(temp_name)
        _compare_source_spaces(src_c, src_c2)
    finally:
        if op.isfile(temp_name):
            os.remove(temp_name)
Example #28
0
def test_mne_c_design(tmp_path):
    """Test MNE-C filter design."""
    tempdir = str(tmp_path)
    temp_fname = op.join(tempdir, 'test_raw.fif')
    out_fname = op.join(tempdir, 'test_c_raw.fif')
    x = np.zeros((1, 10001))
    x[0, 5000] = 1.
    time_sl = slice(5000 - 4096, 5000 + 4097)
    sfreq = 1000.
    RawArray(x, create_info(1, sfreq, 'eeg')).save(temp_fname)

    tols = dict(rtol=1e-4, atol=1e-4)
    cmd = ('mne_process_raw', '--projoff', '--raw', temp_fname, '--save',
           out_fname)
    run_subprocess(cmd)
    h = design_mne_c_filter(sfreq, None, 40)
    h_c = read_raw_fif(out_fname)[0][0][0][time_sl]
    assert_allclose(h, h_c, **tols)

    run_subprocess(cmd + ('--highpass', '5', '--highpassw', '2.5'))
    h = design_mne_c_filter(sfreq, 5, 40, 2.5)
    h_c = read_raw_fif(out_fname)[0][0][0][time_sl]
    assert_allclose(h, h_c, **tols)

    run_subprocess(cmd + ('--lowpass', '1000', '--highpass', '10'))
    h = design_mne_c_filter(sfreq, 10, None, verbose=True)
    h_c = read_raw_fif(out_fname)[0][0][0][time_sl]
    assert_allclose(h, h_c, **tols)
Example #29
0
def test_volume_source_space():
    """Test setting up volume source spaces
    """
    fname_vol = op.join(data_path, 'subjects', 'sample', 'bem',
                        'volume-7mm-src.fif')
    src = read_source_spaces(fname_vol)
    temp_name = op.join(tempdir, 'temp-src.fif')
    try:
        # The one in the sample dataset (uses bem as bounds)
        src_new = setup_volume_source_space('sample',
                                            temp_name,
                                            pos=7.0,
                                            bem=fname_bem,
                                            mri=fname_mri,
                                            subjects_dir=subjects_dir)
        _compare_source_spaces(src, src_new, mode='approx')
        src_new = read_source_spaces(temp_name)
        _compare_source_spaces(src, src_new, mode='approx')

        # let's try the spherical one (no bem or surf supplied)
        run_subprocess([
            'mne_volume_source_space', '--grid', '15.0', '--src', temp_name,
            '--mri', fname_mri
        ])
        src = read_source_spaces(temp_name)
        src_new = setup_volume_source_space('sample',
                                            temp_name,
                                            pos=15.0,
                                            mri=fname_mri,
                                            subjects_dir=subjects_dir)
        _compare_source_spaces(src, src_new, mode='approx')

        # now without MRI argument, it should give an error when we try
        # to read it
        run_subprocess(
            ['mne_volume_source_space', '--grid', '15.0', '--src', temp_name])
        assert_raises(ValueError, read_source_spaces, temp_name)
    finally:
        if op.isfile(temp_name):
            os.remove(temp_name)
Example #30
0
def test_mne_c_design():
    """Test MNE-C filter design."""
    tempdir = _TempDir()
    temp_fname = op.join(tempdir, 'test_raw.fif')
    out_fname = op.join(tempdir, 'test_c_raw.fif')
    x = np.zeros((1, 10001))
    x[0, 5000] = 1.
    time_sl = slice(5000 - 4096, 5000 + 4097)
    sfreq = 1000.
    RawArray(x, create_info(1, sfreq, 'eeg')).save(temp_fname)

    tols = dict(rtol=1e-4, atol=1e-4)
    cmd = ('mne_process_raw', '--projoff', '--raw', temp_fname,
           '--save', out_fname)
    run_subprocess(cmd)
    h = design_mne_c_filter(sfreq, None, 40)
    h_c = read_raw_fif(out_fname)[0][0][0][time_sl]
    assert_allclose(h, h_c, **tols)

    run_subprocess(cmd + ('--highpass', '5', '--highpassw', '2.5'))
    h = design_mne_c_filter(sfreq, 5, 40, 2.5)
    h_c = read_raw_fif(out_fname)[0][0][0][time_sl]
    assert_allclose(h, h_c, **tols)

    run_subprocess(cmd + ('--lowpass', '1000', '--highpass', '10'))
    h = design_mne_c_filter(sfreq, 10, None, verbose=True)
    h_c = read_raw_fif(out_fname)[0][0][0][time_sl]
    assert_allclose(h, h_c, **tols)
Example #31
0
def test_average_forward_solution():
    """Test averaging forward solutions
    """
    temp_dir = _TempDir()
    fwd = read_forward_solution(fname_meeg)
    # input not a list
    assert_raises(TypeError, average_forward_solutions, 1)
    # list is too short
    assert_raises(ValueError, average_forward_solutions, [])
    # negative weights
    assert_raises(ValueError, average_forward_solutions, [fwd, fwd], [-1, 0])
    # all zero weights
    assert_raises(ValueError, average_forward_solutions, [fwd, fwd], [0, 0])
    # weights not same length
    assert_raises(ValueError, average_forward_solutions, [fwd, fwd], [0, 0, 0])
    # list does not only have all dict()
    assert_raises(TypeError, average_forward_solutions, [1, fwd])

    # try an easy case
    fwd_copy = average_forward_solutions([fwd])
    assert_true(isinstance(fwd_copy, Forward))
    assert_array_equal(fwd["sol"]["data"], fwd_copy["sol"]["data"])

    # modify a fwd solution, save it, use MNE to average with old one
    fwd_copy["sol"]["data"] *= 0.5
    fname_copy = op.join(temp_dir, "copy-fwd.fif")
    write_forward_solution(fname_copy, fwd_copy, overwrite=True)
    cmd = ("mne_average_forward_solutions", "--fwd", fname_meeg, "--fwd", fname_copy, "--out", fname_copy)
    run_subprocess(cmd)

    # now let's actually do it, with one filename and one fwd
    fwd_ave = average_forward_solutions([fwd, fwd_copy])
    assert_array_equal(0.75 * fwd["sol"]["data"], fwd_ave["sol"]["data"])
    # fwd_ave_mne = read_forward_solution(fname_copy)
    # assert_array_equal(fwd_ave_mne['sol']['data'], fwd_ave['sol']['data'])

    # with gradient
    fwd = read_forward_solution(fname_meeg_grad)
    fwd_ave = average_forward_solutions([fwd, fwd])
    compare_forwards(fwd, fwd_ave)
Example #32
0
def test_make_forward_solution_sphere():
    """Test making a forward solution with a sphere model."""
    temp_dir = _TempDir()
    fname_src_small = op.join(temp_dir, 'sample-oct-2-src.fif')
    src = setup_source_space('sample', 'oct2', subjects_dir=subjects_dir,
                             add_dist=False)
    write_source_spaces(fname_src_small, src)  # to enable working with MNE-C
    out_name = op.join(temp_dir, 'tmp-fwd.fif')
    run_subprocess(['mne_forward_solution', '--meg', '--eeg',
                    '--meas', fname_raw, '--src', fname_src_small,
                    '--mri', fname_trans, '--fwd', out_name])
    fwd = read_forward_solution(out_name)
    sphere = make_sphere_model(verbose=True)
    fwd_py = make_forward_solution(fname_raw, fname_trans, src, sphere,
                                   meg=True, eeg=True, verbose=True)
    _compare_forwards(fwd, fwd_py, 366, 108,
                      meg_rtol=5e-1, meg_atol=1e-6,
                      eeg_rtol=5e-1, eeg_atol=5e-1)
    # Since the above is pretty lax, let's check a different way
    for meg, eeg in zip([True, False], [False, True]):
        fwd_ = pick_types_forward(fwd, meg=meg, eeg=eeg)
        fwd_py_ = pick_types_forward(fwd, meg=meg, eeg=eeg)
        assert_allclose(np.corrcoef(fwd_['sol']['data'].ravel(),
                                    fwd_py_['sol']['data'].ravel())[0, 1],
                        1.0, rtol=1e-3)
    # Number of layers in the sphere model doesn't matter for MEG
    # (as long as no sources are omitted due to distance)
    assert len(sphere['layers']) == 4
    fwd = make_forward_solution(fname_raw, fname_trans, src, sphere,
                                meg=True, eeg=False)
    sphere_1 = make_sphere_model(head_radius=None)
    assert len(sphere_1['layers']) == 0
    assert_array_equal(sphere['r0'], sphere_1['r0'])
    fwd_1 = make_forward_solution(fname_raw, fname_trans, src, sphere,
                                  meg=True, eeg=False)
    _compare_forwards(fwd, fwd_1, 306, 108, meg_rtol=1e-12, meg_atol=1e-12)
    # Homogeneous model
    sphere = make_sphere_model(head_radius=None)
    with pytest.raises(RuntimeError, match='zero shells.*EEG'):
        make_forward_solution(fname_raw, fname_trans, src, sphere)
Example #33
0
def generate_commands_rst(app=None):
    from sphinx_gallery import sphinx_compatibility
    out_dir = op.abspath(op.join(op.dirname(__file__), '..', 'generated'))
    if not op.isdir(out_dir):
        os.mkdir(out_dir)
    out_fname = op.join(out_dir, 'commands.rst.new')

    command_path = op.abspath(
        op.join(os.path.dirname(__file__), '..', '..', 'mne', 'commands'))
    fnames = sorted([
        op.basename(fname)
        for fname in glob.glob(op.join(command_path, 'mne_*.py'))])
    iterator = sphinx_compatibility.status_iterator(
        fnames, 'generating MNE command help ... ', length=len(fnames))
    with open(out_fname, 'w') as f:
        f.write(header)
        for fname in iterator:
            cmd_name = fname[:-3]
            run_name = op.join(command_path, fname)
            output, _ = run_subprocess([sys.executable, run_name, '--help'],
                                       stdout=subprocess.PIPE,
                                       stderr=subprocess.PIPE, verbose=False)
            output = output.splitlines()

            # Swap usage and title lines
            output[0], output[2] = output[2], output[0]

            # Add header marking
            for idx in (1, 0):
                output.insert(idx, '-' * len(output[0]))

            # Add code styling for the "Usage: " line
            for li, line in enumerate(output):
                if line.startswith('Usage: mne '):
                    output[li] = 'Usage: ``%s``' % line[7:]
                    break

            # Turn "Options:" into field list
            if 'Options:' in output:
                ii = output.index('Options:')
                output[ii] = 'Options'
                output.insert(ii + 1, '-------')
                output.insert(ii + 2, '')
                output.insert(ii + 3, '.. rst-class:: field-list cmd-list')
                output.insert(ii + 4, '')
            output = '\n'.join(output)
            f.write(command_rst % (cmd_name,
                                   cmd_name.replace('mne_', 'mne '),
                                   '=' * len(cmd_name),
                                   output))
    _replace_md5(out_fname)
    print('[Done]')
def test_discrete_source_space(tmpdir):
    """Test setting up (and reading/writing) discrete source spaces."""
    src = read_source_spaces(fname)
    v = src[0]['vertno']

    # let's make a discrete version with the C code, and with ours
    temp_name = tmpdir.join('temp-src.fif')
    # save
    temp_pos = tmpdir.join('temp-pos.txt')
    np.savetxt(str(temp_pos), np.c_[src[0]['rr'][v], src[0]['nn'][v]])
    # let's try the spherical one (no bem or surf supplied)
    run_subprocess([
        'mne_volume_source_space', '--meters', '--pos', temp_pos, '--src',
        temp_name
    ])
    src_c = read_source_spaces(temp_name)
    pos_dict = dict(rr=src[0]['rr'][v], nn=src[0]['nn'][v])
    src_new = setup_volume_source_space(pos=pos_dict)
    assert src_new.kind == 'discrete'
    _compare_source_spaces(src_c, src_new, mode='approx')
    assert_allclose(src[0]['rr'][v], src_new[0]['rr'], rtol=1e-3, atol=1e-6)
    assert_allclose(src[0]['nn'][v], src_new[0]['nn'], rtol=1e-3, atol=1e-6)

    # now do writing
    write_source_spaces(temp_name, src_c, overwrite=True)
    src_c2 = read_source_spaces(temp_name)
    _compare_source_spaces(src_c, src_c2)

    # now do MRI
    with pytest.raises(ValueError, match='Cannot create interpolation'):
        setup_volume_source_space('sample', pos=pos_dict, mri=fname_mri)
    assert repr(src_new).split('~')[0] == repr(src_c).split('~')[0]
    assert ' kB' in repr(src_new)
    assert src_new.kind == 'discrete'
    assert _get_src_type(src_new, None) == 'discrete'

    with pytest.raises(RuntimeError, match='finite'):
        setup_volume_source_space(
            pos=dict(rr=[[0, 0, float('inf')]], nn=[[0, 1, 0]]))
Example #35
0
def test_bti():
    """
    Testing the functionality of the raw_to_bids conversion for BTi data.
    """
    output_path = _TempDir()
    data_path = op.join(base_path, 'bti', 'tests', 'data')
    raw_fname = op.join(data_path, 'test_pdf_linux')
    config_fname = op.join(data_path, 'test_config_linux')
    headshape_fname = op.join(data_path, 'test_hs_linux')

    raw_to_bids(subject_id=subject_id,
                session_id=session_id,
                run=run,
                task=task,
                raw_file=raw_fname,
                config=config_fname,
                hsp=headshape_fname,
                output_path=output_path,
                verbose=True,
                overwrite=True)
    cmd = ['bids-validator', output_path]
    run_subprocess(cmd, shell=shell)
Example #36
0
def test_vhdr():
    """Test write_raw_bids conversion for BrainVision data."""
    output_path = _TempDir()
    data_path = op.join(base_path, 'brainvision', 'tests', 'data')
    raw_fname = op.join(data_path, 'test.vhdr')

    raw = mne.io.read_raw_brainvision(raw_fname)
    write_raw_bids(raw, bids_basename, output_path, overwrite=False)

    cmd = ['bids-validator', '--bep006', output_path]
    run_subprocess(cmd, shell=shell)

    # Test that correct channel units are written
    channels_tsv_name = op.join(output_path, 'sub-' + subject_id,
                                'ses-' + session_id, 'eeg',
                                bids_basename + '_channels.tsv')
    df = pd.read_csv(channels_tsv_name, sep='\t', keep_default_na=False)
    assert df.loc[df['name'] == 'FP1', 'units'].all() == 'µV'
    assert df.loc[df['name'] == 'CP5', 'units'].all() == 'n/a'

    # create another bids folder with the overwrite command and check
    # no files are in the folder
    data_path = make_bids_folders(subject=subject_id,
                                  session=session_id,
                                  kind='eeg',
                                  output_path=output_path,
                                  overwrite=True)
    assert len([f for f in os.listdir(data_path) if op.isfile(f)]) == 0

    # Also cover iEEG
    # We use the same data and pretend that eeg channels are ecog
    raw.set_channel_types(
        {raw.ch_names[i]: 'ecog'
         for i in mne.pick_types(raw.info, eeg=True)})
    output_path = _TempDir()
    write_raw_bids(raw, bids_basename, output_path, overwrite=False)

    cmd = ['bids-validator', '--bep010', output_path]
    run_subprocess(cmd, shell=shell)
Example #37
0
def test_make_forward_solution_sphere():
    """Test making a forward solution with a sphere model."""
    temp_dir = _TempDir()
    fname_src_small = op.join(temp_dir, 'sample-oct-2-src.fif')
    src = setup_source_space('sample',
                             'oct2',
                             subjects_dir=subjects_dir,
                             add_dist=False)
    write_source_spaces(fname_src_small, src)  # to enable working with MNE-C
    out_name = op.join(temp_dir, 'tmp-fwd.fif')
    run_subprocess([
        'mne_forward_solution', '--meg', '--eeg', '--meas', fname_raw, '--src',
        fname_src_small, '--mri', fname_trans, '--fwd', out_name
    ])
    fwd = read_forward_solution(out_name)
    sphere = make_sphere_model(verbose=True)
    fwd_py = make_forward_solution(fname_raw,
                                   fname_trans,
                                   src,
                                   sphere,
                                   meg=True,
                                   eeg=True,
                                   verbose=True)
    _compare_forwards(fwd,
                      fwd_py,
                      366,
                      108,
                      meg_rtol=5e-1,
                      meg_atol=1e-6,
                      eeg_rtol=5e-1,
                      eeg_atol=5e-1)
    # Since the above is pretty lax, let's check a different way
    for meg, eeg in zip([True, False], [False, True]):
        fwd_ = pick_types_forward(fwd, meg=meg, eeg=eeg)
        fwd_py_ = pick_types_forward(fwd, meg=meg, eeg=eeg)
        assert_allclose(np.corrcoef(fwd_['sol']['data'].ravel(),
                                    fwd_py_['sol']['data'].ravel())[0, 1],
                        1.0,
                        rtol=1e-3)
Example #38
0
def test_scale_mri():
    """Test creating fsaverage and scaling it"""
    # create fsaverage
    create_default_subject(subjects_dir=tempdir)
    is_mri = _is_mri_subject('fsaverage', tempdir)
    assert_true(is_mri, "Creating fsaverage failed")

    fid_path = os.path.join(tempdir, 'fsaverage', 'bem',
                            'fsaverage-fiducials.fif')
    os.remove(fid_path)
    create_default_subject(update=True, subjects_dir=tempdir)
    assert_true(os.path.exists(fid_path), "Updating fsaverage")

    # create source space
    path = os.path.join(tempdir, 'fsaverage', 'bem', 'fsaverage-ico-6-src.fif')
    if not os.path.exists(path):
        cmd = [
            'mne_setup_source_space', '--subject', 'fsaverage', '--ico', '6'
        ]
        env = os.environ.copy()
        env['SUBJECTS_DIR'] = tempdir
        run_subprocess(cmd, env=env)

    # scale fsaverage
    scale_mri('fsaverage',
              'flachkopf', [1, .2, .8],
              True,
              subjects_dir=tempdir)
    is_mri = _is_mri_subject('flachkopf', tempdir)
    assert_true(is_mri, "Scaling fsaverage failed")
    src_path = os.path.join(tempdir, 'flachkopf', 'bem',
                            'flachkopf-ico-6-src.fif')
    assert_true(os.path.exists(src_path), "Source space was not scaled")
    scale_labels('flachkopf', subjects_dir=tempdir)

    # scale source space separately
    os.remove(src_path)
    scale_source_space('flachkopf', 'ico-6', subjects_dir=tempdir)
    assert_true(os.path.exists(src_path), "Source space was not scaled")
Example #39
0
def test_discrete_source_space():
    """Test setting up (and reading/writing) discrete source spaces."""
    tempdir = _TempDir()
    src = read_source_spaces(fname)
    v = src[0]['vertno']

    # let's make a discrete version with the C code, and with ours
    temp_name = op.join(tempdir, 'temp-src.fif')
    try:
        # save
        temp_pos = op.join(tempdir, 'temp-pos.txt')
        np.savetxt(temp_pos, np.c_[src[0]['rr'][v], src[0]['nn'][v]])
        # let's try the spherical one (no bem or surf supplied)
        run_subprocess(['mne_volume_source_space', '--meters',
                        '--pos', temp_pos, '--src', temp_name])
        src_c = read_source_spaces(temp_name)
        pos_dict = dict(rr=src[0]['rr'][v], nn=src[0]['nn'][v])
        src_new = setup_volume_source_space(pos=pos_dict)
        assert src_new.kind == 'discrete'
        _compare_source_spaces(src_c, src_new, mode='approx')
        assert_allclose(src[0]['rr'][v], src_new[0]['rr'],
                        rtol=1e-3, atol=1e-6)
        assert_allclose(src[0]['nn'][v], src_new[0]['nn'],
                        rtol=1e-3, atol=1e-6)

        # now do writing
        write_source_spaces(temp_name, src_c, overwrite=True)
        src_c2 = read_source_spaces(temp_name)
    finally:
        if op.isfile(temp_name):
            os.remove(temp_name)
    _compare_source_spaces(src_c, src_c2)

    # now do MRI
    pytest.raises(ValueError, setup_volume_source_space, 'sample',
                  pos=pos_dict, mri=fname_mri)
    assert repr(src_new) == repr(src_c)
    assert src_new.kind == 'discrete'
    assert _get_src_type(src_new, None) == 'discrete'
Example #40
0
def test_discrete_source_space():
    """Test setting up (and reading/writing) discrete source spaces."""
    tempdir = _TempDir()
    src = read_source_spaces(fname)
    v = src[0]['vertno']

    # let's make a discrete version with the C code, and with ours
    temp_name = op.join(tempdir, 'temp-src.fif')
    try:
        # save
        temp_pos = op.join(tempdir, 'temp-pos.txt')
        np.savetxt(temp_pos, np.c_[src[0]['rr'][v], src[0]['nn'][v]])
        # let's try the spherical one (no bem or surf supplied)
        run_subprocess(['mne_volume_source_space', '--meters',
                        '--pos', temp_pos, '--src', temp_name])
        src_c = read_source_spaces(temp_name)
        pos_dict = dict(rr=src[0]['rr'][v], nn=src[0]['nn'][v])
        src_new = setup_volume_source_space(pos=pos_dict)
        assert src_new.kind == 'discrete'
        _compare_source_spaces(src_c, src_new, mode='approx')
        assert_allclose(src[0]['rr'][v], src_new[0]['rr'],
                        rtol=1e-3, atol=1e-6)
        assert_allclose(src[0]['nn'][v], src_new[0]['nn'],
                        rtol=1e-3, atol=1e-6)

        # now do writing
        write_source_spaces(temp_name, src_c, overwrite=True)
        src_c2 = read_source_spaces(temp_name)
    finally:
        if op.isfile(temp_name):
            os.remove(temp_name)
    _compare_source_spaces(src_c, src_c2)

    # now do MRI
    pytest.raises(ValueError, setup_volume_source_space, 'sample',
                  pos=pos_dict, mri=fname_mri)
    assert repr(src_new) == repr(src_c)
    assert src_new.kind == 'discrete'
    assert _get_src_type(src_new, None) == 'discrete'
Example #41
0
def run_freesurfer_command(command, subjects_dir):
    "Run a FreeSurfer command"
    env = os.environ.copy()
    env['SUBJECTS_DIR'] = subjects_dir

    # find FREESURFER_HOME
    fs_home = mne.get_config('FREESURFER_HOME')
    save_fs_home = False
    while True:
        problem = fs_home_problem(fs_home)
        if problem:
            save_fs_home = True
            print problem
            if fs_home == os.environ.get('FREESURFER_HOME', 0):
                print(
                    "WARNING: This directory is set as FREESURFER_HOME "
                    "environment variable. As long as you don't remove this "
                    "environment variable, you will be asked for the proper "
                    "FreeSurfer location every time a FreeSurfer command is "
                    "run.")
            message = "Please select the directory where FreeSurfer is installed"
            print message
            fs_home = ui.ask_dir("Select FreeSurfer Directory", message)
            if fs_home is False:
                raise RuntimeError("Could not find FreeSurfer")
        else:
            break
    if save_fs_home:
        mne.set_config('FREESURFER_HOME', fs_home)

    # adjust environment
    env['FREESURFER_HOME'] = fs_home
    bin_path = os.path.join(fs_home, 'bin')
    if bin_path not in env['PATH']:
        env['PATH'] = ':'.join((bin_path, env['PATH']))

    # run command
    run_subprocess(command, env=env)
Example #42
0
def fetch_sss_files(p, subjects, run_indices):
    """Pull SSS files (only designed for *nix platforms)"""
    if len(subjects) == 0:
        return
    includes = []
    for subj in subjects:
        includes += [
            '--include', subj, '--include',
            op.join(subj, 'sss_fif'), '--include',
            op.join(subj, 'sss_fif', '*'), '--include',
            op.join(subj, 'sss_log'), '--include',
            op.join(subj, 'sss_log', '*')
        ]
    assert ' ' not in p.sws_dir
    assert ' ' not in p.sws_ssh
    cmd = (['rsync', '-ave',
            'ssh -p %s' % p.sws_port, '--partial', '-K'] + includes +
           ['--exclude', '*'])
    cmd += ['%s:%s' % (p.sws_ssh, op.join(p.sws_dir, '*')), '.']
    run_subprocess(cmd,
                   cwd=p.work_dir,
                   stdout=subprocess.PIPE,
                   stderr=subprocess.PIPE)
Example #43
0
def test_other_volume_source_spaces():
    """Test setting up other volume source spaces"""
    # these are split off because they require the MNE tools, and
    # Travis doesn't seem to like them

    # let's try the spherical one (no bem or surf supplied)
    tempdir = _TempDir()
    temp_name = op.join(tempdir, 'temp-src.fif')
    run_subprocess([
        'mne_volume_source_space', '--grid', '7.0', '--src', temp_name,
        '--mri', fname_mri
    ])
    src = read_source_spaces(temp_name)
    src_new = setup_volume_source_space('sample',
                                        temp_name,
                                        pos=7.0,
                                        mri=fname_mri,
                                        subjects_dir=subjects_dir)
    _compare_source_spaces(src, src_new, mode='approx')
    assert_true('volume, shape' in repr(src))
    del src
    del src_new
    assert_raises(
        ValueError,
        setup_volume_source_space,
        'sample',
        temp_name,
        pos=7.0,
        sphere=[1., 1.],
        mri=fname_mri,  # bad sphere
        subjects_dir=subjects_dir)

    # now without MRI argument, it should give an error when we try
    # to read it
    run_subprocess(
        ['mne_volume_source_space', '--grid', '7.0', '--src', temp_name])
    assert_raises(ValueError, read_source_spaces, temp_name)
Example #44
0
def run_freesurfer_command(command, subjects_dir):
    "Run a FreeSurfer command"
    env = os.environ.copy()
    env['SUBJECTS_DIR'] = subjects_dir

    # find FREESURFER_HOME
    fs_home = mne.get_config('FREESURFER_HOME')
    save_fs_home = False
    while True:
        problem = fs_home_problem(fs_home)
        if problem:
            save_fs_home = True
            print problem
            if fs_home == os.environ.get('FREESURFER_HOME', 0):
                print("WARNING: This directory is set as FREESURFER_HOME "
                      "environment variable. As long as you don't remove this "
                      "environment variable, you will be asked for the proper "
                      "FreeSurfer location every time a FreeSurfer command is "
                      "run.")
            message = "Please select the directory where FreeSurfer is installed"
            print message
            fs_home = ui.ask_dir("Select FreeSurfer Directory", message)
            if fs_home is False:
                raise RuntimeError("Could not find FreeSurfer")
        else:
            break
    if save_fs_home:
        mne.set_config('FREESURFER_HOME', fs_home)

    # adjust environment
    env['FREESURFER_HOME'] = fs_home
    bin_path = os.path.join(fs_home, 'bin')
    if bin_path not in env['PATH']:
        env['PATH'] = ':'.join((bin_path, env['PATH']))

    # run command
    run_subprocess(command, env=env)
Example #45
0
def generate_commands_rst(app):
    out_dir = op.abspath(op.join(op.dirname(__file__), '..', 'generated'))
    out_fname = op.join(out_dir, 'commands.rst')

    command_path = op.join(os.path.dirname(__file__), '..', '..', 'mne', 'commands')
    print(command_path)
    fnames = glob.glob(op.join(command_path, 'mne_*.py'))

    with open(out_fname, 'w') as f:
        f.write(header)
        for fname in fnames:
            cmd_name = op.basename(fname)[:-3]

            output, _ = run_subprocess(['python', fname, '--help'])
            f.write(command_rst % (cmd_name, cmd_name.replace('mne_', 'mne '), output))

    print('Done')
Example #46
0
def generate_commands_rst(app):
    out_dir = op.abspath(op.join(op.dirname(__file__), '..', 'generated'))
    out_fname = op.join(out_dir, 'commands.rst')

    command_path = op.join(os.path.dirname(__file__), '..', '..', 'mne',
                           'commands')
    print('Generating commands for: %s ... ' % command_path, end='')
    fnames = glob.glob(op.join(command_path, 'mne_*.py'))

    with open(out_fname, 'w') as f:
        f.write(header)
        for fname in fnames:
            cmd_name = op.basename(fname)[:-3]

            output, _ = run_subprocess(['python', fname, '--help'])
            f.write(command_rst %
                    (cmd_name, cmd_name.replace('mne_', 'mne '), output))
    print('[Done]')
Example #47
0
def generate_commands_rst(app):
    out_dir = op.abspath(op.join(op.dirname(__file__), '..', 'generated'))
    if not op.isdir(out_dir):
        os.mkdir(out_dir)
    out_fname = op.join(out_dir, 'commands.rst')

    command_path = op.join(os.path.dirname(__file__), '..', '..', 'mne',
                           'commands')
    print('Generating commands for: %s ... ' % op.abspath(command_path),
          end='')
    fnames = glob.glob(op.join(command_path, 'mne_*.py'))

    with open(out_fname, 'w') as f:
        f.write(header)
        for fname in fnames:
            cmd_name = op.basename(fname)[:-3]

            output, _ = run_subprocess([sys.executable, fname, '--help'],
                                       stdout=subprocess.PIPE,
                                       stderr=subprocess.PIPE)
            f.write(command_rst %
                    (cmd_name, cmd_name.replace('mne_', 'mne '), output))
    print('[Done]')
Example #48
0
def generate_commands_rst(app):
    out_dir = op.abspath(op.join(op.dirname(__file__), '..', 'generated'))
    if not op.isdir(out_dir):
        os.mkdir(out_dir)
    out_fname = op.join(out_dir, 'commands.rst')

    command_path = op.join(os.path.dirname(__file__), '..', '..', 'mne',
                           'commands')
    print('Generating commands for: %s ... ' % op.abspath(command_path),
          end='')
    fnames = glob.glob(op.join(command_path, 'mne_*.py'))

    with open(out_fname, 'w') as f:
        f.write(header)
        for fname in fnames:
            cmd_name = op.basename(fname)[:-3]

            output, _ = run_subprocess([sys.executable, fname, '--help'],
                                       stdout=subprocess.PIPE,
                                       stderr=subprocess.PIPE)
            f.write(command_rst % (cmd_name, cmd_name.replace('mne_', 'mne '),
                                   output))
    print('[Done]')
def _run(subjects_dir, subject, force, overwrite, verbose=None):
    this_env = copy.copy(os.environ)
    this_env['SUBJECTS_DIR'] = subjects_dir
    this_env['SUBJECT'] = subject

    if 'SUBJECTS_DIR' not in this_env:
        raise RuntimeError('The environment variable SUBJECTS_DIR should '
                           'be set')

    if not op.isdir(subjects_dir):
        raise RuntimeError('subjects directory %s not found, specify using '
                           'the environment variable SUBJECTS_DIR or '
                           'the command line option --subjects-dir')

    if 'MNE_ROOT' not in this_env:
        raise RuntimeError('MNE_ROOT environment variable is not set')

    if 'FREESURFER_HOME' not in this_env:
        raise RuntimeError('The FreeSurfer environment needs to be set up '
                           'for this script')
    force = '--force' if force else '--check'
    subj_path = op.join(subjects_dir, subject)
    if not op.exists(subj_path):
        raise RuntimeError('%s does not exits. Please check your subject '
                           'directory path.' % subj_path)

    if op.exists(op.join(subj_path, 'mri', 'T1.mgz')):
        mri = 'T1.mgz'
    else:
        mri = 'T1'

    logger.info('1. Creating a dense scalp tessellation with mkheadsurf...')

    def check_seghead(surf_path=op.join(subj_path, 'surf')):
        for k in ['/lh.seghead', '/lh.smseghead']:
            surf = surf_path + k if op.exists(surf_path + k) else None
            if surf is not None:
                break
        return surf

    my_seghead = check_seghead()
    if my_seghead is None:
        run_subprocess(['mkheadsurf', '-subjid', subject, '-srcvol', mri],
                       env=this_env)

    surf = check_seghead()
    if surf is None:
        raise RuntimeError('mkheadsurf did not produce the standard output '
                           'file.')

    dense_fname = '{0}/{1}/bem/{1}-head-dense.fif'.format(subjects_dir,
                                                          subject)
    logger.info('2. Creating %s ...' % dense_fname)
    _check_file(dense_fname, overwrite)
    run_subprocess(['mne_surf2bem', '--surf', surf, '--id', '4', force,
                    '--fif', dense_fname], env=this_env)
    levels = 'medium', 'sparse'
    my_surf = mne.read_bem_surfaces(dense_fname)[0]
    tris = [30000, 2500]
    if os.getenv('_MNE_TESTING_SCALP', 'false') == 'true':
        tris = [len(my_surf['tris'])]  # don't actually decimate
    for ii, (n_tri, level) in enumerate(zip(tris, levels), 3):
        logger.info('%i. Creating %s tessellation...' % (ii, level))
        logger.info('%i.1 Decimating the dense tessellation...' % ii)
        points, tris = mne.decimate_surface(points=my_surf['rr'],
                                            triangles=my_surf['tris'],
                                            n_triangles=n_tri)
        other_fname = dense_fname.replace('dense', level)
        logger.info('%i.2 Creating %s' % (ii, other_fname))
        _check_file(other_fname, overwrite)
        tempdir = _TempDir()
        surf_fname = tempdir + '/tmp-surf.surf'
        # convert points to meters, make mne_analyze happy
        mne.write_surface(surf_fname, points * 1e3, tris)
        # XXX for some reason --check does not work here.
        try:
            run_subprocess(['mne_surf2bem', '--surf', surf_fname, '--id', '4',
                            '--force', '--fif', other_fname], env=this_env)
        finally:
            del tempdir
Example #50
0
def test_module_nesting():
    """Test that module imports are properly nested."""
    stdout, stderr, code = run_subprocess([sys.executable, '-c', run_script],
                                          return_code=True)
    assert code == 0, stdout + stderr
Example #51
0
 def compensate_mne(fname, grad):
     tmp_fname = op.join(tempdir, 'mne_ctf_test_raw.fif')
     cmd = ['mne_process_raw', '--raw', fname, '--save', tmp_fname,
            '--grad', str(grad), '--projoff', '--filteroff']
     run_subprocess(cmd)
     return Raw(tmp_fname, preload=True)
Example #52
0
 def _validate(output_path):
     cmd = bids_validator_exe + [output_path]
     run_subprocess(cmd, shell=shell)
def _run(subjects_dir, subject, force, overwrite, no_decimate, verbose=None):
    this_env = copy.copy(os.environ)
    subjects_dir = get_subjects_dir(subjects_dir, raise_error=True)
    this_env['SUBJECTS_DIR'] = subjects_dir
    this_env['SUBJECT'] = subject
    if 'FREESURFER_HOME' not in this_env:
        raise RuntimeError('The FreeSurfer environment needs to be set up '
                           'for this script')
    incomplete = 'warn' if force else 'raise'
    subj_path = op.join(subjects_dir, subject)
    if not op.exists(subj_path):
        raise RuntimeError('%s does not exist. Please check your subject '
                           'directory path.' % subj_path)

    mri = 'T1.mgz' if op.exists(op.join(subj_path, 'mri', 'T1.mgz')) else 'T1'

    logger.info('1. Creating a dense scalp tessellation with mkheadsurf...')

    def check_seghead(surf_path=op.join(subj_path, 'surf')):
        surf = None
        for k in ['lh.seghead', 'lh.smseghead']:
            this_surf = op.join(surf_path, k)
            if op.exists(this_surf):
                surf = this_surf
                break
        return surf

    my_seghead = check_seghead()
    if my_seghead is None:
        run_subprocess(['mkheadsurf', '-subjid', subject, '-srcvol', mri],
                       env=this_env)

    surf = check_seghead()
    if surf is None:
        raise RuntimeError('mkheadsurf did not produce the standard output '
                           'file.')

    dense_fname = '{0}/{1}/bem/{1}-head-dense.fif'.format(
        subjects_dir, subject)
    logger.info('2. Creating %s ...' % dense_fname)
    _check_file(dense_fname, overwrite)
    surf = mne.bem._surfaces_to_bem(
        [surf], [mne.io.constants.FIFF.FIFFV_BEM_SURF_ID_HEAD], [1],
        incomplete=incomplete)[0]
    mne.write_bem_surfaces(dense_fname, surf)
    levels = 'medium', 'sparse'
    tris = [] if no_decimate else [30000, 2500]
    if os.getenv('_MNE_TESTING_SCALP', 'false') == 'true':
        tris = [len(surf['tris'])]  # don't actually decimate
    for ii, (n_tri, level) in enumerate(zip(tris, levels), 3):
        logger.info('%i. Creating %s tessellation...' % (ii, level))
        logger.info('%i.1 Decimating the dense tessellation...' % ii)
        with ETSContext():
            points, tris = mne.decimate_surface(points=surf['rr'],
                                                triangles=surf['tris'],
                                                n_triangles=n_tri)
        dec_fname = dense_fname.replace('dense', level)
        logger.info('%i.2 Creating %s' % (ii, dec_fname))
        _check_file(dec_fname, overwrite)
        dec_surf = mne.bem._surfaces_to_bem(
            [dict(rr=points, tris=tris)],
            [mne.io.constants.FIFF.FIFFV_BEM_SURF_ID_HEAD], [1],
            rescale=False,
            incomplete=incomplete)
        mne.write_bem_surfaces(dec_fname, dec_surf)
Example #54
0
def test_dipole_fitting():
    """Test dipole fitting"""
    amp = 10e-9
    tempdir = _TempDir()
    rng = np.random.RandomState(0)
    fname_dtemp = op.join(tempdir, 'test.dip')
    fname_sim = op.join(tempdir, 'test-ave.fif')
    fwd = convert_forward_solution(read_forward_solution(fname_fwd),
                                   surf_ori=False, force_fixed=True)
    evoked = read_evokeds(fname_evo)[0]
    cov = read_cov(fname_cov)
    n_per_hemi = 5
    vertices = [np.sort(rng.permutation(s['vertno'])[:n_per_hemi])
                for s in fwd['src']]
    nv = sum(len(v) for v in vertices)
    stc = SourceEstimate(amp * np.eye(nv), vertices, 0, 0.001)
    with warnings.catch_warnings(record=True):  # semi-def cov
        evoked = generate_evoked(fwd, stc, evoked, cov, snr=20,
                                 random_state=rng)
    # For speed, let's use a subset of channels (strange but works)
    picks = np.sort(np.concatenate([
        pick_types(evoked.info, meg=True, eeg=False)[::2],
        pick_types(evoked.info, meg=False, eeg=True)[::2]]))
    evoked.pick_channels([evoked.ch_names[p] for p in picks])
    evoked.add_proj(make_eeg_average_ref_proj(evoked.info))
    write_evokeds(fname_sim, evoked)

    # Run MNE-C version
    run_subprocess([
        'mne_dipole_fit', '--meas', fname_sim, '--meg', '--eeg',
        '--noise', fname_cov, '--dip', fname_dtemp,
        '--mri', fname_fwd, '--reg', '0', '--tmin', '0',
    ])
    dip_c = read_dipole(fname_dtemp)

    # Run mne-python version
    sphere = make_sphere_model(head_radius=0.1)
    dip, residuals = fit_dipole(evoked, fname_cov, sphere, fname_fwd)

    # Sanity check: do our residuals have less power than orig data?
    data_rms = np.sqrt(np.sum(evoked.data ** 2, axis=0))
    resi_rms = np.sqrt(np.sum(residuals ** 2, axis=0))
    assert_true((data_rms > resi_rms).all())

    # Compare to original points
    transform_surface_to(fwd['src'][0], 'head', fwd['mri_head_t'])
    transform_surface_to(fwd['src'][1], 'head', fwd['mri_head_t'])
    src_rr = np.concatenate([s['rr'][v] for s, v in zip(fwd['src'], vertices)],
                            axis=0)
    src_nn = np.concatenate([s['nn'][v] for s, v in zip(fwd['src'], vertices)],
                            axis=0)

    # MNE-C skips the last "time" point :(
    dip.crop(dip_c.times[0], dip_c.times[-1])
    src_rr, src_nn = src_rr[:-1], src_nn[:-1]

    # check that we did at least as well
    corrs, dists, gc_dists, amp_errs, gofs = [], [], [], [], []
    for d in (dip_c, dip):
        new = d.pos
        diffs = new - src_rr
        corrs += [np.corrcoef(src_rr.ravel(), new.ravel())[0, 1]]
        dists += [np.sqrt(np.mean(np.sum(diffs * diffs, axis=1)))]
        gc_dists += [180 / np.pi * np.mean(np.arccos(np.sum(src_nn * d.ori,
                                                     axis=1)))]
        amp_errs += [np.sqrt(np.mean((amp - d.amplitude) ** 2))]
        gofs += [np.mean(d.gof)]
    assert_true(dists[0] >= dists[1], 'dists: %s' % dists)
    assert_true(corrs[0] <= corrs[1], 'corrs: %s' % corrs)
    assert_true(gc_dists[0] >= gc_dists[1], 'gc-dists (ori): %s' % gc_dists)
    assert_true(amp_errs[0] >= amp_errs[1], 'amplitude errors: %s' % amp_errs)
Example #55
0
def test_dipole_fitting():
    """Test dipole fitting."""
    amp = 10e-9
    tempdir = _TempDir()
    rng = np.random.RandomState(0)
    fname_dtemp = op.join(tempdir, 'test.dip')
    fname_sim = op.join(tempdir, 'test-ave.fif')
    fwd = convert_forward_solution(read_forward_solution(fname_fwd),
                                   surf_ori=False, force_fixed=True)
    evoked = read_evokeds(fname_evo)[0]
    cov = read_cov(fname_cov)
    n_per_hemi = 5
    vertices = [np.sort(rng.permutation(s['vertno'])[:n_per_hemi])
                for s in fwd['src']]
    nv = sum(len(v) for v in vertices)
    stc = SourceEstimate(amp * np.eye(nv), vertices, 0, 0.001)
    evoked = simulate_evoked(fwd, stc, evoked.info, cov, snr=20,
                             random_state=rng)
    # For speed, let's use a subset of channels (strange but works)
    picks = np.sort(np.concatenate([
        pick_types(evoked.info, meg=True, eeg=False)[::2],
        pick_types(evoked.info, meg=False, eeg=True)[::2]]))
    evoked.pick_channels([evoked.ch_names[p] for p in picks])
    evoked.add_proj(make_eeg_average_ref_proj(evoked.info))
    write_evokeds(fname_sim, evoked)

    # Run MNE-C version
    run_subprocess([
        'mne_dipole_fit', '--meas', fname_sim, '--meg', '--eeg',
        '--noise', fname_cov, '--dip', fname_dtemp,
        '--mri', fname_fwd, '--reg', '0', '--tmin', '0',
    ])
    dip_c = read_dipole(fname_dtemp)

    # Run mne-python version
    sphere = make_sphere_model(head_radius=0.1)
    dip, residuals = fit_dipole(evoked, fname_cov, sphere, fname_fwd)

    # Sanity check: do our residuals have less power than orig data?
    data_rms = np.sqrt(np.sum(evoked.data ** 2, axis=0))
    resi_rms = np.sqrt(np.sum(residuals ** 2, axis=0))
    factor = 1.
    # XXX weird, inexplicable differenc for 3.5 build we'll assume is due to
    # Anaconda bug for now...
    if os.getenv('TRAVIS', 'false') == 'true' and \
            sys.version[:3] in ('3.5', '2.7'):
        factor = 0.8
    assert_true((data_rms > factor * resi_rms).all(),
                msg='%s (factor: %s)' % ((data_rms / resi_rms).min(), factor))

    # Compare to original points
    transform_surface_to(fwd['src'][0], 'head', fwd['mri_head_t'])
    transform_surface_to(fwd['src'][1], 'head', fwd['mri_head_t'])
    src_rr = np.concatenate([s['rr'][v] for s, v in zip(fwd['src'], vertices)],
                            axis=0)
    src_nn = np.concatenate([s['nn'][v] for s, v in zip(fwd['src'], vertices)],
                            axis=0)

    # MNE-C skips the last "time" point :(
    dip.crop(dip_c.times[0], dip_c.times[-1])
    src_rr, src_nn = src_rr[:-1], src_nn[:-1]

    # check that we did at least as well
    corrs, dists, gc_dists, amp_errs, gofs = [], [], [], [], []
    for d in (dip_c, dip):
        new = d.pos
        diffs = new - src_rr
        corrs += [np.corrcoef(src_rr.ravel(), new.ravel())[0, 1]]
        dists += [np.sqrt(np.mean(np.sum(diffs * diffs, axis=1)))]
        gc_dists += [180 / np.pi * np.mean(np.arccos(np.sum(src_nn * d.ori,
                                                     axis=1)))]
        amp_errs += [np.sqrt(np.mean((amp - d.amplitude) ** 2))]
        gofs += [np.mean(d.gof)]
    assert_true(dists[0] >= dists[1] * factor, 'dists: %s' % dists)
    assert_true(corrs[0] <= corrs[1] / factor, 'corrs: %s' % corrs)
    assert_true(gc_dists[0] >= gc_dists[1] * factor,
                'gc-dists (ori): %s' % gc_dists)
    assert_true(amp_errs[0] >= amp_errs[1] * factor,
                'amplitude errors: %s' % amp_errs)
    assert_true(gofs[0] <= gofs[1] / factor, 'gof: %s' % gofs)
Example #56
0
 def compensate_mne(fname, grad):
     tmp_fname = op.join(tempdir, 'mne_ctf_test_raw.fif')
     cmd = ['mne_process_raw', '--raw', fname, '--save', tmp_fname,
            '--grad', str(grad), '--projoff', '--filteroff']
     run_subprocess(cmd)
     return Raw(tmp_fname, preload=True)
def _run(subjects_dir, subject, force, overwrite, no_decimate, verbose=None):
    this_env = copy.copy(os.environ)
    subjects_dir = get_subjects_dir(subjects_dir, raise_error=True)
    this_env['SUBJECTS_DIR'] = subjects_dir
    this_env['SUBJECT'] = subject
    if 'FREESURFER_HOME' not in this_env:
        raise RuntimeError('The FreeSurfer environment needs to be set up '
                           'for this script')
    incomplete = 'warn' if force else 'raise'
    subj_path = op.join(subjects_dir, subject)
    if not op.exists(subj_path):
        raise RuntimeError('%s does not exist. Please check your subject '
                           'directory path.' % subj_path)

    mri = 'T1.mgz' if op.exists(op.join(subj_path, 'mri', 'T1.mgz')) else 'T1'

    logger.info('1. Creating a dense scalp tessellation with mkheadsurf...')

    def check_seghead(surf_path=op.join(subj_path, 'surf')):
        surf = None
        for k in ['lh.seghead', 'lh.smseghead']:
            this_surf = op.join(surf_path, k)
            if op.exists(this_surf):
                surf = this_surf
                break
        return surf

    my_seghead = check_seghead()
    if my_seghead is None:
        run_subprocess(['mkheadsurf', '-subjid', subject, '-srcvol', mri],
                       env=this_env)

    surf = check_seghead()
    if surf is None:
        raise RuntimeError('mkheadsurf did not produce the standard output '
                           'file.')

    bem_dir = op.join(subjects_dir, subject, 'bem')
    if not op.isdir(bem_dir):
        os.mkdir(bem_dir)
    dense_fname = op.join(bem_dir, '%s-head-dense.fif' % subject)
    logger.info('2. Creating %s ...' % dense_fname)
    _check_file(dense_fname, overwrite)
    surf = mne.bem._surfaces_to_bem(
        [surf], [mne.io.constants.FIFF.FIFFV_BEM_SURF_ID_HEAD], [1],
        incomplete=incomplete)[0]
    mne.write_bem_surfaces(dense_fname, surf)
    levels = 'medium', 'sparse'
    tris = [] if no_decimate else [30000, 2500]
    if os.getenv('_MNE_TESTING_SCALP', 'false') == 'true':
        tris = [len(surf['tris'])]  # don't actually decimate
    for ii, (n_tri, level) in enumerate(zip(tris, levels), 3):
        logger.info('%i. Creating %s tessellation...' % (ii, level))
        logger.info('%i.1 Decimating the dense tessellation...' % ii)
        with ETSContext():
            points, tris = mne.decimate_surface(points=surf['rr'],
                                                triangles=surf['tris'],
                                                n_triangles=n_tri)
        dec_fname = dense_fname.replace('dense', level)
        logger.info('%i.2 Creating %s' % (ii, dec_fname))
        _check_file(dec_fname, overwrite)
        dec_surf = mne.bem._surfaces_to_bem(
            [dict(rr=points, tris=tris)],
            [mne.io.constants.FIFF.FIFFV_BEM_SURF_ID_HEAD], [1], rescale=False,
            incomplete=incomplete)
        mne.write_bem_surfaces(dec_fname, dec_surf)
Example #58
0
def test_dipole_fitting():
    """Test dipole fitting."""
    amp = 100e-9
    tempdir = _TempDir()
    rng = np.random.RandomState(0)
    fname_dtemp = op.join(tempdir, 'test.dip')
    fname_sim = op.join(tempdir, 'test-ave.fif')
    fwd = convert_forward_solution(read_forward_solution(fname_fwd),
                                   surf_ori=False,
                                   force_fixed=True,
                                   use_cps=True)
    evoked = read_evokeds(fname_evo)[0]
    cov = read_cov(fname_cov)
    n_per_hemi = 5
    vertices = [
        np.sort(rng.permutation(s['vertno'])[:n_per_hemi]) for s in fwd['src']
    ]
    nv = sum(len(v) for v in vertices)
    stc = SourceEstimate(amp * np.eye(nv), vertices, 0, 0.001)
    evoked = simulate_evoked(fwd,
                             stc,
                             evoked.info,
                             cov,
                             nave=evoked.nave,
                             random_state=rng)
    # For speed, let's use a subset of channels (strange but works)
    picks = np.sort(
        np.concatenate([
            pick_types(evoked.info, meg=True, eeg=False)[::2],
            pick_types(evoked.info, meg=False, eeg=True)[::2]
        ]))
    evoked.pick_channels([evoked.ch_names[p] for p in picks])
    evoked.add_proj(make_eeg_average_ref_proj(evoked.info))
    write_evokeds(fname_sim, evoked)

    # Run MNE-C version
    run_subprocess([
        'mne_dipole_fit',
        '--meas',
        fname_sim,
        '--meg',
        '--eeg',
        '--noise',
        fname_cov,
        '--dip',
        fname_dtemp,
        '--mri',
        fname_fwd,
        '--reg',
        '0',
        '--tmin',
        '0',
    ])
    dip_c = read_dipole(fname_dtemp)

    # Run mne-python version
    sphere = make_sphere_model(head_radius=0.1)
    with pytest.warns(RuntimeWarning, match='projection'):
        dip, residuals = fit_dipole(evoked, cov, sphere, fname_fwd)

    # Sanity check: do our residuals have less power than orig data?
    data_rms = np.sqrt(np.sum(evoked.data**2, axis=0))
    resi_rms = np.sqrt(np.sum(residuals**2, axis=0))
    assert (data_rms > resi_rms * 0.95).all(), \
        '%s (factor: %s)' % ((data_rms / resi_rms).min(), 0.95)

    # Compare to original points
    transform_surface_to(fwd['src'][0], 'head', fwd['mri_head_t'])
    transform_surface_to(fwd['src'][1], 'head', fwd['mri_head_t'])
    assert_equal(fwd['src'][0]['coord_frame'], FIFF.FIFFV_COORD_HEAD)
    src_rr = np.concatenate([s['rr'][v] for s, v in zip(fwd['src'], vertices)],
                            axis=0)
    src_nn = np.concatenate([s['nn'][v] for s, v in zip(fwd['src'], vertices)],
                            axis=0)

    # MNE-C skips the last "time" point :(
    out = dip.crop(dip_c.times[0], dip_c.times[-1])
    assert (dip is out)
    src_rr, src_nn = src_rr[:-1], src_nn[:-1]

    # check that we did about as well
    corrs, dists, gc_dists, amp_errs, gofs = [], [], [], [], []
    for d in (dip_c, dip):
        new = d.pos
        diffs = new - src_rr
        corrs += [np.corrcoef(src_rr.ravel(), new.ravel())[0, 1]]
        dists += [np.sqrt(np.mean(np.sum(diffs * diffs, axis=1)))]
        gc_dists += [
            180 / np.pi * np.mean(np.arccos(np.sum(src_nn * d.ori, axis=1)))
        ]
        amp_errs += [np.sqrt(np.mean((amp - d.amplitude)**2))]
        gofs += [np.mean(d.gof)]
    if os.getenv('TRAVIS', 'false').lower() == 'true' and \
            'OPENBLAS_NUM_THREADS' in os.environ:
        # XXX possibly some OpenBLAS numerical differences make
        # things slightly worse for us
        factor = 0.7
    else:
        factor = 0.8
    assert dists[0] / factor >= dists[1], 'dists: %s' % dists
    assert corrs[0] * factor <= corrs[1], 'corrs: %s' % corrs
    assert gc_dists[0] / factor >= gc_dists[1] * 0.8, \
        'gc-dists (ori): %s' % gc_dists
    assert amp_errs[0] / factor >= amp_errs[1],\
        'amplitude errors: %s' % amp_errs
    # This one is weird because our cov/sim/picking is weird
    assert gofs[0] * factor <= gofs[1] * 2, 'gof: %s' % gofs