How to use mne - 10 common examples

To help you get started, we’ve selected a few mne examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github mne-tools / mne-python / mne / time_frequency / psd.py View on Github external
-------
    psds : ndarray, shape (..., n_freqs) or (..., n_freqs, n_segments)
        The power spectral densities. If ``average='mean`` or
        ``average='median'``, the returned array will have the same shape
        as the input data plus an additional frequency dimension.
        If ``average=None``, the returned array will have the same shape as
        the input data plus two additional dimensions corresponding to
        frequencies and the unaggregated segments, respectively.
    freqs : ndarray, shape (n_freqs,)
        The frequencies.

    Notes
    -----
    .. versionadded:: 0.14.0
    """
    _check_option('average', average, (None, 'mean', 'median'))

    dshape = x.shape[:-1]
    n_times = x.shape[-1]
    x = x.reshape(-1, n_times)

    # Prep the PSD
    n_fft, n_per_seg, n_overlap = _check_nfft(n_times, n_fft, n_per_seg,
                                              n_overlap)
    win_size = n_fft / float(sfreq)
    logger.info("Effective window size : %0.3f (s)" % win_size)
    freqs = np.arange(n_fft // 2 + 1, dtype=float) * (sfreq / n_fft)
    freq_mask = (freqs >= fmin) & (freqs <= fmax)
    freqs = freqs[freq_mask]

    # Parallelize across first N-1 dimensions
    x_splits = np.array_split(x, n_jobs)
github mne-tools / mne-python / mne / viz / _3d.py View on Github external
idx = np.argmax(dipole.gof)
    elif idx == 'amplitude':
        idx = np.argmax(np.abs(dipole.amplitude))
    else:
        idx = _ensure_int(idx, 'idx', 'an int or one of ["gof", "amplitude"]')

    vox, ori, pos, data = _get_dipole_loc(
        dipole, trans, subject, subjects_dir, coord_frame)

    dims = len(data)  # Symmetric size assumed.
    dd = dims // 2
    if ax is None:
        fig = plt.figure()
        ax = Axes3D(fig)
    else:
        _validate_type(ax, Axes3D, "ax", "Axes3D")
        fig = ax.get_figure()

    gridx, gridy = np.meshgrid(np.linspace(-dd, dd, dims),
                               np.linspace(-dd, dd, dims), indexing='ij')
    params = {'ax': ax, 'data': data, 'idx': idx, 'dipole': dipole,
              'vox': vox, 'gridx': gridx, 'gridy': gridy,
              'ori': ori, 'coord_frame': coord_frame,
              'show_all': show_all, 'pos': pos,
              'color': color, 'highlight_color': highlight_color}
    _plot_dipole(**params)
    ax.view_init(elev=30, azim=-140)

    callback_func = partial(_dipole_changed, params=params)
    fig.canvas.mpl_connect('scroll_event', callback_func)
    fig.canvas.mpl_connect('key_press_event', callback_func)
github mne-tools / mne-python / examples / testing / test_bem_commands.py View on Github external
# -*- coding: utf-8 -*-
import os
from os import path as op
import shutil
import warnings
from nose.tools import assert_true

from mne.commands import mne_watershed_bem
from mne.utils import (run_tests_if_main, _TempDir, ArgvSetter)
from mne.datasets import sample


subjects_dir = op.join(sample.data_path(download=False), 'subjects')

warnings.simplefilter('always')


def check_usage(module, force_help=False):
    """Helper to ensure we print usage"""
    args = ('--help',) if force_help else ()
    with ArgvSetter(args) as out:
        try:
            module.run()
        except SystemExit:
            pass
        assert_true('Usage: ' in out.stdout.getvalue())


def test_watershed_bem():
github mne-tools / mne-python / mne / io / nirx / nirx.py View on Github external
subject_info = {}
        names = inf['name'].split()
        if len(names) > 0:
            subject_info['first_name'] = \
                inf['name'].split()[0].replace("\"", "")
        if len(names) > 1:
            subject_info['last_name'] = \
                inf['name'].split()[-1].replace("\"", "")
        if len(names) > 2:
            subject_info['middle_name'] = \
                inf['name'].split()[-2].replace("\"", "")
        # subject_info['birthday'] = inf['age']  # TODO: not formatted properly
        subject_info['sex'] = inf['gender'].replace("\"", "")
        # Recode values
        if subject_info['sex'] in {'M', 'Male', '1'}:
            subject_info['sex'] = FIFF.FIFFV_SUBJ_SEX_MALE
        elif subject_info['sex'] in {'F', 'Female', '2'}:
            subject_info['sex'] = FIFF.FIFFV_SUBJ_SEX_FEMALE
        # NIRStar does not record an id, or handedness by default

        # Read header file
        # The header file isn't compliant with the configparser. So all the
        # text between comments must be removed before passing to parser
        with open(files['hdr']) as f:
            hdr_str = f.read()
        hdr_str = re.sub('#.*?#', '', hdr_str, flags=re.DOTALL)
        hdr = RawConfigParser()
        hdr.read_string(hdr_str)

        # Check that the file format version is supported
        if not any(item == hdr['GeneralInfo']['NIRStar'] for item in
                   ["\"15.0\"", "\"15.2\""]):
github alexandrebarachant / pyRiemann / examples / stats / oneWay_Manova_ERP.py View on Github external
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=True)
raw.filter(2, None, method='iir')  # replace baselining with high-pass
events = mne.read_events(event_fname)

raw.info['bads'] = ['MEG 2443']  # set bad channels
picks = mne.pick_types(raw.info, meg='grad', eeg=False, stim=False, eog=False,
                       exclude='bads')

# Read epochs
epochs = mne.Epochs(raw, events, event_id, tmin, tmax, proj=False,
                    picks=picks, baseline=None, preload=True, verbose=False)

labels = epochs.events[::5, -1]

# get epochs
epochs_data = epochs.get_data()[::5]

n_perms = 100
###############################################################################
# Pairwise distance based permutation test
###############################################################################
t_init = time()
p_test = PermutationDistance(n_perms, metric='riemann', mode='pairwise',
                             estimator=XdawnCovariances(2))
p, F = p_test.test(epochs_data, labels)
duration = time() - t_init
github mne-tools / mne-python / examples / preprocessing / plot_run_ica.py View on Github external
# Read and preprocess the data. Preprocessing consists of:
#
# - MEG channel selection
# - 1-30 Hz band-pass filter
# - epoching -0.2 to 0.5 seconds with respect to events

data_path = sample.data_path()
raw_fname = data_path + '/MEG/sample/sample_audvis_filt-0-40_raw.fif'

raw = mne.io.read_raw_fif(raw_fname, preload=True)
raw.pick_types(meg=True, eeg=False, exclude='bads', stim=True)
raw.filter(1, 30, fir_design='firwin')

# longer + more epochs for more artifact exposure
events = mne.find_events(raw, stim_channel='STI 014')
epochs = mne.Epochs(raw, events, event_id=None, tmin=-0.2, tmax=0.5)

###############################################################################
# Fit ICA model using the FastICA algorithm, detect and plot components
# explaining ECG artifacts.

ica = ICA(n_components=0.95, method='fastica').fit(epochs)

ecg_epochs = create_ecg_epochs(raw, tmin=-.5, tmax=.5)
ecg_inds, scores = ica.find_bads_ecg(ecg_epochs)

ica.plot_components(ecg_inds)

###############################################################################
# Plot properties of ECG components:
ica.plot_properties(epochs, picks=ecg_inds)
github mne-tools / mne-hcp / hcp / preprocessing.py View on Github external
on decimated data. This is legitimate because the linear model does
       not have any representation of time, only the distributions
       matter.

    Parameters
    ----------
    raw : instance of Raw
        The BTi/4D raw data.
    decim_fit : int
        The decimation factor used for fitting the model.
        Defaults to 100.
    """
    from sklearn.linear_model import LinearRegression

    meg_picks = mne.pick_types(raw.info, ref_meg=False, meg=True)
    ref_picks = mne.pick_types(raw.info, ref_meg=True, meg=False)
    if len(ref_picks) == 0:
        raise ValueError('Could not find meg ref channels.')

    estimator = LinearRegression(normalize=True)  # ref MAG + GRAD
    Y_pred = estimator.fit(
        raw[ref_picks][0][:, ::decim_fit].T,
        raw[meg_picks][0][:, ::decim_fit].T).predict(
        raw[ref_picks][0].T)
    raw._data[meg_picks] -= Y_pred.T
github mne-tools / mne-python / mne / io / artemis123 / utils.py View on Github external
def _load_mne_locs(fname=None):
    """Load MNE locs structure from file (if exists) or recreate it."""
    if (not fname):
        # find input file
        resource_dir = op.join(op.dirname(op.abspath(__file__)), 'resources')
        fname = op.join(resource_dir, 'Artemis123_mneLoc.csv')

    if not op.exists(fname):
        raise IOError('MNE locs file "%s" does not exist' % (fname))

    logger.info('Loading mne loc file {}'.format(fname))
    locs = dict()
    with open(fname, 'r') as fid:
        for line in fid:
            vals = line.strip().split(',')
            locs[vals[0]] = np.array(vals[1::], np.float)

    return locs
github mne-tools / mne-python / mne / chpi.py View on Github external
The start time of each fitting interval
    chpi_digs :ndarray, shape (N, 1)
        Array of dig structures containing the cHPI locations. Includes
        goodness of fit for each cHPI.

    Notes
    -----
    The number of time points ``N`` will depend on the velocity of head
    movements as well as ``t_step_max`` and ``t_step_min``.

    See Also
    --------
    read_head_pos
    write_head_pos
    """
    _check_option('too_close', too_close, ['raise', 'warning', 'info'])

    # extract initial geometry from info['hpi_results']
    hpi_dig_head_rrs = _get_hpi_initial_fit(raw.info)

    # extract hpi system information
    hpi = _setup_hpi_struct(raw.info, int(round(t_window * raw.info['sfreq'])))

    # move to device coords
    head_dev_t = invert_transform(raw.info['dev_head_t'])['trans']
    hpi_dig_dev_rrs = apply_trans(head_dev_t, hpi_dig_head_rrs)

    # setup last iteration structure
    last = dict(sin_fit=None, fit_time=t_step_min,
                coil_dev_rrs=hpi_dig_dev_rrs)

    t_begin = raw.times[0]
github mne-tools / mne-python / mne / stats / cluster_level.py View on Github external
def _permutation_cluster_test(X, threshold, n_permutations, tail, stat_fun,
                              connectivity, n_jobs, seed, max_step,
                              exclude, step_down_p, t_power, out_type,
                              check_disjoint, buffer_size):
    n_jobs = check_n_jobs(n_jobs)
    """Aux Function.

    Note. X is required to be a list. Depending on the length of X
    either a 1 sample t-test or an F test / more sample permutation scheme
    is elicited.
    """
    _check_option('out_type', out_type, ['mask', 'indices'])
    if not isinstance(threshold, dict):
        threshold = float(threshold)
        if (tail < 0 and threshold > 0 or tail > 0 and threshold < 0 or
                tail == 0 and threshold < 0):
            raise ValueError('incompatible tail and threshold signs, got '
                             '%s and %s' % (tail, threshold))

    # check dimensions for each group in X (a list at this stage).
    X = [x[:, np.newaxis] if x.ndim == 1 else x for x in X]
    n_samples = X[0].shape[0]
    n_times = X[0].shape[1]

    sample_shape = X[0].shape[1:]
    for x in X:
        if x.shape[1:] != sample_shape:
            raise ValueError('All samples mush have the same size')