• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

Python mne.read_proj函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Python中mne.read_proj函数的典型用法代码示例。如果您正苦于以下问题:Python read_proj函数的具体用法?Python read_proj怎么用?Python read_proj使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了read_proj函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。

示例1: test_plot_topomap

def test_plot_topomap():
    """Testing topomap plotting
    """
    # evoked
    evoked = fiff.read_evoked(evoked_fname, 'Left Auditory',
                              baseline=(None, 0))
    evoked.plot_topomap(0.1, 'mag', layout=layout)
    plot_evoked_topomap(evoked, None, ch_type='mag')
    times = [0.1, 0.2]
    plot_evoked_topomap(evoked, times, ch_type='eeg')
    plot_evoked_topomap(evoked, times, ch_type='grad')
    plot_evoked_topomap(evoked, times, ch_type='planar1')
    plot_evoked_topomap(evoked, times, ch_type='planar2')
    with warnings.catch_warnings(True):  # delaunay triangulation warning
        plot_evoked_topomap(evoked, times, ch_type='mag', layout='auto')
    assert_raises(RuntimeError, plot_evoked_topomap, evoked, 0.1, 'mag',
                  proj='interactive')  # projs have already been applied
    evoked.proj = False  # let's fake it like they haven't been applied
    plot_evoked_topomap(evoked, 0.1, 'mag', proj='interactive')
    assert_raises(RuntimeError, plot_evoked_topomap, evoked, np.repeat(.1, 50))
    assert_raises(ValueError, plot_evoked_topomap, evoked, [-3e12, 15e6])

    # projs
    projs = read_proj(ecg_fname)[:7]
    plot_projs_topomap(projs)
    plt.close('all')
开发者ID:dichaelen,项目名称:mne-python,代码行数:26,代码来源:test_viz.py


示例2: test_plot_topomap

def test_plot_topomap():
    """Test topomap plotting
    """
    # evoked
    warnings.simplefilter('always', UserWarning)
    with warnings.catch_warnings(record=True):
        evoked = fiff.read_evokeds(evoked_fname, 'Left Auditory',
                                  baseline=(None, 0))
        evoked.plot_topomap(0.1, 'mag', layout=layout)
        plot_evoked_topomap(evoked, None, ch_type='mag')
        times = [0.1, 0.2]
        plot_evoked_topomap(evoked, times, ch_type='eeg', vmin=np.min)
        plot_evoked_topomap(evoked, times, ch_type='grad', vmin=np.min,
                            vmax=np.max)
        plot_evoked_topomap(evoked, times, ch_type='planar1')
        plot_evoked_topomap(evoked, times, ch_type='planar2')
        plot_evoked_topomap(evoked, times, ch_type='grad', show_names=True)

        p = plot_evoked_topomap(evoked, times, ch_type='grad',
                                show_names=lambda x: x.replace('MEG', ''))
        subplot = [x for x in p.get_children() if
                   isinstance(x, matplotlib.axes.Subplot)][0]
        assert_true(all('MEG' not in x.get_text()
                        for x in subplot.get_children()
                        if isinstance(x, matplotlib.text.Text)))

        # Test title
        def get_texts(p):
            return [x.get_text() for x in p.get_children() if
                    isinstance(x, matplotlib.text.Text)]

        p = plot_evoked_topomap(evoked, times, ch_type='eeg')
        assert_equal(len(get_texts(p)), 0)
        p = plot_evoked_topomap(evoked, times, ch_type='eeg', title='Custom')
        texts = get_texts(p)
        assert_equal(len(texts), 1)
        assert_equal(texts[0], 'Custom')

        # delaunay triangulation warning
        with warnings.catch_warnings(record=True):
            plot_evoked_topomap(evoked, times, ch_type='mag', layout='auto')
        assert_raises(RuntimeError, plot_evoked_topomap, evoked, 0.1, 'mag',
                      proj='interactive')  # projs have already been applied
        evoked.proj = False  # let's fake it like they haven't been applied
        plot_evoked_topomap(evoked, 0.1, 'mag', proj='interactive')
        assert_raises(RuntimeError, plot_evoked_topomap, evoked,
                      np.repeat(.1, 50))
        assert_raises(ValueError, plot_evoked_topomap, evoked, [-3e12, 15e6])

        projs = read_proj(ecg_fname)
        projs = [p for p in projs if p['desc'].lower().find('eeg') < 0]
        plot_projs_topomap(projs)
        plt.close('all')
        for ch in evoked.info['chs']:
            if ch['coil_type'] == fiff.FIFF.FIFFV_COIL_EEG:
                if ch['eeg_loc'] is not None:
                    ch['eeg_loc'].fill(0)
                ch['loc'].fill(0)
        assert_raises(RuntimeError, plot_evoked_topomap, evoked,
                      times, ch_type='eeg')
开发者ID:lengross,项目名称:mne-python,代码行数:60,代码来源:test_viz.py


示例3: test_plot_topomap

