本文整理汇总了Python中pylsl.StreamInlet类的典型用法代码示例。如果您正苦于以下问题:Python StreamInlet类的具体用法?Python StreamInlet怎么用?Python StreamInlet使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了StreamInlet类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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.))
开发者ID:jelenaLis,项目名称:script-openVibe,代码行数:60,代码来源:python_lsl_stims.py
示例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)
开发者ID:cboulay,项目名称:labstreaminglayer,代码行数:30,代码来源:PerformanceTest.py
示例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
开发者ID:jfrey-xx,项目名称:openMatch,代码行数:25,代码来源:python_lsl_stims.py
示例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
开发者ID:nikolaims,项目名称:nfb,代码行数:47,代码来源:lsl_inlet_n_channels.py
示例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()
开发者ID:xfleckx,项目名称:BeMoBI_Tools,代码行数:55,代码来源:LSL2Vispy.py
示例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
开发者ID:jfrey-xx,项目名称:multiPPG,代码行数:42,代码来源:readerLSL.py
示例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))
开发者ID:cboulay,项目名称:labstreaminglayer,代码行数:37,代码来源:PerformanceTest.py
示例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))
开发者ID:cboulay,项目名称:labstreaminglayer,代码行数:18,代码来源:PerformanceTest.py
示例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)
开发者ID:Egor-Krivov,项目名称:eegstream,代码行数:31,代码来源:experiment_recorder.py
示例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)
开发者ID:cboulay,项目名称:labstreaminglayer,代码行数:30,代码来源:HandleMetadata.py
示例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
开发者ID:eduardo-elizondo,项目名称:eeg_sampling,代码行数:31,代码来源:start_stream.py
示例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)
开发者ID:nikolaims,项目名称:nfb,代码行数:30,代码来源:lsl_send_receive.py
示例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'))
开发者ID:bcimontreal,项目名称:bci_workshop,代码行数:30,代码来源:exercise_01_multichannel.py
示例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
开发者ID:nikolaims,项目名称:nfb,代码行数:30,代码来源:runmain2.py
示例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'))
开发者ID:bcimontreal,项目名称:bci_workshop,代码行数:30,代码来源:exercise_02.py
示例16: MyOVBox
class MyOVBox(OVBox):
def __init__(self):
OVBox.__init__(self)
# the initialize method reads settings and outputs the first header
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
# The process method will be called by openvibe on every clock tick
def process(self):
# A stimulation set is a chunk which starts at current time and end time is the time step between two calls
# init here and filled within triger()
self.stimSet = OVStimulationSet(self.getCurrentTime(), self.getCurrentTime()+1./self.getClock())
if self.init == False :
local_time = local_clock()
initSecond=int(local_time)
initMillis=int((local_time-initSecond)*1000)
self.stimSet.append(OVStimulation(self.initLabel, self.getCurrentTime(), 0.))
self.stimSet.append(OVStimulation(initSecond, self.getCurrentTime(), 0.))
self.stimSet.append(OVStimulation(initMillis, self.getCurrentTime(), 0.))
self.init=True
# read all available stream
samples=[]
sample,timestamp = self.inlet.pull_sample(0)
while sample != None:
samples += sample
sample,timestamp = self.inlet.pull_sample(0)
# every value will be converted to openvibe code and a stim will be create
for label in samples:
label = str(label)
if self.debug:
print "Got label: ", label
self.stimSet.append(OVStimulation(float(label), self.getCurrentTime(), 0.))
# even if it's empty we have to send stim list to keep the rest in sync
self.output[0].append(self.stimSet)
def uninitialize(self):
# we send a stream end.
end = self.getCurrentTime()
self.output[0].append(OVStimulationEnd(end, end))
self.inlet.close_stream()
开发者ID:jfrey-xx,项目名称:openMatch,代码行数:64,代码来源:python_lsl_stims.py
示例17: StreamOutlet
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()
print "The manufacturer is: " + inf.desc().child_value("manufacturer")
print "The cap circumference is: " + inf.desc().child("cap").child_value("size")
print "The channel labels are as follows:"
ch = inf.desc().child("channels").child("channel")
for k in range(info.channel_count()):
print " " + ch.child_value("label")
ch = ch.next_sibling()
time.sleep(3)
开发者ID:dmedine,项目名称:pupil,代码行数:31,代码来源:HandleMetadata.py
示例18: print
"""Example program to show how to read a marker time series from LSL."""
import sys
sys.path.append('./pylsl') # help python find pylsl relative to this example program
from pylsl import StreamInlet, resolve_stream
# first resolve an EEG stream on the lab network
print("looking for an BatteryStatus stream...")
streams = resolve_stream('name', 'BatteryStatus')
streamsFound = len(streams)
if (streamsFound > 0):
print 'found ' + str(streamsFound)
else:
print 'found none'
# create a new inlet to read from the stream
inlet = StreamInlet(streams[0])
hostName = inlet.info().hostname()
while True:
sample, timestamp = inlet.pull_sample()
if(sample):
print(str(timestamp) + ' Battery Status of ' + hostName + ' ' + str(sample[0]) +'%')
开发者ID:xfleckx,项目名称:BeMoBI_Tools,代码行数:28,代码来源:RecieveBatteryStatus.py
示例19: initialize
def initialize(self):
# settings are retrieved in the dictionary
try:
self.samplingFrequency = int(self.setting['Sampling frequency'])
except:
print "Sampling frequency not set or error while parsing."
self.samplingFrequency = 0
print "Sampling frequency: " + str(self.samplingFrequency)
self.epochSampleCount = int(self.setting['Generated epoch sample count'])
self.stream_type=self.setting['Stream type']
# total channels for all streams
self.channelCount = 0
all_streams = self.setting['Get all streams'] == "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:
inlet = StreamInlet(stream)
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 self.samplingFrequency == 0:
print "Set sampling frequency to:" + str(stream_freq)
self.samplingFrequency = stream_freq
elif self.samplingFrequency != stream_freq:
print "WARNING: sampling frequency of current stream (" + str(stream_freq) + ") differs from option set to box (" + str(self.samplingFrequency) + ")."
for i in range(info.channel_count()):
self.dimensionLabels.append(name + ":" + str(i))
# We must delay real inlet/info init because we may know the defifitive sampling frequency
# limit buflen just to what we need to fill each chuck, kinda drift correction
# TODO: not a very pretty code...
buffer_length = int(ceil(float(self.epochSampleCount) / self.samplingFrequency))
print "LSL buffer length: " + str(buffer_length)
inlet = StreamInlet(stream, max_buflen=buffer_length)
info = inlet.info()
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.")
# backup last values pulled in case pull(timeout=0) return None later
self.last_values = self.channelCount*[0]
self.dimensionLabels += self.epochSampleCount*['']
self.dimensionSizes = [self.channelCount, self.epochSampleCount]
self.signalHeader = OVSignalHeader(0., 0., self.dimensionSizes, self.dimensionLabels, self.samplingFrequency)
self.output[0].append(self.signalHeader)
#creation of the first signal chunk
self.endTime = 1.*self.epochSampleCount/self.samplingFrequency
self.signalBuffer = numpy.zeros((self.channelCount, self.epochSampleCount))
self.updateTimeBuffer()
self.updateSignalBuffer()
开发者ID:jfrey-xx,项目名称:OVDLSLReader,代码行数:85,代码来源:python_lsl.py
示例20: print
import sys; sys.path.append('..') # help python find pylsl relative to this example program
from pylsl import StreamInlet, resolve_stream
# 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])
while True:
# get a new sample (you can also omit the timestamp part if you're not interested in it)
sample,timestamp = inlet.pull_sample()
print(timestamp, sample)
开发者ID:dmedine,项目名称:pupil,代码行数:14,代码来源:ReceiveData.py
注:本文中的pylsl.StreamInlet类示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论