示例#1
0
def test_flash_bem():
    """Test mne flash_bem."""
    check_usage(mne_flash_bem, force_help=True)
    # Using the sample dataset
    subjects_dir = op.join(sample.data_path(download=False), 'subjects')
    # Copy necessary files to tempdir
    tempdir = _TempDir()
    mridata_path = op.join(subjects_dir, 'sample', 'mri')
    subject_path_new = op.join(tempdir, 'sample')
    mridata_path_new = op.join(subject_path_new, 'mri')
    os.makedirs(op.join(mridata_path_new, 'flash'))
    os.makedirs(op.join(subject_path_new, 'bem'))
    shutil.copyfile(op.join(mridata_path, 'T1.mgz'),
                    op.join(mridata_path_new, 'T1.mgz'))
    shutil.copyfile(op.join(mridata_path, 'brain.mgz'),
                    op.join(mridata_path_new, 'brain.mgz'))
    # Copy the available mri/flash/mef*.mgz files from the dataset
    flash_path = op.join(mridata_path_new, 'flash')
    for kind in (5, 30):
        in_fname = op.join(mridata_path, 'flash', 'mef%02d.mgz' % kind)
        shutil.copyfile(in_fname, op.join(flash_path, op.basename(in_fname)))
    # Test mne flash_bem with --noconvert option
    # (since there are no DICOM Flash images in dataset)
    out_fnames = list()
    for kind in ('outer_skin', 'outer_skull', 'inner_skull'):
        out_fnames.append(op.join(subject_path_new, 'bem', 'outer_skin.surf'))
    assert not any(op.isfile(out_fname) for out_fname in out_fnames)
    with ArgvSetter(('-d', tempdir, '-s', 'sample', '-n'),
                    disable_stdout=False, disable_stderr=False):
        mne_flash_bem.run()
    # do they exist and are expected size
    for out_fname in out_fnames:
        _, tris = read_surface(out_fname)
        assert len(tris) == 5120
示例#2
0
def test_flash_bem():
    """Test mne flash_bem."""
    check_usage(mne_flash_bem, force_help=True)
    # Using the sample dataset
    subjects_dir = op.join(sample.data_path(download=False), 'subjects')
    # Copy necessary files to tempdir
    tempdir = _TempDir()
    mridata_path = op.join(subjects_dir, 'sample', 'mri')
    mridata_path_new = op.join(tempdir, 'sample', 'mri')
    os.makedirs(op.join(mridata_path_new, 'flash'))
    os.makedirs(op.join(tempdir, 'sample', 'bem'))
    shutil.copyfile(op.join(mridata_path, 'T1.mgz'),
                    op.join(mridata_path_new, 'T1.mgz'))
    shutil.copyfile(op.join(mridata_path, 'brain.mgz'),
                    op.join(mridata_path_new, 'brain.mgz'))
    # Copy the available mri/flash/mef*.mgz files from the dataset
    files = glob.glob(op.join(mridata_path, 'flash', 'mef*.mgz'))
    for infile in files:
        shutil.copyfile(infile, op.join(mridata_path_new, 'flash',
                                        op.basename(infile)))
    # Test mne flash_bem with --noconvert option
    # (since there are no DICOM Flash images in dataset)
    currdir = os.getcwd()
    with ArgvSetter(('-d', tempdir, '-s', 'sample', '-n'),
                    disable_stdout=False, disable_stderr=False):
        mne_flash_bem.run()
    os.chdir(currdir)
示例#3
0
文件: brain.py 项目: nikolaims/nfb
    def _assemble_forward_model_matrix(inverse_operator):
        from mne.datasets import sample

        warn('Currently info is read from the raw file. TODO: change to getting it from the stream')
        data_path = sample.data_path()
        fname_raw = data_path + '/MEG/sample/sample_audvis_raw.fif'
        raw = mne.io.read_raw_fif(fname_raw, verbose='ERROR')
        info = raw.info
        channel_cnt = info['nchan']
        I = np.identity(channel_cnt)
        dummy_raw = mne.io.RawArray(data=I, info=info, verbose='ERROR')
        dummy_raw.set_eeg_reference(verbose='ERROR');

        # Applying inverse modelling to an identity matrix gives us the forward model matrix
        snr = 1.0  # use smaller SNR for raw data
        lambda2 = 1.0 / snr ** 2
        method = "MNE"  # use sLORETA method (could also be MNE or dSPM)
        stc = mne.minimum_norm.apply_inverse_raw(dummy_raw, inverse_operator, lambda2, method)
        return stc.data
示例#4
0
def test_regression():
    """Test Ordinary Least Squares Regression
    """
    data_path = sample.data_path()
    raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
    event_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw-eve.fif'
    tmin, tmax = -0.2, 0.5
    event_id = dict(aud_l=1, aud_r=2)

    # Setup for reading the raw data
    raw = mne.io.Raw(raw_fname)
    events = mne.read_events(event_fname)[:10]
    epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=True,
                        baseline=(None, 0))
    picks = np.arange(len(epochs.ch_names))
    evoked = epochs.average(picks=picks)
    design_matrix = epochs.events[:, 1:].astype(np.float64)
    # makes the intercept
    design_matrix[:, 0] = 1
    # creates contrast: aud_l=0, aud_r=1
    design_matrix[:, 1] -= 1
    with warnings.catch_warnings(record=True) as w:
        lm = linear_regression(epochs, design_matrix, ['intercept', 'aud'])
        assert_true(w[0].category == UserWarning)
        assert_true('non-data' in '%s' % w[0].message)

    for predictor, parameters in lm.items():
        for value in parameters:
            assert_equal(value.data.shape, evoked.data.shape)

    assert_raises(ValueError, linear_regression, [epochs, epochs],
                  design_matrix)

    stc = read_source_estimate(stc_fname).crop(0, 0.02)
    stc_list = [stc, stc, stc]
    stc_gen = (s for s in stc_list)
    lm1 = linear_regression(stc_list, design_matrix[:len(stc_list)])
    lm2 = linear_regression(stc_gen, design_matrix[:len(stc_list)])

    for k in lm1:
        for v1, v2 in zip(lm1[k], lm2[k]):
            assert_array_equal(v1.data, v2.data)
示例#5
0
def test_preload_memmap():
    tmpdir = mkdtemp(dir="/Users/cjb/tmp")
    mmap_fname = opj(tmpdir, "raw_data.dat")

    # fname='ec_rest_before_tsss_mc_rsl.fif'
    data_path = sample.data_path(download=False)
    fname = data_path + "/MEG/sample/sample_audvis_raw.fif"

    raw = Raw(fname, preload=False)
    # """This function actually preloads the data"""
    # data_buffer = mmap_fname
    # raw._data = raw._read_segment(data_buffer=data_buffer)[0]
    # assert len(raw._data) == raw.info['nchan']
    # raw.preload = True
    # raw.close()
    raw.preload_data(data_buffer=mmap_fname)
    data_shape = raw._data.shape

    print("Contents of raw._data after reading from fif:")
    print(type(raw._data))
    print(raw._data[100][:5])

    del raw._data
    raw._data = np.memmap(mmap_fname, dtype="float64", mode="c", shape=data_shape)

    print("Contents of raw._data after RE-loading:")
    print(type(raw._data))
    print(raw._data[100][:5])

    raw.filter(None, 40)
    print("Contents of raw._data after filtering:")
    print(type(raw._data))
    print(raw._data[100][:5])

    # PROBLEM: Now the filtered data are IN MEMORY, but as a memmap
    # What if I'd like to continue from here using it as an ndarray?

    del raw._data

    rmtree(tmpdir, ignore_errors=True)
示例#6
0
from mne.datasets import sample
from mne.label import read_label, label_sign_flip
from mne.event import read_events
from mne.epochs import Epochs
from mne.source_estimate import read_source_estimate, VolSourceEstimate
from mne import fiff, read_cov, read_forward_solution
from mne.minimum_norm.inverse import (apply_inverse, read_inverse_operator,
                                      apply_inverse_raw, apply_inverse_epochs,
                                      make_inverse_operator,
                                      write_inverse_operator,
                                      compute_rank_inverse)
from mne.utils import _TempDir
from ...externals import six

s_path = op.join(sample.data_path(download=False), 'MEG', 'sample')
fname_inv = op.join(s_path, 'sample_audvis-meg-oct-6-meg-inv.fif')
fname_inv_fixed = op.join(s_path, 'sample_audvis-meg-oct-6-meg-fixed-inv.fif')
fname_inv_nodepth = op.join(s_path,
                            'sample_audvis-meg-oct-6-meg-nodepth'
                            '-fixed-inv.fif')
fname_inv_diag = op.join(s_path,
                         'sample_audvis-meg-oct-6-meg-diagnoise-inv.fif')
