How to use pylsl - 10 common examples

To help you get started, we’ve selected a few pylsl examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github Sentdex / BCI / testing_and_making_data.py View on Github external
model.predict( np.zeros((32,16,60)).reshape(reshape) )

ACTION = 'left' # THIS IS THE ACTION YOU'RE THINKING 

FFT_MAX_HZ = 60

HM_SECONDS = 10  # this is approximate. Not 100%. do not depend on this.
TOTAL_ITERS = HM_SECONDS*25  # ~25 iters/sec
BOX_MOVE = "model"  # random or model

last_print = time.time()
fps_counter = deque(maxlen=150)

# first resolve an EEG stream on the lab network
print("looking for an EEG stream...")
streams = resolve_stream('type', 'EEG')
# create a new inlet to read from the stream
inlet = StreamInlet(streams[0])

WIDTH = 800
HEIGHT = 800
SQ_SIZE = 50
MOVE_SPEED = 1

square = {'x1': int(int(WIDTH)/2-int(SQ_SIZE/2)), 
          'x2': int(int(WIDTH)/2+int(SQ_SIZE/2)),
          'y1': int(int(HEIGHT)/2-int(SQ_SIZE/2)),
          'y2': int(int(HEIGHT)/2+int(SQ_SIZE/2))}


box = np.ones((square['y2']-square['y1'], square['x2']-square['x1'], 3)) * np.random.uniform(size=(3,))
horizontal_line = np.ones((HEIGHT, 10, 3)) * np.random.uniform(size=(3,))
github OpenBCI / OpenBCI_LSL / lib / streamerlsl.py View on Github external
new_locs = [loc for loc in locs.split(',')]

      chns = self.info_eeg.desc().child('channels')
      ch = chns.child("channel")
      for label in new_locs:
        ch.set_child_value('label', label)
        ch = ch.next_sibling()

      
      print("New Channel Montage:")
      print(str(new_locs))


      #create StreamOutlet
      self.outlet_eeg = StreamOutlet(self.info_eeg)
      self.outlet_aux = StreamOutlet(self.info_aux)
github alexandrebarachant / muse-lsl / generate_Visual_P300.py View on Github external
return visual.ImageStim(win=mywin, image=filename)

mywin = visual.Window([1920, 1080], monitor="testMonitor", units="deg",
                      fullscr=True)
targets = map(loadImage, glob('stim/target-*.jpg'))
nontargets = map(loadImage, glob('stim/nontarget-*.jpg'))

for ii, trial in trials.iterrows():
    # inter trial interval
    core.wait(iti + np.random.rand() * jitter)

    # onset
    pos = trials['position'].iloc[ii]
    image = choice(targets if pos == 1 else nontargets)
    image.draw()
    timestamp = local_clock()
    outlet.push_sample([markernames[pos]], timestamp)
    mywin.flip()

    # offset
    core.wait(soa)
    mywin.flip()
    if len(event.getKeys()) > 0 or (time() - start) > record_duration:
        break
    event.clearEvents()
# Cleanup
mywin.close()
github dbdq / neurodecode / pycnbi / triggers / pyLptControl.py View on Github external
logger.info('Using software trigger')

            # get data file location
            LSL_SERVER = 'StreamRecorderInfo'
            inlet = cnbi_lsl.start_client(LSL_SERVER)
            evefile = inlet.info().source_id()
            eveoffset_file = evefile[:-4] + '-offset.txt'
            logger.info('Event file is: %s' % evefile)
            self.evefile = open(evefile, 'a')

            if check_lsl_offset:
                # check server LSL time server integrity
                logger.info("Checking LSL server's timestamp integrity for logging software triggers.")
                amp_name, amp_serial = pu.search_lsl()
                sr = StreamReceiver(window_size=1, buffer_size=1, amp_serial=amp_serial, eeg_only=False, amp_name=amp_name)
                local_time = pylsl.local_clock()
                server_time = sr.get_window_list()[1][-1]
                lsl_time_offset = local_time - server_time
                with open(eveoffset_file, 'a') as f:
                    f.write('Local time: %.6f, Server time: %.6f, Offset: %.6f\n' % (local_time, server_time, lsl_time_offset))
                logger.info('LSL timestamp offset (%.3f) saved to %s' % (lsl_time_offset, eveoffset_file))

        elif self.lpttype == 'FAKE' or self.lpttype is None or self.lpttype is False:
            logger.warning('Using a fake trigger.')
            self.lpttype = 'FAKE'
            self.lpt = None

        else:
            logger.error('Unrecognized lpttype device name %s' % lpttype)
            sys.exit(-1)
github BciPy / BciPy / bcipy / signal / viewer / lsl_viewer.py View on Github external
parser.add_option("-f", "--figure",
                      dest="figure", type='string', default="15x6",
                      help="window size.")

    filt = True
    subsample = 3
    buf = 12

    (options, args) = parser.parse_args()

    window = options.window
    scale = options.scale
    figsize = np.int16(options.figure.split('x'))

    logging.debug("looking for an EEG stream...")
    streams = resolve_byprop('type', 'EEG', timeout=2)

    if len(streams) == 0:
        raise(RuntimeError("Cant find EEG stream"))
    logging.debug("Start aquiring data")

    fig, axes = plt.subplots(1, 1, figsize=figsize, sharex=True)
    lslv = LSLViewer(streams[0], fig, axes, window, scale, filter_data=filt)

    lslv.start()

    plt.show()
    lslv.stop()
github labstreaminglayer / App-SigVisualizer / paintwidget.py View on Github external
n = stream.name()
                stream_params = copy.deepcopy(self.def_stream_parms)
                stream_params['metadata'].update({
                    "name": n,
                    "ch_count": stream.channel_count(),
                    "ch_format": stream.channel_format(),
                    "srate": stream.nominal_srate()
                })
                # ch = stream.desc().child("channels").child("channel")
                # for ch_ix in range(stream.channel_count()):
                #     print("  " + ch.child_value("label"))
                #     ch = ch.next_sibling()

                stream_params['inlet'] = pylsl.StreamInlet(stream)
                stream_params['is_marker'] = stream.channel_format() in ["String", pylsl.cf_string]\
                                             and stream.nominal_srate() == pylsl.IRREGULAR_RATE
                if not stream_params['is_marker']:
                    if self.sig_strm_idx < 0:
                        self.sig_strm_idx = k
                    srate = stream.nominal_srate()
                    stream_params['downSampling'] = srate > 1000
                    stream_params['chunkSize'] = round(srate / self.chunksPerScreen * self.seconds_per_screen)
                    if stream_params['downSampling']:
                        stream_params['downSamplingFactor'] = round(srate / 1000)
                        n_buff = round(stream_params['chunkSize'] / stream_params['downSamplingFactor'])
                        stream_params['downSamplingBuffer'] = [[0] * int(stream.channel_count())] * n_buff
                self.stream_params.append(stream_params)

            self.updateStreamNames.emit([_['metadata'] for _ in self.stream_params], self.sig_strm_idx)
            self.start()
github labstreaminglayer / App-SigVisualizer / paintwidget.py View on Github external
for k, stream in enumerate(self.streams):
                n = stream.name()
                stream_params = copy.deepcopy(self.def_stream_parms)
                stream_params['metadata'].update({
                    "name": n,
                    "ch_count": stream.channel_count(),
                    "ch_format": stream.channel_format(),
                    "srate": stream.nominal_srate()
                })
                # ch = stream.desc().child("channels").child("channel")
                # for ch_ix in range(stream.channel_count()):
                #     print("  " + ch.child_value("label"))
                #     ch = ch.next_sibling()

                stream_params['inlet'] = pylsl.StreamInlet(stream)
                stream_params['is_marker'] = stream.channel_format() in ["String", pylsl.cf_string]\
                                             and stream.nominal_srate() == pylsl.IRREGULAR_RATE
                if not stream_params['is_marker']:
                    if self.sig_strm_idx < 0:
                        self.sig_strm_idx = k
                    srate = stream.nominal_srate()
                    stream_params['downSampling'] = srate > 1000
                    stream_params['chunkSize'] = round(srate / self.chunksPerScreen * self.seconds_per_screen)
                    if stream_params['downSampling']:
                        stream_params['downSamplingFactor'] = round(srate / 1000)
                        n_buff = round(stream_params['chunkSize'] / stream_params['downSamplingFactor'])
                        stream_params['downSamplingBuffer'] = [[0] * int(stream.channel_count())] * n_buff
                self.stream_params.append(stream_params)

            self.updateStreamNames.emit([_['metadata'] for _ in self.stream_params], self.sig_strm_idx)
            self.start()
github alexandrebarachant / muse-lsl / stimulus_presentation / generate_N170.py View on Github external
import numpy as np
from pandas import DataFrame
from psychopy import visual, core, event
from pylsl import StreamInfo, StreamOutlet, local_clock

parser = OptionParser()
parser.add_option("-d", "--duration",
                  dest="duration", type='int', default=400,
                  help="duration of the recording in seconds.")

(options, args) = parser.parse_args()

# Create markers stream outlet
info = StreamInfo('Markers', 'Markers', 1, 0, 'int32', 'myuidw43536')
outlet = StreamOutlet(info)

markernames = [1, 2]
start = time()

# Set up trial parameters
n_trials = 2010
iti = 0.3
soa = 0.2
jitter = 0.2
record_duration = np.float32(options.duration)

# Setup trial list
image_type = np.random.binomial(1, 0.5, n_trials)
trials = DataFrame(dict(image_type=image_type,
                        timestamp=np.zeros(n_trials)))
github compmem / smile / smile / lsl.py View on Github external
"""
    if _got_pylsl:
        global _lsl_outlets

        s = "_"
        unique_identifier = s.join([server_name, server_type, str(nchans),
                                    str(suggested_freq), str(channel_format),
                                    str(unique_id)])

        if unique_identifier in _lsl_outlets.keys():
            return _lsl_outlets[unique_identifier]
        else:
            info = StreamInfo(server_name, server_type, nchans, suggested_freq,
                              channel_format, unique_id)
            _lsl_outlets[unique_identifier] = StreamOutlet(info)
            return _lsl_outlets[unique_identifier]
    else:
        print("Unable to setup LSL server! No sync pulses will be made.")
        return None
github alexandrebarachant / muse-lsl / muselsl / stream.py View on Github external
address = found_muse['address']
                name = found_muse['name']

    if not eeg_disabled:
        eeg_info = StreamInfo('Muse', 'EEG', MUSE_NB_EEG_CHANNELS, MUSE_SAMPLING_EEG_RATE, 'float32',
                              'Muse%s' % 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)

    if ppg_enabled:
        ppg_info = StreamInfo('Muse', 'PPG', MUSE_NB_PPG_CHANNELS, MUSE_SAMPLING_PPG_RATE,
                              'float32', 'Muse%s' % address)
        ppg_info.desc().append_child_value("manufacturer", "Muse")
        ppg_channels = ppg_info.desc().append_child("channels")

        for c in ['PPG1', 'PPG2', 'PPG3']:
            ppg_channels.append_child("channel") \
                .append_child_value("label", c) \
                .append_child_value("unit", "mmHg") \
                .append_child_value("type", "PPG")

        ppg_outlet = StreamOutlet(ppg_info, LSL_PPG_CHUNK)

    if acc_enabled: