Esempio n. 1
0
def test_select_components():
    "Test Select-Epochs GUI Document"
    tempdir = TempDir()
    PATH = join(tempdir, 'test-ica.fif')

    data_path = mne.datasets.testing.data_path()
    raw_path = join(data_path, 'MEG', 'sample', 'sample_audvis_trunc_raw.fif')
    raw = mne.io.Raw(raw_path, preload=True).pick_types('mag', stim=True)
    ds = load.fiff.events(raw)
    ds['epochs'] = load.fiff.mne_epochs(ds, tmax=0.1)
    ica = mne.preprocessing.ICA(0.95, max_iter=1)
    with catch_warnings():
        filterwarnings('ignore', 'FastICA did not converge')
        ica.fit(raw)
    ica.save(PATH)

    frame = gui.select_components(PATH, ds)
    frame.model.toggle(1)
    frame.OnSave(None)
    ica = mne.preprocessing.read_ica(PATH)
    assert ica.exclude == [1]

    frame.OnUndo(None)
    frame.OnSave(None)
    ica = mne.preprocessing.read_ica(PATH)
    assert ica.exclude == []

    # plotting
    for i in [ID.BASELINE_NONE, ID.BASELINE_GLOABL_MEAN, ID.BASELINE_CUSTOM]:
        frame.butterfly_baseline = i
        frame.OnPlotGrandAverage(None)

    frame.Close()
Esempio n. 2
0
def test_mne_experiment_visit():
    set_log_level('warning', 'mne')
    tempdir = TempDir()
    datasets.setup_samples_experiment(tempdir, 3, 1, n_visits=2)
    root = join(tempdir, 'SampleExperiment')

    e = Experiment(root)
    ds0 = e.load_events(epoch='target', visit='')
    ds1 = e.load_events(epoch='target', visit='1')
    assert ds0[1, 'trigger'] != ds1[1, 'trigger']
    for _ in e:
        e.make_epoch_selection(auto=2e-12)
    e.set(visit='')
    for _ in e:
        e.make_epoch_selection(auto=2e-12)
    res0 = e.load_test('side', 0.05, 0.15, 0.05, data='sensor', make=True)
    e.set(visit='1')
    with pytest.raises(IOError):
        e.load_test('side', 0.05, 0.15, 0.05, data='sensor')
    res1 = e.load_test('side', 0.05, 0.15, 0.05, data='sensor', make=True)
    assert res1.p.min() != res0.p.min()

    # ica
    e.set(raw='ica')
    with catch_warnings():
        filterwarnings('ignore', "FastICA did not converge", UserWarning)
        assert e.make_ica(visit='') == join(root, 'meg', 'R0000',
                                            'R0000 ica-ica.fif')
        assert e.make_ica(visit='1') == join(root, 'meg', 'R0000',
                                             'R0000 1 ica-ica.fif')
Esempio n. 3
0
def test_sample_sessions():
    set_log_level('warning', 'mne')
    SampleExperiment = import_attr(sample_path / 'sample_experiment_sessions.py', 'SampleExperiment')
    tempdir = TempDir()
    datasets.setup_samples_experiment(tempdir, 2, 1, 2)

    class Experiment(SampleExperiment):

        raw = {
            'ica': RawICA('raw', ('sample1', 'sample2'), 'fastica', max_iter=1),
            **SampleExperiment.raw,
        }

    root = join(tempdir, 'SampleExperiment')
    e = Experiment(root)
    # bad channels
    e.make_bad_channels('0111')
    assert e.load_bad_channels() == ['MEG 0111']
    assert e.load_bad_channels(session='sample2') == []
    e.show_bad_channels()
    e.merge_bad_channels()
    assert e.load_bad_channels(session='sample2') == ['MEG 0111']
    e.show_bad_channels()

    # rejection
    for _ in e:
        for epoch in ('target1', 'target2'):
            e.set(epoch=epoch)
            e.make_epoch_selection(auto=2e-12)

    ds = e.load_evoked('R0000', epoch='target2')
    e.set(session='sample1')
    ds2 = e.load_evoked('R0000')
    assert_dataobj_equal(ds2, ds, decimal=19)

    # super-epoch
    ds1 = e.load_epochs(epoch='target1')
    ds2 = e.load_epochs(epoch='target2')
    ds_super = e.load_epochs(epoch='super')
    assert_dataobj_equal(ds_super['meg'], combine((ds1['meg'], ds2['meg'])))
    # evoked
    dse_super = e.load_evoked(epoch='super', model='modality%side')
    target = ds_super.aggregate('modality%side', drop=('i_start', 't_edf', 'T', 'index', 'trigger', 'session', 'interpolate_channels', 'epoch'))
    assert_dataobj_equal(dse_super, target)

    # conflicting session and epoch settings
    rej_path = join(root, 'meg', 'R0000', 'epoch selection', 'sample2_1-40_target2-man.pickled')
    e.set(epoch='target2', raw='1-40')
    assert not exists(rej_path)
    e.set(session='sample1')
    e.make_epoch_selection(auto=2e-12)
    assert exists(rej_path)

    # ica
    e.set('R0000', raw='ica')
    with catch_warnings():
        filterwarnings('ignore', "FastICA did not converge", UserWarning)
        assert e.make_ica() == join(root, 'meg', 'R0000', 'R0000 ica-ica.fif')
