예제 #1
0
def test_fieldtrip_client():
    """Test fieldtrip_client"""

    neuromag2ft_fname = op.realpath(
        op.join(os.environ['NEUROMAG2FT_ROOT'], 'neuromag2ft'))

    kill_signal = queue.Queue()
    thread = threading.Thread(target=_run_buffer,
                              args=(kill_signal, neuromag2ft_fname))
    thread.daemon = True
    thread.start()
    time.sleep(0.25)

    try:
        # Start the FieldTrip buffer
        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter('always')
            with FieldTripClient(host='localhost',
                                 port=1972,
                                 tmax=5,
                                 wait_max=1) as rt_client:
                tmin_samp1 = rt_client.tmin_samp

        time.sleep(1)  # Pause measurement
        assert_true(len(w) >= 1)

        # Start the FieldTrip buffer again
        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter('always')
            with FieldTripClient(host='localhost',
                                 port=1972,
                                 tmax=5,
                                 wait_max=1) as rt_client:
                raw_info = rt_client.get_measurement_info()

                tmin_samp2 = rt_client.tmin_samp
                picks = mne.pick_types(raw_info,
                                       meg='grad',
                                       eeg=False,
                                       stim=False,
                                       eog=False)
                epoch = rt_client.get_data_as_epoch(n_samples=5, picks=picks)
                n_channels, n_samples = epoch.get_data().shape[1:]

                epoch2 = rt_client.get_data_as_epoch(n_samples=5, picks=picks)
                n_channels2, n_samples2 = epoch2.get_data().shape[1:]

                # case of picks=None
                epoch = rt_client.get_data_as_epoch(n_samples=5)

        assert_true(tmin_samp2 > tmin_samp1)
        assert_true(len(w) >= 1)
        assert_equal(n_samples, 5)
        assert_equal(n_samples2, 5)
        assert_equal(n_channels, len(picks))
        assert_equal(n_channels2, len(picks))
        kill_signal.put(False)  # stop the buffer
    except Exception:
        kill_signal.put(False)  # stop the buffer even if tests fail
        raise
예제 #2
0
def test_fieldtrip_client():
    """Test fieldtrip_client"""

    neuromag2ft_fname = op.realpath(
        op.join(os.environ['NEUROMAG2FT_ROOT'], 'neuromag2ft'))

    kill_signal = queue.Queue()
    thread = threading.Thread(target=_run_buffer,
                              args=(kill_signal, neuromag2ft_fname))
    thread.daemon = True
    thread.start()

    # Start the FieldTrip buffer
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter('always')
        with FieldTripClient(host='localhost', port=1972, tmax=5,
                             wait_max=1) as rt_client:
            tmin_samp1 = rt_client.tmin_samp

    time.sleep(1)  # Pause measurement
    assert_true(len(w) == 1)

    # Start the FieldTrip buffer again
    with warnings.catch_warnings(record=True) as w:
        warnings.simplefilter('always')
        with FieldTripClient(host='localhost', port=1972, tmax=5,
                             wait_max=1) as rt_client:
            print(rt_client.tmin_samp)
            tmin_samp2 = rt_client.tmin_samp

    kill_signal.put(False)  # stop the buffer
    assert_true(tmin_samp2 > tmin_samp1)
    assert_true(len(w) == 1)
