Example #1
0
def stream(address, backend='auto', interface=None, name=None):
    bluemuse = backend == 'bluemuse'
    if not bluemuse:
        if not address:
            found_muse = find_muse(name)
            if not found_muse:
                print('Muse could not be found')
                return
            else:
                address = found_muse['address']
                name = found_muse['name']

    info = StreamInfo('Muse', 'EEG', MUSE_NB_CHANNELS, MUSE_SAMPLING_RATE, 'float32',
                      'Muse%s' % address)

    info.desc().append_child_value("manufacturer", "Muse")
    channels = info.desc().append_child("channels")

    for c in ['TP9', 'AF7', 'AF8', 'TP10', 'Right AUX']:
        channels.append_child("channel") \
            .append_child_value("label", c) \
            .append_child_value("unit", "microvolts") \
            .append_child_value("type", "EEG")

    outlet = StreamOutlet(info, LSL_CHUNK)

    def push_eeg(data, timestamps):
        for ii in range(LSL_CHUNK):
            outlet.push_sample(data[:, ii], timestamps[ii])

    muse = Muse(address=address, callback_eeg=push_eeg,
                backend=backend, interface=interface, name=name)

    if(bluemuse):
        muse.connect()
        if not address and not name:
            print('Targeting first device BlueMuse discovers...')
        else:
            print('Targeting device: ' +
                  ':'.join(filter(None, [name, address])) + '...')
        print('\n*BlueMuse will auto connect and stream when the device is found. \n*You can also use the BlueMuse interface to manage your stream(s).')
        muse.start()
        return

    didConnect = muse.connect()

    if(didConnect):
        print('Connected.')
        muse.start()
        print('Streaming...')

        while time() - muse.last_timestamp < AUTO_DISCONNECT_DELAY:
            try:
                sleep(1)
            except KeyboardInterrupt:
                muse.stop()
                muse.disconnect()
                break

        print('Disconnected.')
Example #2
0
    def _setup_outlet(self):
        """
    Setting up LSL outlet for connectivity values
    :return: StreamOutlet object
    """
        sample_size = self.CONNECTIONS * len(self.freqParams)
        if sample_size == 0:
            return

        # basic info
        info = StreamInfo('RValues', 'Markers', sample_size, IRREGULAR_RATE,
                          cf_float32, "RValues-{}".format(getpid()))
        info.desc().append_child_value("correlation", "R")
        mappings = info.desc().append_child("mappings")
        # in the 'mapping' field, save the IDs of the pair in each connection
        buffer_keys = list(self.buffer.buffers_by_uid.keys())
        pair_index = [
            a for a in list(
                product(np.arange(0, len(buffer_keys)),
                        np.arange(0, len(buffer_keys)))) if a[0] < a[1]
        ]
        for pair in pair_index:
            mappings.append_child("mapping") \
              .append_child_value("from", buffer_keys[pair[0]]) \
              .append_child_value("to", buffer_keys[pair[1]])

        return StreamOutlet(info)
Example #3
0
def _start_mock_lsl_stream(host):
    """Start a mock LSL stream to test LSLClient."""
    from pylsl import StreamInfo, StreamOutlet

    n_channels = 8
    sfreq = 100
    info = StreamInfo('MNE', 'EEG', n_channels, sfreq, 'float32', host)
    info.desc().append_child_value("manufacturer", "MNE")
    channels = info.desc().append_child("channels")
    for c_id in range(1, n_channels + 1):
        channels.append_child("channel") \
                .append_child_value("label", "MNE {:03d}".format(c_id)) \
                .append_child_value("type", "eeg") \
                .append_child_value("unit", "microvolts")

    # next make an outlet
    outlet = StreamOutlet(info)

    print("now sending data...")
    while True:
        mysample = [
            rand(),
            rand(),
            rand(),
            rand(),
            rand(),
            rand(),
            rand(),
            rand()
        ]
        mysample = [x * 1e-6 for x in mysample]
        # now send it and wait for a bit
        outlet.push_sample(mysample)
        time.sleep(0.01)
Example #4
0
def main():
    # Create Gnautilus device
    d = GDS()
    configure_device(d)
    device_name = get_device_name(d)

    # Create LSL outlet
    info = StreamInfo(device_name, 'eeg', 32, d.SamplingRate, 'float32', device_name)
    # Append channel meta-data
    info.desc().append_child_value("manufacturer", "G.tec")
    channels = info.desc().append_child("channels")
    for c in d.GetChannelNames()[0]:
        channels.append_child("channel") \
            .append_child_value("label", c) \
            .append_child_value("unit", "microvolts") \
            .append_child_value("type", "EEG")

    #Print device information
    print_device_configuration(d)

    outlet = StreamOutlet(info)#, chunk_size=2)
    sender = DataSender(outlet)

    try:
        print("stream data ....")

        x = threading.Thread(target=sender.stop_collection)
        x.start()
        d.GetData(1, sender.send_data)
    finally:
        print("Closing device")
        d.Close()