Esempio n. 4
0
def test_failed_load():
    tmp = TempDir()
    frame = gui.load_stcs()
    frame.dir_ctl.SetPath(tmp)
    evt = wx.FileDirPickerEvent()
    evt.SetPath(tmp)
    frame.OnDirChange(evt)
    assert "No .stc" in frame.status.GetStatusText()
    frame.Close()
Esempio n. 5
0
def test_visit():
    tempdir = TempDir()
    for subject in SUBJECTS:
        sdir = os.path.join(tempdir, 'meg', subject)
        os.makedirs(sdir)
    e = VisitExperiment(tempdir, raw='ica')

    assert e.get('ica-file') == os.path.join(tempdir, 'meg', 'R0001',
                                             'R0001 ica-ica.fif')
    e.set(visit='1')
    assert e.get('ica-file') == os.path.join(tempdir, 'meg', 'R0001',
                                             'R0001 1 ica-ica.fif')
Esempio n. 6
0
def test_load_stcs():
    tmp = TempDir()
    _create_fake_files(tmp)
    frame = gui.load_stcs()
    assert frame.dir_ctl.GetPath() == ""
    frame.dir_ctl.SetPath(tmp)
    evt = wx.FileDirPickerEvent()
    evt.SetPath(tmp)
    frame.OnDirChange(evt)
    assert frame.loader is not None
    assert len(frame.factor_name_ctrls) == 2
    assert "verb" in frame.loader.levels[1]
    frame.Close()
Esempio n. 7
0
def test_sample_source():
    set_log_level('warning', 'mne')
    SampleExperiment = import_attr(sample_path / 'sample_experiment.py',
                                   'SampleExperiment')
    tempdir = TempDir()
    datasets.setup_samples_experiment(
        tempdir, 3, 2,
        mris=True)  # TODO: use sample MRI which already has forward solution
    root = join(tempdir, 'SampleExperiment')
    e = SampleExperiment(root)

    # source space tests
    e.set(src='ico-4', rej='', epoch='auditory')
    # These two tests are only identical if the evoked has been cached before the first test is loaded
    ds = e.load_evoked(-1, model='side')
    resp = e.load_test('left=right',
                       0.05,
                       0.2,
                       0.05,
                       samples=100,
                       parc='ac',
                       make=True)
    resm = e.load_test('left=right',
                       0.05,
                       0.2,
                       0.05,
                       samples=100,
                       mask='ac',
                       make=True)
    assert_dataobj_equal(resp.t, resm.t)
    # ROI tests
    e.set(epoch='target')
    ress = e.load_test('left=right',
                       0.05,
                       0.2,
                       0.05,
                       samples=100,
                       data='source.rms',
                       parc='ac',
                       make=True)
    res = ress.res['ac-lh']
    assert res.p.min() == pytest.approx(0.429, abs=.001)
    ress = e.load_test('twostage',
                       0.05,
                       0.2,
                       0.05,
                       samples=100,
                       data='source.rms',
                       parc='ac',
                       make=True)
    res = ress.res['ac-lh']
Esempio n. 8
0
def test_tsv_io():
    """Test tsv I/O"""
    tempdir = TempDir()
    names = ['A', 'B', 'rm', 'intvar', 'fltvar', 'fltvar2', 'index']
    ds = datasets.get_uv()
    ds['fltvar'][5:10] = np.nan
    ds[:4, 'rm'] = ''

    # save and load
    dst = Path(tempdir) / 'ds.txt'
    ds.save_txt(dst)
    ds1 = load.tsv(dst, random='rm')
    assert_dataset_equal(ds1, ds, decimal=10)
    ds1 = load.tsv(dst, skiprows=1, names=names, random='rm')
    assert_dataset_equal(ds1, ds, decimal=10)
    # delimiter
    for delimiter in [' ', ',']:
        ds.save_txt(dst, delimiter=delimiter)
        ds1 = load.tsv(dst, delimiter=delimiter, random='rm')
        assert_dataset_equal(ds1, ds, decimal=10)

    # guess data types with missing
    intvar2 = ds['intvar'].as_factor()
    intvar2[10:] = ''
    ds_intvar = Dataset((intvar2, ))
    ds_intvar.save_txt(dst)
    ds_intvar1 = load.tsv(dst, empty='nan')
    assert_dataobj_equal(ds_intvar1['intvar', :10], ds['intvar', :10])
    assert_array_equal(ds_intvar1['intvar', 10:], np.nan)

    # str with space
    ds[:5, 'A'] = 'a 1'
    ds.save_txt(dst)
    ds1 = load.tsv(dst, random='rm')
    assert_dataset_equal(ds1, ds, decimal=10)
    ds.save_txt(dst, delimiter=' ')
    ds1 = load.tsv(dst, delimiter=' ', random='rm')
    assert_dataset_equal(ds1, ds, decimal=10)

    # Fixed column width
    path = file_path('fox-prestige')
    ds = load.tsv(path, delimiter=' ', skipinitialspace=True)
    assert ds[1] == {
        'id': 'GENERAL.MANAGERS',
        'education': 12.26,
        'income': 25879,
        'women': 4.02,
        'prestige': 69.1,
        'census': 1130,
        'type': 'prof'
    }
Esempio n. 9
0
def test_image():
    "Test FMText Image"
    tempdir = TempDir()
    filename = os.path.join(tempdir, 'rgb.png')
    rgba = np.random.uniform(0, 1, (100, 100, 4))
    rgb = rgba[:, :, :3]

    for array in (rgb, rgba):
        im = fmtxt.Image.from_array(array, alt='array')
        im.save_image(filename)
        assert im.get_html().startswith('<img src=')

        im2 = fmtxt.Image.from_file(filename, alt='array')
        assert im.get_html() == im2.get_html()
Esempio n. 10
0
def test_file_tree():
    "Test file management tree"

    class Tree(FileTree):
        _templates = {
            'a-folder': '{root}/{folder}',
            'a-file': '{a-folder}/{name}.txt',
            'folder': ('f1', 'f2'),
            'name': ('a1', 'a2', 'a3')
        }

        def __init__(self, *args, **kwargs):
            FileTree.__init__(self, *args, **kwargs)
            self._bind_make('a-file', self._make_a)

        def load_a(self):
            with open(self.get('a-file', make=True)) as fid:
                return fid.read()

        def _make_a(self):
            with open(self.get('a-file', mkdir=True), 'w') as fid:
                fid.write(self.format("{folder} {name}"))

    root = TempDir()
    tree = Tree(root=root)
    for _ in tree.iter_temp('a-file'):
        assert tree.load_a() == tree.format("{folder} {name}")

    for i, fname in enumerate(tree.iter_temp('a-file')):
        assert os.path.exists(fname)
    assert i == 5

    assert tree._glob_pattern('a-file', True,
                              folder='f1') == f'{root}/f1/*.txt'

    tree.rm('a-file', name='*', folder='f1', confirm=True)
    for fname in tree.iter_temp('a-file', folder='f1'):
        assert fname[-6:-4] == tree.get('name')
        assert not os.path.exists(fname)
    for fname in tree.iter_temp('a-file', folder='f2'):
        assert fname[-6:-4] == tree.get('name')
        assert os.path.exists(fname)
Esempio n. 11
0
def test_loader():
    tmp = TempDir()
    _create_fake_files(tmp)
    loader = DatasetSTCLoader(tmp)
    levels = loader.levels
    # check detected level names
    assert "level-a" in levels[0]
    assert "level-b" in levels[0]
    assert "noun" in levels[1]
    assert "verb" in levels[1]
    assert "R0000" in loader.subjects
    with pytest.raises(ValueError):
        loader.set_factor_names(["only-one-factor"])
    loader.set_factor_names(["factor1", "factor2"])
    assert loader.design_shape == "2 x 2"
    ds = loader.make_dataset(load_stcs=False)
    assert "factor1" in ds
    assert "factor2" in ds
    assert "subject" in ds
    assert ds["subject"].random