def test_plot_topomap():
    """Test topomap plotting
    """
    # evoked
    warnings.simplefilter("always", UserWarning)
    with warnings.catch_warnings(record=True):
        evoked = read_evokeds(evoked_fname, "Left Auditory", baseline=(None, 0))
        evoked.plot_topomap(0.1, "mag", layout=layout)
        plot_evoked_topomap(evoked, None, ch_type="mag")
        times = [0.1, 0.2]
        plot_evoked_topomap(evoked, times, ch_type="eeg")
        plot_evoked_topomap(evoked, times, ch_type="grad")
        plot_evoked_topomap(evoked, times, ch_type="planar1")
        plot_evoked_topomap(evoked, times, ch_type="planar2")
        plot_evoked_topomap(evoked, times, ch_type="grad", show_names=True)

        p = plot_evoked_topomap(evoked, times, ch_type="grad", show_names=lambda x: x.replace("MEG", ""))
        subplot = [x for x in p.get_children() if isinstance(x, matplotlib.axes.Subplot)][0]
        assert_true(
            all("MEG" not in x.get_text() for x in subplot.get_children() if isinstance(x, matplotlib.text.Text))
        )

        # Test title
        def get_texts(p):
            return [x.get_text() for x in p.get_children() if isinstance(x, matplotlib.text.Text)]

        p = plot_evoked_topomap(evoked, times, ch_type="eeg")
        assert_equal(len(get_texts(p)), 0)
        p = plot_evoked_topomap(evoked, times, ch_type="eeg", title="Custom")
        texts = get_texts(p)
        assert_equal(len(texts), 1)
        assert_equal(texts[0], "Custom")

        # delaunay triangulation warning
        with warnings.catch_warnings(record=True):
            plot_evoked_topomap(evoked, times, ch_type="mag", layout="auto")
        assert_raises(
            RuntimeError, plot_evoked_topomap, evoked, 0.1, "mag", proj="interactive"
        )  # projs have already been applied

        # change to no-proj mode
        evoked = read_evokeds(evoked_fname, "Left Auditory", baseline=(None, 0), proj=False)
        plot_evoked_topomap(evoked, 0.1, "mag", proj="interactive")
        assert_raises(RuntimeError, plot_evoked_topomap, evoked, np.repeat(0.1, 50))
        assert_raises(ValueError, plot_evoked_topomap, evoked, [-3e12, 15e6])

        projs = read_proj(ecg_fname)
        projs = [pp for pp in projs if pp["desc"].lower().find("eeg") < 0]
        plot_projs_topomap(projs)
        plt.close("all")
        for ch in evoked.info["chs"]:
            if ch["coil_type"] == FIFF.FIFFV_COIL_EEG:
                if ch["eeg_loc"] is not None:
                    ch["eeg_loc"].fill(0)
                ch["loc"].fill(0)
        assert_raises(RuntimeError, plot_evoked_topomap, evoked, times, ch_type="eeg")
开发者ID:rgoj,项目名称:mne-python,代码行数:56,代码来源:test_viz.py


示例4: test_plot_topomap

def test_plot_topomap():
    """Testing topomap plotting
    """
    # evoked
    evoked = fiff.read_evoked(evoked_fname, "Left Auditory", baseline=(None, 0))
    evoked.plot_topomap(0.1, "mag", layout=layout)
    plot_evoked_topomap(evoked, None, ch_type="mag")
    times = [0.1, 0.2]
    plot_evoked_topomap(evoked, times, ch_type="grad")
    plot_evoked_topomap(evoked, times, ch_type="planar1")
    plot_evoked_topomap(evoked, times, ch_type="mag", layout="auto")
    plot_evoked_topomap(evoked, 0.1, "mag", proj="interactive")
    assert_raises(RuntimeError, plot_evoked_topomap, evoked, np.repeat(0.1, 50))
    assert_raises(ValueError, plot_evoked_topomap, evoked, [-3e12, 15e6])

    # projs
    projs = read_proj(ecg_fname)[:7]
    plot_projs_topomap(projs)
开发者ID:pauldelprato,项目名称:mne-python,代码行数:18,代码来源:test_viz.py


示例5: test_plot_projs_topomap

def test_plot_projs_topomap():
    """Test plot_projs_topomap."""
    projs = read_proj(ecg_fname)
    info = read_info(raw_fname)
    fast_test = {"res": 8, "contours": 0, "sensors": False}
    plot_projs_topomap(projs, info=info, colorbar=True, **fast_test)
    plt.close('all')
    ax = plt.subplot(111)
    projs[3].plot_topomap()
    plot_projs_topomap(projs[:1], axes=ax, **fast_test)  # test axes param
    plt.close('all')
    plot_projs_topomap(read_info(triux_fname)['projs'][-1:], **fast_test)
    plt.close('all')
    plot_projs_topomap(read_info(triux_fname)['projs'][:1], ** fast_test)
    plt.close('all')
    eeg_avg = make_eeg_average_ref_proj(info)
    pytest.raises(RuntimeError, eeg_avg.plot_topomap)  # no layout
    eeg_avg.plot_topomap(info=info, **fast_test)
    plt.close('all')
开发者ID:Eric89GXL,项目名称:mne-python,代码行数:19,代码来源:test_topomap.py


示例6: test_plot_projs_topomap

def test_plot_projs_topomap():
    """Test plot_projs_topomap."""
    import matplotlib.pyplot as plt
    with warnings.catch_warnings(record=True):  # file conventions
        warnings.simplefilter('always')
        projs = read_proj(ecg_fname)
    info = read_info(raw_fname)
    fast_test = {"res": 8, "contours": 0, "sensors": False}
    plot_projs_topomap(projs, info=info, colorbar=True, **fast_test)
    plt.close('all')
    ax = plt.subplot(111)
    projs[3].plot_topomap()
    plot_projs_topomap(projs[:1], axes=ax, **fast_test)  # test axes param
    plt.close('all')
    plot_projs_topomap(read_info(triux_fname)['projs'][-1:], **fast_test)
    plt.close('all')
    plot_projs_topomap(read_info(triux_fname)['projs'][:1], ** fast_test)
    plt.close('all')
    eeg_avg = make_eeg_average_ref_proj(info)
    assert_raises(RuntimeError, eeg_avg.plot_topomap)  # no layout
    eeg_avg.plot_topomap(info=info, **fast_test)
    plt.close('all')
