本文整理汇总了Python中pylsl.StreamInlet类的典型用法代码示例。如果您正苦于以下问题:Python StreamInlet类的具体用法?Python StreamInlet怎么用?Python StreamInlet使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了StreamInlet类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: initialize
def initialize(self):
self.debug=self.setting['debug'] == "true"
print "Debug: ", self.debug
self.stream_type=self.setting['Stream type']
# total channels for all streams
self.channelCount = 0
all_streams = self.setting['Get all streams'] == "true"
self.overcomeCheck = self.setting['Overcome code check'] == "true"
self.stream_name=self.setting['Stream name'] # in case !all_streams
print "Looking for streams of type: " + self.stream_type
streams = resolve_stream('type',self.stream_type)
print "Nb streams: " + str( len(streams))
if not all_streams:
print "Will only select (first) stream named: " + self.stream_name
self.nb_streams = 1
else:
self.nb_streams = len(streams)
# create inlets to read from each stream
self.inlets = []
# retrieve also corresponding StreamInfo for future uses (eg sampling rate)
self.infos = []
# save inlets and info + build signal header
for stream in streams:
# do not set max_buflen because we *should not* be spammed by values
inlet = StreamInlet(stream, max_buflen=1)
info = inlet.info()
name = info.name()
print "Stream name: " + name
# if target one stream, ignore false ones
if not all_streams and name != self.stream_name:
continue
print "Nb channels: " + str(info.channel_count())
self.channelCount += info.channel_count()
stream_freq = info.nominal_srate()
print "Sampling frequency: " + str(stream_freq)
if stream_freq != 0:
print "WARNING: Wrong stream?"
self.inlets.append(inlet)
self.infos.append(info)
# if we're still here when we target a stream, it means we foand it
if not all_streams:
print "Found target stream"
break
# we need at least one stream before we let go
if self.channelCount <= 0:
raise Exception("Error: no stream found.")
# we append to the box output a stimulation header. This is just a header, dates are 0.
self.output[0].append(OVStimulationHeader(0., 0.))
示例2: BetaInlet
class BetaInlet(object):
def __init__(self):
print("looking for an EEG stream...")
streams = resolve_byprop("type", "EEG")
# create a new inlet to read from the stream
proc_flags = proc_clocksync | proc_dejitter | proc_monotonize
self.inlet = StreamInlet(streams[0], processing_flags=proc_flags)
# The following is an example of how to read stream info
stream_info = self.inlet.info()
stream_Fs = stream_info.nominal_srate()
stream_xml = stream_info.desc()
chans_xml = stream_xml.child("channels")
chan_xml_list = []
ch = chans_xml.child("channel")
while ch.name() == "channel":
chan_xml_list.append(ch)
ch = ch.next_sibling("channel")
self.channel_names = [ch_xml.child_value("label") for ch_xml in chan_xml_list]
print("Reading from inlet named {} with channels {} sending data at {} Hz".format(stream_info.name(),
self.channel_names, stream_Fs))
def update(self):
max_samps = 3276*2
data = np.nan * np.ones((max_samps, len(self.channel_names)), dtype=np.float32)
_, timestamps = self.inlet.pull_chunk(max_samples=max_samps, dest_obj=data)
data = data[:len(timestamps), :]
print("Beta inlet retrieved {} samples.".format(len(timestamps)))
return data, np.asarray(timestamps)
示例3: initialize
def initialize(self):
self.initLabel = 0
self.debug=self.setting['debug'] == "true"
print "Debug: ", self.debug
self.stream_type=self.setting['Stream type']
self.stream_name=self.setting['Stream name']
# total channels for all streams
self.channelCount = 0
#self.stream_name=self.setting['Stream name'] # in case !all_streams
print "Looking for streams of type: " + self.stream_type
streams = resolve_stream('type',self.stream_type)
print "Nb streams: " + str( len(streams))
self.nb_streams = len(streams)
if self.nb_streams == 0:
raise Exception("Error: no stream found.")
self.inlet = StreamInlet(streams[0], max_buflen=1)
self.info = self.inlet.info()
self.channelCount = self.info.channel_count()
print "Stream name: " + self.info.name()
stream_freq = self.info.nominal_srate()
if stream_freq != 0:
raise Exception("Error: no irregular stream found.")
# we append to the box output a stimulation header. This is just a header, dates are 0.
self.output[0].append(OVStimulationHeader(0., 0.))
self.init = False
示例4: __init__
class LSLInlet:
def __init__(self, name=LSL_STREAM_NAMES[2], max_chunklen=8, n_channels=20):
streams = resolve_byprop('name', name, timeout=LSL_RESOLVE_TIMEOUT)
self.inlet = None
self.dtype = 'float64'
if len(streams) > 0:
self.inlet = StreamInlet(streams[0], max_buflen=1, max_chunklen=max_chunklen)
# self.dtype = fmt2string[self.inlet.info().channel_format()]
print(self.dtype)
self.n_channels = n_channels if n_channels else self.inlet.info().channel_count()
def get_next_chunk(self):
# get next chunk
chunk, timestamp = self.inlet.pull_chunk()
# convert to numpy array
chunk = np.array(chunk, dtype=self.dtype)
# return first n_channels channels or None if empty chunk
return chunk[:, :self.n_channels] if chunk.shape[0] > 0 else None
def update_action(self):
pass
def save_info(self, file):
with open(file, 'w') as f:
f.write(self.inlet.info().as_xml())
def get_frequency(self):
return self.inlet.info().nominal_srate()
def get_n_channels(self):
return self.n_channels
def get_channels_labels_bad(self):
time.sleep(0.001)
labels = []
ch = self.inlet.info().desc().child("channels").child("channel")
for k in range(self.get_n_channels()):
labels.append(ch.child_value("label"))
ch = ch.next_sibling()
return
def get_channels_labels(self):
return ch_names[:self.n_channels]
def disconnect(self):
del self.inlet
self.inlet = None
示例5: __init__
def __init__(self):
app.Canvas.__init__(self, title='Use your wheel to zoom!',
keys='interactive')
# first resolve an EEG stream on the lab network
print("looking for an EEG stream...")
streams = resolve_stream('name', 'RandomSpehricalData')
streamInfo = streams[0]
# create a new inlet to read from the stream
self.inlet = StreamInlet(streamInfo)
# Number of cols and rows in the table.
self.nrows = streamInfo.channel_count()
n = streamInfo.nominal_srate()
ncols = 1
# Number of signals.
m = self.nrows*ncols
# Various signal amplitudes.
amplitudes = .1 + .2 * np.random.rand(m, 1).astype(np.float32)
# Generate the signals as a (m, n) array.
self.y = amplitudes * np.random.randn(m, n).astype(np.float32)
color = np.repeat(np.random.uniform(size=(m, 3), low=.5, high=.9),
n, axis=0).astype(np.float32)
# Signal 2D index of each vertex (row and col) and x-index (sample index
# within each signal).
index = np.c_[np.repeat(np.repeat(np.arange(ncols), self.nrows), n),
np.repeat(np.tile(np.arange(self.nrows), ncols), n),
np.tile(np.arange(n), m)].astype(np.float32)
self.program = gloo.Program(VERT_SHADER, FRAG_SHADER)
self.program['a_position'] = self.y.reshape(-1, 1)
self.program['a_color'] = color
self.program['a_index'] = index
self.program['u_scale'] = (1., 1.)
self.program['u_size'] = (self.nrows, ncols)
self.program['u_n'] = n
gloo.set_viewport(0, 0, *self.physical_size)
self._timer = app.Timer('auto', connect=self.on_timer, start=True)
gloo.set_state(clear_color='black', blend=True,
blend_func=('src_alpha', 'one_minus_src_alpha'))
self.sampleFromLSL = None
self.show()
示例6: __init__
def __init__(self, stream_type='PPG', stream_id=None, buflen=5):
"""
stream_type: LSL type of the stream to check
stream_id: will select specifically one stream based on its name "[stream_type]_[stream_id]"
"""
# first resolve said stream type on the network
streams = resolve_stream('type',stream_type)
self.nb_streams = 0
if len(streams) < 1:
raise NameError('LSLTypeNotFound')
print "Detecting", len(streams), stream_type, "streams"
# create inlets to read from each stream
self.inlets = []
# retrieve also corresponding StreamInfo for future uses (eg sampling rate)
self.infos = []
for stream in streams:
inlet = StreamInlet(stream, max_buflen=buflen)
info = inlet.info()
# if an ID is specified, will look only for it, otherwise add everything
if stream_id is not None:
if info.name() == stream_type + "_" + str(stream_id):
# check that there is a unique stream with this name to stop right there any ambiguity
if self.nb_streams > 0:
raise NameError('LSLDuplicateStreamName')
else:
self.inlets.append(inlet)
self.infos.append(info)
self.nb_streams = self.nb_streams + 1
else:
self.inlets.append(inlet)
self.infos.append(info)
self.nb_streams = self.nb_streams + 1
if stream_id and self.nb_streams < 1:
raise NameError('LSLStreamNameNotFound')
# init list of samples
self.samples = [] * self.nb_streams
示例7: MarkerInlet
class MarkerInlet(object):
def __init__(self):
self.task = {'phase':'precue', 'class':1, 'target':1}
print("Looking for stream with type Markers")
streams = resolve_bypred("type='Markers'", minimum=1)
proc_flags = 0 # Marker events are relatively rare. No need to post-process.
self.inlet = StreamInlet(streams[0], processing_flags=proc_flags)
# The following is an example of how to read stream info
stream_info = self.inlet.info()
stream_Fs = stream_info.nominal_srate()
stream_xml = stream_info.desc()
chans_xml = stream_xml.child("channels")
chan_xml_list = []
ch = chans_xml.child("channel")
while ch.name() == "channel":
chan_xml_list.append(ch)
ch = ch.next_sibling("channel")
stream_ch_names = [ch_xml.child_value("label") for ch_xml in chan_xml_list]
print("Reading from inlet named {} with channels {}".format(stream_info.name(), stream_ch_names))
def update(self):
marker_samples, marker_timestamps = self.inlet.pull_chunk(timeout=0.0)
if (marker_timestamps):
[phase_str, class_str, targ_str] = marker_samples[-1][0].split(', ')
if phase_str in ['TargetCue']:
self.task['phase'] = 'cue'
elif phase_str in ['GoCue']:
self.task['phase'] = 'go'
elif phase_str in ['Miss', 'Hit']:
self.task['phase'] = 'evaluate'
elif phase_str[:8] == 'NewTrial':
self.task['phase'] = 'precue'
else:
print(phase_str)
self.task['class'] = int(class_str.split(' ')[1])
self.task['target'] = int(targ_str.split(' ')[1])
print("Marker inlet updated with task {}".format(self.task))
示例8: __init__
def __init__(self):
self.task = {'phase':'precue', 'class':1, 'target':1}
print("Looking for stream with type Markers")
streams = resolve_bypred("type='Markers'", minimum=1)
proc_flags = 0 # Marker events are relatively rare. No need to post-process.
self.inlet = StreamInlet(streams[0], processing_flags=proc_flags)
# The following is an example of how to read stream info
stream_info = self.inlet.info()
stream_Fs = stream_info.nominal_srate()
stream_xml = stream_info.desc()
chans_xml = stream_xml.child("channels")
chan_xml_list = []
ch = chans_xml.child("channel")
while ch.name() == "channel":
chan_xml_list.append(ch)
ch = ch.next_sibling("channel")
stream_ch_names = [ch_xml.child_value("label") for ch_xml in chan_xml_list]
print("Reading from inlet named {} with channels {}".format(stream_info.name(), stream_ch_names))
示例9: len
assert len(sys.argv) > 0, 'No experiment name provided'
filename = sys.argv[1]
timequant = 0.100 #s
print("looking for device stream")
device = OpenBCI8
bci_info = resolve_byprop('source_id', device.source_id, timeout=1)[0]
print("Device stream discovered")
print('Looking for GUI source')
experiment_info = resolve_byprop('source_id', Experiment.source_id,
timeout=100)[0]
print('GUI source discovered')
#print(experiment_info, bci_info)
experiment_inlet = StreamInlet(experiment_info)
bci_inlet = StreamInlet(bci_info)
bci_results = [[], []]
experiment_results = [[], []]
print('Recording')
while True:
# get a new sample (you can also omit the timestamp part if you're not
# interested in it)
bci_values, bci_timestamps = bci_inlet.pull_chunk(max_samples=device.sfreq * 60 *6)
bci_results[0].extend(bci_values)
bci_results[1].extend(bci_timestamps)
experiment_values, experiment_timestamps = experiment_inlet.pull_chunk()
experiment_results[0].extend(experiment_values)
示例10: StreamOutlet
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 ===
# first we resolve a stream whose name is MetaTester (note that there are
# other ways to query a stream, too - for instance by content-type)
results = resolve_stream("name", "MetaTester")
# open an inlet so we can read the stream's data (and meta-data)
inlet = StreamInlet(results[0])
# get the full stream info (including custom meta-data) and dissect it
info = inlet.info()
print("The stream's XML meta-data is: ")
print(info.as_xml())
print("The manufacturer is: %s" % info.desc().child_value("manufacturer"))
print("Cap circumference is: %s" % info.desc().child("cap").child_value("size"))
print("The channel labels are as follows:")
ch = info.desc().child("channels").child("channel")
for k in range(info.channel_count()):
print(" " + ch.child_value("label"))
ch = ch.next_sibling()
time.sleep(3)
示例11: print
import time;
import numpy as np
from pylsl import StreamInlet, resolve_stream
#Input:
#1: Number of secs for test
#2: Datetime
#3: Sample id
channel_len = 8
ignore_first_secs = 0.01
ignore_last_secs = 0.01
# first resolve an EEG stream on the lab network
print("Looking for an EEG stream")
streams = resolve_stream("type","EEG",)
inlet = StreamInlet(streams[0])
print("Stream Found")
datastream = []
time.sleep(ignore_first_secs);
timeout = time.time() + float(sys.argv[2]) - ignore_last_secs
while True:
if time.time() > timeout:
break
#sample[0] has the data, sample[1] has a timestamp
sample = inlet.pull_sample()
datastream.append(sample[0])
#Build folder structure
zpad = 6
示例12: info
# 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)
fs = 1000
info = StreamInfo('python', 'EEG', 2)
# next make an outlet
outlet = StreamOutlet(info)
from pylsl import StreamInlet, resolve_stream
print('resolving stream')
streams = resolve_stream('name', 'matlab')
# create a new inlet to read from the stream
inlet = StreamInlet(streams[0])
print('resolved')
t = 0
mean_time = 0
while True:
#time.sleep(0.002)
t += 1
clock = local_clock()
outlet.push_sample([0, 1])
sample, timestamp = inlet.pull_sample(timeout=1)
dt = local_clock() - clock
mean_time += dt
print(mean_time / t, dt)
#time.sleep(0.001)
示例13: print
import bci_workshop_tools as BCIw # Our own functions for the workshop
if __name__ == "__main__":
""" 1. CONNECT TO EEG STREAM """
# Search for active LSL stream
print('Looking for an EEG stream...')
streams = resolve_byprop('type', 'EEG', timeout=2)
if len(streams) == 0:
raise RuntimeError('Can\'t find EEG stream.')
# Set active EEG stream to inlet and apply time correction
print("Start acquiring data")
inlet = StreamInlet(streams[0], max_chunklen=12)
eeg_time_correction = inlet.time_correction()
# Get the stream info, description, sampling frequency, number of channels
info = inlet.info()
description = info.desc()
fs = int(info.nominal_srate())
n_channels = info.channel_count()
# Get names of all channels
ch = description.child('channels').first_child()
ch_names = [ch.child_value('label')]
for i in range(1, n_channels):
ch = ch.next_sibling()
ch_names.append(ch.child_value('label'))
示例14: print
exptime = 900
dt_rate = 0.1
# allocating buffers
received_data_buf = np.zeros((numch, exptime*srate*1.2))
states_predicted_buf = np.zeros((1, exptime*srate*1.2))
pos = 0
pos_pred = 0
# first resolve an EEG stream on the lab network
print("looking for an EEG stream...")
streams = resolve_stream('type', 'Data')
# create a new inlet to read from the stream
inlet = StreamInlet(streams[0])
globalstart = time.time()
while (time.time() - globalstart < exptime):
startwhile = time.time()
chunk, timestamp = inlet.pull_chunk()
np_ar_chunk = np.asarray(chunk)
chunk_size = np_ar_chunk.shape[0]
if chunk_size > 0:
data_chunk_test = np_ar_chunk.T
示例15: print
default=[0, 1, 2, 3],
help='channel number to use. If not specified, all the channels are used')
args = parser.parse_args()
""" 1. CONNECT TO EEG STREAM """
# Search for active LSL stream
print('Looking for an EEG stream...')
streams = resolve_byprop('type', 'EEG', timeout=2)
if len(streams) == 0:
raise RuntimeError('Can\'t find EEG stream.')
# Set active EEG stream to inlet and apply time correction
print("Start acquiring data")
inlet = StreamInlet(streams[0], max_chunklen=12)
eeg_time_correction = inlet.time_correction()
# Get the stream info, description, sampling frequency, number of channels
info = inlet.info()
description = info.desc()
fs = int(info.nominal_srate())
n_channels = info.channel_count()
# Get names of all channels
ch = description.child('channels').first_child()
ch_names = [ch.child_value('label')]
for i in range(1, n_channels):
ch = ch.next_sibling()
ch_names.append(ch.child_value('label'))