Esempio n. 12
0
def test_sample():
    set_log_level('warning', 'mne')
    # import from file:  http://stackoverflow.com/a/67692/166700
    SampleExperiment = import_attr(sample_path / 'sample_experiment.py',
                                   'SampleExperiment')
    tempdir = TempDir()
    datasets.setup_samples_experiment(tempdir, 3, 2)

    root = join(tempdir, 'SampleExperiment')
    e = SampleExperiment(root)

    assert e.get('raw') == '1-40'
    assert e.get('subject') == 'R0000'
    assert e.get('subject', subject='R0002') == 'R0002'

    # events
    e.set('R0001', rej='')
    ds = e.load_selected_events(epoch='target')
    assert ds.n_cases == 39
    ds = e.load_selected_events(epoch='auditory')
    assert ds.n_cases == 20
    ds = e.load_selected_events(epoch='av')
    assert ds.n_cases == 39

    # evoked cache invalidated by change in bads
    e.set('R0001', rej='', epoch='target')
    ds = e.load_evoked()
    assert ds[0, 'evoked'].info['bads'] == []
    e.make_bad_channels(['MEG 0331'])
    ds = e.load_evoked()
    assert ds[0, 'evoked'].info['bads'] == ['MEG 0331']

    e.set(rej='man', model='modality')
    sds = []
    for _ in e:
        e.make_epoch_selection(auto=2.5e-12)
        sds.append(e.load_evoked())

    ds = e.load_evoked('all')
    assert_dataobj_equal(combine(sds), ds)

    # sensor space tests
    megs = [e.load_evoked(cat='auditory')['meg'] for _ in e]
    res = e.load_test('a>v',
                      0.05,
                      0.2,
                      0.05,
                      samples=100,
                      data='sensor.rms',
                      baseline=False,
                      make=True)
    meg_rms = combine(meg.rms('sensor') for meg in megs).mean('case',
                                                              name='auditory')
    assert_dataobj_equal(res.c1_mean, meg_rms, decimal=21)
    res = e.load_test('a>v',
                      0.05,
                      0.2,
                      0.05,
                      samples=100,
                      data='sensor.mean',
                      baseline=False,
                      make=True)
    meg_mean = combine(meg.mean('sensor')
                       for meg in megs).mean('case', name='auditory')
    assert_dataobj_equal(res.c1_mean, meg_mean, decimal=21)
    with pytest.raises(IOError):
        res = e.load_test('a>v',
                          0.05,
                          0.2,
                          0.05,
                          samples=20,
                          data='sensor',
                          baseline=False)
    res = e.load_test('a>v',
                      0.05,
                      0.2,
                      0.05,
                      samples=20,
                      data='sensor',
                      baseline=False,
                      make=True)
    assert res.p.min() == pytest.approx(.143, abs=.001)
    assert res.difference.max() == pytest.approx(4.47e-13, 1e-15)
    # plot
    e.plot_evoked(1, epoch='target', model='')

    # e._report_subject_info() broke with non-alphabetic subject order
    subjects = e.get_field_values('subject')
    ds = Dataset()
    ds['subject'] = Factor(reversed(subjects))
    ds['n'] = Var(range(3))
    s_table = e._report_subject_info(ds, '')

    # post_baseline_trigger_shift
    # use multiple of tstep to shift by even number of samples
    tstep = 0.008324800548266162
    shift = -7 * tstep

    class Experiment(SampleExperiment):
        epochs = {
            **SampleExperiment.epochs,
            'visual-s':
            SecondaryEpoch('target',
                           "modality == 'visual'",
                           post_baseline_trigger_shift='shift',
                           post_baseline_trigger_shift_max=0,
                           post_baseline_trigger_shift_min=shift),
        }
        variables = {
            **SampleExperiment.variables, 'shift':
            LabelVar('side', {
                'left': 0,
                'right': shift
            }),
            'shift_t':
            LabelVar('trigger', {
                (1, 3): 0,
                (2, 4): shift
            })
        }

    e = Experiment(root)
    # test shift in events
    ds = e.load_events()
    assert_dataobj_equal(ds['shift_t'], ds['shift'], name=False)
    # compare against epochs (baseline correction on epoch level rather than evoked for smaller numerical error)
    ep = e.load_epochs(baseline=True, epoch='visual', rej='').aggregate('side')
    evs = e.load_evoked(baseline=True, epoch='visual-s', rej='', model='side')
    tstart = ep['meg'].time.tmin - shift
    assert_dataobj_equal(evs[0, 'meg'],
                         ep[0, 'meg'].sub(time=(tstart, None)),
                         decimal=20)
    tstop = ep['meg'].time.tstop + shift
    assert_almost_equal(evs[1, 'meg'].x,
                        ep[1, 'meg'].sub(time=(None, tstop)).x,
                        decimal=20)

    # post_baseline_trigger_shift & multiple epochs with same time stamp
    class Experiment(SampleExperiment):
        epochs = {
            **SampleExperiment.epochs,
            'v1': {
                'base': 'visual',
                'vars': {
                    'shift': 'Var([0.0], repeat=len(side))'
                }
            },
            'v2': {
                'base': 'visual',
                'vars': {
                    'shift': 'Var([0.1], repeat=len(side))'
                }
            },
            'vc': {
                'sub_epochs': ('v1', 'v2'),
                'post_baseline_trigger_shift': 'shift',
                'post_baseline_trigger_shift_max': 0.1,
                'post_baseline_trigger_shift_min': 0.0
            },
        }
        groups = {
            'group0': Group(['R0000']),
            'group1': SubGroup('all', ['R0000']),
        }
        variables = {
            'group': GroupVar(['group0', 'group1']),
            **SampleExperiment.variables,
        }

    e = Experiment(root)
    events = e.load_selected_events(epoch='vc')
    ds = e.load_epochs(baseline=True, epoch='vc')
    v1 = ds.sub("epoch=='v1'", 'meg').sub(time=(0, 0.199))
    v2 = ds.sub("epoch=='v2'", 'meg').sub(time=(-0.1, 0.099))
    assert_almost_equal(v1.x, v2.x, decimal=20)

    # duplicate subject
    class BadExperiment(SampleExperiment):
        groups = {'group': ('R0001', 'R0002', 'R0002')}

    with pytest.raises(DefinitionError):
        BadExperiment(root)

    # non-existing subject
    class BadExperiment(SampleExperiment):
        groups = {'group': ('R0001', 'R0003', 'R0002')}

    with pytest.raises(DefinitionError):
        BadExperiment(root)

    # unsorted subjects
    class Experiment(SampleExperiment):
        groups = {'group': ('R0002', 'R0000', 'R0001')}

    e = Experiment(root)
    assert [s for s in e] == ['R0000', 'R0001', 'R0002']

    # changes
    class Changed(SampleExperiment):
        variables = {
            'event': {
                (1, 2, 3, 4): 'target',
                5: 'smiley',
                32: 'button'
            },
            'side': {
                (1, 3): 'left',
                (2, 4): 'right_changed'
            },
            'modality': {
                (1, 2): 'auditory',
                (3, 4): 'visual'
            }
        }
        tests = {
            'twostage':
            TwoStageTest(
                'side_left + modality_a', {
                    'side_left': "side == 'left'",
                    'modality_a': "modality == 'auditory'"
                }),
            'novars':
            TwoStageTest('side + modality'),
        }

    e = Changed(root)

    # changed variable, while a test with model=None is not changed
    class Changed(Changed):
        variables = {
            'side': {
                (1, 3): 'left',
                (2, 4): 'right_changed'
            },
            'modality': {
                (1, 2): 'auditory',
                (3, 4): 'visual_changed'
            }
        }

    e = Changed(root)

    # changed variable, unchanged test with vardef=None
    class Changed(Changed):
        variables = {
            'side': {
                (1, 3): 'left',
                (2, 4): 'right_changed'
            },
            'modality': {
                (1, 2): 'auditory',
                (3, 4): 'visual_changed'
            }
        }

    e = Changed(root)

    # ICA
    # ---
    class Experiment(SampleExperiment):
        raw = {
            'apply-ica': RawApplyICA('tsss', 'ica'),
            **SampleExperiment.raw,
        }

    e = Experiment(root)
    ica_path = e.make_ica(raw='ica')
    e.set(raw='ica1-40', model='')
    e.make_epoch_selection(auto=2e-12, overwrite=True)
    ds1 = e.load_evoked(raw='ica1-40')
    ica = e.load_ica(raw='ica')
    ica.exclude = [0, 1, 2]
    ica.save(ica_path)
    ds2 = e.load_evoked(raw='ica1-40')
    assert not np.allclose(ds1['meg'].x, ds2['meg'].x,
                           atol=1e-20), "ICA change ignored"
    # apply-ICA
    with catch_warnings():
        filterwarnings(
            'ignore',
            "The measurement information indicates a low-pass frequency",
            RuntimeWarning)
        ds1 = e.load_evoked(raw='ica', rej='')
        ds2 = e.load_evoked(raw='apply-ica', rej='')
    assert_dataobj_equal(ds2, ds1)

    # rename subject
    # --------------
    src = Path(e.get('raw-dir', subject='R0001'))
    dst = Path(e.get('raw-dir', subject='R0003', match=False))
    shutil.move(src, dst)
    for path in dst.glob('*.fif'):
        shutil.move(path,
                    dst / path.parent / path.name.replace('R0001', 'R0003'))
    # check subject list
    e = SampleExperiment(root)
    assert list(e) == ['R0000', 'R0002', 'R0003']
    # check that cached test got deleted
    assert e.get('raw') == '1-40'
    with pytest.raises(IOError):
        e.load_test('a>v',
                    0.05,
                    0.2,
                    0.05,
                    samples=20,
                    data='sensor',
                    baseline=False)
    res = e.load_test('a>v',
                      0.05,
                      0.2,
                      0.05,
                      samples=20,
                      data='sensor',
                      baseline=False,
                      make=True)
    assert res.df == 2
    assert res.p.min() == pytest.approx(.143, abs=.001)
    assert res.difference.max() == pytest.approx(4.47e-13, 1e-15)

    # remove subject
    # --------------
    shutil.rmtree(dst)
    # check cache
    e = SampleExperiment(root)
    assert list(e) == ['R0000', 'R0002']
    # check that cached test got deleted
    assert e.get('raw') == '1-40'
    with pytest.raises(IOError):
        e.load_test('a>v',
                    0.05,
                    0.2,
                    0.05,
                    samples=20,
                    data='sensor',
                    baseline=False)

    # label_events
    # ------------
    class Experiment(SampleExperiment):
        def label_events(self, ds):
            SampleExperiment.label_events(self, ds)
            ds = ds.sub("event == 'smiley'")
            ds['new_var'] = Var([i + 1 for i in ds['i_start']])
            return ds

    e = Experiment(root)
    events = e.load_events()
    assert_array_equal(events['new_var'], [67402, 75306])