fname_vol_inv = op.join(s_path, 'sample_audvis-meg-vol-7-meg-inv.fif')
fname_data = op.join(s_path, 'sample_audvis-ave.fif')
fname_cov = op.join(s_path, 'sample_audvis-cov.fif')
fname_fwd = op.join(s_path, 'sample_audvis-meg-oct-6-fwd.fif')
fname_fwd_meeg = op.join(s_path, 'sample_audvis-meg-eeg-oct-6-fwd.fif')
fname_raw = op.join(s_path, 'sample_audvis_filt-0-40_raw.fif')
fname_event = op.join(s_path, 'sample_audvis_filt-0-40_raw-eve.fif')
fname_label = op.join(s_path, 'labels', '%s.label')
#
# License: BSD (3-clause)

import numpy as np
import pylab as pl

import mne
from mne.fiff.pick import pick_types_evoked, pick_types_forward
from mne.datasets import sample
from mne.time_frequency import iir_filter_raw, morlet
from mne.viz import plot_evoked, plot_sparse_source_estimates
from mne.simulation import generate_sparse_stc, generate_evoked

###############################################################################
# Load real data as templates
data_path = sample.data_path('/Users/sudregp/mne-python/examples/')

raw = mne.fiff.Raw(data_path + '/MEG/sample/sample_audvis_raw.fif')
proj = mne.read_proj(data_path + '/MEG/sample/sample_audvis_ecg_proj.fif')
raw.info['projs'] += proj
raw.info['bads'] = ['MEG 2443', 'EEG 053']  # mark bad channels

fwd_fname = data_path + '/MEG/sample/sample_audvis-meg-eeg-oct-6-fwd.fif'
ave_fname = data_path + '/MEG/sample/sample_audvis-no-filter-ave.fif'
cov_fname = data_path + '/MEG/sample/sample_audvis-cov.fif'

fwd = mne.read_forward_solution(fwd_fname, force_fixed=True, surf_ori=True)
fwd = pick_types_forward(fwd, meg=True, eeg=True, exclude=raw.info['bads'])

cov = mne.read_cov(cov_fname)
# -*- coding: utf-8 -*-
"""
============================
Plot an estimate of data SNR
============================

This estimates the SNR as a function of time for a set of data.
"""
# Author: Eric Larson <*****@*****.**>
#
# License: BSD (3-clause)

from os import path as op

from mne.datasets.sample import data_path
from mne.minimum_norm import read_inverse_operator
from mne import read_evokeds
from mne.viz import plot_snr_estimate

print(__doc__)

data_dir = op.join(data_path(), 'MEG', 'sample')
fname_inv = op.join(data_dir, 'sample_audvis-meg-oct-6-meg-inv.fif')
fname_evoked = op.join(data_dir, 'sample_audvis-ave.fif')

inv = read_inverse_operator(fname_inv)
evoked = read_evokeds(fname_evoked, baseline=(None, 0))[0]

plot_snr_estimate(evoked, inv)
示例#9
0
=========================

Find events from the stimulation/trigger channel in the raw data.
The plot them to get an idea of the paradigm.
"""
# Author: Alexandre Gramfort <*****@*****.**>
#
# License: BSD (3-clause)

import mne
from mne.datasets import sample
from mne.io import Raw

print(__doc__)

data_path = sample.data_path()
fname = data_path + '/MEG/sample/sample_audvis_raw.fif'

# Reading events
raw = Raw(fname)

events = mne.find_events(raw, stim_channel='STI 014')

# Writing events
mne.write_events('events.fif', events)

for ind, before, after in events[:5]:
    print("At sample %d stim channel went from %d to %d"
          % (ind, before, after))

# Plot the events to get an idea of the paradigm
示例#10
0
def test_events_sampledata():
    """Test events."""
    data_path = sample.data_path()
    raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
    raw = read_raw_fif(raw_fname, preload=True)
    raw_tmin, raw_tmax = 0, 90

    tmin, tmax = -0.2, 0.5
    event_id = dict(aud_l=1, vis_l=3)

    # select gradiometers
    picks = pick_types(raw.info,
                       meg='grad',
                       eeg=False,
                       eog=True,
                       stim=True,
                       exclude=raw.info['bads'])

    # load data with usual Epochs for later verification
    raw_cropped = raw.copy().crop(raw_tmin, raw_tmax)
    events_offline = find_events(raw_cropped)
    epochs_offline = Epochs(raw_cropped,
                            events_offline,
                            event_id=event_id,
                            tmin=tmin,
                            tmax=tmax,
                            picks=picks,
                            decim=1,
                            reject=dict(grad=4000e-13, eog=150e-6),
                            baseline=None)
    epochs_offline.drop_bad()

    # create the mock-client object
    rt_client = MockRtClient(raw)
    rt_epochs = RtEpochs(rt_client,
                         event_id,
                         tmin,
                         tmax,
                         picks=picks,
                         decim=1,
                         reject=dict(grad=4000e-13, eog=150e-6),
                         baseline=None,
                         isi_max=1.)

    rt_epochs.start()
    rt_client.send_data(rt_epochs,
                        picks,
                        tmin=raw_tmin,
                        tmax=raw_tmax,
                        buffer_size=1000)

    expected_events = epochs_offline.events.copy()
    expected_events[:, 0] = expected_events[:, 0] - raw_cropped.first_samp
    assert np.all(
        expected_events[:, 0] <= (raw_tmax - tmax) * raw.info['sfreq'])
    assert_array_equal(rt_epochs.events, expected_events)
    assert len(rt_epochs) == len(epochs_offline)

    data_picks = pick_types(epochs_offline.info,
                            meg='grad',
                            eeg=False,
                            eog=True,
                            stim=False,
                            exclude=raw.info['bads'])

    for ev_num, ev in enumerate(rt_epochs.iter_evoked()):
        if ev_num == 0:
            X_rt = ev.data[None, data_picks, :]
            y_rt = int(ev.comment)  # comment attribute contains the event_id
        else:
            X_rt = np.concatenate((X_rt, ev.data[None, data_picks, :]), axis=0)
            y_rt = np.append(y_rt, int(ev.comment))

    X_offline = epochs_offline.get_data()[:, data_picks, :]
    y_offline = epochs_offline.events[:, 2]
    assert_array_equal(X_rt, X_offline)
    assert_array_equal(y_rt, y_offline)
"""
# Authors: Alexandre Gramfort <*****@*****.**>
#          Martin Luessi <*****@*****.**>
# License: BSD (3-clause)

print __doc__

import numpy as np

from mne import fiff, read_proj, read_selection
from mne.time_frequency import compute_raw_psd
from mne.datasets import sample

###############################################################################
# Set parameters
data_path = sample.data_path("..")
raw_fname = data_path + "/MEG/sample/sample_audvis_raw.fif"
proj_fname = data_path + "/MEG/sample/sample_audvis_eog_proj.fif"

# Setup for reading the raw data
raw = fiff.Raw(raw_fname)
exclude = raw.info["bads"] + ["MEG 2443", "EEG 053"]  # bads + 2 more

# Add SSP projection vectors to reduce EOG and ECG artifacts
projs = read_proj(proj_fname)
raw.add_proj(projs, remove_existing=True)

# Pick MEG magnetometers in the Left-temporal region
selection = read_selection("Left-temporal")
picks = fiff.pick_types(raw.info, meg="mag", eeg=False, eog=False, stim=False, exclude=exclude, selection=selection)
示例#12
0
 def _guess_surfaces_dir_based_on(mne_forward_model_file_path):
     # If the forward model that was used is from the mne's sample dataset, then we can use curvatures from there
     path_to_sample = os.path.realpath(sample.data_path(verbose='ERROR'))
     if os.path.realpath(mne_forward_model_file_path).startswith(path_to_sample):
         return os.path.join(path_to_sample, "subjects", "sample", "surf")
# -*- coding: utf-8 -*-
"""
======================
Configuring MNE python
======================

This tutorial gives a short introduction to MNE configurations.
"""
import os.path as op

import mne
from mne.datasets.sample import data_path

fname = op.join(data_path(), 'MEG', 'sample', 'sample_audvis_raw.fif')
raw = mne.io.read_raw_fif(fname).crop(0, 10)
original_level = mne.get_config('MNE_LOGGING_LEVEL', 'INFO')

###############################################################################
# MNE-python stores configurations to a folder called `.mne` in the user's
# home directory, or to AppData directory on Windows. The path to the config
# file can be found out by calling :func:`mne.get_config_path`.
print(mne.get_config_path())

###############################################################################
# These configurations include information like sample data paths and plotter
# window sizes. Files inside this folder should never be modified manually.
# Let's see what the configurations contain.
print(mne.get_config())

###############################################################################
# We see fields like "MNE_DATASETS_SAMPLE_PATH". As the name suggests, this is
Reading BEM surfaces from a forward solution
============================================