开发者ID:HSMin,项目名称:mne-python,代码行数:22,代码来源:test_topomap.py


示例7: test_plot_topomap

def test_plot_topomap():
    """Test topomap plotting
    """
    # evoked
    warnings.simplefilter('always', UserWarning)
    with warnings.catch_warnings(record=True):
        evoked = fiff.read_evoked(evoked_fname, 'Left Auditory',
                                  baseline=(None, 0))
        evoked.plot_topomap(0.1, 'mag', layout=layout)
        plot_evoked_topomap(evoked, None, ch_type='mag')
        times = [0.1, 0.2]
        plot_evoked_topomap(evoked, times, ch_type='eeg')
        plot_evoked_topomap(evoked, times, ch_type='grad')
        plot_evoked_topomap(evoked, times, ch_type='planar1')
        plot_evoked_topomap(evoked, times, ch_type='planar2')
        with warnings.catch_warnings(record=True):  # delaunay triangulation warning
            plot_evoked_topomap(evoked, times, ch_type='mag', layout='auto')
        assert_raises(RuntimeError, plot_evoked_topomap, evoked, 0.1, 'mag',
                      proj='interactive')  # projs have already been applied
        evoked.proj = False  # let's fake it like they haven't been applied
        plot_evoked_topomap(evoked, 0.1, 'mag', proj='interactive')
        assert_raises(RuntimeError, plot_evoked_topomap, evoked,
                      np.repeat(.1, 50))
        assert_raises(ValueError, plot_evoked_topomap, evoked, [-3e12, 15e6])

        projs = read_proj(ecg_fname)
        projs = [p for p in projs if p['desc'].lower().find('eeg') < 0]
        plot_projs_topomap(projs)
        plt.close('all')
        for ch in evoked.info['chs']:
            if ch['coil_type'] == fiff.FIFF.FIFFV_COIL_EEG:
                if ch['eeg_loc'] is not None:
                    ch['eeg_loc'].fill(0)
                ch['loc'].fill(0)
        assert_raises(RuntimeError, plot_evoked_topomap, evoked,
                      times, ch_type='eeg')
开发者ID:TalLinzen,项目名称:mne-python,代码行数:36,代码来源:test_viz.py


示例8: test_plot_topomap

def test_plot_topomap():
    """Test topomap plotting
    """
    import matplotlib.pyplot as plt
    from matplotlib.patches import Circle
    # evoked
    warnings.simplefilter('always')
    res = 16
    evoked = read_evokeds(evoked_fname, 'Left Auditory',
                          baseline=(None, 0))
    ev_bad = evoked.pick_types(meg=False, eeg=True, copy=True)
    ev_bad.pick_channels(ev_bad.ch_names[:2])
    ev_bad.plot_topomap(times=ev_bad.times[:2] - 1e-6)  # auto, should plot EEG
    assert_raises(ValueError, ev_bad.plot_topomap, ch_type='mag')
    assert_raises(TypeError, ev_bad.plot_topomap, head_pos='foo')
    assert_raises(KeyError, ev_bad.plot_topomap, head_pos=dict(foo='bar'))
    assert_raises(ValueError, ev_bad.plot_topomap, head_pos=dict(center=0))
    assert_raises(ValueError, ev_bad.plot_topomap, times=[-100])  # bad time
    assert_raises(ValueError, ev_bad.plot_topomap, times=[[0]])  # bad time

    evoked.plot_topomap(0.1, layout=layout, scale=dict(mag=0.1))
    plt.close('all')
    mask = np.zeros_like(evoked.data, dtype=bool)
    mask[[1, 5], :] = True
    evoked.plot_topomap(None, ch_type='mag', outlines=None)
    times = [0.1]
    evoked.plot_topomap(times, ch_type='eeg', res=res, scale=1)
    evoked.plot_topomap(times, ch_type='grad', mask=mask, res=res)
    evoked.plot_topomap(times, ch_type='planar1', res=res)
    evoked.plot_topomap(times, ch_type='planar2', res=res)
    evoked.plot_topomap(times, ch_type='grad', mask=mask, res=res,
                        show_names=True, mask_params={'marker': 'x'})
    plt.close('all')
    assert_raises(ValueError, evoked.plot_topomap, times, ch_type='eeg',
                  res=res, average=-1000)
    assert_raises(ValueError, evoked.plot_topomap, times, ch_type='eeg',
                  res=res, average='hahahahah')

    p = evoked.plot_topomap(times, ch_type='grad', res=res,
                            show_names=lambda x: x.replace('MEG', ''),
                            image_interp='bilinear')
    subplot = [x for x in p.get_children() if
               isinstance(x, matplotlib.axes.Subplot)][0]
    assert_true(all('MEG' not in x.get_text()
                    for x in subplot.get_children()
                    if isinstance(x, matplotlib.text.Text)))

    # Test title
    def get_texts(p):
        return [x.get_text() for x in p.get_children() if
                isinstance(x, matplotlib.text.Text)]

    p = evoked.plot_topomap(times, ch_type='eeg', res=res, average=0.01)
    assert_equal(len(get_texts(p)), 0)
    p = evoked.plot_topomap(times, ch_type='eeg', title='Custom', res=res)
    texts = get_texts(p)
    assert_equal(len(texts), 1)
    assert_equal(texts[0], 'Custom')
    plt.close('all')

    # delaunay triangulation warning
    with warnings.catch_warnings(record=True):  # can't show
        warnings.simplefilter('always')
        evoked.plot_topomap(times, ch_type='mag', layout=None, res=res)
    assert_raises(RuntimeError, plot_evoked_topomap, evoked, 0.1, 'mag',
                  proj='interactive')  # projs have already been applied

    # change to no-proj mode
    evoked = read_evokeds(evoked_fname, 'Left Auditory',
                          baseline=(None, 0), proj=False)
    with warnings.catch_warnings(record=True):
        warnings.simplefilter('always')
        evoked.plot_topomap(0.1, 'mag', proj='interactive', res=res)
    assert_raises(RuntimeError, plot_evoked_topomap, evoked,
                  np.repeat(.1, 50))
    assert_raises(ValueError, plot_evoked_topomap, evoked, [-3e12, 15e6])

    with warnings.catch_warnings(record=True):  # file conventions
        warnings.simplefilter('always')
        projs = read_proj(ecg_fname)
    projs = [pp for pp in projs if pp['desc'].lower().find('eeg') < 0]
    plot_projs_topomap(projs, res=res)
    plt.close('all')
    for ch in evoked.info['chs']:
        if ch['coil_type'] == FIFF.FIFFV_COIL_EEG:
            if ch['eeg_loc'] is not None:
                ch['eeg_loc'].fill(0)
            ch['loc'].fill(0)

    # Remove extra digitization point, so EEG digitization points
    # correspond with the EEG electrodes
    del evoked.info['dig'][85]

    pos = make_eeg_layout(evoked.info).pos
    pos, outlines = _check_outlines(pos, 'head')
    # test 1: pass custom outlines without patch

    def patch():
        return Circle((0.5, 0.4687), radius=.46,
                      clip_on=True, transform=plt.gca().transAxes)