def test_fieldtrip_client(free_tcp_port):
    """Test fieldtrip_client"""

    kill_signal = _start_buffer_thread(free_tcp_port)

    time.sleep(0.5)

    try:
        # Start the FieldTrip buffer
        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter('always')
            with FieldTripClient(host='localhost',
                                 port=free_tcp_port,
                                 tmax=5,
                                 wait_max=2) as rt_client:
                tmin_samp1 = rt_client.tmin_samp

        time.sleep(1)  # Pause measurement
        assert len(w) >= 1

        # Start the FieldTrip buffer again
        with warnings.catch_warnings(record=True) as w:
            warnings.simplefilter('always')
            with FieldTripClient(host='localhost',
                                 port=free_tcp_port,
                                 tmax=5,
                                 wait_max=2) as rt_client:
                raw_info = rt_client.get_measurement_info()

                tmin_samp2 = rt_client.tmin_samp
                picks = pick_types(raw_info,
                                   meg='grad',
                                   eeg=False,
                                   stim=False,
                                   eog=False)
                epoch = rt_client.get_data_as_epoch(n_samples=5, picks=picks)
                n_channels, n_samples = epoch.get_data().shape[1:]

                epoch2 = rt_client.get_data_as_epoch(n_samples=5, picks=picks)
                n_channels2, n_samples2 = epoch2.get_data().shape[1:]

                # case of picks=None
                epoch = rt_client.get_data_as_epoch(n_samples=5)

        assert tmin_samp2 > tmin_samp1
        assert len(w) >= 1
        assert n_samples == 5
        assert n_samples2 == 5
        assert n_channels == len(picks)
        assert n_channels2 == len(picks)
    finally:
        kill_signal.put(False)  # stop the buffer
예제 #4
0
def test_fieldtrip_rtepochs(free_tcp_port, tmpdir):
    """Test FieldTrip RtEpochs."""
    raw_tmax = 7
    raw = read_raw_fif(raw_fname, preload=True)
    raw.crop(tmin=0, tmax=raw_tmax)
    events_offline = find_events(raw, stim_channel='STI 014')
    event_id = list(np.unique(events_offline[:, 2]))
    tmin, tmax = -0.2, 0.5
    epochs_offline = Epochs(raw, events_offline, event_id=event_id,
                            tmin=tmin, tmax=tmax)
    epochs_offline.drop_bad()
    isi_max = (np.max(np.diff(epochs_offline.events[:, 0])) /
               raw.info['sfreq']) + 1.0

    neuromag2ft_fname = op.realpath(op.join(os.environ['NEUROMAG2FT_ROOT'],
                                            'neuromag2ft'))
    # Works with neuromag2ft-3.0.2
    cmd = (neuromag2ft_fname, '--file', raw_fname, '--speed', '8.0',
           '--bufport', str(free_tcp_port))

    with running_subprocess(cmd, after='terminate', verbose=False):
        data_rt = None
        events_ids_rt = None
        with pytest.warns(RuntimeWarning, match='Trying to guess it'):
            with FieldTripClient(host='localhost', port=free_tcp_port,
                                 tmax=raw_tmax, wait_max=2) as rt_client:
                # get measurement info guessed by MNE-Python
                raw_info = rt_client.get_measurement_info()
                assert ([ch['ch_name'] for ch in raw_info['chs']] ==
                        [ch['ch_name'] for ch in raw.info['chs']])

                # create the real-time epochs object
                epochs_rt = RtEpochs(rt_client, event_id, tmin, tmax,
                                     stim_channel='STI 014', isi_max=isi_max)
                epochs_rt.start()

                time.sleep(0.5)
                for ev_num, ev in enumerate(epochs_rt.iter_evoked()):
                    if ev_num == 0:
                        data_rt = ev.data[None, :, :]
                        events_ids_rt = int(
                            ev.comment)  # comment attribute contains event_id
                    else:
                        data_rt = np.concatenate(
                            (data_rt, ev.data[None, :, :]), axis=0)
                        events_ids_rt = np.append(events_ids_rt,
                                                  int(ev.comment))

                _call_base_epochs_public_api(epochs_rt, tmpdir)
                epochs_rt.stop(stop_receive_thread=True)

        assert_array_equal(events_ids_rt, epochs_rt.events[:, 2])
        assert_array_equal(data_rt, epochs_rt.get_data())
        assert len(epochs_rt) == len(epochs_offline)
        assert_array_equal(events_ids_rt, epochs_offline.events[:, 2])
        assert_allclose(epochs_rt.get_data(), epochs_offline.get_data(),
                        rtol=1.e-5, atol=1.e-8)  # defaults of np.isclose
