예제 #1
0
def test_1020_selection():
    """Test making a 10/20 selection dict."""
    base_dir = op.join(testing.data_path(download=False), 'EEGLAB')
    raw_fname = op.join(base_dir, 'test_raw.set')
    loc_fname = op.join(base_dir, 'test_chans.locs')
    raw = read_raw_eeglab(raw_fname, preload=True)
    montage = read_custom_montage(loc_fname)
    raw = raw.rename_channels(dict(zip(raw.ch_names, montage.ch_names)))
    raw.set_montage(montage)

    for input in ("a_string", 100, raw, [1, 2]):
        pytest.raises(TypeError, make_1020_channel_selections, input)

    sels = make_1020_channel_selections(raw.info)
    # are all frontal channels placed before all occipital channels?
    for name, picks in sels.items():
        fs = min([
            ii for ii, pick in enumerate(picks)
            if raw.ch_names[pick].startswith("F")
        ])
        ps = max([
            ii for ii, pick in enumerate(picks)
            if raw.ch_names[pick].startswith("O")
        ])
        assert fs > ps

    # are channels in the correct selection?
    fz_c3_c4 = [raw.ch_names.index(ch) for ch in ("Fz", "C3", "C4")]
    for channel, roi in zip(fz_c3_c4, ("Midline", "Left", "Right")):
        assert channel in sels[roi]
예제 #2
0
def load_openBCI_csv_as_raw(
        filename,
        sfreq=256.,
        ch_ind=[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
        stim_ind=16,
        replace_ch_names=None,
        verbose=1):
    """Load CSV files into a Raw object.

    Args:
        filename (str or list): path or paths to CSV files to load

    Keyword Args:
        subject_nb (int or str): subject number. If 'all', load all
            subjects.
        session_nb (int or str): session number. If 'all', load all
            sessions.
        sfreq (float): EEG sampling frequency
        ch_ind (list): indices of the EEG channels to keep
        stim_ind (int): index of the stim channel
        replace_ch_names (dict or None): dictionary containing a mapping to
            rename channels. Useful when an external electrode was used.

    Returns:
        (mne.io.array.array.RawArray): loaded EEG
        """
    n_channel = len(ch_ind)
    raw = []
    for fname in filename:
        # read the file
        data = pd.read_csv(fname, index_col=0)
        # name of each channels
        ch_names = list(data.columns)[0:n_channel] + ['Stim']
        if replace_ch_names is not None:
            ch_names = [
                c if c not in replace_ch_names.keys() else replace_ch_names[c]
                for c in ch_names
            ]
        # type of each channels
        ch_types = ['eeg'] * n_channel + ['stim']
        montage = read_custom_montage('standard_1005')
        # get data and exclude Aux channel
        data = data.values[:, ch_ind + [stim_ind]].T
        # convert in Volts (from uVolts)
        data[:-1] *= 1e-6
        # create MNE object
        info = create_info(ch_names=ch_names,
                           ch_types=ch_types,
                           sfreq=sfreq,
                           montage=montage,
                           verbose=verbose)
        raw.append(RawArray(data=data, info=info, verbose=verbose))
        print(raw)
        # concatenate all raw objects
        raws = concatenate_raws(raw, verbose=verbose)
    return raws
예제 #3
0
def test_read_locs():
    """Test reading EEGLAB locs."""
    data = read_custom_montage(locs_montage_fname)._get_ch_pos()
    assert_allclose(
        actual=np.stack([data[kk]
                         for kk in ('FPz', 'EOG1', 'F3', 'Fz')]  # 4 random chs
                        ),
        desired=[[0., 0.094979, -0.001996], [0.02933, 0.069097, -0.058226],
                 [-0.053871, 0.064321, 0.044561], [0., 0.067885, 0.066458]],
        atol=1e-6)
예제 #4
0
def test_io_set_raw(fname):
    """Test importing EEGLAB .set files."""
    montage = read_custom_montage(montage_path)
    montage.ch_names = [
        'EEG {0:03d}'.format(ii) for ii in range(len(montage.ch_names))
    ]

    kws = dict(reader=read_raw_eeglab, input_fname=fname)
    if fname.endswith('test_raw_chanloc.set'):
        with pytest.warns(RuntimeWarning,
                          match="The data contains 'boundary' events"):
            raw0 = _test_raw_reader(**kws)
    elif '_h5' in fname:  # should be safe enough, and much faster
        raw0 = read_raw_eeglab(fname, preload=True)
    else:
        raw0 = _test_raw_reader(**kws)

    # test that preloading works
    if fname.endswith('test_raw_chanloc.set'):
        raw0.set_montage(montage, on_missing='ignore')
        # crop to check if the data has been properly preloaded; we cannot
        # filter as the snippet of raw data is very short
        raw0.crop(0, 1)
    else:
        raw0.set_montage(montage)
        raw0.filter(1,
                    None,
                    l_trans_bandwidth='auto',
                    filter_length='auto',
                    phase='zero')

    # test that using uint16_codec does not break stuff
    read_raw_kws = dict(input_fname=fname, preload=False, uint16_codec='ascii')
    if fname.endswith('test_raw_chanloc.set'):
        with pytest.warns(RuntimeWarning,
                          match="The data contains 'boundary' events"):
            raw0 = read_raw_eeglab(**read_raw_kws)
            raw0.set_montage(montage, on_missing='ignore')
    else:
        raw0 = read_raw_eeglab(**read_raw_kws)
        raw0.set_montage(montage)

    # Annotations
    if fname != raw_fname_chanloc:
        assert len(raw0.annotations) == 154
        assert set(raw0.annotations.description) == {'rt', 'square'}
        assert_array_equal(raw0.annotations.duration, 0.)
예제 #5
0
def set_raw_montage_from_locs(raw: Raw,
                              path_to_locs: str,
                              show_montage: False = bool) -> Raw:
    """
    Reads channels locations from a file and applies them to Raw instance.
    Parameters
    ----------
    raw: the Raw instance with missing channel locations
    path_to_locs: the full path to the channel locations file
    (e.g. Starstim20.locs)
    show_montage: whether to show channel locations in a plot

    Returns
    -------
    Raw instance
    """
    if Path(path_to_locs).exists():
        montage = read_custom_montage(path_to_locs)

        # check if there are any channels not in raw instance
        missing_channel_locations = [
            ch_name for ch_name in raw.ch_names
            if ch_name not in montage.ch_names
        ]
        if missing_channel_locations:
            logger.info(f"There are {len(missing_channel_locations)} channel "
                        f"positions not present in the "
                        f"{Path(path_to_locs).stem} file.")
            logger.info(f"Assuming these ({missing_channel_locations}) "
                        f"are not EEG channels, dropping them from Raw.")

            raw.drop_channels(missing_channel_locations)

        logger.info("Applying channel locations to Raw instance.")
        raw.set_montage(montage)

        if show_montage:
            raw.plot_sensors(show_names=True)

    else:
        logger.warning(f"Montage file {path_to_locs} path does not exist! "
                       f"Returning unmodified raw.")

    return raw
예제 #6
0
# Derivatives directory
deriv_dir = data_dir / 'derivatives' / f'task-{task}'
deriv_dir.mkdir(parents=True, exist_ok=True)

# Analysis Directory
analysis_dir = data_dir / 'analyses' / f'task-{task}'
analysis_dir.mkdir(parents=True, exist_ok=True)

# Report directory
report_dir = deriv_dir / 'reports'
report_dir.mkdir(parents=True, exist_ok=True)

# BVEF File
bvef_file = Path('..') / 'brainvision_64.bvef'
bv_montage = read_custom_montage(bvef_file, head_size=.08)

# Define event dictionary
event_dict = {
    'bot/stan/a1': 10,
    'bot/stan/a2': 11,
    'bot/stan/a3': 12,
    'bot/stan/a4': 13,
    'bot/stan/a5': 14,
    'bot/stan/a6': 15,
    'bot/stan/a7': 16,
    'bot/stan/a8': 17,
    'bot/odd/a1': 20,
    'bot/odd/a2': 21,
    'bot/odd/a3': 22,
    'bot/odd/a4': 23,
예제 #7
0
#     FreeSurfer surface RAS (called "mri" in MNE) coordinates using the
#     transformations that FreeSurfer computes during reconstruction.
#     ``nibabel`` calls this transformation the ``vox2ras_tkr`` transform
#     and operates in millimeters, so we can load it, convert it to meters,
#     and then apply it::
#
#         >>> pos_vox = ...  # loaded from a file somehow
#         >>> img = nibabel.load(fname_T1)
#         >>> vox2mri_t = img.header.get_vox2ras_tkr()  # voxel -> mri trans
#         >>> pos_mri = mne.transforms.apply_trans(vox2mri_t, pos_vox)
#         >>> pos_mri /= 1000.  # mm -> m
#
#     You can also verify that these are correct (or manually convert voxels
#     to MRI coords) by looking at the points in Freeview or tkmedit.

dig_montage = read_custom_montage(fname_mon, head_size=None, coord_frame='mri')
dig_montage.plot()

##############################################################################
# We can then get our transformation from the MRI coordinate frame (where our
# points are defined) to the head coordinate frame from the object.

trans = compute_native_head_t(dig_montage)
print(trans)  # should be mri->head, as the "native" space here is MRI

##############################################################################
# Let's apply this digitization to our dataset, and in the process
# automatically convert our locations to the head coordinate frame, as
# shown by :meth:`~mne.io.Raw.plot_sensors`.

raw = mne.io.read_raw_fif(fname_raw)
    #eegData = eegData[:, eegStartIndex:eegStartIndex+4000]
    #eegData = eeg.fillExcludedChannels(eegData, excludedChannels[0, 0])
    nElectrodes = eegData.shape[0]

    fs = 1000
    frameSize = 2000
    downsampleFactor = 8
    eegData = scipy.signal.decimate(eegData, downsampleFactor)
    fs = fs / downsampleFactor
    frameSize = int(frameSize / downsampleFactor)

    eegDataSplit = eeg.eegSplit(eegData, frameSize)

    thresholds = [12500]

    montage = channels.read_custom_montage(electrodeLocationsPath)
    eegInfo = mne.create_info(montage.ch_names, fs, "eeg")
    raw = io.RawArray(eegData * 0.000001, eegInfo, 0)
    raw.set_montage(montage)
    # raw.filter(1, 40)
    # ica = mne.preprocessing.ICA(n_components=20, random_state=97, max_iter=800)
    # ica.fit(raw)
    # ica.plot_properties(raw)

    #print(montage)
    #viz.plot_montage(montage)

    for t in thresholds:
        print("Current Thresh: " + str(t))
        for i in range(0, nFrames):
            print("Current frame: " + str(i))
예제 #9
0
def read_brainvision(fname, apply_montage=True, preload=False):
    """Load brainvision data. If apply_montage=True, load and apply the standard
    montage for the 64-channel acticap. If add_ref=True add a reference
    channel with all zeros"""

    raw = read_raw_brainvision(fname, preload=preload)
    if apply_montage:
        mapping = {
            "1": "Fp1",
            "2": "Fp2",
            "3": "F7",
            "4": "F3",
            "5": "Fz",
            "6": "F4",
            "7": "F8",
            "8": "FC5",
            "9": "FC1",
            "10": "FC2",
            "11": "FC6",
            "12": "T7",
            "13": "C3",
            "14": "Cz",
            "15": "C4",
            "16": "T8",
            "17": "TP9",
            "18": "CP5",
            "19": "CP1",
            "20": "CP2",
            "21": "CP6",
            "22": "TP10",
            "23": "P7",
            "24": "P3",
            "25": "Pz",
            "26": "P4",
            "27": "P8",
            "28": "PO9",
            "29": "O1",
            "30": "Oz",
            "31": "O2",
            "32": "PO10",
            "33": "AF7",
            "34": "AF3",
            "35": "AF4",
            "36": "AF8",
            "37": "F5",
            "38": "F1",
            "39": "F2",
            "40": "F6",
            "41": "FT9",
            "42": "FT7",
            "43": "FC3",
            "44": "FC4",
            "45": "FT8",
            "46": "FT10",
            "47": "C5",
            "48": "C1",
            "49": "C2",
            "50": "C6",
            "51": "TP7",
            "52": "CP3",
            "53": "CPz",
            "54": "CP4",
            "55": "TP8",
            "56": "P5",
            "57": "P1",
            "58": "P2",
            "59": "P6",
            "60": "PO7",
            "61": "PO3",
            "62": "POz",
            "63": "PO4",
            "64": "PO8"
        }
        raw.rename_channels(mapping)
        montage = read_custom_montage(
            Path(os.environ["EXPDIR"]) / Path("AS-96_REF.bvef"))
        raw.set_montage(montage)
    return raw
예제 #10
0
#Loading freesurfer samples
data_path = mne.datasets.sample.data_path()
subjects_dir = op.join(data_path, 'subjects')
fname_raw = op.join(data_path, 'MEG', 'sample', 'sample_audvis_raw.fif')
bem_dir = op.join(subjects_dir, 'sample', 'bem')
fname_bem = op.join(bem_dir, 'sample-5120-5120-5120-bem-sol.fif')
fname_src = op.join(bem_dir, 'sample-oct-6-src.fif')

#Loading channel
channel_dir='channel location pathway'


#Loading custom montage directory and creating montage
fname_montage_custom='.loc file of channel locations (from eeglab)'
dig_montage = read_custom_montage(fname_montage_custom, head_size=0.095, coord_frame='mri')

#Plotting Montage to check for placement
dig_montage.plot()
fig = dig_montage.plot(kind='3d')
fig.gca().view_init(azim=70, elev=15)
#dig_montage.plot(kind='topomap', show_names=False)

#Matrix of head configuration of montage
trans = compute_native_head_t(dig_montage)

#Defining channel information
channel_names = ['AFz','C3','C4','CPz','Cz','F3','F4','F7','F8','FC1','FC2','FC5','FC6','Fp1','Fp2','FT9','FT10','Fz','T7','T8']
n_channels = 20
channel_types=['eeg']*20 
sampling_rate = 1000
예제 #11
0
"""Test reading BESA fileformats."""
import inspect
import pytest
from pathlib import Path

from mne.io import read_evoked_besa
from mne.channels import read_custom_montage

FILE = Path(inspect.getfile(inspect.currentframe()))
data_dir = FILE.parent / 'data'
avr_file = data_dir / 'simulation.avr'
avr_file_oldstyle = data_dir / 'simulation_oldstyle.avr'
mul_file = data_dir / 'simulation.mul'
montage = read_custom_montage(data_dir / 'simulation.elp')


@pytest.mark.filterwarnings("ignore:Fiducial point nasion not found")
@pytest.mark.parametrize('fname', (avr_file, avr_file_oldstyle, mul_file))
def test_read_evoked_besa(fname):
    """Test reading MESA .avr and .mul files."""
    ev = read_evoked_besa(fname)
    assert len(ev.ch_names) == len(ev.data) == 33
    assert ev.info['sfreq'] == 200
    assert ev.tmin == -0.1
    assert len(ev.times) == 200
    assert ev.ch_names == montage.ch_names
    assert ev.comment == 'simulation'


def test_read_evoked_besa_avr_incomplete(tmp_path):
    """Test reading incomplete BESA .avr files."""