Esempio n. 13
0
def root_dir():
    tempdir = TempDir()
    for subject in SUBJECTS:
        sdir = os.path.join(tempdir, 'meg', subject)
        os.makedirs(sdir)
    return tempdir
Esempio n. 14
0
def test_mne_experiment_templates():
    "Test MneExperiment template formatting"
    tempdir = TempDir()
    e = BaseExperiment(tempdir, False)

    # Don't create dirs without root
    assert e.get('raw-file', mkdir=True).endswith('-raw.fif')

    # model
    assert e.get('model', model='a % b') == 'a%b'
    assert e.get('model', model='b % a') == 'a%b'
    with pytest.raises(ValueError):
        e.set(model='a*b')
    with pytest.raises(ValueError):
        e.set(model='log(a)')

    # compounds
    assert e.get('src_kind') == '0-40 bestreg free-3-dSPM'
    e.set_inv('fixed')
    assert e.get('src_kind') == '0-40 bestreg fixed-3-dSPM'
    e.set(cov='noreg')
    assert e.get('src_kind') == '0-40 noreg fixed-3-dSPM'
    e.set(raw='1-40')
    assert e.get('src_kind') == '1-40 noreg fixed-3-dSPM'
    e.set(src='ico-5')
    assert e.get('src_kind') == '1-40 noreg ico-5 fixed-3-dSPM'
    e.set(src='ico-4')
    assert e.get('src_kind') == '1-40 noreg fixed-3-dSPM'

    # find terminal field names
    assert e.find_keys('raw-file') == ['root', 'subject', 'session', 'visit']
    assert e.find_keys('evoked-file', False) == [
        'subject', 'raw', 'epoch', 'visit', 'model', 'rej',
        'equalize_evoked_count'
    ]

    assert_inv_works(e, 'free-3-MNE', ('free', 3, 'MNE'), {
        'loose': 1,
        'depth': 0.8
    }, {
        'method': 'MNE',
        'lambda2': 1 / 9
    })
    assert_inv_works(e, 'free-3-dSPM-0.2-pick_normal',
                     ('free', 3, 'dSPM', .2, True), {
                         'loose': 1,
                         'depth': 0.2
                     }, {
                         'method': 'dSPM',
                         'lambda2': 1 / 9,
                         'pick_ori': 'normal'
                     })
    assert_inv_works(e, 'fixed-2-MNE-0.2', ('fixed', 2, 'MNE', .2), {
        'fixed': True,
        'depth': 0.2
    }, {
        'method': 'MNE',
        'lambda2': 1 / 4
    })
    assert_inv_works(e, 'loose.2-2-MNE-pick_normal',
                     (0.2, 2, 'MNE', None, True), {
                         'loose': 0.2,
                         'depth': 0.8
                     }, {
                         'method': 'MNE',
                         'lambda2': 1 / 4,
                         'pick_ori': 'normal'
                     })
    assert_inv_works(e, 'loose.5-3-sLORETA', (0.5, 3, 'sLORETA'), {
        'loose': 0.5,
        'depth': 0.8
    }, {
        'method': 'sLORETA',
        'lambda2': 1 / 9
    })
    assert_inv_works(e, 'fixed-1-MNE-0', ('fixed', 1, 'MNE', 0), {
        'fixed': True,
        'depth': None
    }, {
        'method': 'MNE',
        'lambda2': 1
    })
    # should remove this
    assert_inv_works(e, 'fixed-1-MNE-0.8', ('fixed', 1, 'MNE', 0.8), {
        'fixed': True,
        'depth': 0.8
    }, {
        'method': 'MNE',
        'lambda2': 1
    })

    with pytest.raises(ValueError):
        e.set_inv('free', -3, 'dSPM')
    with pytest.raises(ValueError):
        e.set(inv='free-3-mne')
    with pytest.raises(ValueError):
        e.set(inv='free-3-MNE-2')

    assert e.find_keys('test-file', False) == [
        'analysis', 'group', 'epoch', 'visit', 'test', 'test_options',
        'test_dims'
    ]
    assert e._glob_pattern('test-file', True, group='all') == os.path.join(
        tempdir, 'eelbrain-cache', 'test', '* all', '* *.pickled')
