def activate(self):
		eeg_stream = "OpenBCI_EEG"
		eeg_id = "openbci_eeg_id1"
		aux_stream = "OpenBCI_AUX"
		aux_id = "openbci_aux_id1"
		
		if len(self.args) > 0:
			eeg_stream = self.args[0]
		if len(self.args) > 1:
			eeg_id = self.args[1]
		if len(self.args) > 2:
			aux_stream = self.args[2]
		if len(self.args) > 3:
			aux_id = self.args[3]

		# Create a new streams info, one for EEG values, one for AUX (eg, accelerometer) values
		print "Creating LSL stream for EEG. Name:", eeg_stream, "- ID:", eeg_id, "- data type: float32.", self.eeg_channels, "channels at", self.sample_rate, "Hz."
		info_eeg = StreamInfo(eeg_stream, 'EEG', self.eeg_channels,self.sample_rate,'float32',eeg_id);
		# NB: set float32 instead of int16 so as OpenViBE takes it into account
		print "Creating LSL stream for AUX. Name:", aux_stream, "- ID:", aux_id, "- data type: float32.", self.aux_channels, "channels at", self.sample_rate, "Hz."
		info_aux = StreamInfo(aux_stream, 'AUX', self.aux_channels,self.sample_rate,'float32',aux_id);
		
		# make outlets
		self.outlet_eeg = StreamOutlet(info_eeg)
		self.outlet_aux = StreamOutlet(info_aux)
예제 #2
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)
예제 #3
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))
예제 #4
0
    def second_init(self):
        """Used because otherwise multiprocessing cannot pickle LSL instances"""

        # LSL Settings
        self.eeg_streamname = 'testeeg_stream'
        self.marker_streamname = 'marker_stream'
        self.period_time = 1.0 / self.data.samplerate  # seconds

        # EEG stream
        self.eeg_info = StreamInfo(name=self.eeg_streamname,
                                   nominal_srate=self.data.samplerate,
                                   type='EEG',
                                   channel_count=self.data.num_channels,
                                   channel_format='float32',
                                   source_id='eeg_stream_test',
                                   handle=None)
        self.lsl_eeg = StreamOutlet(self.eeg_info)

        # Marker Stream
        self.marker_info = StreamInfo(name=self.marker_streamname,
                                      type='P300_Marker',
                                      nominal_srate=IRREGULAR_RATE,
                                      channel_count=1,
                                      channel_format='int8',
                                      source_id='marker_stream',
                                      handle=None)
        self.marker_info.desc().append_child_value('flash_mode',
                                                   self.data.flash_mode)
        self.marker_info.desc().append_child_value('num_rows', '6')
        self.marker_info.desc().append_child_value('num_cols', '6')
        self.lsl_marker = StreamOutlet(self.marker_info)
예제 #5
0
파일: stream.py 프로젝트: ecmyhre/muse-lsl
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.')
예제 #6
0
파일: mock.py 프로젝트: pyreiz/pyliesl
    def __init__(
        self,
        name="Liesl-Mock-EEG",
        type="EEG",
        channel_count=8,
        nominal_srate=1000,
        channel_format="float32",
        source_id=None,
    ):

        threading.Thread.__init__(self)

        if source_id == None:
            source_id = str(hash(self))

        self.info = StreamInfo(name, type, channel_count, nominal_srate,
                               channel_format, source_id)
        self.channel_count = channel_count
        self.samplestep = 1 / nominal_srate
        self.is_running = False
        channels = self.info.desc().append_child("channels")
        types = (f"MockEEG" for x in range(1, channel_count + 1, 1))
        units = ("au" for x in range(1, channel_count + 1, 1))
        names = (f"C{x:03d}" for x in range(1, channel_count + 1, 1))
        for c, u, t in zip(names, units, types):
            channels.append_child("channel").append_child_value(
                "label",
                c).append_child_value("unit", u).append_child_value("type", t)