Plot BEM surfaces used for forward solution generation.
"""
# Author: Jaakko Leppakangas <*****@*****.**>
#
# License: BSD (3-clause)
import os.path as op
from mayavi import mlab

import mne
from mne.datasets.sample import data_path

print(__doc__)

data_path = data_path()
fname = op.join(data_path, 'MEG', 'sample', 'sample_audvis_raw.fif')
raw = mne.io.read_raw_fif(fname)
subjects_dir = op.join(data_path, 'subjects')

###############################################################################
# Here we use :func:`mne.viz.plot_trans` with ``trans=None`` to plot only the
# surfaces without any transformations. For plotting transformation, see
# :ref:`tut_forward`.

mne.viz.plot_trans(raw.info, trans=None, subject='sample',
                   subjects_dir=subjects_dir, meg_sensors=[], eeg_sensors=[],
                   head='outer_skin', skull=['inner_skull', 'outer_skull'])
mlab.view(40, 60)
示例#15
0
from nose.tools import assert_true
import nose
import copy

from mne.datasets import sample
from mne.label import read_label, label_sign_flip
from mne.event import read_events
from mne.epochs import Epochs
from mne.source_estimate import read_source_estimate
from mne import fiff, read_cov, read_forward_solution
from mne.minimum_norm.inverse import apply_inverse, read_inverse_operator, \
    apply_inverse_raw, apply_inverse_epochs, make_inverse_operator, \
    write_inverse_operator

examples_folder = op.join(op.dirname(__file__), '..', '..', '..', 'examples')
s_path = op.join(sample.data_path(examples_folder), 'MEG', 'sample')
fname_inv = op.join(s_path, 'sample_audvis-meg-oct-6-meg-inv.fif')
fname_inv_fixed = op.join(s_path, 'sample_audvis-meg-oct-6-meg-fixed-inv.fif')
fname_vol_inv = op.join(s_path, 'sample_audvis-meg-vol-7-meg-inv.fif')
fname_data = op.join(s_path, 'sample_audvis-ave.fif')
fname_cov = op.join(s_path, 'sample_audvis-cov.fif')
fname_fwd = op.join(s_path, 'sample_audvis-meg-oct-6-fwd.fif')
fname_raw = op.join(s_path, 'sample_audvis_filt-0-40_raw.fif')
fname_event = op.join(s_path, 'sample_audvis_filt-0-40_raw-eve.fif')
fname_label = op.join(s_path, 'labels', '%s.label')

inverse_operator = read_inverse_operator(fname_inv)
inverse_operator_fixed = read_inverse_operator(fname_inv_fixed)
inverse_operator_vol = read_inverse_operator(fname_vol_inv)
label_lh = read_label(fname_label % 'Aud-lh')
label_rh = read_label(fname_label % 'Aud-rh')
示例#16
0
WEIGHT_PATH = join(NETWORK_PATH, 'weights')
NETWORK_VALIDATION_PATH = join(NETWORK_PATH, 'validation')
UTILS_PATH = join(ROOT, 'utils')
PREDICTION_PATH = join(ROOT, 'epoch_validation')

##############
# DATA MODEL #
##############

if not os.environ.get("FREESURFER_HOME"):
    print("FREESURFER_HOME environment variable not found. Have you installed Freesurfer properly?")

SPACING = 'ico3'  # Source space grid spacing. Options: ico3, ico4, ico5, oct4,  oct5 or oct6
DATA_PATH = None
#SUBJECTS_DIR = os.environ.get("SUBJECTS_DIR") or join(sample.data_path(), 'subjects')
SUBJECTS_DIR = join(sample.data_path(), 'subjects')
os.environ["SUBJECTS_DIR"] = SUBJECTS_DIR
SUBJECT_NAME = None
RAW_PATH = None
BEM_PATH = None
COV_PATH = None
TRANS_PATH = None
SRC_PATH = None
RAW_EMPTY_ROOM_PATH = None

EMPTY_SIGNAL = 0.5  # Proportion of empty signal in addition to simulated data
SNR = 1.0
N_DIPOLES = 1  # If N_DIPOLES = 1
# then only one hemisphere (left hemisphere) gets simulated.

SIMULATION_MODEL_KWARGS = get_simulation_model_kwargs(N_DIPOLES, SNR)
示例#17
0
"""Find number of examples in MNE-Python.
"""

# Author: Mainak Jas <*****@*****.**>

import os
import os.path as op
import fnmatch

from mne.datasets import sample


def recursive_search(path, pattern):
    """Auxiliary function for recursive_search of the directory.
    """
    filtered_files = list()
    for dirpath, dirnames, files in os.walk(path):
        for f in fnmatch.filter(files, pattern):
            filtered_files.append(op.realpath(op.join(dirpath, f)))

    return filtered_files


# assuming sample data is in examples dir
example_path = op.dirname(sample.data_path())
tutorial_path = op.join(op.split(example_path)[0], 'tutorials')
tutorial_files = recursive_search(tutorial_path, '*.py')
example_files = recursive_search(example_path, '*.py')
print('Number of examples is %d' % len(example_files))
print('Number of tutorials is %d' % len(tutorial_files))
          :ref:`ch_morph`.
"""
# Author: Tommy Clausner <*****@*****.**>
#
# License: BSD (3-clause)
import os

import mne
from mne.datasets import sample

print(__doc__)

###############################################################################
# Setup paths

sample_dir_raw = sample.data_path()
sample_dir = os.path.join(sample_dir_raw, 'MEG', 'sample')
subjects_dir = os.path.join(sample_dir_raw, 'subjects')

fname_stc = os.path.join(sample_dir, 'sample_audvis-meg')

###############################################################################
# Load example data

# Read stc from file
stc = mne.read_source_estimate(fname_stc, subject='sample')

###############################################################################
# Setting up SourceMorph for SourceEstimate
# -----------------------------------------
#
示例#19
0
import os.path as op

# from numpy.testing import assert_array_almost_equal

import mne
from mne.datasets import sample

examples_folder = op.join(op.dirname(__file__), '..', '..', 'examples')
data_path = sample.data_path(examples_folder)
fname = op.join(data_path, 'subjects', 'sample', 'bem',
                                        'sample-5120-5120-5120-bem-sol.fif')


def test_io_bem_surfaces():
    """Testing reading of bem surfaces
    """
    surf = mne.read_bem_surfaces(fname, add_geom=False)
    surf = mne.read_bem_surfaces(fname, add_geom=True)
    print "Number of surfaces : %d" % len(surf)
示例#20
0
import os.path as op

from mayavi import mlab

import mne
from mne.io import read_raw_fif, read_raw_ctf, read_raw_bti, read_raw_kit
from mne.io import read_raw_artemis123
from mne.datasets import sample, spm_face, testing
from mne.viz import plot_trans

print(__doc__)

bti_path = op.abspath(op.dirname(mne.__file__)) + '/io/bti/tests/data/'
kit_path = op.abspath(op.dirname(mne.__file__)) + '/io/kit/tests/data/'
raws = dict(
    Neuromag=read_raw_fif(sample.data_path() +
                          '/MEG/sample/sample_audvis_raw.fif'),
    CTF_275=read_raw_ctf(spm_face.data_path() +
                         '/MEG/spm/SPM_CTF_MEG_example_faces1_3D.ds'),
    Magnes_3600wh=read_raw_bti(op.join(bti_path, 'test_pdf_linux'),
                               op.join(bti_path, 'test_config_linux'),
                               op.join(bti_path, 'test_hs_linux')),
    KIT=read_raw_kit(op.join(kit_path, 'test.sqd')),
    Artemis123=read_raw_artemis123(op.join(testing.data_path(), 'ARTEMIS123',
                                   'Artemis_Data_2016-11-03-15h-58m_test.bin'))
)