Esempio n. 15
0
def test_table():
    table = fmtxt.Table('ll')
    table.cells('A', 'B')
    table.midrule()
    table.cells('a1', 'b1', 'a2', 'b2')
    assert str(table) == 'A    B \n-------\na1   b1\na2   b2'
    assert html(table) == (
        '<figure><table border="1" cellpadding="2" frame="hsides" rules="none"><tr>\n'
        ' <td>A</td>\n <td>B</td>\n</tr>\n<tr>\n'
        ' <td>a1</td>\n <td>b1</td>\n</tr>\n<tr>\n'
        ' <td>a2</td>\n <td>b2</td>\n</tr></table></figure>')
    assert table.get_rtf() == ('\\trowd\n\\cellx0000\n\\cellx1000\n\\row\n'
                               'A\\intbl\\cell\nB\\intbl\\cell\n\\row\n'
                               'a1\\intbl\\cell\nb1\\intbl\\cell\n\\row\n'
                               'a2\\intbl\\cell\nb2\\intbl\\cell\n\\row')
    assert table.get_tex() == (
        '\\begin{center}\n\\begin{tabular}{ll}\n\\toprule\n'
        'A & B \\\\\n\\midrule\n'
        'a1 & b1 \\\\\na2 & b2 \\\\\n'
        '\\bottomrule\n\\end{tabular}\n\\end{center}')

    # empty table
    str(fmtxt.Table(''))

    # saving
    tempdir = TempDir()
    # HTML
    path = os.path.join(tempdir, 'test.html')
    table.save_html(path)
    assert open(path).read() == (
        '<!DOCTYPE html>\n<html>\n<head>\n'
        '    <title>Untitled</title>\n'
        '<style>\n\n.float {\n    float:left\n}\n\n'
        '</style>\n</head>\n\n'
        '<body>\n\n<figure>'
        '<table border="1" cellpadding="2" frame="hsides" rules="none"><tr>\n'
        ' <td>A</td>\n <td>B</td>\n</tr>\n<tr>\n'
        ' <td>a1</td>\n <td>b1</td>\n</tr>\n<tr>\n'
        ' <td>a2</td>\n <td>b2</td>\n</tr>'
        '</table></figure>\n\n</body>\n</html>\n')
    # rtf
    path = os.path.join(tempdir, 'test.rtf')
    table.save_rtf(path)
    assert open(path).read() == ('{\\rtf1\\ansi\\deff0\n\n'
                                 '\\trowd\n\\cellx0000\n\\cellx1000\n\\row\n'
                                 'A\\intbl\\cell\nB\\intbl\\cell\n\\row\n'
                                 'a1\\intbl\\cell\nb1\\intbl\\cell\n\\row\n'
                                 'a2\\intbl\\cell\nb2\\intbl\\cell\n\\row\n}')
    # TeX
    path = os.path.join(tempdir, 'test.tex')
    table.save_tex(path)
    assert open(path).read() == (
        '\\begin{center}\n\\begin{tabular}{ll}\n\\toprule\n'
        'A & B \\\\\n\\midrule\n'
        'a1 & b1 \\\\\na2 & b2 \\\\\n'
        '\\bottomrule\n\\end{tabular}\n\\end{center}')
    # txt
    path = os.path.join(tempdir, 'test.txt')
    table.save_txt(path)
    assert open(path).read() == 'A    B \n-------\na1   b1\na2   b2'

    # editing
    table[0, 0] = 'X'
    assert str(table) == 'X    B \n-------\na1   b1\na2   b2'
    table[0] = ['C', 'D']
    assert str(table) == 'C    D \n-------\na1   b1\na2   b2'
    table[2, 0] = 'cd'
    assert str(table) == 'C    D \n-------\ncd   b1\na2   b2'
    table[2:4, 1] = ['x', 'y']
    assert str(table) == 'C    D\n------\ncd   x\na2   y'