예제 #5
0
def test_fieldtrip_rtepochs(free_tcp_port, tmpdir):
    """Test FieldTrip RtEpochs."""
    raw_tmax = 7
    raw = read_raw_fif(raw_fname, preload=True)
    raw.crop(tmin=0, tmax=raw_tmax)
    events_offline = find_events(raw, stim_channel='STI 014')
    event_id = list(np.unique(events_offline[:, 2]))
    tmin, tmax = -0.2, 0.5
    epochs_offline = Epochs(raw, events_offline, event_id=event_id,
                            tmin=tmin, tmax=tmax)
    epochs_offline.drop_bad()
    isi_max = (np.max(np.diff(epochs_offline.events[:, 0])) /
               raw.info['sfreq']) + 1.0

    kill_signal = _start_buffer_thread(free_tcp_port)

    try:
        data_rt = None
        events_ids_rt = None
        with pytest.warns(RuntimeWarning, match='Trying to guess it'):
            with FieldTripClient(host='localhost', port=free_tcp_port,
                                 tmax=raw_tmax, wait_max=2) as rt_client:
                # get measurement info guessed by MNE-Python
                raw_info = rt_client.get_measurement_info()
                assert ([ch['ch_name'] for ch in raw_info['chs']] ==
                        [ch['ch_name'] for ch in raw.info['chs']])

                # create the real-time epochs object
                epochs_rt = RtEpochs(rt_client, event_id, tmin, tmax,
                                     stim_channel='STI 014', isi_max=isi_max)
                epochs_rt.start()

                time.sleep(0.5)
                for ev_num, ev in enumerate(epochs_rt.iter_evoked()):
                    if ev_num == 0:
                        data_rt = ev.data[None, :, :]
                        events_ids_rt = int(
                            ev.comment)  # comment attribute contains event_id
                    else:
                        data_rt = np.concatenate(
                            (data_rt, ev.data[None, :, :]), axis=0)
                        events_ids_rt = np.append(events_ids_rt,
                                                  int(ev.comment))

                _call_base_epochs_public_api(epochs_rt, tmpdir)
                epochs_rt.stop(stop_receive_thread=True)

        assert_array_equal(events_ids_rt, epochs_rt.events[:, 2])
        assert_array_equal(data_rt, epochs_rt.get_data())
        assert len(epochs_rt) == len(epochs_offline)
        assert_array_equal(events_ids_rt, epochs_offline.events[:, 2])
        assert_allclose(epochs_rt.get_data(), epochs_offline.get_data(),
                        rtol=1.e-5, atol=1.e-8)  # defaults of np.isclose
    finally:
        kill_signal.put(False)  # stop the buffer
예제 #6
0
def test_fieldtrip_client(free_tcp_port):
    """Test fieldtrip_client."""
    neuromag2ft_fname = op.realpath(op.join(os.environ['NEUROMAG2FT_ROOT'],
                                            'neuromag2ft'))
    # Works with neuromag2ft-3.0.2
    cmd = (neuromag2ft_fname, '--file', raw_fname, '--speed', '8.0',
           '--bufport', str(free_tcp_port))

    time.sleep(0.5)

    with running_subprocess(cmd, after='terminate', verbose=False):
        # Start the FieldTrip buffer
        with pytest.warns(RuntimeWarning):
            with FieldTripClient(host='localhost', port=free_tcp_port,
                                 tmax=5, wait_max=2) as rt_client:
                tmin_samp1 = rt_client.tmin_samp

        time.sleep(1)  # Pause measurement

        # Start the FieldTrip buffer again
        with pytest.warns(RuntimeWarning):
            with FieldTripClient(host='localhost', port=free_tcp_port,
                                 tmax=5, wait_max=2) as rt_client:
                raw_info = rt_client.get_measurement_info()

                tmin_samp2 = rt_client.tmin_samp
                picks = pick_types(raw_info, meg='grad', eeg=False,
                                   stim=False, eog=False)
                epoch = rt_client.get_data_as_epoch(n_samples=5, picks=picks)
                n_channels, n_samples = epoch.get_data().shape[1:]

                epoch2 = rt_client.get_data_as_epoch(n_samples=5, picks=picks)
                n_channels2, n_samples2 = epoch2.get_data().shape[1:]

                # case of picks=None
                epoch = rt_client.get_data_as_epoch(n_samples=5)

        assert tmin_samp2 > tmin_samp1
        assert n_samples == 5
        assert n_samples2 == 5
        assert n_channels == len(picks)
        assert n_channels2 == len(picks)
예제 #7
0
from mne.viz import plot_events
from mne.realtime import FieldTripClient, RtEpochs

print(__doc__)

# select the left-auditory condition
event_id, tmin, tmax = 1, -0.2, 0.5

# user must provide list of bad channels because
# FieldTrip header object does not provide that
bads = ['MEG 2443', 'EEG 053']

plt.ion()  # make plot interactive
_, ax = plt.subplots(2, 1, figsize=(8, 8))  # create subplots

with FieldTripClient(host='localhost', port=1972, tmax=150,
                     wait_max=10) as rt_client:

    # get measurement info guessed by MNE-Python
    raw_info = rt_client.get_measurement_info()

    # select gradiometers
    picks = mne.pick_types(raw_info,
                           meg='grad',
                           eeg=False,
                           eog=True,
                           stim=True,
                           exclude=bads)

    # create the real-time epochs object
    rt_epochs = RtEpochs(rt_client,
                         event_id,
예제 #8
0
_, ax = plt.subplots(2, 1, figsize=(8, 8))  # create subplots

speedup = 10
command = [
    "neuromag2ft", "--file",
    "{}/MEG/sample/sample_audvis_raw.fif".format(data_path), "--speed",
    str(speedup)
]
with running_subprocess(command,
                        after='kill',
                        stdout=subprocess.PIPE,
                        stderr=subprocess.PIPE):
    with FieldTripClient(host='localhost',
                         port=1972,
                         tmax=30,
                         wait_max=5,
                         info=info) as rt_client:

        # get measurement info guessed by MNE-Python
        raw_info = rt_client.get_measurement_info()

        # select gradiometers
        picks = mne.pick_types(raw_info,
                               meg='grad',
                               eeg=False,
                               eog=True,
                               stim=True,
                               exclude=bads)

        # create the real-time epochs object and start acquisition
예제 #9
0
                  current_event_type) in enumerate(recent_event_list):
            recent_data[ind] = np.array(
                ftc.getData([
                    np.int(current_event_ind - self.n_sample_per_trial_neg),
                    current_event_ind + self.n_sample_per_trial_pos
                ])).T

        recent_epochs = mne.EpochsArray(recent_data,
                                        self.raw_info,
                                        tmin=self.trial_tmin,
                                        baseline=None,
                                        proj=False)

        return recent_epochs, recent_event_list


if __name__ == "__main__":
    # test
    rt_client = FieldTripClient(info=None,
                                host="localhost",
                                port=1972,
                                tmax=150,
                                wait_max=10)
    with FieldTripClient(host='localhost', port=1972, tmax=150,
                         wait_max=10) as rt_client:
        recent_epochs_obj = biosemi_fieldtrip_recent_epochs(rt_client)
        recent_epochs, recent_event_list = recent_epochs_obj.get_recent_epochs(
        )
        recent_epochs.resample(512.0)
        recent_epochs.apply_baseline((None, 0))
예제 #10
0
ftc_mne.connect('localhost', 1972)    # might throw IOError
print ftc_mne.getHeader().nSamples
ftc_mne.getHeader().labels
ftc_mne.disconnect()


# the FieldTripClient class in MNE initializes and connects only in the 
#__enter__ function

with FieldTripClient(host='localhost', port=1972,
                     tmax=150, wait_max=10) as rt_client:
    a = rt_client.get_data_as_epoch()


# debugging, simulate the with clause
rt_client = FieldTripClient(info = None, host = "localhost", port = 1972, 
                            tmax = 150, wait_max = 10)
rt_client.__enter__()
print rt_client.ft_client.getHeader().labels
n_sample = rt_client.ft_client.getHeader().nSamples
tmp_data = rt_client.ft_client.getData([n_sample-50000, n_sample])

# debugging: last 280 were all of it
tmp_data1 = tmp_data[:,-280::]
plt.figure()
plt.plot(tmp_data1.mean(axis = 0),'*-')
plt.figure()
plt.plot(tmp_data1.std(axis = 0),'*-')
plt.figure()  
plt.plot(tmp_data1[:,277])
plt.figure()
plt.plot(tmp_data1[:,278::])