Example #5
0
def create_outlet(d_id: str, d_type: str, c_desc: dict, d_manufacturer, d_name,
                  d_serial):
    """
    Generate LSL outlet from Metadata
    :rtype: StreamOutlet
    :param d_id: id for the device, usually the manufacturer and device type combined
    :param d_type: type of device (e.g. EEG, Wristband)
    :param c_desc: channel description. keys should be channel id. values should contain ('freq', 'unit' and 'type')
    :param d_manufacturer: manufacturer of the device
    :param d_name: name of the device
    :param d_serial: serial number of the device (for uniqueness)
    :return: StreamOutlet object to send data streams through
    """
    info = StreamInfo(d_id, d_type, len(c_desc.keys()), IRREGULAR_RATE,
                      'float32', d_serial)
    info.desc().append_child_value("manufacturer",
                                   d_manufacturer).append_child_value(
                                       "device", d_name)
    channels = info.desc().append_child("channels")
    for c in c_desc.keys():
        channels.append_child("channel") \
            .append_child_value("label", c) \
            .append_child_value("unit", c_desc[c]['unit']) \
            .append_child_value("type", c_desc[c]['type']) \
            .append_child_value("freq", c_desc[c]['freq']) \
            # next make an outlet; we set the transmission chunk size to 32 samples and

    # the outgoing buffer size to 360 seconds (max.)
    return StreamOutlet(info, 32, 60)
Example #6
0
    def __init__(self, type_, n_chs, sfreq, send_data=False):
        """Add docstring here."""
        if type_ not in ["Markers", "EEG"]:
            raise ValueError("`type_` must be 'Markers' or 'EEG'.")
        self.type_ = type_
        self.n_chs = n_chs
        self.sfreq = sfreq
        self.send_data = send_data

        self.stream_name = "test_{}_{}".format(self.type_, randint(1, 100))
        self.stream_type = 'float32' if self.type_ == "EEG" else 'int32'

        info = StreamInfo(self.stream_name, self.type_, self.n_chs, self.sfreq,
                          self.stream_type, self.stream_name + '_1234')
        # Add metadata.
        info.desc().append_child_value("nominal_srate", str(self.sfreq))
        if self.type_ == "EEG":
            ch_names = ['ch{}'.format(x) for x in range(1, self.n_chs + 1)]
            for c in ch_names:
                info.desc().append_child("channel")\
                    .append_child_value("name", c)\
                    .append_child_value("unit", "millivolts")\
                    .append_child_value("type", "EEG")
        self.outlet = StreamOutlet(info)
        if self.send_data:
            self.event = Event()
            self.thread = Thread(target=self._send_data)
            self.thread.start()
Example #7
0
    def _get_gyro_outlet(self):
        gyro_info = StreamInfo('Muse', 'GYRO', MUSE_NB_GYRO_CHANNELS,
                               MUSE_SAMPLING_GYRO_RATE, 'float32',
                               'Muse%s' % self.get_muse_address())
        gyro_info.desc().append_child_value("manufacturer", "Muse")

        gyro_outlet = StreamOutlet(gyro_info, LSL_GYRO_CHUNK)

        return gyro_outlet
Example #8
0
    def _get_acc_outlet(self):
        acc_info = StreamInfo('Muse', 'ACC', MUSE_NB_ACC_CHANNELS,
                              MUSE_SAMPLING_ACC_RATE, 'float32',
                              'Muse%s' % self.get_muse_address())
        acc_info.desc().append_child_value("manufacturer", "Muse")

        acc_outlet = StreamOutlet(acc_info, LSL_ACC_CHUNK)

        return acc_outlet
Example #9
0
    def _get_ppg_outlet(self):
        # Connecting to MUSE
        ppg_info = StreamInfo('Muse', 'PPG', MUSE_NB_PPG_CHANNELS,
                              MUSE_SAMPLING_PPG_RATE, 'float32',
                              'Muse%s' % self.get_muse_address())
        ppg_info.desc().append_child_value("manufacturer", "Muse")

        ppg_outlet = StreamOutlet(ppg_info, LSL_PPG_CHUNK)

        return ppg_outlet
Example #10
0
def createOutlet(index, filename):
    streamName = 'FrameMarker' + str(index + 1)
    info = StreamInfo(name=streamName,
                      type='videostream',
                      channel_format='float32',
                      channel_count=1,
                      source_id=str(uuid.uuid4()))
    if sys.platform == "linux":
        videoFile = os.path.splitext(filename)[0] + '.ogv'
    info.desc().append_child_value("videoFile", filename)
    return StreamOutlet(info)
Example #11
0
def channel_names(stream_info: pylsl.StreamInfo) -> List[str]:
    """Extracts the channel names from the LSL Stream metadata."""
    channels = []
    if stream_info.desc().child("channels").empty():
        return channels

    channel = stream_info.desc().child("channels").child("channel")
    for _ in range(stream_info.channel_count()):
        channel_name = channel.child_value("label")
        channels.append(channel_name)
        channel = channel.next_sibling()

    return channels
 def _setup_outlet_power(self):
     sample_size = self.STREAM_COUNT * self.channel_count * len(
         self.freqParams)
     self.logger.warning(
         'power sample size is %s %s %s' %
         (self.STREAM_COUNT, self.channel_count, len(self.freqParams)))
     if sample_size == 0:
         return
     info = StreamInfo('Powervals', 'Markers', sample_size, IRREGULAR_RATE,
                       cf_float32, "Pvals-{}".format(getpid()))
     info.desc().append_child_value('subjects',
                                    '_'.join(list(self.buffers.keys())))
     return StreamOutlet(info)