Esempio n. 16
0
def test_select_epochs():
    "Test Select-Epochs GUI Document"
    set_log_level('warning', 'mne')

    data_path = mne.datasets.testing.data_path()
    raw_path = join(data_path, 'MEG', 'sample', 'sample_audvis_trunc_raw.fif')
    raw = mne.io.Raw(raw_path, preload=True).pick_types('mag', stim=True)
    ds = load.fiff.events(raw)
    ds['meg'] = load.fiff.epochs(ds, tmax=0.1)

    tempdir = TempDir()
    path = join(tempdir, 'rej.pickled')

    # Test Document
    # =============
    # create a file
    doc = Document(ds, 'meg')
    doc.set_path(path)
    doc.set_case(1, False, 'tag', None)
    doc.set_case(2, None, None, ['2'])
    doc.set_bad_channels([1])
    # check modifications
    assert doc.accept[1] == False
    assert doc.tag[1] == 'tag'
    assert doc.interpolate[1] == []
    assert doc.interpolate[2] == ['2']
    assert doc.bad_channels == [1]
    assert_array_equal(doc.accept[2:], True)
    # save
    doc.save()

    # check the file
    ds_ = load.unpickle(path)
    assert doc.epochs.sensor._array_index(ds_.info['bad_channels']) == [1]

    # load the file
    doc = Document(ds, 'meg', path=path)
    # modification checks
    assert doc.accept[1] == False
    assert doc.tag[1] == 'tag'
    assert doc.interpolate[1] == []
    assert doc.interpolate[2] == ['2']
    assert doc.bad_channels == [1]
    assert_array_equal(doc.accept[2:], True)

    # Test Model
    # ==========
    doc = Document(ds, 'meg')
    model = Model(doc)

    # accept
    model.set_case(0, False, None, None)
    assert doc.accept[0] == False
    model.history.undo()
    assert doc.accept[0] == True
    model.history.redo()
    assert doc.accept[0] == False

    # interpolate
    model.toggle_interpolation(2, '3')
    assert doc.interpolate[2] == ['3']
    model.toggle_interpolation(2, '4')
    assert doc.interpolate[2] == ['3', '4']
    model.toggle_interpolation(2, '3')
    assert doc.interpolate[2] == ['4']
    model.toggle_interpolation(3, '3')
    assert doc.interpolate[2] == ['4']
    assert doc.interpolate[3] == ['3']
    model.history.undo()
    model.history.undo()
    assert doc.interpolate[2] == ['3', '4']
    assert doc.interpolate[3] == []
    model.history.redo()
    assert doc.interpolate[2] == ['4']

    # bad channels
    model.set_bad_channels([1])
    model.set_bad_channels([1, 10])
    assert doc.bad_channels == [1, 10]
    model.history.undo()
    assert doc.bad_channels == [1]
    model.history.redo()
    assert doc.bad_channels == [1, 10]

    # reload to reset
    model.load(path)
    # tests
    assert doc.accept[1] == False
    assert doc.tag[1] == 'tag'
    assert doc.interpolate[1] == []
    assert doc.interpolate[2] == ['2']
    assert doc.bad_channels == [1]
    assert_array_equal(doc.accept[2:], True)

    # Test GUI
    # ========
    frame = gui.select_epochs(ds, nplots=9)
    assert not frame.CanBackward()
    assert frame.CanForward()
    frame.OnForward(None)
    frame.SetVLim(1e-12)