示例#1
0
def test_update_stim_channel():
    sample_folder = mne.datasets.sample.data_path()
    sample_fname = os.path.join(sample_folder, 'MEG', 'sample',
                                'sample_audvis_raw.fif')
    raw = mne.io.read_raw_fif(sample_fname, preload=True)

    events_before = find_events(raw)

    update_stim_channel(raw, [[100, 0, 1]])

    events_after = find_events(raw)

    assert (len(events_after) == len(events_before) + 1)
示例#2
0
    def run(self):
        try:
            subject = self.experiment.active_subject
            if not subject:
                return ""

            raw = subject.get_raw()

            stim_ch = find_stim_channel(raw)
            if not stim_ch:
                return ""

            events = find_events(raw, stim_ch=stim_ch)
            if events is None:
                return ""

            bins = np.bincount(events[:,2])
            event_counts = dict()
            for event_id in set(events[:, 2]):
                event_counts[event_id] = bins[event_id]

            events_string = ""
            for key, value in event_counts.items():
                events_string += 'Trigger %s, %s events\n' % (str(key), str(value))

            return events_string
        except Exception as exc:
            return ""
示例#3
0
def test_evoked():
    with tempfile.TemporaryDirectory() as dirpath:

        sample_folder = mne.datasets.sample.data_path()
        sample_fname = os.path.join(sample_folder, 'MEG', 'sample', 'sample_audvis_raw.fif')

        name = 'TestEvoked'
        cond_name = 'cond_1'
        evoked_dir = os.path.join(dirpath, 'evoked')

        raw = mne.io.read_raw_fif(sample_fname, preload=True)
        events = find_events(raw, id_=1)
        mne_evoked = mne.Epochs(raw, events).average()

        # As meggie-style evokeds can be based on multiple mne evoked objects,
        # content is dict-type.
        content = {cond_name: mne_evoked}

        params = {}

        # Create meggie-Evoked object
        # and save it to evoked directory
        evoked = Evoked(name, evoked_dir, params, content=content)
        ensure_folders([evoked_dir])
        evoked.save_content()

        # Creating meggie-Evoked object with same name and folder should allow
        # accessing the saved content.
        loaded_evoked = Evoked(name, evoked_dir, params)

        assert(loaded_evoked.content[cond_name].nave == 72)
示例#4
0
def test_epochs():
    with tempfile.TemporaryDirectory() as dirpath:

        sample_folder = mne.datasets.sample.data_path()
        sample_fname = os.path.join(sample_folder, 'MEG', 'sample', 'sample_audvis_raw.fif')

        raw = mne.io.read_raw_fif(sample_fname, preload=True)
        events = find_events(raw, id_=1)
        mne_epochs = mne.Epochs(raw, events)

        name = 'TestEpochs'
        epochs_dir = os.path.join(dirpath, 'epochs')

        params = {}

        # Create meggie-Epochs object with mne-Epochs stored within
        # and save it to epochs directory
        epochs = Epochs(name, epochs_dir, params, content=mne_epochs)
        ensure_folders([epochs_dir])
        epochs.save_content()

        # Creating meggie-Epochs object with same name and folder should allow
        # accessing the saved content
        loaded_epochs = Epochs(name, epochs_dir, params)

        assert(epochs.count == loaded_epochs.count == 72)
示例#5
0
def test_find_events():
    sample_folder = mne.datasets.sample.data_path()
    sample_fname = os.path.join(sample_folder, 'MEG', 'sample',
                                'sample_audvis_raw.fif')
    raw = mne.io.read_raw_fif(sample_fname, preload=True)

    id_ = 1
    mask = 32 + 16 + 8 + 4 + 2 + 1
    events_all_with_mask = find_events(raw, mask=mask, id_=1)

    events_all = find_events(raw)

    events_1 = find_events(raw, id_=1)

    assert (len(events_all_with_mask) == len(events_all) == 320)
    assert (len(events_1) == 72)
    assert (np.array_equal(events_1[:, 2], [1] * len(events_1)))
示例#6
0
    def run(self):

        subject = self.experiment.active_subject
        raw = subject.get_raw()
        if not raw:
            return

        old_bads = raw.info['bads'].copy()
        old_annotations = raw.annotations.copy()

        # find events
        stim_ch = find_stim_channel(raw)
        if not stim_ch:
            events = None
        else:
            events = find_events(raw, stim_ch=stim_ch)

        def handle_close(event):
            bads_changed = (sorted(raw.info['bads']) != sorted(old_bads))

            annotations_changed = False
            if len(raw.annotations) != len(old_annotations):
                annotations_changed = True
            elif not np.allclose(raw.annotations.onset, old_annotations.onset):
                annotations_changed = True

            params = {}
            params['bads'] = raw.info['bads']
            params['annotations'] = list(raw.annotations)
            params['bads_changed'] = bads_changed
            params['annotations_changed'] = annotations_changed

            try:
                self.handler(subject, params)
            except Exception as exc:
                exc_messagebox(self.window, exc)

        fig = raw.plot(events=events, show=False)
        fig.canvas.mpl_connect('close_event', handle_close)
        plt.show()
示例#7
0
def test_tfr():
    with tempfile.TemporaryDirectory() as dirpath:

        sample_folder = mne.datasets.sample.data_path()
        sample_fname = os.path.join(sample_folder, 'MEG', 'sample',
                                    'sample_audvis_raw.fif')

        name = 'TestTFR'
        cond_name = 'cond_1'
        tfr_dir = os.path.join(dirpath, 'tfr')

        raw = mne.io.read_raw_fif(sample_fname, preload=True)
        events = find_events(raw, id_=1)
        freqs = [8, 9, 10, 11, 12]
        n_cycles = 2
        mne_tfr = tfr_morlet(mne.Epochs(raw, events),
                             freqs,
                             n_cycles,
                             return_itc=False)

        # As meggie-style tfrs can be based on multiple mne TFR objects,
        # content is dict-type. conditions-param is added to avoid accidents
        # in content loading..
        content = {cond_name: mne_tfr}
        params = {'conditions': [cond_name]}

        # Create meggie-TFR object
        # and save it to tfr directory
        tfr = TFR(name, tfr_dir, params, content=content)
        ensure_folders([tfr_dir])
        tfr.save_content()

        # Creating meggie-TFR object with same name and folder should allow
        # accessing the saved content.
        loaded_tfr = TFR(name, tfr_dir, params)

        assert (loaded_tfr.content[cond_name].nave == 72)
示例#8
0
def create_epochs_from_events(subject, params):
    """ Creates epochs based on events.
    """
    raw = subject.get_raw()

    params = copy.deepcopy(params)
    event_params = params['events']
    reject_params = params['reject']

    # convert reject params from human readable units to standard units
    for key in reject_params:
        reject_params[key] /= get_scaling(key)

    # remove params that don't match with the channel types present in raw
    if mne.pick_types(raw.info, meg='grad', eeg=False).size == 0:
        reject_params.pop('grad', None)
    if mne.pick_types(raw.info, meg='mag', eeg=False).size == 0:
        reject_params.pop('mag', None)
    if mne.pick_types(raw.info, meg=False, eeg=True).size == 0:
        reject_params.pop('eeg', None)

    events = []
    category = {}

    stim_channel = find_stim_channel(raw)

    # event_id should not matter after epochs are created,
    # so we just add placeholders as 1, 2, 3...
    if len(event_params) > 0:
        for idx, item in enumerate(event_params):
            event_id = item['event_id']
            mask = item['mask']
            category_id = ('id_' + str(event_id) + '_mask_' + str(mask))

            new_events = find_events(raw, stim_channel, mask, event_id)

            if len(new_events) == 0:
                logging.warning('No events found with setting ' +
                                str(category_id))
                continue

            category[category_id] = idx + 1
            new_events[:, 2] = idx + 1

            events.extend([[
                event[0] + int(round(raw.info['sfreq'] * params['delay'])),
                event[1], event[2]
            ] for event in new_events])

    if len(events) == 0:
        raise ValueError(
            'No matching events found. Please check rejection limits and other parameters.'
        )

    # prepare parameters for pick_types
    if params['mag'] and params['grad']:
        meg = True
    elif params['mag']:
        meg = 'mag'
    elif params['grad']:
        meg = 'grad'
    else:
        meg = False

    eeg = params['eeg']

    # find all proper picks, dont exclude bads
    picks = mne.pick_types(raw.info, meg=meg, eeg=eeg, exclude=[])

    if len(picks) == 0:
        raise ValueError('You should select at least one channel type')

    mne_epochs = mne.Epochs(raw,
                            np.array(events),
                            category,
                            params['tmin'],
                            params['tmax'],
                            baseline=(params['bstart'], params['bend']),
                            picks=picks,
                            reject=reject_params)

    if len(mne_epochs.get_data()) == 0:
        raise ValueError('Could not find any data. Perhaps the ' +
                         'rejection thresholds are too strict...')

    n_dropped = len(events) - len(mne_epochs.get_data())

    if n_dropped > 0:
        logging.getLogger('ui_logger').info(
            str(n_dropped) + ' epochs dropped.')

    epochs_directory = subject.epochs_directory
    epochs = Epochs(params['collection_name'],
                    epochs_directory,
                    params,
                    content=mne_epochs)

    epochs.save_content()
    subject.add(epochs, 'epochs')