Example #13
0
def make_stream(eyetracker):
    """Creates a stream outlet and defines meta-data.
    https://labstreaminglayer.readthedocs.io/"""
    info = StreamInfo('TobiiET', 'ET', 1, 120, 'float32',
                      eyetracker.serial_number)
    info.desc().append_child_value("manufacturer", "Tobii")
    channels = info.desc().append_child("channels")
    for c in ["LX", "LY", "RX", "RY"]:
        channels.append_child("channel") \
            .append_child_value("label", c) \
            .append_child_value("unit", "normalised location") \
            .append_child_value("type", "ET")
    return StreamOutlet(info)
Example #14
0
def main():

    # Set up LabStreamingLayer stream.
    info = StreamInfo(name='PsychoPyMarker',
                      type='Markers',
                      channel_count=3,
                      channel_format='double64',
                      source_id='unique012345')
    chns = info.desc().append_child("channels")
    #MarkerTime is the time you want to add a marker. It is an epoch time.
    #MarkerValue is value of marker
    #CurrentTime is current time at epoch time
    for label in ["MarkerTime", "MarkerValue", "CurrentTime"]:
        ch = chns.append_child("channel")
        ch.append_child_value("label", label)
        ch.append_child_value("type", "Marker")
    info.desc().append_child_value("manufacturer", "PsychoPy")

    outlet = StreamOutlet(info)  # Broadcast the stream.

    # Instantiate the PsychoPy window and stimuli.
    win = visual.Window([800, 600],
                        allowGUI=False,
                        monitor='testMonitor',
                        units='deg')

    while (True):
        markerValue = random.randint(1, 99)
        print("Marker value: ", markerValue)
        displayText = visual.TextStim(win,
                                      text="Send Marker has value: " +
                                      str(markerValue))
        displayText.draw()
        win.flip()

        now = datetime.datetime.now().timestamp()
        print(now)
        # data: MarkerTime, MarkerValue, Current EpochTime
        data = [now, markerValue, now]

        outlet.push_sample(data)

        if 'escape' in event.getKeys():  # Exit if user presses escape.
            break
        core.wait(1.0)  # Display text for 1.0 second.
        win.flip()
        core.wait(0.5)  # ISI of 0.5 seconds.

    win.close()
    core.quit()
    def __init__(self, class_list=[1, 3], classes_rand=True, target_list=[1, 2], targets_rand=True):
        """

        :param class_list:  A list of integers comprising different class ids. Default: [1, 3]
        :param classes_rand: If True, classes are chosen randomly from list. If False, the list is cycled. Default: True
        :param target_list: A list of integers comprising different target ids. Default: [1, 2]
        :param targets_rand: If True, targets are chosen randomly from list. If False, the list is cycled. Default: True
        """
        stream_name = 'GeneratedCentreOutMarkers'
        stream_type = 'Markers'
        outlet_info = StreamInfo(name=stream_name, type=stream_type,
                   channel_count=1, nominal_srate=0,
                   channel_format='string',
                   source_id='centreoutmarkergen1234')
        outlet_xml = outlet_info.desc()
        channels_xml = outlet_xml.append_child("channels")
        chan_xml = channels_xml.append_child("channel")
        chan_xml.append_child_value("label", "EventMarkers")
        chan_xml.append_child_value("type", "generated")
        self.outlet = StreamOutlet(outlet_info)
        print("Created outlet with name {} and type {}".format(stream_name, stream_type))

        self.class_list = class_list
        self.classes_rand = classes_rand
        self.target_list = target_list
        self.targets_rand = targets_rand
        self.next_transition = -1
        self.in_phase = 'evaluate'
        self.trial_ix = 0
        self.class_id = self.class_list[0]
        self.target_id = self.target_list[0]
Example #16
0
 def update(self):
     if isinstance(self.i.data, pd.core.frame.DataFrame):
         if not self._outlet:
             labels = list(
                 self.i.data.select_dtypes(
                     include=[self._dtypes[self._format]]))
             info = StreamInfo(
                 self._name,
                 self._type,
                 len(labels),
                 self._rate,
                 self._format,
                 self._source,
             )
             channels = info.desc().append_child("channels")
             for label in labels:
                 if not isinstance("string", type(label)):
                     label = str(label)
                 channels.append_child("channel").append_child_value(
                     "label", label)
             self._outlet = StreamOutlet(info)
         values = self.i.data.select_dtypes(
             include=[self._dtypes[self._format]]).values
         stamps = self.i.data.index.values.astype(np.float64)
         for row, stamp in zip(values, stamps):
             self._outlet.push_sample(row, stamp)
Example #17
0
def simulate_bci_signal(fs, chunk_size=8, verbose=False):
    # setup stream
    info = StreamInfo(name='NFBLab_data',
                      type='',
                      channel_count=1,
                      nominal_srate=fs)
    channels = info.desc().append_child("channels")
    channels.append_child("channel").append_child_value("name", 'BCI')
    print('Stream info:\n\tname: {}, fs: {}Hz, channels: {}'.format(
        info.name(), int(info.nominal_srate()), ['BCI']))
    outlet = StreamOutlet(info)
    print('Now sending data...')

    # prepare main loop
    start = time()
    counter = chunk_size
    x = x_base = np.ones((chunk_size, 1))
    n_chunks = 0

    # main loop
    while True:
        while time() - start < counter / fs:
            sleep(1 / fs)
        if np.random.randint(0, fs / chunk_size / 2) == 0:
            x = x_base * np.random.randint(0, 2 + 1)
        outlet.push_chunk(x)
        n_chunks += 1
        counter += chunk_size
        if verbose:
            # print('counter time: {:.2f}\ttime: {:.2f}'.format(counter/fs, time() - start))
            if n_chunks % 50 == 0:
                print('Chunk {} was sent'.format(n_chunks))
Example #18
0
def main(argv):
    # Set the default host name parameter. The SDK is socket based so any
    # networked Motion Service is available.
    host = ""
    if len(argv) > 1:
        host = argv[1]


    sys.stdout.write("\n=== outstream_shadowsuit.py ===\n\n")
    sys.stdout.flush()

    # Setup outlet stream infos
    mocap_channels = 32
    sample_size = 8

    sys.stdout.write("Creating LSL outlets...")
    sys.stdout.flush()

    stream_info_mocap = StreamInfo('ShadowSuit', 'MOCAP', mocap_channels * sample_size, 200)
    channels = stream_info_mocap.desc().append_child("channels")
    
    channel_list = ["lq0", "lq1", "lq2", "lq3",
        "c0", "c1", "c2", "c3"]

    for c in channel_list:
        channels.append_child(c) 

    # Create outlets
    outlet_mocap = StreamOutlet(stream_info_mocap)

    sys.stdout.write("created.\n")
    sys.stdout.flush()

    shadow_client(host, PortConfigurable, outlet_mocap)
Example #19
0
def StartStream(STREAMNAME):

    info = StreamInfo(STREAMNAME, 'ECG', 1, ECG_SAMPLING_FREQ, 'float32',
                      'myuid2424')

    info.desc().append_child_value("manufacturer", "Polar")
    channels = info.desc().append_child("channels")
    for c in ["ECG"]:
        channels.append_child("channel")\
            .append_child_value("name", c)\
            .append_child_value("unit", "microvolts")\
            .append_child_value("type", "ECG")

    # next make an outlet; we set the transmission chunk size to 74 samples and
    # the outgoing buffer size to 360 seconds (max.)
    return StreamOutlet(info, 74, 360)
    def create_stream(self, stream_name):
        # Configure LSL streams
        info = StreamInfo(*self.stream_descriptions[stream_name])

        # append channels meta-data
        channels = info.desc().append_child("channels")
        for c in self.stream_channels[stream_name]:
            if c == 'gidx':
                channels.append_child("channel") \
                    .append_child_value("name", c) \
                    .append_child_value("unit", "na") \
                    .append_child_value("type", "marker")
            elif c == 's':
                channels.append_child("channel") \
                    .append_child_value("name", c) \
                    .append_child_value("unit", "na") \
                    .append_child_value("type", "marker")
            else:
                channels.append_child("channel") \
                    .append_child_value("name", c) \
                    .append_child_value("unit", "mm") \
                    .append_child_value("type", "coordinate")

        outlet = StreamOutlet(info)

        return outlet
Example #21
0
def simulate_bci_signal(fs, verbose=False):
    """
    :param fs: sampling frequency
    :param verbose: if verbose == True print info
    """

    # setup stream
    info = StreamInfo(name='NFBLab_data',
                      type='',
                      channel_count=1,
                      nominal_srate=fs)
    channels = info.desc().append_child("channels")
    channels.append_child("channel").append_child_value("name", 'BCI')
    print('Stream info:\n\tname: {}, fs: {}Hz, channels: {}'.format(
        info.name(), int(info.nominal_srate()), ['BCI']))
    outlet = StreamOutlet(info)
    print('Now sending data...')

    # prepare main loop
    start = time()
    counter = 0
    # main loop
    while True:
        while time() - start < counter / fs:
            sleep(1 / fs)

        x = 1 - int((counter % 1501) < 250)
        outlet.push_sample([x])
        counter += 1
        if verbose:
            if counter % fs == 0:
                print(x)
Example #22
0
def main():
    PORT = '1234'
    info = StreamInfo('Muse', 'EEG', 4, 220, 'float32',
                      'MuseName')

    info.desc().append_child_value("manufacturer", "Muse")
    channels = info.desc().append_child("channels")

    for c in ['TP9-l_ear', 'FP1-l_forehead', 'FP2-r_forehead', 'TP10-r_ear']:
        channels.append_child("channel") \
            .append_child_value("label", c) \
            .append_child_value("unit", "microvolts") \
            .append_child_value("type", "EEG")

    # create a pylsl outlet; specify info, chunk size (each push yields one chunk), and maximum buffered data
    outlet = StreamOutlet(info, 1, 360)
    if outlet:
        print('EEG outlet created.')

    # connect to the server; start pushing muse data to the pylsl outlet
    try:
        muse_server = server.PylibloServer(PORT, server.process, outlet)
    except server.ServerError:
        raise ValueError('Cannot create PylibloServer Object.')
    if muse_server:
        muse_server.connect()
    else:
        print('No muse connection.')
        return

    # connect to inlets
    # Create MuseEEGStream object
    eeg_stream = st.MuseEEGStream()

    # ensure eeg stream is receiving data before trying to access data
    while not eeg_stream.data:
        time.sleep(0.1)

    for i in range(1000):
        try:
            # print the eeg data every second
            print(eeg_stream.data[-1])
            time.sleep(1)
        except:
            break

    muse_server.stop()
Example #23
0
    def _get_eeg_outlet(self):
        # Connecting to MUSE
        eeg_info = StreamInfo('Muse', 'EEG', MUSE_NB_EEG_CHANNELS,
                              MUSE_SAMPLING_EEG_RATE, 'float32',
                              'Muse%s' % self.get_muse_address())
        eeg_info.desc().append_child_value("manufacturer", "Muse")
        eeg_channels = eeg_info.desc().append_child("channels")

        for c in ['TP9', 'AF7', 'AF8', 'TP10', 'Right AUX']:
            eeg_channels.append_child("channel") \
                .append_child_value("label", c) \
                .append_child_value("unit", "microvolts") \
                .append_child_value("type", "EEG")

        eeg_outlet = StreamOutlet(eeg_info, LSL_EEG_CHUNK)

        return eeg_outlet
Example #24
0
def new_lsl_stream_info(config, qtm_host, qtm_port):
    info = StreamInfo(
        name="Qualisys",
        type="Mocap",
        channel_count=config.channel_count(),
        channel_format=cf_float32,
        source_id="{}:{}".format(qtm_host, qtm_port),
    )
    channels = info.desc().append_child("channels")
    setup = info.desc().append_child("setup")
    markers = setup.append_child("markers")
    objects = setup.append_child("objects")
    cameras = setup.append_child("cameras")
    lsl_stream_info_add_markers(config, channels, markers)
    lsl_stream_info_add_6dof(config, channels, objects)
    lsl_stream_info_add_cameras(config, cameras)
    info.desc().append_child("acquisition") \
        .append_child_value("manufacturer", "Qualisys") \
        .append_child_value("model", "Qualisys Track Manager")
    return info
Example #25
0
def stream():
    #print(address)
    #print(name)
    print(
        "Creating LSL stream for EEG. \nName: OpenBCIEEG\nID: OpenBCItestEEG\n"
    )

    info_eeg = StreamInfo('OpenBCIEEG', 'EEG', 16, 250, 'float32',
                          'OpenBCItestEEG')

    # print("Creating LSL stream for AUX. \nName: OpenBCIAUX\nID: OpenBCItestEEG\n")

    # info_aux = StreamInfo('OpenBCIAUX', 'AUX', 3, 250, 'float32', 'OpenBCItestAUX')

    info_eeg.desc().append_child_value("manufacturer", "OpenBCI")
    eeg_channels = info_eeg.desc().append_child("channels")

    for c in [
            'Fp1', 'Fp2', 'C3', 'C4', 'P7', 'P8', 'O1', 'O2', 'F7', 'F8', 'F3',
            'F4', 'T7', 'T8', 'P3', 'P4'
    ]:
        eeg_channels.append_child("channel") \
            .append_child_value("label", c) \
            .append_child_value("unit", "microvolts") \
            .append_child_value("type", "EEG")

    # eeg_outlet = StreamOutlet(eeg_info, LSL_EEG_CHUNK)

    outlet_eeg = StreamOutlet(info_eeg)

    # outlet_aux = StreamOutlet(info_aux)

    def lsl_streamers(sample):
        outlet_eeg.push_sample(
            np.array(sample.channels_data) * SCALE_FACTOR_EEG)
        # outlet_aux.push_sample(np.array(sample.aux_data)*SCALE_FACTOR_AUX)

    #board = OpenBCICyton(port='COM3', daisy=True)
    board = OpenBCICyton(port='/dev/tty.usbserial-DM01N7JO', daisy=True)

    board.start_stream(lsl_streamers)
Example #26
0
class SignalsOutlet:
    def __init__(self, signals, fs):
        self.info = StreamInfo(name='NFBLab_data', type='', channel_count=len(signals), source_id='nfblab42',
                               nominal_srate=fs)
        self.info.desc().append_child_value("manufacturer", "BioSemi")
        channels = self.info.desc().append_child("channels")
        for c in signals:
            channels.append_child("channel").append_child_value("name", c)
        self.outlet = StreamOutlet(self.info)

    def push_sample(self, data):
        self.outlet.push_sample(data)

    def push_repeated_chunk(self, data, n=1):
        #chunk = repeat(data, n).reshape(-1, n).T.tolist()
        #self.outlet.push_chunk(chunk)
        for k in range(n):
            self.outlet.push_sample(data)

    def push_chunk(self, data, n=1):
        self.outlet.push_chunk(data)