#.........这里部分代码省略.........
开发者ID:Lem97,项目名称:mne-python,代码行数:101,代码来源:test_topomap.py


示例9: mne_raw

def mne_raw(path=None, proj=False, **kwargs):
    """
    Returns a mne.fiff.Raw object with added projections if appropriate.

    Parameters
    ----------
    path : None | str(path)
        path to the raw fiff file. If ``None``, a file can be chosen form a
        file dialog.
    proj : bool | str(path)
        Add projections from a separate file to the Raw object.
        **``False``**: No proj file will be added.
        **``True``**: ``'{raw}*proj.fif'`` will be used.
        ``'{raw}'`` will be replaced with the raw file's path minus '_raw.fif',
        and '*' will be expanded using fnmatch. If multiple files match the
        pattern, a ValueError will be raised.
        **``str``**: A custom path template can be provided, ``'{raw}'`` and
        ``'*'`` will be treated as with ``True``.
    kwargs
        Additional keyword arguments are forwarded to mne.fiff.Raw
        initialization.

    """
    if path is None:
        path = ui.ask_file("Pick a Raw Fiff File", "Pick a Raw Fiff File",
                           [('Functional image file (*.fif)', '*.fif'),
                            ('KIT Raw File (*.sqd,*.con', '*.sqd;*.con')])
        if not path:
            return

    if not os.path.isfile(path):
        raise IOError("%r is not a file" % path)

    if isinstance(path, basestring):
        _, ext = os.path.splitext(path)
        if ext.startswith('.fif'):
            raw = mne.fiff.Raw(path, **kwargs)
        elif ext in ('.sqd', '.con'):
            from mne.fiff.kit import read_raw_kit
            raw = read_raw_kit(path, **kwargs)
        else:
            raise ValueError("Unknown extension: %r" % ext)
    else:
        raw = mne.fiff.Raw(path, **kwargs)

    if proj:
        if proj == True:
            proj = '{raw}*proj.fif'

        if '{raw}' in proj:
            raw_file = raw.info['filename']
            raw_root, _ = os.path.splitext(raw_file)
            raw_root = raw_root.rstrip('raw')
            proj = proj.format(raw=raw_root)

        if '*' in proj:
            head, tail = os.path.split(proj)
            names = fnmatch.filter(os.listdir(head), tail)
            if len(names) == 1:
                proj = os.path.join(head, names[0])
            else:
                if len(names) == 0:
                    err = "No file matching %r"
                else:
                    err = "Multiple files matching %r"
                raise ValueError(err % proj)

        # add the projections to the raw file
        proj = mne.read_proj(proj)
        raw.add_proj(proj, remove_existing=True)

    return raw
开发者ID:imclab,项目名称:Eelbrain,代码行数:72,代码来源:fiff.py


示例10: run


#.........这里部分代码省略.........
                      "(one per line)", default=None)
    parser.add_option("--event-id", dest="event_id", type="int",
                      help="ID to use for events", default=998)
    parser.add_option("--event-raw", dest="raw_event_fname",
                      help="raw file to use for event detection", default=None)
    parser.add_option("--tstart", dest="tstart", type="float",
                      help="Start artifact detection after tstart seconds",
                      default=0.)
    parser.add_option("-c", "--channel", dest="ch_name", type="string",
                      help="Custom EOG channel(s), comma separated",
                      default=None)

    options, args = parser.parse_args()

    raw_in = options.raw_in

    if raw_in is None:
        parser.print_help()
        sys.exit(1)

    tmin = options.tmin
    tmax = options.tmax
    n_grad = options.n_grad
    n_mag = options.n_mag
    n_eeg = options.n_eeg
    l_freq = options.l_freq
    h_freq = options.h_freq
    eog_l_freq = options.eog_l_freq
    eog_h_freq = options.eog_h_freq
    average = options.average
    preload = options.preload
    filter_length = options.filter_length
    n_jobs = options.n_jobs
    reject = dict(grad=1e-13 * float(options.rej_grad),
                  mag=1e-15 * float(options.rej_mag),
                  eeg=1e-6 * float(options.rej_eeg),
                  eog=1e-6 * float(options.rej_eog))
    avg_ref = options.avg_ref
    no_proj = options.no_proj
    bad_fname = options.bad_fname
    event_id = options.event_id
    proj_fname = options.proj
    raw_event_fname = options.raw_event_fname
    tstart = options.tstart
    ch_name = options.ch_name

    if bad_fname is not None:
        with open(bad_fname, 'r') as fid:
            bads = [w.rstrip() for w in fid.readlines()]
        print('Bad channels read : %s' % bads)
    else:
        bads = []

    if raw_in.endswith('_raw.fif') or raw_in.endswith('-raw.fif'):
        prefix = raw_in[:-8]
    else:
        prefix = raw_in[:-4]

    eog_event_fname = prefix + '_eog-eve.fif'

    if average:
        eog_proj_fname = prefix + '_eog_avg-proj.fif'
    else:
        eog_proj_fname = prefix + '_eog-proj.fif'

    raw = mne.io.read_raw_fif(raw_in, preload=preload)

    if raw_event_fname is not None:
        raw_event = mne.io.read_raw_fif(raw_event_fname)
    else:
        raw_event = raw

    flat = None  # XXX : not exposed to the user
    projs, events = mne.preprocessing.compute_proj_eog(
        raw=raw, raw_event=raw_event, tmin=tmin, tmax=tmax, n_grad=n_grad,
        n_mag=n_mag, n_eeg=n_eeg, l_freq=l_freq, h_freq=h_freq,
        average=average, filter_length=filter_length,
        n_jobs=n_jobs, reject=reject, flat=flat, bads=bads,
        avg_ref=avg_ref, no_proj=no_proj, event_id=event_id,
        eog_l_freq=eog_l_freq, eog_h_freq=eog_h_freq,
        tstart=tstart, ch_name=ch_name, copy=False)

    raw.close()

    if raw_event_fname is not None:
        raw_event.close()

    if proj_fname is not None:
        print('Including SSP projections from : %s' % proj_fname)
        # append the eog projs, so they are last in the list
        projs = mne.read_proj(proj_fname) + projs

    if isinstance(preload, string_types) and os.path.exists(preload):
        os.remove(preload)

    print("Writing EOG projections in %s" % eog_proj_fname)
    mne.write_proj(eog_proj_fname, projs)

    print("Writing EOG events in %s" % eog_event_fname)
    mne.write_events(eog_event_fname, events)
开发者ID:SherazKhan,项目名称:mne-python,代码行数:101,代码来源:mne_compute_proj_eog.py


示例11: test_plot_topomap

def test_plot_topomap():
    """Test topomap plotting
    """
    # evoked
    warnings.simplefilter('always', UserWarning)
    res = 16
    with warnings.catch_warnings(record=True):
        evoked = read_evokeds(evoked_fname, 'Left Auditory',
                              baseline=(None, 0))
        evoked.plot_topomap(0.1, 'mag', layout=layout)
        mask = np.zeros_like(evoked.data, dtype=bool)
        mask[[1, 5], :] = True
        evoked.plot_topomap(None, ch_type='mag', outlines=None)
        times = [0.1]
        evoked.plot_topomap(times, ch_type='eeg', res=res)
        evoked.plot_topomap(times, ch_type='grad', mask=mask, res=res)
        evoked.plot_topomap(times, ch_type='planar1', res=res)
        evoked.plot_topomap(times, ch_type='planar2', res=res)
        evoked.plot_topomap(times, ch_type='grad', mask=mask, res=res,
                            show_names=True, mask_params={'marker': 'x'})
        assert_raises(ValueError, evoked.plot_topomap, times, ch_type='eeg',
                      res=res, average=-1000)
        assert_raises(ValueError, evoked.plot_topomap, times, ch_type='eeg',
                      res=res, average='hahahahah')

        p = evoked.plot_topomap(times, ch_type='grad', res=res,
                                show_names=lambda x: x.replace('MEG', ''),
                                image_interp='bilinear')
        subplot = [x for x in p.get_children() if
                   isinstance(x, matplotlib.axes.Subplot)][0]
        assert_true(all('MEG' not in x.get_text()
                        for x in subplot.get_children()
                        if isinstance(x, matplotlib.text.Text)))

        # Test title
        def get_texts(p):
            return [x.get_text() for x in p.get_children() if
                    isinstance(x, matplotlib.text.Text)]

        p = evoked.plot_topomap(times, ch_type='eeg', res=res, average=0.01)
        assert_equal(len(get_texts(p)), 0)
        p = evoked.plot_topomap(times, ch_type='eeg', title='Custom', res=res)
        texts = get_texts(p)
        assert_equal(len(texts), 1)
        assert_equal(texts[0], 'Custom')

        # delaunay triangulation warning
        with warnings.catch_warnings(record=True):
            evoked.plot_topomap(times, ch_type='mag', layout=None, res=res)
        assert_raises(RuntimeError, plot_evoked_topomap, evoked, 0.1, 'mag',
                      proj='interactive')  # projs have already been applied

        # change to no-proj mode
        evoked = read_evokeds(evoked_fname, 'Left Auditory',
                              baseline=(None, 0), proj=False)
        evoked.plot_topomap(0.1, 'mag', proj='interactive', res=res)
        assert_raises(RuntimeError, plot_evoked_topomap, evoked,
                      np.repeat(.1, 50))
        assert_raises(ValueError, plot_evoked_topomap, evoked, [-3e12, 15e6])

        projs = read_proj(ecg_fname)
        projs = [pp for pp in projs if pp['desc'].lower().find('eeg') < 0]
        plot_projs_topomap(projs, res=res)
        plt.close('all')
        for ch in evoked.info['chs']:
            if ch['coil_type'] == FIFF.FIFFV_COIL_EEG:
                if ch['eeg_loc'] is not None:
                    ch['eeg_loc'].fill(0)
                ch['loc'].fill(0)

        # Remove extra digitization point, so EEG digitization points
        # correspond with the EEG electrodes
        del evoked.info['dig'][85]
        plot_evoked_topomap(evoked, times, ch_type='eeg')

        # Remove digitization points. Now topomap should fail
        evoked.info['dig'] = None
        assert_raises(RuntimeError, plot_evoked_topomap, evoked,
                      times, ch_type='eeg')
开发者ID:agramfort,项目名称:mne-python,代码行数:79,代码来源:test_topomap.py


示例12: test_plot_topomap

def test_plot_topomap():
    """Test topomap plotting
    """
    import matplotlib.pyplot as plt
    from matplotlib.patches import Circle
    # evoked
    warnings.simplefilter('always')
    res = 16
    evoked = read_evokeds(evoked_fname, 'Left Auditory',
                          baseline=(None, 0))
    ev_bad = evoked.pick_types(meg=False, eeg=True, copy=True)
    ev_bad.pick_channels(ev_bad.ch_names[:2])
    ev_bad.plot_topomap(times=ev_bad.times[:2] - 1e-6)  # auto, should plot EEG
    assert_raises(ValueError, ev_bad.plot_topomap, ch_type='mag')
    assert_raises(TypeError, ev_bad.plot_topomap, head_pos='foo')
    assert_raises(KeyError, ev_bad.plot_topomap, head_pos=dict(foo='bar'))
    assert_raises(ValueError, ev_bad.plot_topomap, head_pos=dict(center=0))
    assert_raises(ValueError, ev_bad.plot_topomap, times=[-100])  # bad time
    assert_raises(ValueError, ev_bad.plot_topomap, times=[[0]])  # bad time
    assert_raises(ValueError, ev_bad.plot_topomap, times=[[0]])  # bad time

    evoked.plot_topomap(0.1, layout=layout, scale=dict(mag=0.1))
    plt.close('all')
    axes = [plt.subplot(221), plt.subplot(222)]
    evoked.plot_topomap(axes=axes, colorbar=False)
    plt.close('all')
    evoked.plot_topomap(times=[-0.1, 0.2])
    plt.close('all')
    mask = np.zeros_like(evoked.data, dtype=bool)
    mask[[1, 5], :] = True
    evoked.plot_topomap(ch_type='mag', outlines=None)
    times = [0.1]
    evoked.plot_topomap(times, ch_type='eeg', res=res, scale=1)
    evoked.plot_topomap(times, ch_type='grad', mask=mask, res=res)
    evoked.plot_topomap(times, ch_type='planar1', res=res)
    evoked.plot_topomap(times, ch_type='planar2', res=res)
    evoked.plot_topomap(times, ch_type='grad', mask=mask, res=res,
                        show_names=True, mask_params={'marker': 'x'})
    plt.close('all')
    assert_raises(ValueError, evoked.plot_topomap, times, ch_type='eeg',
                  res=res, average=-1000)
    assert_raises(ValueError, evoked.plot_topomap, times, ch_type='eeg',
                  res=res, average='hahahahah')

    p = evoked.plot_topomap(times, ch_type='grad', res=res,
                            show_names=lambda x: x.replace('MEG', ''),
                            image_interp='bilinear')
    subplot = [x for x in p.get_children() if
               isinstance(x, matplotlib.axes.Subplot)][0]
    assert_true(all('MEG' not in x.get_text()
                    for x in subplot.get_children()
                    if isinstance(x, matplotlib.text.Text)))

    # Test title
    def get_texts(p):
        return [x.get_text() for x in p.get_children() if
                isinstance(x, matplotlib.text.Text)]

    p = evoked.plot_topomap(times, ch_type='eeg', res=res, average=0.01)
    assert_equal(len(get_texts(p)), 0)
    p = evoked.plot_topomap(times, ch_type='eeg', title='Custom', res=res)
    texts = get_texts(p)
    assert_equal(len(texts), 1)
    assert_equal(texts[0], 'Custom')
    plt.close('all')

    # delaunay triangulation warning
    with warnings.catch_warnings(record=True):  # can't show
        warnings.simplefilter('always')
        evoked.plot_topomap(times, ch_type='mag', layout=None, res=res)
    assert_raises(RuntimeError, plot_evoked_topomap, evoked, 0.1, 'mag',
                  proj='interactive')  # projs have already been applied

    # change to no-proj mode
    evoked = read_evokeds(evoked_fname, 'Left Auditory',
                          baseline=(None, 0), proj=False)
    with warnings.catch_warnings(record=True):
        warnings.simplefilter('always')
        evoked.plot_topomap(0.1, 'mag', proj='interactive', res=res)
    assert_raises(RuntimeError, plot_evoked_topomap, evoked,
                  np.repeat(.1, 50))
    assert_raises(ValueError, plot_evoked_topomap, evoked, [-3e12, 15e6])

    with warnings.catch_warnings(record=True):  # file conventions
        warnings.simplefilter('always')
        projs = read_proj(ecg_fname)
    projs = [pp for pp in projs if pp['desc'].lower().find('eeg') < 0]
    plot_projs_topomap(projs, res=res)
    plt.close('all')
    ax = plt.subplot(111)
    plot_projs_topomap([projs[0]], res=res, axes=ax)  # test axes param
    plt.close('all')
    for ch in evoked.info['chs']:
        if ch['coil_type'] == FIFF.FIFFV_COIL_EEG:
            ch['loc'].fill(0)

    # Remove extra digitization point, so EEG digitization points
    # correspond with the EEG electrodes
    del evoked.info['dig'][85]

#.........这里部分代码省略.........
开发者ID:appscluster,项目名称:mne-python,代码行数:101,代码来源:test_topomap.py


示例13: run


#.........这里部分代码省略.........
    parser.add_option("--tstart", dest="tstart", type="float",
                      help="Start artifact detection after tstart seconds",
                      default=0.)
    parser.add_option("--qrsthr", dest="qrs_threshold", type="string",
                      help="QRS detection threshold. Between 0 and 1. Can "
                      "also be 'auto' for automatic selection",
                      default='auto')

    options, args = parser.parse_args()

    raw_in = options.raw_in

    if raw_in is None:
        parser.print_help()
        sys.exit(1)

    tmin = options.tmin
    tmax = options.tmax
    n_grad = options.n_grad
    n_mag = options.n_mag
    n_eeg = options.n_eeg
    l_freq = options.l_freq
    h_freq = options.h_freq
    ecg_l_freq = options.ecg_l_freq
    ecg_h_freq = options.ecg_h_freq
    average = options.average
    preload = options.preload
    filter_length = options.filter_length
    n_jobs = options.n_jobs
    ch_name = options.ch_name
    reject = dict(grad=1e-13 * float(options.rej_grad),
                  mag=1e-15 * float(options.rej_mag),
                  eeg=1e-6 * float(options.rej_eeg),
                  eog=1e-6 * float(options.rej_eog))
    avg_ref = options.avg_ref
    no_proj = options.no_proj
    bad_fname = options.bad_fname
    event_id = options.event_id
    proj_fname = options.proj
    raw_event_fname = options.raw_event_fname
    tstart = options.tstart
    qrs_threshold = options.qrs_threshold
    if qrs_threshold != 'auto':
        try:
            qrs_threshold = float(qrs_threshold)
        except ValueError:
            raise ValueError('qrsthr must be "auto" or a float')

    if bad_fname is not None:
        with open(bad_fname, 'r') as fid:
            bads = [w.rstrip() for w in fid.readlines()]
        print('Bad channels read : %s' % bads)
    else:
        bads = []

    if raw_in.endswith('_raw.fif') or raw_in.endswith('-raw.fif'):
        prefix = raw_in[:-8]
    else:
        prefix = raw_in[:-4]

    ecg_event_fname = prefix + '_ecg-eve.fif'

    if average:
        ecg_proj_fname = prefix + '_ecg_avg-proj.fif'
    else:
        ecg_proj_fname = prefix + '_ecg-proj.fif'

    raw = mne.io.read_raw_fif(raw_in, preload=preload)

    if raw_event_fname is not None:
        raw_event = mne.io.read_raw_fif(raw_event_fname)
    else:
        raw_event = raw

    flat = None  # XXX : not exposed to the user
    cpe = mne.preprocessing.compute_proj_ecg
    projs, events = cpe(raw, raw_event, tmin, tmax, n_grad, n_mag, n_eeg,
                        l_freq, h_freq, average, filter_length, n_jobs,
                        ch_name, reject, flat, bads, avg_ref, no_proj,
                        event_id, ecg_l_freq, ecg_h_freq, tstart,
                        qrs_threshold, copy=False)

    raw.close()

    if raw_event_fname is not None:
        raw_event.close()

    if proj_fname is not None:
        print('Including SSP projections from : %s' % proj_fname)
        # append the ecg projs, so they are last in the list
        projs = mne.read_proj(proj_fname) + projs

    if isinstance(preload, string_types) and os.path.exists(preload):
        os.remove(preload)

    print("Writing ECG projections in %s" % ecg_proj_fname)
    mne.write_proj(ecg_proj_fname, projs)

    print("Writing ECG events in %s" % ecg_event_fname)
    mne.write_events(ecg_event_fname, events)
开发者ID:Pablo-Arias,项目名称:mne-python,代码行数:101,代码来源:mne_compute_proj_ecg.py


示例14: BSD

=================================
Plot SSP projections topographies
=================================

