예제 #1
0
def test_samples_sesssions():
    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)

    root = join(tempdir, 'SampleExperiment')
    e = SampleExperiment(root)
    # bad channels
    e.make_bad_channels('0111')
    eq_(e.load_bad_channels(), ['MEG 0111'])
    eq_(e.load_bad_channels(session='sample2'), [])
    e.show_bad_channels()
    e.merge_bad_channels()
    eq_(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_rej(auto=2e-12)

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

    # 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'])))
예제 #2
0
def test_table():
    table = fmtxt.Table('ll')
    table.cells('A', 'B')
    table.midrule()
    table.cells('a1', 'b1', 'a2', 'b2')
    eq_(str(table), 'A    B \n-------\na1   b1\na2   b2')
    eq_(table.get_html(), u'<figure><table rules="none" cellpadding="2" '
                          u'frame="hsides" border="1"><tr>\n'
                          u' <td>A</td>\n <td>B</td>\n</tr>\n<tr>\n'
                          u' <td>a1</td>\n <td>b1</td>\n</tr>\n<tr>\n'
                          u' <td>a2</td>\n <td>b2</td>\n</tr></table></figure>')
    eq_(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')
    eq_(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)
    eq_(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 rules="none" cellpadding="2" frame="hsides" '
                            'border="1"><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)
    eq_(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)
    eq_(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)
    eq_(open(path).read(), 'A    B \n-------\na1   b1\na2   b2')
예제 #3
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)
        ok_(im.get_html().startswith('<img src='))

        im2 = fmtxt.Image.from_file(filename, alt='array')
        eq_(im.get_html(), im2.get_html())
예제 #4
0
def test_file_handling():
    "Test MneExperiment with actual files"
    tempdir = TempDir()
    for subject in SUBJECTS:
        sdir = os.path.join(tempdir, 'meg', subject)
        os.makedirs(sdir)

    e = FileExperiment(tempdir)

    eq_(e.get('subject'), SUBJECTS[0])
    eq_([s for s in e.iter(group='all')], SUBJECTS)
    eq_([s for s in e.iter(group='gsub')], SUBJECTS[1:])
    eq_([s for s in e.iter(group='gexc')], SUBJECTS[1:])
    eq_([s for s in e.iter(group='gexc2')], SUBJECTS[1:-1])
    eq_(e.get('subject'), SUBJECTS[1])
    eq_(e.get('subject', group='all'), SUBJECTS[1])
    e.set(SUBJECTS[0])
    eq_(e.get('subject'), SUBJECTS[0])
    eq_(e.get('subject', group='gsub'), SUBJECTS[1])

    e = FileExperimentDefaults(tempdir)
    eq_(e.get('group'), 'gsub')
    eq_(e.get('subject'), SUBJECTS[1])
예제 #5
0
def test_select_components():
    "Test Select-Epochs GUI Document"
    tempdir = TempDir()
    PATH = join(tempdir, 'test-ica.fif')

    ds = datasets.get_mne_sample()
    ds['epochs'] = ds['epochs'].pick_types('mag')
    ica = mne.preprocessing.ICA(0.95)
    ica.fit(ds['epochs'])
    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 == []

    frame.Close()
예제 #6
0
def test_mne_experiment_templates():
    "Test MneExperiment template formatting"
    tempdir = TempDir()
    e = BaseExperiment(tempdir, False)

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

    # model
    eq_(e.get('model', model='a % b'), 'a%b')
    eq_(e.get('model', model='b % a'), 'a%b')
    assert_raises(ValueError, e.set, model='a*b')
    assert_raises(ValueError, e.set, model='log(a)')

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

    # find terminal field names
    eq_(e.find_keys('raw-file'), {'root', 'subject', 'session'})
    eq_(
        e.find_keys('evoked-file', False), {
            'subject',
            'session',
            'modality',
            'raw',
            'epoch',
            'rej',
            'equalize_evoked_count',
            'model',
        })

    # inv
    SNR1 = 1.
    SNR2 = 1. / 2**2
    SNR3 = 1. / 3**2

    def set_inv(inv, make_kw, apply_kw, *args):
        e.reset()
        e.set(inv=inv)
        eq_(e._params['make_inv_kw'], make_kw)
        eq_(e._params['apply_inv_kw'], apply_kw)
        e.reset()
        e.set_inv(*args)
        eq_(e.get('inv'), inv)
        eq_(e._params['make_inv_kw'], make_kw)
        eq_(e._params['apply_inv_kw'], apply_kw)

    yield (set_inv, 'free-3-MNE', {
        'loose': 1,
        'depth': 0.8
    }, {
        'method': 'MNE',
        'lambda2': SNR3
    }, 'free', 3, 'MNE')
    yield (set_inv, 'free-3-dSPM-0.2-pick_normal', {
        'loose': 1,
        'depth': 0.2
    }, {
        'method': 'dSPM',
        'lambda2': SNR3,
        'pick_ori': 'normal'
    }, 'free', 3, 'dSPM', .2, True)
    yield (set_inv, 'fixed-2-MNE-0.2', {
        'fixed': True,
        'depth': 0.2
    }, {
        'method': 'MNE',
        'lambda2': SNR2
    }, 'fixed', 2, 'MNE', .2)
    yield (set_inv, 'fixed-2-MNE-pick_normal', {
        'fixed': True,
        'depth': 0.8
    }, {
        'method': 'MNE',
        'lambda2': SNR2,
        'pick_ori': 'normal'
    }, 'fixed', 2, 'MNE', None, True)
    yield (set_inv, 'loose.5-3-sLORETA', {
        'loose': 0.5,
        'depth': 0.8
    }, {
        'method': 'sLORETA',
        'lambda2': SNR3
    }, 0.5, 3, 'sLORETA')
    yield (set_inv, 'fixed-1-MNE-0', {
        'fixed': True,
        'depth': None
    }, {
        'method': 'MNE',
        'lambda2': SNR1
    }, 'fixed', 1, 'MNE', 0)
    # should remove this
    yield (set_inv, 'fixed-1-MNE-0.8', {
        'fixed': True,
        'depth': 0.8
    }, {
        'method': 'MNE',
        'lambda2': SNR1
    }, 'fixed', 1, 'MNE', 0.8)

    assert_raises(ValueError, e.set_inv, 'free', -3, 'dSPM')
    assert_raises(ValueError, e.set, inv='free-3-mne')
    assert_raises(ValueError, e.set, inv='free-3-MNE-2')
예제 #7
0
def test_select_epochs():
    "Test Select-Epochs GUI Document"
    set_log_level('warning', 'mne')
    ds = datasets.get_mne_sample(sns=True)
    tempdir = TempDir()
    path = os.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
    eq_(doc.accept[1], False)
    eq_(doc.tag[1], 'tag')
    eq_(doc.interpolate[1], [])
    eq_(doc.interpolate[2], ['2'])
    eq_(doc.bad_channels, [1])
    assert_array_equal(doc.accept[2:], True)
    # save
    doc.save()

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

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

    # Test Model
    # ==========
    ds = datasets.get_mne_sample(sns=True)
    doc = Document(ds, 'meg')
    model = Model(doc)

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

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

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

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

    # Test GUI
    # ========
    frame = gui.select_epochs(ds)
    assert_false(frame.CanBackward())
    ok_(frame.CanForward())
    frame.OnForward(None)
예제 #8
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)

    eq_(e.get('subject'), 'R0000')
    eq_(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()
    eq_(ds[0, 'evoked'].info['bads'], [])
    e.make_bad_channels(['MEG 0331'])
    ds = e.load_evoked()
    eq_(ds[0, 'evoked'].info['bads'], ['MEG 0331'])

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

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

    # test with data parameter
    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',
                      sns_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',
                      sns_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)

    # 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, '')

    # test multiple epochs with same time stamp
    class Experiment(SampleExperiment):
        epochs = SampleExperiment.epochs.copy()
    Experiment.epochs['v1'] = {'base': 'visual', 'vars': {'shift': 'Var([0.0], repeat=len(side))'}}
    Experiment.epochs['v2'] = {'base': 'visual', 'vars': {'shift': 'Var([0.1], repeat=len(side))'}}
    Experiment.epochs['vc'] = {'sub_epochs': ('v1', 'v2'), 'post_baseline_trigger_shift': 'shift', 'post_baseline_trigger_shift_max': 0.1, 'post_baseline_trigger_shift_min': 0.0}
    e = Experiment(root)
    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_dataobj_equal(v1, v2, decimal=20)

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

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

    # unsorted subjects
    class Experiment(SampleExperiment):
        groups = {'group': ('R0002', 'R0000', 'R0001')}
    e = Experiment(root)
    eq_([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': {
                'kind': 'two-stage',
                'stage 1': 'side_left + modality_a',
                'vars': {
                    'side_left': "side == 'left'",
                    'modality_a': "modality == 'auditory'",
                }
            },
            'novars': {
                'kind': 'two-stage',
                'stage 1': '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
    # ---
    e = SampleExperiment(root)
    ica_path = e.make_ica(raw='ica')
    e.set(raw='ica1-40', model='')
    e.make_rej(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"