Example #27
0
class SignalsOutlet:
    def __init__(self, signals, fs, name='NFBLab_data1'):
        self.info = StreamInfo(name=name, type='', channel_count=len(signals), source_id='nfblab42',
                               nominal_srate=fs)
        self.info.desc().append_child_value("manufacturer", "BioSemi")
        channels = self.info.desc().append_child("channels")
        for c in signals:
            channels.append_child("channel").append_child_value("name", c)
        self.outlet = StreamOutlet(self.info)

    def push_sample(self, data):
        self.outlet.push_sample(data)

    def push_repeated_chunk(self, data, n=1):
        #chunk = repeat(data, n).reshape(-1, n).T.tolist()
        #self.outlet.push_chunk(chunk)
        for k in range(n):
            self.outlet.push_sample(data)

    def push_chunk(self, data, n=1):
        self.outlet.push_chunk(data)
Example #28
0
    def __init__(self, device_info):
        n_chan = device_info['adc_mask'].count(1)
        self.exg_fs = device_info['sampling_rate']
        orn_fs = 20

        info_exg = StreamInfo(device_info["device_name"] + "_ExG", 'ExG',
                              n_chan, self.exg_fs, 'float32', 'ExG')
        info_exg.desc().append_child_value("manufacturer", "Mentalab")
        channels = info_exg.desc().append_child("channels")
        for i, mask in enumerate(device_info['adc_mask']):
            if mask == 1:
                channels.append_child("channel")\
                    .append_child_value("name", EXG_CHANNELS[i])\
                    .append_child_value("unit", EXG_UNITS[i])\
                    .append_child_value("type", "ExG")

        info_orn = StreamInfo(device_info["device_name"] + "_ORN",
                              'Orientation', 9, orn_fs, 'float32', 'ORN')
        info_orn.desc().append_child_value("manufacturer", "Mentalab")
        channels = info_exg.desc().append_child("channels")
        for chan, unit in zip(ORN_CHANNELS, ORN_UNITS):
            channels.append_child("channel") \
                .append_child_value("name", chan) \
                .append_child_value("unit", unit) \
                .append_child_value("type", "ORN")

        info_marker = StreamInfo(device_info["device_name"] + "_Marker",
                                 'Markers', 1, 0, 'int32', 'Marker')

        self.orn_outlet = StreamOutlet(info_orn)
        self.exg_outlet = StreamOutlet(info_exg)
        self.marker_outlet = StreamOutlet(info_marker)
Example #29
0
    def create_lsl_output(self):
        """Creates an LSL Stream outlet"""
        info = StreamInfo(name=self.config.lsl_streamname.get(), type='P300_Marker',
                          channel_count=1, channel_format='int8', nominal_srate=IRREGULAR_RATE,
                          source_id='marker_stream', handle=None)

        if self.config.flash_mode == 1:
            info.desc().append_child_value('flash_mode', 'Row and Column')
        elif self.config.flash_mode == 2:
            info.desc().append_child_value('flash_mode', 'Single Value')

        info.desc().append_child_value('num_rows', str(self.config.number_of_rows.get()))
        info.desc().append_child_value('num_cols', str(self.config.number_of_columns.get()))

        return StreamOutlet(info)
Example #30
0
    def __init__(self,
                 lsl_data_name=config.INFERENCE_LSL_NAME,
                 lsl_data_type=config.INFERENCE_LSL_TYPE
                 ):  # default board_id 2 for Cyton
        self.lsl_data_type = lsl_data_type
        self.lsl_data_name = lsl_data_name

        # TODO need to change the channel count when adding eeg
        info = StreamInfo(lsl_data_name,
                          lsl_data_type,
                          channel_count=config.EYE_TOTAL_POINTS_PER_INFERENCE,
                          channel_format='float32',
                          source_id='myuid2424')
        info.desc().append_child_value("apocalyvec", "RealityNavigation")

        # chns = info.desc().append_child("eeg_channels")
        # channel_names = ["C3", "C4", "Cz", "FPz", "POz", "CPz", "O1", "O2", '1','2','3','4','5','6','7','8']
        # for label in channel_names:
        #     ch = chns.append_child("channel")
        #     ch.append_child_value("label", label)
        #     ch.append_child_value("unit", "microvolts")
        #     ch.append_child_value("type", "EEG")

        chns = info.desc().append_child("eye")
        channel_names = [
            'left_pupil_diameter_sample', 'right_pupil_diameter_sample'
        ]
        for label in channel_names:
            ch = chns.append_child("channel")
            ch.append_child_value("label", label)
            ch.append_child_value("unit", "mm")
            ch.append_child_value("type", "eye")

        self.outlet = StreamOutlet(info, max_buffered=360)
        self.start_time = local_clock()

        self.inlet = None
        self.connect_inference_result_stream()
Example #31
0
class BalanceBoardLSLOut(Outlet):
    def __init__(self, root, datarate=250):
        super(BalanceBoardLSLOut, self).__init__(root, "LSLOut")
        logging.debug("Configuring LSL stream for 'wobble' data...")
        # configure LSL stream
        self.info = StreamInfo('BalanceBoard', 'wobble', 9, datarate,
                               'float32', self.root.id)
        # append some meta-data
        self.info.desc().append_child_value("manufacturer", "play")
        channels = self.info.desc().append_child("channels")
        for c in [
                "accx", "accy", "accz", "acclinx", "accliny", "acclinz", "yaw",
                "pitch", "roll"
        ]:
            channels.append_child("channel") \
                .append_child_value("label", c) \
                .append_child_value("type", "wobble")

        # next make an outlet; we set the transmission chunk size to 32 samples and
        # the outgoing buffer size to 360 seconds (max.)
        self.outlet = StreamOutlet(self.info, 32, 360)

    def work(self, data):
        sample = [
            data['accx'], data['accy'], data['accz'], data['laccx'],
            data['laccy'], data['laccz'], data['yaw'], data['pitch'],
            data['roll']
        ]
        # ,
        # data['yaw'], data['pitch'], data['roll']]
        # get a time stamp in seconds
        stamp = local_clock()
        # now send it
        self.outlet.push_sample(sample, stamp)
        self.pump(sample)

    def shutdown(self):
        pass
    def _setup_outlet(self):
        sample_size = self.CONNECTIONS * len(self.freqParams)
        if sample_size == 0:
            return

        info = StreamInfo('RValues', 'Markers', sample_size, IRREGULAR_RATE,
                          cf_float32, "RValues-{}".format(getpid()))
        info.desc().append_child_value("correlation", "R")

        mappings = info.desc().append_child("mappings")
        buffer_keys = list(self.buffers.keys())
        pair_index = [
            a for a in list(
                product(np.arange(0, len(buffer_keys)),
                        np.arange(0, len(buffer_keys)))) if a[0] < a[1]
        ]

        for pair in pair_index:
            mappings.append_child("mapping") \
                .append_child_value("from", buffer_keys[pair[0]]) \
                .append_child_value("to", buffer_keys[pair[1]])

        return StreamOutlet(info)
Example #33
0
def run_events_sim(name='events_example'):
    info = StreamInfo(name=name, type='EEG', channel_count=1, channel_format='float32', source_id='myuid34234')

    # channels labels (in accordance with XDF format, see also code.google.com/p/xdf)

    chns = info.desc().append_child("channels")
    for label in ['STIM']:
        ch = chns.append_child("channel")
        ch.append_child_value("label", label)
    outlet = StreamOutlet(info)

    # send data and print some info every 5 sec
    print('now sending data...')

    while True:
        outlet.push_sample([42])
        time.sleep(1)
        print('42 sent')
    pass
    def __init__(self, Fs=2**14, FreqBeta=20.0, AmpBeta=100.0, AmpNoise=20.0, NCyclesPerChunk=4,
                 channels=["RAW1", "SPK1", "RAW2", "SPK2", "RAW3", "SPK3"]):
        """
        :param Fs:              Sampling rate
        :param FreqBeta:        Central frequency of beta band
        :param AmpBeta:         Amplitude of beta (uV)
        :param AmpNoise:        Amplitude of pink noise (uV)
        :param NCyclesPerChunk: Minimum number of cycles of beta in a chunk.
        :param channels:        List of channel names
        """
        # Saved arguments
        self.FreqBeta = FreqBeta
        self.AmpBeta = AmpBeta                                          # Amplitude of Beta (uV)
        self.AmpNoise = AmpNoise                                        # Amplitude of pink noise
        self.channels = channels
        # Derived variables
        chunk_dur = NCyclesPerChunk / self.FreqBeta           # Duration, in sec, of one chunk
        chunk_len = int(Fs * chunk_dur)                  # Number of samples in a chunk
        self.tvec = 1.0 * (np.arange(chunk_len) + 1) / Fs     # time vector for chunk (sec)
        # Pink noise generator
        self.pinkNoiseGen = PinkNoiseGenerator(nSampsPerBlock=chunk_len)

        # Create a stream of fake 'raw' data
        raw_info = StreamInfo(name='BetaGen', type='EEG',
                           channel_count=len(self.channels), nominal_srate=Fs,
                           channel_format='float32', source_id='betagen1234')
        raw_xml = raw_info.desc()
        chans = raw_xml.append_child("channels")
        for channame in self.channels:
            chn = chans.append_child("channel")
            chn.append_child_value("label", channame)
            chn.append_child_value("unit", "microvolts")
            chn.append_child_value("type", "generated")
        self.eeg_outlet = StreamOutlet(raw_info)
        print("Created outlet with name BetaGen and type EEG")

        self.last_time = local_clock()
"""Example program that shows how to attach meta-data to a stream, and how to
later on retrieve the meta-data again at the receiver side."""

import time

from pylsl import StreamInfo, StreamOutlet, StreamInlet, resolve_stream

# create a new StreamInfo object which shall describe our stream
info = StreamInfo("MetaTester", "EEG", 8, 100, "float32", "myuid56872")

# now attach some meta-data (in accordance with XDF format,
# see also code.google.com/p/xdf)
chns = info.desc().append_child("channels")
for label in ["C3", "C4", "Cz", "FPz", "POz", "CPz", "O1", "O2"]:
    ch = chns.append_child("channel")
    ch.append_child_value("label", label)
    ch.append_child_value("unit", "microvolts")
    ch.append_child_value("type", "EEG")
info.desc().append_child_value("manufacturer", "SCCN")
cap = info.desc().append_child("cap")
cap.append_child_value("name", "EasyCap")
cap.append_child_value("size", "54")
cap.append_child_value("labelscheme", "10-20")

# create outlet for the stream
outlet = StreamOutlet(info)

# (...normally here one might start sending data into the outlet...)

# === the following could run on another computer ===
Example #36
0
import sys; sys.path.append('..') # help python find pylsl relative to this example program
from pylsl import StreamInfo, StreamOutlet, StreamInlet, resolve_stream
import time

# create a new StreamInfo and declare some meta-data (in accordance with XDF format)
info = StreamInfo("MetaTester","EEG",8,100,"float32","myuid56872")
chns = info.desc().append_child("channels")
for label in ["C3","C4","Cz","FPz","POz","CPz","O1","O2"]:
    ch = chns.append_child("channel")
    ch.append_child_value("label",label)
    ch.append_child_value("unit","microvolts")
    ch.append_child_value("type","EEG")
info.desc().append_child_value("manufacturer","SCCN")
cap = info.desc().append_child("cap")
cap.append_child_value("name","EasyCap")
cap.append_child_value("size","54")
cap.append_child_value("labelscheme","10-20")

# create outlet for the stream
outlet = StreamOutlet(info)


# === the following could run on another computer ===

# resolve the stream and open an inlet
results = resolve_stream("name","MetaTester")
inlet = StreamInlet(results[0])
# get the full stream info (including custom meta-data) and dissect it
inf = inlet.info()
print "The stream's XML meta-data is: "
print inf.as_xml()
Example #37
0
import sys; sys.path.append('..') # help python find pylsl relative to this example program
from pylsl import StreamInfo, StreamOutlet, local_clock
import random
import time

# first create a new stream info (here we set the name to BioSemi, the content-type to EEG, 8 channels, 100 Hz, and float-valued data)
# The last value would be the serial number of the device or some other more or less locally unique identifier for the stream as far as available (you could also omit it but interrupted connections wouldn't auto-recover).
info = StreamInfo('BioSemi','EEG',8,100,'float32','myuid2424');

# append some meta-data
info.desc().append_child_value("manufacturer","BioSemi")
channels = info.desc().append_child("channels")
for c in ["C3","C4","Cz","FPz","POz","CPz","O1","O2"]:
	channels.append_child("channel").append_child_value("name",c).append_child_value("unit","microvolts").append_child_value("type","EEG")

# next make an outlet; we set the transmission chunk size to 32 samples and the outgoing buffer size to 360 seconds (max.)
outlet = StreamOutlet(info,32,360)

print("now sending data...")
while True:
	# make a new random 8-channel sample; this is converted into a pylsl.vectorf (the data type that is expected by push_sample)
	mysample = [random.random(),random.random(),random.random(),random.random(),random.random(),random.random(),random.random(),random.random()]
    # get a time stamp in seconds (we pretend that our samples are actually 125ms old, e.g., as if coming from some external hardware)
	stamp = local_clock()-0.125
	# now send it and wait for a bit
	outlet.push_sample(mysample,stamp)
	time.sleep(0.01)
Example #38
0
def run_eeg_sim(freq=None, chunk_size=0, source_buffer=None, name='example', labels=None):
    """
    Make LSL Stream Outlet and send source_buffer data or simulate sin data
    :param n_channels: number of channels
    :param freq: frequency
    :param chunk_size: chunk size
    :param source_buffer: buffer for samples to push (if it's None sine data will be sended)
    :param name: name of outlet
    :return:
    """
    # default freq
    freq = freq or 500

    # labels and n_channels
    labels = labels or ch_names32
    n_channels = len(labels) if labels is not None else 32

    # stream info
    info = StreamInfo(name=name, type='EEG', channel_count=n_channels, nominal_srate=freq,
                      channel_format='float32', source_id='myuid34234')

    # channels labels (in accordance with XDF format, see also code.google.com/p/xdf)

    chns = info.desc().append_child("channels")
    for label in labels:
        ch = chns.append_child("channel")
        ch.append_child_value("label", label)
    outlet = StreamOutlet(info, chunk_size=chunk_size)

    # send data and print some info every 5 sec
    print('now sending data...')
    t0 = time.time()
    t = t0
    c = 1
    ampl = 10
    freqs = np.arange(n_channels)*5 + 10
    sample = np.zeros((n_channels,))
    if source_buffer is not None:
        source_buffer = np.concatenate([source_buffer.T, source_buffer.T[::-1]]).T

    while True:
        # if source_buffer is not None get sample from source_buffer
        # else simulate sin(a*t)*sin(b*t)
        if source_buffer is not None:
            sample[:source_buffer.shape[0]] = source_buffer[:, c % source_buffer.shape[1]]
        else:
            sample = np.sin(2 * np.pi * time.time() * 50) * 0 + np.sin(2 * np.pi * time.time() * freqs)
            # sample *= (np.sin(2 * np.pi * time.time() * 0.25) + 1) * ampl
            sample *= c % (500 * 4) * ampl

        if c % 20000 > 10000:
            sample[0] *= 1
        # push sample end sleep 1/freq sec
        outlet.push_sample(sample)
        time.sleep(1. / freq)
        # print time, frequency and samples count every 5 sec
        if c % (freq * 5) == 0:
            t_curr = time.time()
            print('t={:.1f}, f={:.2f}, c={}'.format(t_curr - t0, 1. / (t_curr - t) * freq * 5, c))
            t = t_curr
        c += 1
    pass