for system, raw in raws.items():
    # We don't have coil definitions for KIT refs, so exclude them
    ref_meg = False if system == 'KIT' else True
    fig = plot_trans(raw.info, trans=None, dig=False, eeg_sensors=False,
# Authors: Richard Höchenberger <*****@*****.**>
# License: BSD (3-clause)

###############################################################################
# Load the ``sample`` dataset, and create a concatenated raw data object.

from pathlib import Path
from tempfile import NamedTemporaryFile

import mne
from mne.datasets import sample

from mne_bids import write_raw_bids, BIDSPath


data_path = Path(sample.data_path())
raw_fname = data_path / 'MEG' / 'sample' / 'sample_audvis_raw.fif'
output_path = data_path / '..' / 'MNE-sample-data-bids'
bids_path = BIDSPath(subject='01', task='audiovisual', root=output_path)

raw = mne.io.read_raw_fif(raw_fname)
raw.info['line_freq'] = 60
raw_concat = mne.concatenate_raws([raw.copy(), raw])

###############################################################################
# Trying to write these data will fail.

try:
    write_raw_bids(raw=raw_concat, bids_path=bids_path, overwrite=True)
except ValueError as e:
    print(f'Data cannot be written. Exception message was: {e}')
Configuration parameters for the study. This should be in a folder called
``library/`` inside the ``processing/`` directory.
"""

import os
import numpy as np
from mne.datasets import sample

###############################################################################
# DIRECTORIES
# -----------
# Let's set the `study path`` where the data is stored on your system
# study_path = '/Users/sophie/Dropbox/CBD_Hackaton_PreProc/MNE-sample-data/'
# study_path = '../MNE-sample-data/'
study_path = sample.data_path()

# The ``subjects_dir`` and ``meg_dir`` for reading anatomical and MEG files.

subjects_dir = os.path.join(study_path, 'subjects')
meg_dir = os.path.join(study_path, 'MEG')

###############################################################################
# DEFINE SUBJECTS
# ---------------
#
# A list of ``subject names``
# These are the ``nips`` in neurospin lingo

# To define the subjects, we use a list with all the subject names. Even if its
# a single subject, it needs to be set up as a list with a single element.
示例#23
0
文件: brain.py 项目: nikolaims/nfb
 def make_inverse_operator():
     from mne.datasets import sample
     from mne.minimum_norm import read_inverse_operator
     data_path = sample.data_path()
     filename_inv = data_path + '/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif'
     return read_inverse_operator(filename_inv, verbose='ERROR')
示例#24
0
# License: BSD (3-clause)

import numpy as np
import pylab as pl

import mne
from mne.fiff.pick import pick_types_evoked, pick_types_forward
from mne.datasets import sample
from mne.time_frequency import iir_filter_raw, morlet
from mne.viz import plot_evoked, plot_sparse_source_estimates
from mne.simulation import generate_sparse_stc, generate_evoked
import virtual_electrode as ve

###############################################################################
# Load real data as templates
data_path = sample.data_path('/Users/sudregp/mne-python/examples/')

raw = mne.fiff.Raw(data_path + '/MEG/sample/sample_audvis_raw.fif', preload=True)

fwd_fname = data_path + '/MEG/sample/sample_audvis-meg-eeg-oct-6-fwd.fif'
ave_fname = data_path + '/MEG/sample/sample_audvis-no-filter-ave.fif'
cov_fname = data_path + '/MEG/sample/sample_audvis-cov.fif'

fwd = mne.read_forward_solution(fwd_fname, force_fixed=True, surf_ori=True)
fwd = pick_types_forward(fwd, meg=True)

cov = mne.read_cov(cov_fname)

evoked_template = mne.fiff.read_evoked(ave_fname, setno=0, baseline=None)

label_names = ['Aud-lh', 'Aud-lh', 'Aud-lh', 'Aud-lh', 'Aud-lh']
示例#25
0
# -*- coding: utf-8 -*-
"""
======================
Configuring MNE python
======================

This tutorial gives a short introduction to MNE configurations.
"""
import os.path as op

import mne
from mne.datasets.sample import data_path

fname = op.join(data_path(), 'MEG', 'sample', 'sample_audvis_raw.fif')
raw = mne.io.read_raw_fif(fname).crop(0, 10)
original_level = mne.get_config('MNE_LOGGING_LEVEL', 'INFO')

###############################################################################
# MNE-python stores configurations to a folder called `.mne` in the user's
# home directory, or to AppData directory on Windows. The path to the config
# file can be found out by calling :func:`mne.get_config_path`.
print(mne.get_config_path())

###############################################################################
# These configurations include information like sample data paths and plotter
# window sizes. Files inside this folder should never be modified manually.
# Let's see what the configurations contain.
print(mne.get_config())

###############################################################################
# We see fields like "MNE_DATASETS_SAMPLE_PATH". As the name suggests, this is
示例#26
0
import os.path as op

# from numpy.testing import assert_array_almost_equal

import mne
from mne.datasets import sample

examples_folder = op.join(op.dirname(__file__), '..', '..', 'examples')
data_path = sample.data_path(examples_folder)
fname = op.join(data_path, 'subjects', 'sample', 'bem',
                'sample-5120-5120-5120-bem-sol.fif')


def test_io_bem_surfaces():
    """Testing reading of bem surfaces
    """
    surf = mne.read_bem_surfaces(fname, add_geom=False)
    surf = mne.read_bem_surfaces(fname, add_geom=True)
    print "Number of surfaces : %d" % len(surf)
示例#27
0
import os

import numpy as np
import mne
from mne.datasets import sample
from mne.minimum_norm import read_inverse_operator

from .. import MISC_CHANNEL_TYPE
from ..helpers.misc import all_upper

data_path = sample.data_path(verbose='ERROR')
sample_dir = os.path.join(data_path, 'MEG', 'sample')
neuromag_forward_file_path = os.path.join(sample_dir,
                                          'sample_audvis-meg-oct-6-fwd.fif')
standard_1005_forward_file_path = os.path.join(
    sample_dir, 'sample_1005-eeg-oct-6-fwd.fif')


def _pick_columns_from_matrix(matrix: np.ndarray, output_column_labels: list,
                              input_column_labels: list) -> np.ndarray:
    """
    From matrix take only the columns that correspond to output_column_labels - in the order of the latter.
    :param matrix: each column in matrix has a label (eg. EEG channel name)
    :param output_column_labels: labels that we need
    :param input_column_labels: labels that we have
    :return: np.ndarray with len(output_column_labels) columns and the same number of rows as matrix has.
    """

    # Choose the right columns, put zeros where label is missing
    row_count = matrix.shape[0]
    output_matrix = np.zeros((row_count, len(output_column_labels)))
示例#28
0
from mne.datasets import sample
from mne.label import read_label, label_sign_flip
from mne.event import read_events
from mne.epochs import Epochs
from mne.source_estimate import read_source_estimate, VolSourceEstimate
from mne import read_cov, read_forward_solution
from mne.fiff import read_evokeds, Raw, pick_types
from mne.minimum_norm.inverse import (apply_inverse, read_inverse_operator,
                                      apply_inverse_raw, apply_inverse_epochs,
                                      make_inverse_operator,
                                      write_inverse_operator,
                                      compute_rank_inverse)
from mne.utils import _TempDir
from ...externals import six

s_path = op.join(sample.data_path(download=False), 'MEG', 'sample')
fname_inv = op.join(s_path, 'sample_audvis-meg-oct-6-meg-inv.fif')
fname_inv_fixed = op.join(s_path, 'sample_audvis-meg-oct-6-meg-fixed-inv.fif')
fname_inv_nodepth = op.join(
    s_path, 'sample_audvis-meg-oct-6-meg-nodepth'
    '-fixed-inv.fif')
fname_inv_diag = op.join(s_path,
                         'sample_audvis-meg-oct-6-meg-diagnoise-inv.fif')
fname_vol_inv = op.join(s_path, 'sample_audvis-meg-vol-7-meg-inv.fif')
fname_data = op.join(s_path, 'sample_audvis-ave.fif')
fname_cov = op.join(s_path, 'sample_audvis-cov.fif')
fname_fwd = op.join(s_path, 'sample_audvis-meg-oct-6-fwd.fif')
fname_fwd_meeg = op.join(s_path, 'sample_audvis-meg-eeg-oct-6-fwd.fif')
fname_raw = op.join(s_path, 'sample_audvis_filt-0-40_raw.fif')
fname_event = op.join(s_path, 'sample_audvis_filt-0-40_raw-eve.fif')
fname_label = op.join(s_path, 'labels', '%s.label')
示例#29
0
import os.path as op

from mayavi import mlab

import mne
from mne.io import read_raw_fif, read_raw_ctf, read_raw_bti, read_raw_kit
from mne.datasets import sample, spm_face
from mne.viz import plot_trans

print(__doc__)

bti_path = op.abspath(op.dirname(mne.__file__)) + "/io/bti/tests/data/"
kit_path = op.abspath(op.dirname(mne.__file__)) + "/io/kit/tests/data/"
raws = dict(
    Neuromag=read_raw_fif(sample.data_path() + "/MEG/sample/sample_audvis_raw.fif"),
    CTF_275=read_raw_ctf(spm_face.data_path() + "/MEG/spm/SPM_CTF_MEG_example_faces1_3D.ds"),
    Magnes_3600wh=read_raw_bti(
        op.join(bti_path, "test_pdf_linux"), op.join(bti_path, "test_config_linux"), op.join(bti_path, "test_hs_linux")
    ),
    KIT=read_raw_kit(op.join(kit_path, "test.sqd")),
)

for system, raw in raws.items():
    # We don't have coil definitions for KIT refs, so exclude them
    ref_meg = False if system == "KIT" else True
    fig = plot_trans(
        raw.info, trans=None, dig=False, eeg_sensors=False, meg_sensors=True, coord_frame="meg", ref_meg=ref_meg
    )
    mlab.title(system)
示例#30
0
from scipy import sparse
from nose.tools import assert_true, assert_raises
import copy

from mne.datasets import sample
from mne.label import read_label, label_sign_flip
from mne.event import read_events
from mne.epochs import Epochs
from mne.source_estimate import read_source_estimate
from mne import fiff, read_cov, read_forward_solution
from mne.minimum_norm.inverse import apply_inverse, read_inverse_operator, \
    apply_inverse_raw, apply_inverse_epochs, make_inverse_operator, \
    write_inverse_operator, compute_rank_inverse
from mne.utils import _TempDir

s_path = op.join(sample.data_path(), 'MEG', 'sample')
fname_inv = op.join(s_path, 'sample_audvis-meg-oct-6-meg-inv.fif')
fname_inv_fixed = op.join(s_path, 'sample_audvis-meg-oct-6-meg-fixed-inv.fif')
fname_inv_nodepth = op.join(s_path,
                           'sample_audvis-meg-oct-6-meg-nodepth-fixed-inv.fif')
fname_inv_diag = op.join(s_path,
                         'sample_audvis-meg-oct-6-meg-diagnoise-inv.fif')
fname_vol_inv = op.join(s_path, 'sample_audvis-meg-vol-7-meg-inv.fif')
fname_data = op.join(s_path, 'sample_audvis-ave.fif')
fname_cov = op.join(s_path, 'sample_audvis-cov.fif')
fname_fwd = op.join(s_path, 'sample_audvis-meg-oct-6-fwd.fif')
fname_raw = op.join(s_path, 'sample_audvis_filt-0-40_raw.fif')
fname_event = op.join(s_path, 'sample_audvis_filt-0-40_raw-eve.fif')
fname_label = op.join(s_path, 'labels', '%s.label')

inverse_operator = read_inverse_operator(fname_inv)
"""Find number of examples in MNE-Python.
"""

# Author: Mainak Jas <*****@*****.**>

import os
import os.path as op
import fnmatch

from mne.datasets import sample


def recursive_search(path, pattern):
    """Auxiliary function for recursive_search of the directory.
    """
    filtered_files = list()
    for dirpath, dirnames, files in os.walk(path):
        for f in fnmatch.filter(files, pattern):
            filtered_files.append(op.realpath(op.join(dirpath, f)))

    return filtered_files

# assuming sample data is in examples dir
example_path = op.dirname(sample.data_path())
example_files = recursive_search(example_path, '*.py')
print('Number of examples is %d' % len(example_files))
示例#32
0
from sklearn.linear_model import LogisticRegression # Logistic Regression classifier.
'''
- TransformerMixin : Mixin class for all transformers in scikit-learn. 이 클래스는 fit(),transform()메서드를 나만의 변환기에 생성하였을 경우 마지막 메서드인 fit_transform()를 자동으로 생성
- Pipeline : 여러가지의 변환기들을 하나로 연결
- Logistic Regression (로지스틱 회귀) : 변수를 입력할 경우 이를 0~1의 범위로 변환 후 이를 통해서 확률값을 계산하고 마지막으로 분류(어떤 클래스에 대한 확률이 가장 높은지 계산)하는 지도 학습 알고리즘.
'''

# tools for plotting confusion matrices (confusion matrix : 지도 학습으로 훈련된 분류 알고리즘의 성능을 시각화한 표 / 행과 열은 각각 예측 된 클래스의 인스턴스와 실제 클래스의 인스턴스를 나타냄)
from matplotlib import pyplot as plt # matplotlib : 파이썬 기반의 시각화 라이브러리. 여러 가지 그래프를 그려주는 함수들 내장.

# while the default tensorflow ordering is 'channels_last' we set it here 
# to be explicit in case if the user has changed the default ordering
K.set_image_data_format(‘channels_last’) # Sets the value of the image data format convention.

## Process, filter and epoch the data ##
data_path = sample.data_path() # mne.datasets.sample.data_path : 샘플 데이터셋의 복사본의 로컬 경로를 가져오는 함수

# Set parameters and read data
raw_fname = data_path + ‘/MEG/sample/sample_audvis_filt_0-40_raw.fif’
event_fname = data_path + ‘/MEG/sample/sample_audvis_filt_0-40_raw-eve.fif’
tmin, tmax = -0., 1 
event_id = dict(aud_l=1, aud_r=2, vis_l=3, vis_r=4)

# Setup for reading the raw data
raw = io.Raw(raw_fname, preload=False, verbose=False)
raw.filter(2, None, method=’iir’) # replace baselining with high-pass
events = mne.read_events(event_fname)
'''
mne.io.Raw : FIF 파일 형식의 raw data.
- raw_fname (str) : load할 raw file 파일명.
 파일명이 raw.fif, raw_sss.fif, raw_tsss.fif, _meg.fif, _eeg.fif, _ieeg.fif로 끝나야 오류 발생 안 함
示例#33
0
from main import get_data
from mne.channels import read_ch_connectivity
from mne.stats import permutation_cluster_test
import numpy as np
from mne.io import read_raw_fif
from mne.datasets import sample
from mne.channels import find_layout
from mne.viz import plot_topomap
import os
import matplotlib.pyplot as plt
from scipy.signal import butter, lfilter


info = read_raw_fif(sample.data_path() + '/MEG/sample/sample_audvis_raw.fif',verbose=False).info
connectivity = read_ch_connectivity('neuromag306planar_neighb.mat', picks=None)



def butter_lowpass(cutoff, fs, order=5):
    nyq = 0.5 * fs
    normal_cutoff = cutoff / nyq
    b, a = butter(order, normal_cutoff, btype='low', analog=False)
    return b, a

def butter_lowpass_filter(data, cutoff, fs, order=5):
    b, a = butter_lowpass(cutoff, fs, order=order)
    y=np.zeros(data.shape)
    for tr in range(data.shape[0]):
        for ch in range(data.shape[2]):
            y[tr,:,ch] = lfilter(b, a, data[tr,:,ch])
    return y
示例#34
0
# First, we will load the example dataset from MNE, and have a quick look at the data.
#
# The MNE sample dataset is a combined MEG/EEG recording with an audiovisual task, as
# described `here <https://mne.tools/stable/overview/datasets_index.html?#sample>`_.
#
# For the current example, we are going to sub-select only the EEG data,
# and analyze it as continuous (non-epoched) data.
#
# Note that if you don't already have the data, the ``sample.data_path`` method
# will download the MNE sample dataset.
#

###################################################################################################

# Get the data path for the MNE example data
raw_fname = sample.data_path() + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'

# Load the file of example MNE data
raw = io.read_raw_fif(raw_fname, preload=True, verbose=False)

###################################################################################################

# Select EEG channels from the dataset
raw = raw.pick_types(meg=False, eeg=True, eog=False, exclude='bads')

# Grab the sampling rate from the data
fs = raw.info['sfreq']

###################################################################################################

# Settings for exploring an example channel of data
示例#35
0
from nose.tools import assert_true
import nose
import copy

from mne.datasets import sample
from mne.label import read_label, label_sign_flip
from mne.event import read_events
from mne.epochs import Epochs
from mne.source_estimate import read_source_estimate
from mne import fiff, read_cov, read_forward_solution
from mne.minimum_norm.inverse import apply_inverse, read_inverse_operator, \
    apply_inverse_raw, apply_inverse_epochs, make_inverse_operator, \
    write_inverse_operator

examples_folder = op.join(op.dirname(__file__), '..', '..', '..', 'examples')
s_path = op.join(sample.data_path(examples_folder), 'MEG', 'sample')
fname_inv = op.join(s_path, 'sample_audvis-meg-oct-6-meg-inv.fif')
fname_inv_fixed = op.join(s_path, 'sample_audvis-meg-oct-6-meg-fixed-inv.fif')
fname_vol_inv = op.join(s_path, 'sample_audvis-meg-vol-7-meg-inv.fif')
fname_data = op.join(s_path, 'sample_audvis-ave.fif')
fname_cov = op.join(s_path, 'sample_audvis-cov.fif')
fname_fwd = op.join(s_path, 'sample_audvis-meg-oct-6-fwd.fif')
fname_raw = op.join(s_path, 'sample_audvis_filt-0-40_raw.fif')
fname_event = op.join(s_path, 'sample_audvis_filt-0-40_raw-eve.fif')
fname_label = op.join(s_path, 'labels', '%s.label')

inverse_operator = read_inverse_operator(fname_inv)
inverse_operator_fixed = read_inverse_operator(fname_inv_fixed)
inverse_operator_vol = read_inverse_operator(fname_vol_inv)
label_lh = read_label(fname_label % 'Aud-lh')
label_rh = read_label(fname_label % 'Aud-rh')
示例#36
0
def test_volume_source_morph():
    """Test volume source estimate morph, special cases and exceptions."""
    import nibabel as nib
    data_path = sample.data_path(
        download=False)  # because testing data has no brain.mgz
    subjects_dir = os.path.join(data_path, 'subjects')
    sample_dir = os.path.join(data_path, 'MEG', 'sample')
    fname_inv_vol = os.path.join(sample_dir,
                                 'sample_audvis-meg-vol-7-meg-inv.fif')

    inverse_operator_vol = read_inverse_operator(fname_inv_vol)

    stc_vol = read_source_estimate(fname_vol, 'sample')

    # check for invalid input type
    with pytest.raises(ValueError, match='src must be an instance of'):
        SourceMorph(src=42)

    # check for raising an error if neither
    # inverse_operator_vol['src'][0]['subject_his_id'] nor subject_from is set,
    # but attempting to perform a volume morph
    src = inverse_operator_vol['src']
    src[0]['subject_his_id'] = None

    with pytest.raises(ValueError, match='subject_from is None.'):
        SourceMorph(src=src, subjects_dir=subjects_dir)

    # check infer subject_from from src[0]['subject_his_id']
    src[0]['subject_his_id'] = 'sample'

    with pytest.raises(ValueError, match='Inter-hemispheric morphing'):
        SourceMorph(src=src, subjects_dir=subjects_dir, xhemi=True)

    with pytest.raises(ValueError, match='Only surface'):
        SourceMorph(src=src, sparse=True)

    source_morph_vol = SourceMorph(subjects_dir=subjects_dir,
                                   src=inverse_operator_vol['src'],
                                   niter_affine=(1, ),
                                   niter_sdr=(1, ),
                                   spacing=7)

    assert source_morph_vol.subject_from == 'sample'

    # the brain used in sample data has shape (255, 255, 255)
    assert (tuple(
        source_morph_vol.params['DiffeomorphicMap']['domain_shape']) == (37,
                                                                         37,
                                                                         37))

    assert (tuple(
        source_morph_vol.params['AffineMap']['domain_shape']) == (37, 37, 37))

    # proofs the above
    assert source_morph_vol.spacing == 7

    # assure proper src shape
    assert source_morph_vol.params['src_shape_full'] == (src[0]['mri_height'],
                                                         src[0]['mri_depth'],
                                                         src[0]['mri_width'])

    fwd = read_forward_solution(
        os.path.join(sample_dir, 'sample_audvis-meg-vol-7-fwd.fif'))
    # check input via path to src and path to subject_to
    source_morph_vol = SourceMorph(subject_from='sample',
                                   subject_to=os.path.join(
                                       data_path, 'subjects', 'fsaverage',
                                       'mri', 'brain.mgz'),
                                   subjects_dir=subjects_dir,
                                   niter_affine=(1, ),
                                   src=fwd['src'],
                                   niter_sdr=(1, ),
                                   spacing=7)

    # check wrong subject_to
    with pytest.raises(IOError, match='cannot read file'):
        SourceMorph(subject_from='sample',
                    subject_to='42',
                    subjects_dir=subjects_dir,
                    src=fwd['src'])

    # two different ways of saving
    source_morph_vol.save(os.path.join(tempdir, 'vol'))

    # check loading
    source_morph_vol_r = read_source_morph(
        os.path.join(tempdir, 'vol-morph.h5'))

    # check for invalid file name handling ()
    with pytest.raises(IOError, match='not found'):
        read_source_morph(os.path.join(tempdir, '42'))

    # check morph
    stc_vol_morphed = source_morph_vol(stc_vol)

    # check as_volume=True
    assert isinstance(source_morph_vol(stc_vol, as_volume=True),
                      nib.Nifti1Image)

    # check for subject_from mismatch
    source_morph_vol_r.subject_from = '42'
    with pytest.raises(ValueError, match='subject_from must match'):
        source_morph_vol_r(stc_vol_morphed)

    # check if nifti is in grid morph space with voxel_size == spacing
    img_morph_res = source_morph_vol.as_volume(stc_vol_morphed,
                                               mri_resolution=False)

    # assure morph spacing
    assert isinstance(img_morph_res, nib.Nifti1Image)
    assert img_morph_res.header.get_zooms()[:3] == (7., 7., 7.)

    # assure src shape
    img_mri_res = source_morph_vol.as_volume(stc_vol_morphed,
                                             mri_resolution=True)
    assert isinstance(img_mri_res, nib.Nifti1Image)
    assert (img_mri_res.shape == (src[0]['mri_height'], src[0]['mri_depth'],
                                  src[0]['mri_width']) +
            (img_mri_res.shape[3], ))

    # check if nifti is defined resolution with voxel_size == (5., 5., 5.)
    img_any_res = source_morph_vol.as_volume(stc_vol_morphed,
                                             mri_resolution=(5., 5., 5.),
                                             fname=os.path.join(tempdir, '42'))
    assert isinstance(img_any_res, nib.Nifti1Image)
    assert img_any_res.header.get_zooms()[:3] == (5., 5., 5.)

    # check if morph outputs correct data
    assert isinstance(stc_vol_morphed, VolSourceEstimate)

    # check if loaded and saved objects contain the same
    assert (all([
        read == saved
        for read, saved in zip(sorted(source_morph_vol_r.__dict__),
                               sorted(source_morph_vol.__dict__))
    ]))

    # check __repr__
    assert isinstance(source_morph_vol.__repr__(), string_types)

    # check Nifti2Image
    assert isinstance(
        source_morph_vol.as_volume(stc_vol_morphed,
                                   mri_resolution=True,
                                   mri_space=True,
                                   format='nifti2'), nib.Nifti2Image)

    with pytest.raises(ValueError, match='subject_from does not match'):
        SourceMorph(src=src, subject_from='42')

    # check wrong format
    with pytest.raises(ValueError, match='invalid format specifier'):
        source_morph_vol.as_volume(stc_vol_morphed, format='42')

    with pytest.raises(ValueError, match='invalid format specifier'):
        stc_vol_morphed.as_volume(inverse_operator_vol['src'], format='42')
示例#37
0
import os.path as op

from mayavi import mlab

import mne
from mne.io import read_raw_fif, read_raw_ctf, read_raw_bti, read_raw_kit
from mne.io import read_raw_artemis123
from mne.datasets import sample, spm_face, testing
from mne.viz import plot_alignment

print(__doc__)

bti_path = op.abspath(op.dirname(mne.__file__)) + '/io/bti/tests/data/'
kit_path = op.abspath(op.dirname(mne.__file__)) + '/io/kit/tests/data/'
raws = {
    'Neuromag': read_raw_fif(sample.data_path() +
                             '/MEG/sample/sample_audvis_raw.fif'),
    'CTF 275': read_raw_ctf(spm_face.data_path() +
                            '/MEG/spm/SPM_CTF_MEG_example_faces1_3D.ds'),
    'Magnes 3600wh': read_raw_bti(op.join(bti_path, 'test_pdf_linux'),
                                  op.join(bti_path, 'test_config_linux'),
                                  op.join(bti_path, 'test_hs_linux')),
    'KIT': read_raw_kit(op.join(kit_path, 'test.sqd')),
    'Artemis123': read_raw_artemis123(op.join(
        testing.data_path(), 'ARTEMIS123',
        'Artemis_Data_2017-04-14-10h-38m-59s_Phantom_1k_HPI_1s.bin')),
}

for system, raw in sorted(raws.items()):
    meg = ['helmet', 'sensors']
    # We don't have coil definitions for KIT refs, so exclude them
示例#38
0
文件: victory.py 项目: nikolaims/nfb
import mne
import numpy as np
import pylab as plt
from mne.datasets import sample

# create data
fs = 500
ch_names = ['Fp1','Fp2','F7','F3','Fz','F4','F8','Ft9','Fc5','Fc1','Fc2','Fc6','Ft10','T7','C3','Cz','C4','T8','Tp9',
              'Cp5','Cp1','Cp2','Cp6','Tp10','P7','P3','Pz','P4','P8','O1','Oz','O2']
info = mne.create_info(ch_names=ch_names, sfreq=fs, montage=mne.channels.read_montage(kind='standard_1005'), ch_types=['eeg' for ch in ch_names])
data = np.random.normal(loc=0, scale=0.00001, size=(5000, len(info["ch_names"])))
raw = mne.io.RawArray(data.T, info)
#raw.plot()
#plt.show()

# create cov matrix
noise_cov = mne.compute_raw_covariance(raw)
mne.viz.plot_cov(noise_cov, raw.info)

# forward solution
fname_fwd = sample.data_path() + '/MEG/sample/sample_audvis-meg-oct-6-fwd.fif'
fwd = mne.read_forward_solution(fname_fwd, surf_ori=True)

示例#39
0
import os.path as op

from mayavi import mlab

import mne
from mne.io import Raw, read_raw_ctf, read_raw_bti, read_raw_kit
from mne.datasets import sample, spm_face
from mne.viz import plot_trans

print(__doc__)

bti_path = op.abspath(op.dirname(mne.__file__)) + '/io/bti/tests/data/'
kit_path = op.abspath(op.dirname(mne.__file__)) + '/io/kit/tests/data/'
raws = dict(
    Neuromag=Raw(sample.data_path() + '/MEG/sample/sample_audvis_raw.fif'),
    CTF_275=read_raw_ctf(spm_face.data_path() +
                         '/MEG/spm/SPM_CTF_MEG_example_faces1_3D.ds'),
    Magnes_3600wh=read_raw_bti(bti_path + 'test_pdf_linux',
                               bti_path + 'test_config_linux',
                               bti_path + 'test_hs_linux'),
    KIT=read_raw_kit(kit_path + 'test.sqd'),
)

for system, raw in raws.items():
    # We don't have coil definitions for KIT refs, so exclude them
    ref_meg = False if system == 'KIT' else True
    fig = plot_trans(raw.info, trans=None, dig=False, eeg_sensors=False,
                     meg_sensors=True, coord_frame='meg', ref_meg=ref_meg)
    mlab.title(system)
# License: BSD (3-clause)
import os

import matplotlib.pyplot as plt

import nibabel as nib
import mne
from mne.datasets import sample
from mne.minimum_norm import apply_inverse, read_inverse_operator
from nilearn.plotting import plot_glass_brain

print(__doc__)

###############################################################################
# Setup paths
sample_dir_raw = sample.data_path()
sample_dir = os.path.join(sample_dir_raw, 'MEG', 'sample')
subjects_dir = os.path.join(sample_dir_raw, 'subjects')

fname_evoked = os.path.join(sample_dir, 'sample_audvis-ave.fif')
fname_inv = os.path.join(sample_dir, 'sample_audvis-meg-vol-7-meg-inv.fif')

fname_t1_fsaverage = os.path.join(subjects_dir, 'fsaverage', 'mri',
                                  'brain.mgz')

###############################################################################
# Compute example data. For reference see
# :ref:`sphx_glr_auto_examples_inverse_plot_compute_mne_inverse_volume.py`
#
# Load data:
evoked = mne.read_evokeds(fname_evoked, condition=0, baseline=(None, 0))
示例#41
0
    """Decorator to skip test if scikit-learn >= 0.12 is not available"""
    @wraps(function)
    def dec(*args, **kwargs):
        if not check_sklearn_version(min_version='0.12'):
            from nose.plugins.skip import SkipTest
            raise SkipTest('Test %s skipped, requires scikit-learn >= 0.12'
                           % function.__name__)
        ret = function(*args, **kwargs)
        return ret
    return dec


if not lacks_mayavi:
    mlab.options.backend = 'test'

data_dir = data_path()
subjects_dir = op.join(data_dir, 'subjects')
sample_src = read_source_spaces(op.join(data_dir, 'subjects', 'sample',
                                        'bem', 'sample-oct-6-src.fif'))
ecg_fname = op.join(data_dir, 'MEG', 'sample', 'sample_audvis_ecg_proj.fif')
evoked_fname = op.join(data_dir, 'MEG', 'sample', 'sample_audvis-ave.fif')
base_dir = op.join(op.dirname(__file__), '..', 'fiff', 'tests', 'data')
fname = op.join(base_dir, 'test-ave.fif')
raw_fname = op.join(base_dir, 'test_raw.fif')
cov_fname = op.join(base_dir, 'test-cov.fif')
event_name = op.join(base_dir, 'test-eve.fif')
event_id, tmin, tmax = 1, -0.2, 0.5
n_chan = 15

raw = fiff.Raw(raw_fname, preload=False)
events = read_events(event_name)
示例#42
0
import mne
from mne.io import read_raw_fif, read_raw_ctf, read_raw_bti, read_raw_kit
from mne.io import read_raw_artemis123
from mne.datasets import sample, spm_face, testing
from mne.viz import plot_alignment, set_3d_title

print(__doc__)

###############################################################################
# Neuromag
# --------

kwargs = dict(eeg=False, coord_frame='meg', show_axes=True, verbose=True)

raw = read_raw_fif(sample.data_path() + '/MEG/sample/sample_audvis_raw.fif')
fig = plot_alignment(raw.info, meg=('helmet', 'sensors'), **kwargs)
set_3d_title(figure=fig, title='Neuromag')

###############################################################################
# CTF
# ---

raw = read_raw_ctf(spm_face.data_path() +
                   '/MEG/spm/SPM_CTF_MEG_example_faces1_3D.ds')
fig = plot_alignment(raw.info, meg=('helmet', 'sensors', 'ref'), **kwargs)
set_3d_title(figure=fig, title='CTF 275')

###############################################################################
# BTi
# ---
示例#43
0
from scipy import sparse
from nose.tools import assert_true, assert_raises
import copy

from mne.datasets import sample
from mne.label import read_label, label_sign_flip
from mne.event import read_events
from mne.epochs import Epochs
from mne.source_estimate import read_source_estimate
from mne import fiff, read_cov, read_forward_solution
from mne.minimum_norm.inverse import apply_inverse, read_inverse_operator, \
    apply_inverse_raw, apply_inverse_epochs, make_inverse_operator, \
    write_inverse_operator, compute_rank_inverse
from mne.utils import _TempDir

s_path = op.join(sample.data_path(), 'MEG', 'sample')
fname_inv = op.join(s_path, 'sample_audvis-meg-oct-6-meg-inv.fif')
fname_inv_fixed = op.join(s_path, 'sample_audvis-meg-oct-6-meg-fixed-inv.fif')
fname_inv_nodepth = op.join(s_path,
                           'sample_audvis-meg-oct-6-meg-nodepth-fixed-inv.fif')
fname_inv_diag = op.join(s_path,
                         'sample_audvis-meg-oct-6-meg-diagnoise-inv.fif')
fname_vol_inv = op.join(s_path, 'sample_audvis-meg-vol-7-meg-inv.fif')
fname_data = op.join(s_path, 'sample_audvis-ave.fif')
fname_cov = op.join(s_path, 'sample_audvis-cov.fif')
fname_fwd = op.join(s_path, 'sample_audvis-meg-oct-6-fwd.fif')
fname_raw = op.join(s_path, 'sample_audvis_filt-0-40_raw.fif')
fname_event = op.join(s_path, 'sample_audvis_filt-0-40_raw-eve.fif')
fname_label = op.join(s_path, 'labels', '%s.label')

label_lh = read_label(fname_label % 'Aud-lh')
示例#44
0
文件: utils.py 项目: wh28325/DeepEEG
def SimulateRaw(amp1=50, amp2=100, freq=1., batch=1):
    """Create simulated raw data and events of two kinds
  
  Keyword Args:
      amp1 (float): amplitude of first condition effect
      amp2 (float): ampltiude of second condition effect, 
          null hypothesis amp1=amp2
      freq (float): Frequency of simulated signal 1. for ERP 10. for alpha
      batch (int): number of groups of 255 trials in each condition
  Returns: 
      raw: simulated EEG MNE raw object with two event types
      event_id: dict of the two events for input to PreProcess()
  """

    data_path = sample.data_path()
    raw_fname = data_path + '/MEG/sample/sample_audvis_raw.fif'
    trans_fname = data_path + '/MEG/sample/sample_audvis_raw-trans.fif'
    src_fname = data_path + '/subjects/sample/bem/sample-oct-6-src.fif'
    bem_fname = (data_path +
                 '/subjects/sample/bem/sample-5120-5120-5120-bem-sol.fif')

    raw_single = mne.io.read_raw_fif(raw_fname, preload=True)
    raw_single.set_eeg_reference(projection=True)
    raw_single = raw_single.crop(0., 255.)
    raw_single = raw_single.copy().pick_types(meg=False,
                                              eeg=True,
                                              eog=True,
                                              stim=True)

    #concatenate 4 raws together to make 1000 trials
    raw = []
    for i in range(batch):
        raw.append(raw_single)
    raw = concatenate_raws(raw)

    epoch_duration = 1.

    def data_fun(amp, freq):
        """Create function to create fake signal"""
        def data_fun_inner(times):
            """Create fake signal with no noise"""
            n_samp = len(times)
            window = np.zeros(n_samp)
            start, stop = [int(ii * float(n_samp) / 2) for ii in (0, 1)]
            window[start:stop] = np.hamming(stop - start)
            data = amp * 1e-9 * np.sin(2. * np.pi * freq * times)
            data *= window
            return data

        return data_fun_inner

    times = raw.times[:int(raw.info['sfreq'] * epoch_duration)]
    src = read_source_spaces(src_fname)

    stc_zero = simulate_sparse_stc(src,
                                   n_dipoles=1,
                                   times=times,
                                   data_fun=data_fun(amp1, freq),
                                   random_state=0)
    stc_one = simulate_sparse_stc(src,
                                  n_dipoles=1,
                                  times=times,
                                  data_fun=data_fun(amp2, freq),
                                  random_state=0)

    raw_sim_zero = simulate_raw(raw,
                                stc_zero,
                                trans_fname,
                                src,
                                bem_fname,
                                cov='simple',
                                blink=True,
                                n_jobs=1,
                                verbose=True)
    raw_sim_one = simulate_raw(raw,
                               stc_one,
                               trans_fname,
                               src,
                               bem_fname,
                               cov='simple',
                               blink=True,
                               n_jobs=1,
                               verbose=True)

    stim_pick = raw_sim_one.info['ch_names'].index('STI 014')
    raw_sim_one._data[stim_pick][np.where(
        raw_sim_one._data[stim_pick] == 1)] = 2
    raw = concatenate_raws([raw_sim_zero, raw_sim_one])
    event_id = {'CondZero': 1, 'CondOne': 2}
    return raw, event_id
示例#45
0
# House funcs here so PertInv is just scripting
import mne
from _make_perturbed_forward import make_pert_forward_solution, make_pert_forward_dipole
from mne.datasets import sample
import numpy as np  # noqa
from mne.transforms import (_ensure_trans, transform_surface_to, apply_trans,
                          _get_trans, invert_transform, _print_coord_trans, _coord_frame_name,
                          Transform)
# local_data_path = 'C:\MEG\Local_mne_data'
data_path = sample.data_path()  # local copy of mne sample data
raw_fname = data_path + '/MEG/sample/sample_audvis_raw.fif'
cov_fname = data_path + '/MEG/sample/sample_audvis-cov.fif'
subjects_dir = data_path + '/subjects'
subject = 'sample'
trans = data_path + '\MEG\sample/sample_audvis_raw-trans.fif'
mri_head_t, trans = _get_trans(trans)
head_mri_t = invert_transform(mri_head_t)
cov = mne.read_cov(cov_fname)
info = mne.io.read_info(raw_fname)


def fit_dips(min_rad, max_rad, nn, sphere, perts, sourcenorm):
    testsources = dict(rr=[], nn=[])
    nsources = max_rad - min_rad + 1
    vertices = np.zeros((nsources, 1))
    for i in range(min_rad, max_rad + 1):
        ex, ey, ez = sourcenorm[0], sourcenorm[1], sourcenorm[2]
        source = [.001*i*ex, .001*i*ey, .001*i*ez]
        normal = [nn[0], nn[1], nn[2]]
        testsources['rr'].append(source)
        testsources['nn'].append(normal)
示例#46
0
## does run with jupyter notebook but then 


# In[3]:


# %load plotforward.py
# going through https://martinos.org/mne/dev/auto_tutorials/plot_forward.html
# conda activate mne 
# the sample data relies upon environment variable
# MNE_DATASETS_SAMPLE_PATH ->
# downloading sample data now

import mne
from mne.datasets import sample
data_path = sample.data_path() # original version
# MNE_DATASETS_SAMPLE_PATH = os.environ['MNE_DATASETS_SAMPLE_PATH']
#MNE_DATASETS_SAMPLE_PATH = '/usr/local/MNE-C/data'
#data_path = MNE_DATA_ROOT + '/MNE-sample-data'


# In[4]:


# the raw file containing the channel location + types
raw_fname = data_path + '/MEG/sample/sample_audvis_raw.fif'
# The paths to Freesurfer reconstructions
# subjects_dir = data_path + '/subjects' # subjects_dir = '/usr/local/freesurfer/stable5/subjects'
freesurfer_path = '/usr/local/freesurfer/stable5'
subjects_dir = data_path + '/subjects' # use the sample data as a source
# subjects_dir = freesurfer_path + '/subjects'
the selected channels.
"""
print __doc__

# Authors: Alexandre Gramfort <*****@*****.**>
#          Denis Engemann <*****@*****.**>
#
# License: BSD (3-clause)

import pylab as pl

import mne
from mne import fiff
from mne.datasets import sample
from mne.layouts import read_layout
data_path = sample.data_path('.')

###############################################################################
# Set parameters
raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'
event_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw-eve.fif'
event_id, tmin, tmax = 1, -0.2, 0.5

# Setup for reading the raw data
raw = fiff.Raw(raw_fname)
events = mne.read_events(event_fname)

# Set up pick list: EEG + MEG - bad channels (modify to your needs)
raw.info['bads'] = ['MEG 2443', 'EEG 053']
picks = fiff.pick_types(raw.info, meg='grad', eeg=False, stim=True, eog=True,
                            exclude=raw.info['bads'])
示例#48
0
"""
# Authors: Alexandre Gramfort <*****@*****.**>
#
# License: BSD (3-clause)

print __doc__

import mne
from mne import fiff
from mne.datasets import sample
from mne.minimum_norm import read_inverse_operator, source_band_induced_power

###############################################################################
# Set parameters
data_path = sample.data_path('..')
raw_fname = data_path + '/MEG/sample/sample_audvis_raw.fif'
fname_inv = data_path + '/MEG/sample/sample_audvis-meg-oct-6-meg-inv.fif'
tmin, tmax, event_id = -0.2, 0.5, 1

# Setup for reading the raw data
raw = fiff.Raw(raw_fname)
events = mne.find_events(raw)
inverse_operator = read_inverse_operator(fname_inv)

include = []
exclude = raw.info['bads'] + ['MEG 2443', 'EEG 053']  # bads + 2 more

# picks MEG gradiometers
picks = fiff.pick_types(raw.info,
                        meg=True,
示例#49
0
import os.path as op

import numpy as np
from numpy.testing import assert_array_almost_equal
from nose.tools import assert_true, assert_raises

from mne.datasets import sample
from mne import read_label, read_forward_solution
from mne.time_frequency import morlet
from mne.simulation import generate_sparse_stc, generate_evoked
from mne import read_cov
from mne.fiff import Raw, read_evokeds
from mne.fiff.pick import pick_types_evoked, pick_types_forward


data_path = sample.data_path(download=False)
fwd_fname = op.join(data_path, 'MEG', 'sample',
                    'sample_audvis-meg-eeg-oct-6-fwd.fif')
raw_fname = op.join(op.dirname(__file__), '..', '..', 'fiff', 'tests',
                    'data', 'test_raw.fif')
ave_fname = op.join(op.dirname(__file__), '..', '..', 'fiff', 'tests',
                    'data', 'test-ave.fif')
cov_fname = op.join(op.dirname(__file__), '..', '..', 'fiff', 'tests',
                    'data', 'test-cov.fif')


@sample.requires_sample_data
def test_simulate_evoked():
    """ Test simulation of evoked data """

    raw = Raw(raw_fname)
示例#50
0
from ...externals.six import string_types
import os

import numpy as np
from numpy.testing import assert_allclose
from nose.tools import (assert_equal, assert_almost_equal, assert_false,
                        assert_raises, assert_true)
import warnings

import mne
from mne.datasets import sample
from mne.io.kit.tests import data_dir as kit_data_dir
from mne.utils import _TempDir, requires_traits, requires_mne_fs_in_env


data_path = sample.data_path(download=False)
raw_path = os.path.join(data_path, 'MEG', 'sample', 'sample_audvis_raw.fif')
kit_raw_path = os.path.join(kit_data_dir, 'test_bin_raw.fif')
subjects_dir = os.path.join(data_path, 'subjects')
warnings.simplefilter('always')

tempdir = _TempDir()

trans_dst = os.path.join(tempdir, 'test-trans.fif')


@sample.requires_sample_data
@requires_traits
def test_coreg_model():
    """Test CoregModel"""
    from mne.gui._coreg_gui import CoregModel
示例#51
0
"""
# Author: Roman Goj <*****@*****.**>
#
# License: BSD (3-clause)

import mne
from mne import compute_covariance
from mne.io import Raw
from mne.datasets import sample
from mne.event import make_fixed_length_events
from mne.beamformer import tf_lcmv
from mne.viz import plot_source_spectrogram

print(__doc__)

data_path = sample.data_path()
raw_fname = data_path + '/MEG/sample/sample_audvis_raw.fif'
noise_fname = data_path + '/MEG/sample/ernoise_raw.fif'
event_fname = data_path + '/MEG/sample/sample_audvis_raw-eve.fif'
fname_fwd = data_path + '/MEG/sample/sample_audvis-meg-eeg-oct-6-fwd.fif'
subjects_dir = data_path + '/subjects'
label_name = 'Aud-lh'
fname_label = data_path + '/MEG/sample/labels/%s.label' % label_name

###############################################################################
# Read raw data, preload to allow filtering
raw = Raw(raw_fname, preload=True)
raw.info['bads'] = ['MEG 2443']  # 1 bad MEG channel

# Pick a selection of magnetometer channels. A subset of all channels was used
# to speed up the example. For a solution based on all MEG channels use
               xmin=-test_time_start / (test_time_end - test_time_start),
               xmax=(duration - test_time_start) /
               (test_time_end - test_time_start))
    return pl


def add_alpha(p_cols, alphas):
    cols = [to_rgb(c) for c in p_cols]
    return [(c[0], c[1], c[2], a) for c, a in zip(cols, alphas[-len(p_cols):])]


###############################################################################
# Load EEG data
# -------------

raw_fname = os.path.join(sample.data_path(), 'MEG', 'sample',
                         'sample_audvis_filt-0-40_raw.fif')
raw = read_raw_fif(raw_fname, preload=True, verbose=False)
sfreq = int(raw.info['sfreq'])  # 150 Hz

###############################################################################
# Offline processing of EEG data
# ------------------------------

# Apply common average reference on EEG channels
raw.pick_types(meg=False, eeg=True).apply_proj()

# Select two EEG channels for the example, preferably without artifact at the
# beginning, to have a reliable calibration
ch_names = ['EEG 010', 'EEG 015']