예제 #7
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)
예제 #8
0
def initializeOutlet(interface):
    """
    Initializes and returns an LSL outlet
    :param interface: Interface
        the Python interface to communicate with node
    :return: StreamOutlet
        returns a labstreaminglayer StreamOutlet
    """
    numChans = None
    while not numChans:
        msg = interface.recv()
        try:
            dicty = json.loads(msg)
            numChans = dicty.get('numChans')
            sampleRate = dicty.get('sampleRate')
        except ValueError as e:
            print(e)
    data_info = StreamInfo('OpenBCI_EEG', 'EEG', numChans, sampleRate,
                           'float32', 'myuid34234')
    marker_info = StreamInfo('MarkerStream', 'Markers', 1, 0, 'string',
                             'markerstream12345')
    data_outlet = StreamOutlet(data_info)
    marker_outlet = StreamOutlet(marker_info)

    print('init')
    return data_outlet, marker_outlet
    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
예제 #10
0
 def create_lsl(self):
     info_eeg = StreamInfo("OpenBCI_EEG", 'EEG', self.eeg_channels,
                           self.sample_rate, 'float32', "openbci_eeg_id1")
     info_aux = StreamInfo("OpenBCI_AUX", 'AUX', self.aux_channels,
                           self.sample_rate, 'float32', "openbci_aux_id1")
     self.outlet_eeg = StreamOutlet(info_eeg)
     self.outlet_aux = StreamOutlet(info_aux)
예제 #11
0
    def __setup_output_stream(self, stream_name, stream_type):
        """
        Initialize a LSL outlet of particular name and type
        Parameters
        ----------
        stream_name : str
            Name of LSL outlet to initialize. Can be anything.
        stream_type : str
            Type of LSL outlet to initialze. Typical choices are 'marker', 'data',
            or 'eeg'.
        Returns
        -------
        outlet : LSL Outlet
            Creates a LSL-ready outlet for streaming data over the network.
        """
        # Identify the type of data we are sending back.
        if stream_type.casefold() == 'marker'.casefold():
            info = StreamInfo(stream_name,
                              stream_type,
                              channel_count=1,
                              nominal_srate=0,
                              channel_format='string',
                              source_id='single314uid')
        elif stream_type.casefold() == 'data'.casefold():
            info = StreamInfo(stream_name,
                              stream_type,
                              channel_count=1,
                              nominal_srate=0,
                              source_id='single314uid')

        # Make the stream outlet using the infor provided above
        print('...setting up LSL outlet object...')
        outlet = StreamOutlet(info)

        return outlet
예제 #12
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)
    def second_init(self):
        """Used because otherwise multiprocessing cannot pickle LSL instances"""

        # LSL Settings
        self.eeg_streamname = "testeeg_stream"
        self.marker_streamname = "marker_stream"
        self.period_time = 1.0 / self.data.samplerate  # seconds

        # EEG stream
        self.eeg_info = StreamInfo(
            name=self.eeg_streamname,
            nominal_srate=self.data.samplerate,
            type="EEG",
            channel_count=self.data.num_channels,
            channel_format="float32",
            source_id="eeg_stream_test",
            handle=None,
        )
        self.lsl_eeg = StreamOutlet(self.eeg_info)

        # Marker Stream
        self.marker_info = StreamInfo(
            name=self.marker_streamname,
            type="P300_Marker",
            nominal_srate=IRREGULAR_RATE,
            channel_count=1,
            channel_format="int8",
            source_id="marker_stream",
            handle=None,
        )
        self.marker_info.desc().append_child_value("flash_mode",
                                                   self.data.flash_mode)
        self.marker_info.desc().append_child_value("num_rows", "6")
        self.marker_info.desc().append_child_value("num_cols", "6")
        self.lsl_marker = StreamOutlet(self.marker_info)
예제 #14
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()
예제 #15
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)
예제 #16
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)
예제 #17
0
    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]
예제 #18
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)
예제 #19
0
 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)
예제 #20
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
예제 #21
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
예제 #22
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
예제 #23
0
 def __init__(self, info: pylsl.StreamInfo, plt: pg.PlotItem):
     super().__init__(info)
     # calculate the size for our buffer, i.e. two times the displayed data
     bufsize = (2 * math.ceil(info.nominal_srate() * plot_duration), info.channel_count())
     self.buffer = np.empty(bufsize, dtype=self.dtypes[info.channel_format()])
     empty = np.array([])
     # create one curve object for each channel/line that will handle displaying the data
     self.curves = [pg.PlotCurveItem(x=empty, y=empty, autoDownsample=True) for _ in range(self.channel_count)]
     for curve in self.curves:
         plt.addItem(curve)
예제 #24
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)
예제 #25
0
 def start_lsl(self):
     """
     initial lsl communication and allow data to send according to number of device in the robot
     """
     self.pos_outlet = StreamOutlet(
         StreamInfo('Softhand Position Data', 'Position',
                    3 * len(self.devices), 100, 'int16', 'myshpos20191002'))
     self.cur_outlet = StreamOutlet(
         StreamInfo('Softhand Current Data', 'Current',
                    2 * len(self.devices), 100, 'int16', 'myshcur20191002'))
     self.is_lsl = True
예제 #26
0
    def __init__(self):
        print("\n-------INSTANTIATING DUMMY BOARD-------")
        self.n_channels = 4
        self.sample_freq = 250

        self.state = self.IDLE

        self.stream_info = StreamInfo("DummyStream", "EEG", self.n_channels,
                                      self.sample_freq, 'float32',
                                      "dummy_eeg_id1")
        self.outlet = StreamOutlet(self.stream_info)
예제 #27
0
    def __init__(self, name, idNum):
        print("\n-------INSTANTIATING DUMMY BOARD-------")
        self.n_channels = 32
        self.sample_freq = 250
        self.name = name
        self.id = idNum
        self.state = self.IDLE

        self.stream_info = StreamInfo(self.name, "EEG", self.n_channels,
                                      self.sample_freq, 'float32',
                                      "dummy_eeg_id%s" % str(self.id))
        self.outlet = StreamOutlet(self.stream_info)
예제 #28
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)
 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)
예제 #30
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
예제 #31
0
    def __init__(self, info: pylsl.StreamInfo):
        # create an inlet and connect it to the outlet we found earlier.
        # max_buflen is set so data older the plot_duration is discarded
        # automatically and we only pull data new enough to show it

        # Also, perform online clock synchronization so all streams are in the
        # same time domain as the local lsl_clock()
        # (see https://labstreaminglayer.readthedocs.io/projects/liblsl/ref/enums.html#_CPPv414proc_clocksync)
        # and dejitter timestamps
        self.inlet = pylsl.StreamInlet(info, max_buflen=plot_duration,
                                       processing_flags=pylsl.proc_clocksync | pylsl.proc_dejitter)
        # store the name and channel count
        self.name = info.name()
        self.channel_count = info.channel_count()
예제 #32
0
 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)
예제 #33
0
파일: generators.py 프로젝트: nikolaims/nfb
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
예제 #34
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)
예제 #35
0
    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()
예제 #36
0
		connection=1;
		break
	except TypeError:
		print "MAC address (%s) is not defined..." %macAddress
		print "connecting to BITalino(%s)..." 
	except ValueError:
		print "MAC address (%s) is not defined..." %macAddress
		print "connecting to BITalino(%s)..." 
	
# Set battery threshold
device.battery(batteryThreshold)
# Read BITalino version
print device.version()
print "connected to BITalino(%s)" %macAddress
print "creating Signal stream..."
info = StreamInfo('BiTalino','BiTalino',+len(acqChannels),samplingRate,'float32','myuid34234');
# next make an outlet
outlet = StreamOutlet(info)
print"created Signal stream : %s" %info.name()
print("starting acquisition...")
# Start Acquisition
device.start(samplingRate, acqChannels)
# Read samples
while 1:
	data=device.read(nSamples)
	print data
 	outlet.push_sample(data[0][defaultChannel+1:])

# Turn BITalino led on
device.trigger(digitalOutput)
# Stop acquisition
예제 #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)
예제 #38
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()
예제 #39
0
파일: generators.py 프로젝트: nikolaims/nfb
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
예제 #40
0
"""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 ===