This example shows how to display topographies of SSP projection vectors.
The projections used are the ones correcting for ECG artifacts.
"""
# Author: Alexandre Gramfort <[email protected]>
#         Denis A. Engemann <[email protected]>
#         Teon Brooks <[email protected]>

# License: BSD (3-clause)

from mne import read_proj, read_evokeds
from mne.datasets import sample

print(__doc__)

data_path = sample.data_path()

ecg_fname = data_path + '/MEG/sample/sample_audvis_ecg-proj.fif'
ave_fname = data_path + '/MEG/sample/sample_audvis-ave.fif'

evoked = read_evokeds(ave_fname, condition='Left Auditory',
                      baseline=(None, 0.))

projs = read_proj(ecg_fname)
evoked.add_proj(projs)

evoked.plot_projs_topomap()
开发者ID:Pablo-Arias,项目名称:mne-python,代码行数:30,代码来源:plot_ssp_projs_topomaps.py


示例15: run

def run():
    """Run command."""
    import matplotlib.pyplot as plt

    from mne.commands.utils import get_optparser

    parser = get_optparser(__file__)

    parser.add_option("--raw", dest="raw_in", help="Input raw FIF file", metavar="FILE")
    parser.add_option("--proj", dest="proj_in", help="Projector file", metavar="FILE", default="")
    parser.add_option("--eve", dest="eve_in", help="Events file", metavar="FILE", default="")
    parser.add_option(
        "-d", "--duration", dest="duration", type="float", help="Time window for plotting (sec)", default=10.0
    )
    parser.add_option("-t", "--start", dest="start", type="float", help="Initial start time for plotting", default=0.0)
    parser.add_option(
        "-n", "--n_channels", dest="n_channels", type="int", help="Number of channels to plot at a time", default=20
    )
    parser.add_option("-o", "--order", dest="order", help="Order for plotting ('type' or 'original')", default="type")
    parser.add_option("-p", "--preload", dest="preload", help="Preload raw data (for faster navigaton)", default=False)
    parser.add_option("-s", "--show_options", dest="show_options", help="Show projection options dialog", default=False)
    parser.add_option(
        "--allowmaxshield", dest="maxshield", help="Allow loading MaxShield processed data", action="store_true"
    )
    parser.add_option(
        "--highpass", dest="highpass", type="float", help="Display high-pass filter corner frequency", default=-1
    )
    parser.add_option(
        "--lowpass", dest="lowpass", type="float", help="Display low-pass filter corner frequency", default=-1
    )
    parser.add_option("--filtorder", dest="filtorder", type="int", help="Display filtering IIR order", default=4)
    parser.add_option(
        "--clipping",
        dest="clipping",
        help="Enable trace clipping mode, either 'clip' or " "'transparent'",
        default=None,
    )
    parser.add_option("--filterchpi", dest="filterchpi", help="Enable filtering cHPI signals.", default=None)

    options, args = parser.parse_args()

    raw_in = options.raw_in
    duration = options.duration
    start = options.start
    n_channels = options.n_channels
    order = options.order
    preload = options.preload
    show_options = options.show_options
    proj_in = options.proj_in
    eve_in = options.eve_in
    maxshield = options.maxshield
    highpass = options.highpass
    lowpass = options.lowpass
    filtorder = options.filtorder
    clipping = options.clipping
    filterchpi = options.filterchpi

    if raw_in is None:
        parser.print_help()
        sys.exit(1)

    raw = mne.io.read_raw_fif(raw_in, preload=preload, allow_maxshield=maxshield)
    if len(proj_in) > 0:
        projs = mne.read_proj(proj_in)
        raw.info["projs"] = projs
    if len(eve_in) > 0:
        events = mne.read_events(eve_in)
    else:
        events = None

    if filterchpi:
        if not preload:
            raise RuntimeError("Raw data must be preloaded for chpi, use --preload")
        raw = mne.chpi.filter_chpi(raw)

    highpass = None if highpass < 0 or filtorder <= 0 else highpass
    lowpass = None if lowpass < 0 or filtorder <= 0 else lowpass
    filtorder = 4 if filtorder <= 0 else filtorder
    raw.plot(
        duration=duration,
        start=start,
        n_channels=n_channels,
        order=order,
        show_options=show_options,
        events=events,
        highpass=highpass,
        lowpass=lowpass,
        filtorder=filtorder,
        clipping=clipping,
    )
    plt.show(block=True)
开发者ID:nwilming,项目名称:mne-python,代码行数:91,代码来源:mne_browse_raw.py


示例16: run

def run():
    import matplotlib.pyplot as plt

    from mne.commands.utils import get_optparser

    parser = get_optparser(__file__)

    parser.add_option("--raw", dest="raw_in",
                      help="Input raw FIF file", metavar="FILE")
    parser.add_option("--proj", dest="proj_in",
                      help="Projector file", metavar="FILE",
                      default='')
    parser.add_option("--eve", dest="eve_in",
                      help="Events file", metavar="FILE",
                      default='')
    parser.add_option("-d", "--duration", dest="duration", type="float",
                      help="Time window for plotting (sec)",
                      default=10.0)
    parser.add_option("-t", "--start", dest="start", type="float",
                      help="Initial start time for plotting",
                      default=0.0)
    parser.add_option("-n", "--n_channels", dest="n_channels", type="int",
                      help="Number of channels to plot at a time",
                      default=20)
    parser.add_option("-o", "--order", dest="order",
                      help="Order for plotting ('type' or 'original')",
                      default='type')
    parser.add_option("-p", "--preload", dest="preload",
                      help="Preload raw data (for faster navigaton)",
                      default=False)
    parser.add_option("-s", "--show_options", dest="show_options",
                      help="Show projection options dialog",
                      default=False)

    options, args = parser.parse_args()

    raw_in = options.raw_in
    duration = options.duration
    start = options.start
    n_channels = options.n_channels
    order = options.order
    preload = options.preload
    show_options = options.show_options
    proj_in = options.proj_in
    eve_in = options.eve_in

    if raw_in is None:
        parser.print_help()
        sys.exit(1)

    raw = mne.io.Raw(raw_in, preload=preload)
    if len(proj_in) > 0:
        projs = mne.read_proj(proj_in)
        raw.info['projs'] = projs
     

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Python mne.read_selection函数代码示例发布时间:2022-05-27
下一篇:
Python mne.read_labels_from_annot函数代码示例发布时间:2022-05-27
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap