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:
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.))
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
def lookout_stream(): # first resolve an EEG stream on the lab network print("looking for LSL stream named [" + stream_name +"]") streams = resolve_stream('name', stream_name) # create a new inlet to read from the stream print("got it") return StreamInlet(streams[0])
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()
def configure(self, **kwargs): """Configure the lsl device. This method looks for open lsl streams and picks the first `EEG` and `Markers` streams and opens lsl inlets for them. Note that lsl amplifiers cannot be configured via lsl, as the protocol was not designed for that. You can only connect (i.e. subscribe) to devices that connected (publishing) via the lsl protocol. """ # lsl defined self.max_samples = 1024 # open EEG stream logger.debug('Opening EEG stream...') streams = pylsl.resolve_stream('type', 'EEG') if len(streams) > 1: logger.warning('Number of EEG streams is > 0, picking the first one.') self.lsl_inlet = pylsl.StreamInlet(streams[0]) # open marker stream logger.debug('Opening Marker stream...') # TODO: should add a timeout here in case there is no marker # stream streams = pylsl.resolve_stream('type', 'Markers') if len(streams) > 1: logger.warning('Number of Marker streams is > 0, picking the first one.') self.lsl_marker_inlet = pylsl.StreamInlet(streams[0]) info = self.lsl_inlet.info() self.n_channels = info.channel_count() self.channels = ['Ch %i' % i for i in range(self.n_channels)] self.fs = info.nominal_srate() logger.debug('Initializing time correction...') self.lsl_marker_inlet.time_correction() self.lsl_inlet.time_correction() logger.debug('Configuration done.')
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
def __init__(self, subject="test", nChannels=31, frequency=512, streamer_type="Brainvision Recorder", channels=None): global screen, total_ch, freq, select_ch freq = int(frequency) total_ch = int(nChannels) select_ch = range(1, total_ch + 1) channel_names=channels self.streamer = str(streamer_type) self.name = self.__class__.__name__ self.running = True self.server_running = True self.server_connected = False self.sock = None self.global_time = time.clock() self.EEGdata = np.zeros((freq * EEGdata_size, total_ch + 1)) self.label = "" self.samples=0 self.print_label=0 self.edx=0 print("{}: Looking for an EEG stream...".format(self.name)) if (self.streamer == "OpenVibe"): print("{}: Looking for an EEG stream...".format(self.name)) streams = resolve_stream('type', 'signal') self.inlet = StreamInlet(streams[0]) i = 1 fname = "{}/{}_{}_{}t{}c{}s{}ch_{}".format(folder, date, data_type, num_trials, num_classes, window_sec, len(select_ch), subject) self.filename = "{}_{}.txt".format(fname, i) while os.path.exists(self.filename): i += 1 self.filename = "{}_{}.txt".format(fname, i) self.file = open(self.filename, "w") print("{}: Writing to {}".format(self.name, self.filename)) self.output_data = [] self.output_label = [] self.class_count = [0] * num_classes
def getData(classifier, mu_ft, std_ft): print('looking for an EEG stream...') streams = resolve_stream('type', 'EEG') if len(streams) == 0: raise (RunTimeError('Cant find EEG stream :(')) window = 1 inlet = StreamInlet(streams[0]) info = inlet.info() descriptions = info.desc() sfreq = info.nominal_srate() n_samples = int(window * sfreq) n_chan = info.channel_count() print('Acquiring data...') data = np.zeros((n_samples, n_chan)) times = np.arange(-window, 0, 1. / sfreq) timer = time.time() while True: samples, timestamps = inlet.pull_chunk(timeout=1.0, max_samples=12) if timestamps: timestamps = np.float64( np.arange(len(timestamps)) ) #creates an array of numbers of numbers from 0 to length timestamps timestamps /= sfreq #divides that array by our sampling freq timestamps += times[-1] + 1 / sfreq # not sure times = np.concatenate( [times, timestamps]) #adds timestamps to the end of the times array times = times[-n_samples:] #takes the last n_samples from times data = np.vstack([data, samples ]) #adds our new samples to the data array data = data[-n_samples:] timer = time.time() n_samples, n_chan = data.shape epochs, remainder = tools.epoching(data, n_samples, samples_overlap=0) feature_matrix = tools.compute_feature_matrix(epochs, sfreq) y_hat = tools.classifier_test(classifier, feature_matrix, mu_ft, std_ft) print(y_hat)
def findStream(self, hostname=None, timeout=1): # Gather lsl stream and create respective inlet and buffer, returns channelcount of that stream print("Searching for streams with a timeout of " + str(timeout) + " seconds") streams = resolve_stream(timeout) if len(streams) < 1: print("No stream found - exiting") return -1 else: print("Found " + str(len(streams)) + " streams") if hostname is None: print( "No stream hostname has been specified - selecting first stream" ) self.stream = streams[0] else: for stream in streams: if stream.hostname() == hostname: self.stream = stream print("Selected stream with hostname " + str(hostname)) break if self.stream is None: print("No stream with hostname " + str(hostname) + " has been found - exiting") self.inlet = StreamInlet(self.stream) self.info = self.inlet.info() self.channelCount = self.info.channel_count() self.srate = self.info.nominal_srate() self.data = np.empty((0, self.channelCount)) try: self.offset = self.inlet.time_correction(timeout=3) print("Offset: " + str(self.offset)) except TimeoutError: self.offset = 0 print("Offset Retrieval Timed Out") #print("Stream Meta Info:") #print(self.info.as_xml()) return self.channelCount
def Start(): v = None streams = resolve_stream() listStreams = classifyStreamInlet(streams) dialog = DialogDE(listStreams) if (len(listStreams) == 0): dialog.showErrorNoStreams() else: if dialog.exec_() and dialog.checkLineEditPattern(): selectedStreams, update_rate = dialog.returnWindowParameters() if len(selectedStreams) == 0: dialog.showErrorNoStreamSelected() else: v = Viewer(selectedStreams, streams, int(update_rate)) v.show() else: print("Window was not created.") return v
def main(): # first resolve an EEG stream on the lab network print("looking for an EyeData stream...") streams = resolve_stream('name', 'BAlert') # create a new inlet to read from the stream inlet = StreamInlet(streams[0]) samples = [] while True: # get a new sample (you can also omit the timestamp part if you're not # interested in it) try: sample, timestamp = inlet.pull_sample() print(timestamp, sample) print(len(sample)) samples.append((timestamp, sample)) except KeyboardInterrupt: if len(samples) > 1: f_sample = 1. / ((samples[-1][0] - samples[0][0]) / len(samples)) print('Interrupted, f_sample is ' + str(f_sample)) break
def imp_check_pauser(imp_limit): from pylsl import StreamInlet, resolve_stream # first resolve an EEG stream on the lab network print('Searching for Impedances Stream...') streams = resolve_stream('type', 'Impeadance') # type='Impeadance') # create a new inlet to read from the stream inlet = StreamInlet(streams[0]) # Keyword Paramters. imps = [] channels = ['Fz', 'Cz', 'Pz', 'P4', 'P3', 'O1', 'O2'] controller = 0 num_chans = 7 if imp_limit is None: imp_limit = 15 # Timed Imp Check Controller Operatin/ while controller == 0: # Grab Impedances Data Chunks. chunk, timestamps = inlet.pull_chunk(timeout=2, max_samples=500) if timestamps: imps = np.asarray(chunk) imps = imps[:, 0:num_chans] print(imps.shape) imps = zero_mean(imps) for j in range(1): con_list = np.zeros(num_chans) # , dtype=int for i in range(num_chans): # Range value of channel durng pause. r_val = np.amax(imps[:, i]) - np.amin(imps[:, i]) if r_val > imp_limit: print( '----Channel Impedances Awaiting Stabilization: {0} | Range Value: {1}' .format(channels[i], r_val)) elif r_val < imp_limit: con_list[i] = 1 print( '----Channel Impedances Stabilised: {0} | Range Value: {1}' .format(channels[i], r_val)) if np.sum(con_list) == num_chans: controller = 1
def record(channel_data=[], time_stamps=[]): streams = pylsl.resolve_stream('type', 'EEG') inlet = pylsl.stream_inlet(streams[0]) while True: try: sample, time_stamp = inlet.pull_sample() time_stamp += inlet.time_correction() time_stamps.append(time_stamp) channel_data.append(sample) # first col of one row of the record_data matrix is time_stamp, # the following cols are the sampled channels except KeyboardInterrupt: complete_samples = min(len(time_stamps), len(channel_data)) sio.savemat( "recording_" + time_str() + ".mat", { "time_stamps": time_stamps[:complete_samples], "channel_data": channel_data[:complete_samples] }) break
def receiveData(q): ''' Create channel to receive EEG data from pylsl Save data received to queue ''' # first resolve an EEG stream on the lab network print("looking for an EEG stream...") streams = resolve_stream('type', 'EEG') print("Stream Found") # create a new inlet to read from the stream inlet = StreamInlet(streams[0]) # open file to save data to #datetime = strftime("%Y-%m-%d_%H:%M:%S", gmtime()) #outFile = open('Cogniotics_{}.csv'.format(datetime), mode='w') #eegWriter = csv.writer(outFile, delimiter = ',') while True: sample, timestamp = inlet.pull_sample() #print(sample) eegSample = np.asarray(sample, dtype=float) q.push(eegSample)
def lab_streaming_layer(): # first resolve an tobii stream on the lab network print("looking for an Tobii stream...") streams = resolve_stream('type', 'eyetracker') # create a new inlet to read from the stream inlet = StreamInlet(streams[0]) f = "" # Collect measurements until time period is finished while time.time() < t_end: sample, timestamp = inlet.pull_sample(timeout=1) if 'nan' in str(sample): for m in range(6): if 'nan' in str(sample[m]): sample[m] = 'NaN' string = "{},{},{},{},{},{},{},{}\n".format(timestamp, sample[0], sample[1], sample[2], sample[3], sample[4], sample[5], task[sample[6]]) f += string # Create the JSON string with all the processing procedurs available in the jsonString = { "type": dataType, "device": device, "apiUrl": apiUrl, "id": dataId, "attributes": attributes, "data": f } # Buffer the data in a json file with open('buffer/eyetracker.json', 'w') as jsonEyetracker: json.dump(jsonString, jsonEyetracker)
def configure(self, **kwargs): """Configure the lsl device. This method looks for open lsl streams and picks the first `EEG` and `Markers` streams and opens lsl inlets for them. Note that lsl amplifiers cannot be configured via lsl, as the protocol was not designed for that. You can only connect (i.e. subscribe) to devices that connected (publishing) via the lsl protocol. """ # lsl defined self.max_samples = 1024 # open EEG stream logger.debug('Opening EEG stream...') streams = pylsl.resolve_stream('type', 'EEG') if len(streams) > 1: logger.warning( 'Number of EEG streams is > 0, picking the first one.') self.lsl_inlet = pylsl.StreamInlet(streams[0]) # open marker stream # logger.debug('Opening Marker stream...') # TODO: should add a timeout here in case there is no marker # stream # streams = pylsl.resolve_stream('type', 'Markers') # if len(streams) > 1: # logger.warning('Number of Marker streams is > 0, picking the first one.') # self.lsl_marker_inlet = pylsl.StreamInlet(streams[0]) info = self.lsl_inlet.info() self.n_channels = info.channel_count() self.channels = ['Ch %i' % i for i in range(self.n_channels)] self.fs = info.nominal_srate() logger.debug('Initializing time correction...') # self.lsl_marker_inlet.time_correction() self.lsl_inlet.time_correction() logger.debug('Configuration done.')
def getData(runtime=60): print('looking for an EEG stream...') runTime = runtime streams = resolve_stream('type', 'EEG') if len(streams) == 0: raise (RunTimeError('Cant find EEG stream :(')) window = 1 inlet = StreamInlet(streams[0]) info = inlet.info() descriptions = info.desc() sfreq = info.nominal_srate() n_samples = int(window * sfreq) n_chan = info.channel_count() print('Acquiring data...') data = np.zeros((1, n_chan)) times = np.arange(-window, 0, 1. / sfreq) timer = time.time() end = timer + runTime while end > timer: samples, timestamps = inlet.pull_chunk(timeout=1.0, max_samples=12) if timestamps: timestamps = np.float64( np.arange(len(timestamps)) ) #creates an array of numbers of numbers from 0 to length timestamps timestamps /= sfreq #divides that array by our sampling freq timestamps += times[-1] + 1 / sfreq # not sure times = np.concatenate( [times, timestamps]) #adds timestamps to the end of the times array times = times[-n_samples:] #takes the last n_samples from times data = np.vstack([data, samples ]) #adds our new samples to the data array timer = time.time() data = np.delete(data, 0, 0) #deletes first column of zeros return data, sfreq
def eeg_in(): global rsample global lsample # first resolve a LiSiLity stream on the lab network print('Looking for a LiSiLity stream...') streams = resolve_stream('type', 'LiSiLity.Angles') # create a new inlet to read from the stream inlet_left = StreamInlet(streams[0]) inlet_right = StreamInlet(streams[1]) while True: # get a new sample (you can also omit the timestamp part if you’re not # interested in it) lsample, ltimestamp = inlet_left.pull_sample() rsample, rtimestamp = inlet_right.pull_sample() for i in range(len(lsample)): lsample[i] = round(lsample[i], 2) for i in range(len(rsample)): rsample[i] = round(rsample[i], 2) print(round(ltimestamp, 0), lsample, rsample) move()
def save_data(): print("looking for an EEG stream...") streams = resolve_stream('type', 'EEG') # create a new inlet to read from the stream # here the streams[0] means select the first stream in the streams inlet = StreamInlet(streams[0], max_buflen=60) start_state = True # global start_state while True: sample, timestamp = inlet.pull_chunk(timeout=0.0, max_samples=15000) if sample: if start_state: print("please waiting for 5s the data to stabilize") time.sleep(5) start_state = False else: sample_list = sample_arr(sample) # list filter_list = filter(sample_list) # filter down_sample = signal.resample(filter_list, 100) # down sample epoch_buffer.set_raw_data(filter_list) # save filter data epoch_buffer.set_data(down_sample.tolist()) # save down sample # print(down_sample[0]) time.sleep(1)
import time import numpy as np import pandas as pd from squaternion import Quaternion # To convert Quaternions into angles from pylsl import StreamInlet, resolve_stream # To communicate with the EEG headset and Emotiv PRO app # Print settings used for debugging more easily np.set_printoptions(precision=3) # Only .xxx np.set_printoptions(linewidth=300) ### Initialization ### # Resolve EEG streams on the lab network print("looking for EEG stream...") streamEEG = resolve_stream('type', 'EEG') print("EEG stream found:",streamEEG) print("looking for Motion stream...") streamMotion = resolve_stream('type', 'Motion') print("Motion stream found:",streamMotion) inlet = StreamInlet(streamEEG[0]) # create a new inlet to read EEG data from the stream inlet2 = StreamInlet(streamMotion[0]) # create a new inlet to read Motion data from the stream # Check if data is received correctly by printing one sample sample, timestamp = inlet.pull_sample() # Input from EEG print("EEG 00 seconds, timestamp: ", timestamp, sample) # Print 1st input sample, timestamp = inlet2.pull_sample() # Input from Motion print("EEG 00 seconds, timestamp: ", timestamp, sample) # Print 1st input
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()
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)
import numpy as np # 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)
def lslstream(): print("looking for an EEG stream...") streams = resolve_stream('type', 'EEG') print("Found it!") return StreamInlet(streams[0])
"""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]) +'%')
"""Example program to demonstrate how to read string-valued markers from LSL.""" from pylsl import StreamInlet, resolve_stream # first resolve a marker stream on the lab network print("looking for a marker stream...") streams = resolve_stream('type', 'Markers') # 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("got %s at time %s" % (sample[0], timestamp))
"""Example program to show how to read a multi-channel time series from LSL.""" import pylsl # first resolve an EEG stream on the lab network print("looking for an EEG stream...") streams = pylsl.resolve_stream('type', 'EEG') # create a new inlet to read from the stream inlet = pylsl.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
# -*- coding: utf-8 -*- """Example program to demonstrate how to read a multi-channel time-series from LSL in a chunk-by-chunk manner (which is more efficient).""" from pylsl import StreamInlet, resolve_stream """EEG""" # 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]) """MARKERS""" # first resolve a marker stream on the lab network print("looking for a marker stream...") streamsMARKER = resolve_stream('type', 'Markers') # create a new inlet to read from the stream inletMARKER = StreamInlet(streamsMARKER[0]) while True: # get a new sample (you can also omit the timestamp part if you're not # interested in it) chunk, timestamps = inlet.pull_chunk() if timestamps: print('**********************INLET_DATA*******************') print('SAMPLE_STAMP:' + str(timestamps)) print('SAMPLE:' + str(chunk)) marker, timestampM = inletMARKER.pull_sample() if timestampM:
# Compute the positions for the frequency values within the input range and trim the frequency and fft arrays frequency_range_positions = [min(valid_frequency_positions[0]), max(valid_frequency_positions[0])] frequency_values = frequency_values[frequency_range_positions[0] : frequency_range_positions[1]] signal_fft = signal_fft[:, frequency_range_positions[0] : frequency_range_positions[1]] # Return and exit return frequency_values, signal_fft # Use stream information from sender (Either custom script or Windows app) # Configure data stream stream_name = "RandomVectors" stream_type = "EEG" # Find out if there is a stream with the requested name and type streams = resolve_stream("type", stream_type) # Obtain an inlet (a socket-like object) which has access to the data inlet = StreamInlet(streams[0]) # Use an infinite loop to receive the data from the Stream print("Receiving data from a " + stream_type + " Stream...") sampling_rate_data = 512 frequency_range_data = [1, 30] buffer_size = 200 number_channels = 8 buffer_index = -1 buffer = numpy.zeros([number_channels, buffer_size]) plt.ion() fig = plt.figure()
import sys; 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
"""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 targetStreamType = 'Unity.Quaternion' print 'looking for an stream of type ' + targetStreamType streams = resolve_stream('type', targetStreamType) 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]) while True: sample, timestamp = inlet.pull_sample() if(sample): print str(timestamp) + ' Quaternion: ' + ' '.join(str(sample[x]) for x in range(0,len(sample))), "\r", sys.stdout.flush()
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)
### Set Networking mode to LSL, FFT data type, and # Chan to 125 ### Thanks to @Sentdex - Nov 2019 from pylsl import StreamInlet, resolve_stream import numpy as np import time import matplotlib.pyplot as plt from matplotlib import style from collections import deque last_print = time.time() fps_counter = deque(maxlen=150) duration = 5 # first resolve an EEG stream on the lab network print("looking for an EEG stream...") streams = resolve_stream('type', 'FFT') # create a new inlet to read from the stream inlet = StreamInlet(streams[0]) channel_data = {} for i in range(duration ): # how many iterations. Eventually this would be a while True for i in range(16): # each of the 16 channels here sample, timestamp = inlet.pull_sample() if i not in channel_data: channel_data[i] = sample else: channel_data[i].append(sample)
"""Example program to show how to read a multi-channel 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 Unity3D.AppStatistics stream...") streams = resolve_stream('type', 'Unity3D.FPS.FT') # 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 '\r' + str(round(timestamp)) + '\t' + str(sample), sys.stdout.flush()
import sys; sys.path.append('..') # make sure that pylsl is found (note: in a normal program you would bundle pylsl with the program) import pylsl import random import time from PIL import Image import struct info = pylsl.stream_info('VideoFrameCommandStream','Markers',1,0,pylsl.cf_string,'dgeyurtutu567sdf'); outlet = pylsl.stream_outlet(info) print("looking for video frame stream...") streams = pylsl.resolve_stream('type','VideoRaw') # create a new inlet to read from the stream inlet = pylsl.stream_inlet(streams[0]) print("now sending markers...") flatFrame = pylsl.vectori() i=0 while True: # choose a marker string randomly and store it as a pylsl.vectorstr (note that this is actually a list since there can be multiple channels in the sample, even though it is of little use for markers) mysample = pylsl.vectorstr([ 'Request Image' ]) # now send it and wait for a bit outlet.push_sample(mysample) if(inlet.pull_sample(flatFrame,1)): print 'got frame' buf = struct.pack('b'*len(flatFrame), *flatFrame) #It is possible to load the width and height from the stream header, but not implemented here.
import numpy import matplotlib.pyplot as plt import matplotlib.animation as animation from pylsl import StreamInlet, resolve_stream import time # Start Audio stream print("looking for an Audio stream...") streams = resolve_stream('type', 'Audio') inlet = StreamInlet(streams[0]) n_samples = 250 time_interval = 100 # Pre-allocate line fig, ax = plt.subplots() line, = ax.plot(numpy.random.rand(n_samples)) ax.set_ylim(-1, 1) # Create a function to pull N number of samples from the Audio Stream def pull_stream_samples(number_samples, nt): # Pre-allocate variables and output buffer_iteration = -1 time_buffer = numpy.arange(number_samples) sample_buffer = numpy.array(time_buffer, dtype='f') amplifier_factor = 1000 # Fill the sample buffer while buffer_iteration < len(sample_buffer) - 1:
user = pointer(userID) ready = 0 state = c_int(0) systemUpTime = c_float(0.0) batteryLevel = c_long(0) batteryLevelP = pointer(batteryLevel) maxBatteryLevel = c_int(0) maxBatteryLevelP = pointer(maxBatteryLevel) systemUpTime = c_float(0.0) wirelessStrength = c_int(0) # first resolve an ContactQuality stream on the lab network print("looking for a ContactQuality stream...") streams = resolve_stream('type', 'ContactQuality') # LED Strip Setup numpixels = 72 # Number of LEDs in strip strip = Adafruit_DotStar(numpixels, 125000, order='bgr') print 'strip object created' strip.begin() # Initialize pins for output strip.setBrightness(8) # Limit brightness to ~1/4 duty cycle # reset strip for ledi in range(0, numpixels): strip.setPixelColor(ledi, 0x00FF00) strip.show()
#plt.pause(3) # počakam 3s... #plt.close() # ... in zdaj jo lahko zaprem. idx = 1 while idx > 0: idx = int(input('Select index: ')) print(ax[idx]) command = bci.analyze_data(ax[idx], ay[idx], az[idx]) print(command) print() elif option == 'stream': """Read a multi-channel time series from LSL.""" # first resolve an EEG stream on the lab network print("looking for data stream...") stream1 = resolve_stream('name', 'obci_eeg1') #stream2 = resolve_stream('name', 'obci_eeg2') # create a new inlet to read from the stream inlet1 = StreamInlet(stream1[0]) #inlet2 = StreamInlet(stream2[0]) # prikažem dolžino vzorčnega vektorja print("sample size:", len(signal)) time.sleep(3) start = time.time() while True: # get a new sample (you can also omit the timestamp part if you're not # interested in it) sample1, timestamp = inlet1.pull_sample()
"""Example program to demonstrate how to read a multi-channel time-series from LSL in a chunk-by-chunk manner (which is more efficient).""" from pylsl import StreamInlet, resolve_stream # first resolve an EEG stream on the lab network print("looking for an EEG stream...") streams = resolve_stream('name', '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) chunk, timestamps = inlet.pull_chunk() if timestamps: print(timestamps, chunk)
import sys; sys.path.append('..') # make sure that pylsl is found (note: in a normal program you would bundle pylsl with the program) import pylsl # first resolve a marker stream on the lab network print("looking for a marker stream...") streams = pylsl.resolve_stream('type','Markers') # create a new inlet to read from the stream inlet = pylsl.stream_inlet(streams[0]) sample = pylsl.vectorstr() while True: # get a new sample (you can also omit the timestamp part if you're not interested in it) timestamp = inlet.pull_sample(sample) print("got ",sample[0]," at time ",timestamp)
__author__ = 'Mauricio Merino' # Import required libraries from pylsl import StreamInlet, resolve_stream # Use stream information from sender (Either custom script or Windows app) # Configure data stream stream_name = 'Keyboard' stream_type = 'Markers' # Find out if there is a stream with the requested name and type streams = resolve_stream('type', stream_type) # Obtain an inlet (a socket-like object) which has access to the data inlet = StreamInlet(streams[0]) # Use an infinite loop to receive the data from the Stream print("Receiving data from a "+stream_type+" Stream...") while True: # Pull sample from Stream current_sample, timestamp = inlet.pull_sample() # Print current sample print(current_sample)
import sys; sys.path.append('..') # make sure that pylsl is found (note: in a normal program you would bundle pylsl with the program) import pylsl # first resolve an EEG stream on the lab network print("looking for an EEG stream...") streams = pylsl.resolve_stream('type','EEG') # create a new inlet to read from the stream inlet = pylsl.stream_inlet(streams[0]) sample = pylsl.vectorf() while True: # get a new sample (you can also omit the timestamp part if you're not interested in it) timestamp = inlet.pull_sample(sample) print(timestamp, list(sample))
def lslstream(): print("looking for an EEG stream...") streams = resolve_stream('type','EEG') print("Found it!") return StreamInlet(streams[0])
from pylsl import StreamInlet, resolve_stream # first resolve an EEG stream on the lab network print("looking for an EEG stream...") streams = resolve_stream('name', 'ConcentrationStream') # 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)
def main(): #Boilerplate. pg.init() pg.font.init() fnt = pg.font.SysFont('Arial', 36) HEIGHT = 500 WIDTH = 500 pg.display.set_caption('State Classification') screen = pg.display.set_mode((WIDTH, HEIGHT)) clock = pg.time.Clock() print('Establishing LSL connection.') streams = resolve_stream('type', 'EEG') inlet = StreamInlet(streams[0]) print('LSL connection established.') model = tf.keras.models.load_model('models/first.h5') cont = True predictions = [0] * 10 while cont: screen.fill((255, 255, 255)) delta = clock.tick(30) pg.draw.rect(screen, ( 150, 0, 0, ), (0, 0, WIDTH, HEIGHT * .33)) pg.draw.rect(screen, (0, 150, 0), (0, HEIGHT * .33, WIDTH, HEIGHT * .33)) pg.draw.rect(screen, (0, 0, 150), (0, HEIGHT * .66, WIDTH, HEIGHT * .33)) #Labels screen.blit(fnt.render('Gaming', True, (255, 255, 255)), dest=(WIDTH * .4, HEIGHT * .1)) screen.blit(fnt.render('Reading', True, (255, 255, 255)), dest=(WIDTH * .4, HEIGHT * .45)) screen.blit(fnt.render('Meditating', True, (255, 255, 255)), dest=(WIDTH * .4, HEIGHT * .8)) #Collect data data = [] for i in range(20): sample, timestamp = inlet.pull_sample() data.append(sample[:60]) data = np.asarray(data) predictions.pop(0) predictions.append(model.predict( np.asarray(data).reshape((1, 20, 60)))) # Determine the position of the box based on the maximum index from the last 2 seconds of predictions sums = sum(predictions).tolist()[0] print(sums) idx = sums.index(max(sums)) POS = [HEIGHT * .1, HEIGHT * .4, HEIGHT * .75] pg.draw.rect(screen, (0, 0, 0), (0, POS[idx], WIDTH / 8, HEIGHT / 10)) for event in pg.event.get(): if (event.type == pg.QUIT): cont = False pg.display.update()
return model except IOError: print(IOError) return None #####the code above is just some import ################get the EEG filtered signal from the Windows. if __name__ == '__main__': print_version_info() print('Resolving streams') stream = pylsl.resolve_stream( 'type', 'EEGPre') # EEG for the raw signal; EEGPre for a preprocessed signal print('Found at least one stream') inlet = pylsl.stream_inlet(stream[0]) info = inlet.info() print(info.as_xml()) while True: x_streamed, time = inlet.pull_sample() X = np.array(x_streamed) X_test = np.zeros((1, 3, 1024)) X_test[0, 0, :] = X[:1024] X_test[0, 1, :] = X[1024:2048] X_test[0, 2, :] = X[2048:3072] print(X_test.shape)
STIMULUS_SEQUENCE_LENGTH = 26 # How many stimulus per trial, should match the SSVEP experiment file # This is a hard-coded approximate value for the trial duration, should match SSVEP experiment file TRIAL_TIME = ((STIMULUS_SEQUENCE_LENGTH*STIMULUS_TIME)*2)+AFTER_TRIAL_PAUSE EXTRA_SAMPLES = 50 # Keep recording to ensure the SSVEP experiment has been completed MAX_SAMPLE = SAMPLING_RATE*((TRIAL_TIME*NUMBER_OF_TRIALS)+EXTRA_SAMPLES) # Pre-allocate the matrix to storage EEG recordings and the vector for the time log sample_matrix = np.zeros([NUMBER_OF_CHANNELS, MAX_SAMPLE]) time_vector = np.zeros([1, MAX_SAMPLE]) index = 0 # Find out if there is a stream with the requested name and type EEG_stream = resolve_stream('type', 'EEG') #Marker_stream = resolve_stream('type', 'Markers') # Obtain an inlet (a socket-like object) which has access to the data EEG_inlet = StreamInlet(EEG_stream[0]) #Marker_inlet = StreamInlet(Marker_stream[0]) # Use an infinite loop to receive the data from the Stream print("Receiving data from a EEG and Event Streams...") # Record the current time as a reference for all the following events' time measurements time.clock() # First clock call that serves as time reference time_now = datetime.datetime.now() reference_time = [time_now.hour, time_now.minute, time_now.second, time_now.microsecond] while index < MAX_SAMPLE-1:
import time import pylsl import sys import keyboard print('beginning readings') #GLOBAL_VARS stop_key = 'j' #press j to kill the code attention_threshold = 65 attention_confirm_threshold = 3 #tried 3,4,5... 3 is the best because too hard to turn on #attentions = [] this is there to debug when the attention values are low attention_confirmation = 0 # read the neurosky recordings via python through OpenVibe EEG Software streams = pylsl.resolve_stream('type', 'signal') # continuously read from the EEG while True: # this snippet gets the readings from the neurosky at the # current time inlet = pylsl.stream_inlet(streams[0]) sample, timestamp = inlet.pull_sample() attention = sample[1] #print(attention) #attentions.append(attention) # high attention values lead to if (attention > attention_threshold): attention_confirmation += 1
def __init__(self): # have EEGmodule inherit attributes of QGroupBox pg.setConfigOptions(antialias=True) super(QGroupBox, self).__init__() # set title of EEGmodule # self.setTitle("EEG Module") # create layout for EEG Module self.layout = QGridLayout() # set layout for module self.setLayout(self.layout) # Creating graphs self.alphaGraph = EEG_Graph_Submodule() self.alphaGraph.setGraphTitle( '<span style="color:white;font-size:20px">Alpha Band (8-12Hz)</span>' ) self.alphaBand = -3 self.alphaG = self.alphaGraph.plotWidgetMain ###################################### self.thetaGraph = EEG_Graph_Submodule() self.thetaGraph.setGraphTitle( '<span style="color:white;font-size:20px">Theta Band (4-7Hz)</span>' ) self.thetaBand = -2 self.thetaG = self.thetaGraph.plotWidgetMain ###################################### self.deltaGraph = EEG_Graph_Submodule() self.deltaGraph.setGraphTitle( '<span style="color:white;font-size:20px">Delta Band (0-4Hz)</span>' ) self.deltaG = self.deltaGraph.plotWidgetMain self.deltaBand = -1 ####################################### # checkbox for alphaGraph self.alphaBox = QCheckBox("Alpha Band", self) self.alphaBox.setStyleSheet("QCheckBox{color:white;}") self.alphaBox.setChecked(True) self.alphaBox.stateChanged.connect(lambda: self.hideGraph(button=self.alphaBox)) ################################################### self.thetaBox = QCheckBox("Theta Band", self) self.thetaBox.setStyleSheet("QCheckBox{color:white;}") self.thetaBox.setChecked(True) self.thetaBox.stateChanged.connect(lambda: self.hideGraph(button=self.thetaBox)) self.thetaBox.move(100, 0) ################################################### self.deltaBox = QCheckBox("Delta Band", self) self.deltaBox.setStyleSheet("QCheckBox{color:white;}") self.deltaBox.setChecked(True) self.deltaBox.stateChanged.connect(lambda: self.hideGraph(button=self.deltaBox)) self.deltaBox.move(200, 0) ################################################### ####################################################### #add check boxes to layout self.layout.addWidget(self.alphaBox,1,4) self.layout.addWidget(self.deltaBox,1,0) self.layout.addWidget(self.thetaBox,1,2) # add graphs to widget self.layout.addWidget(self.deltaG, 2, 0, 1, 2) self.layout.addWidget(self.thetaG, 2, 2, 1, 2) self.layout.addWidget(self.alphaG, 2, 4, 1, 2) #self.layout.addWidget(CmapImage(), 3, 2, 1, 2) # = QLabel("Normalized Power") #label.setStyleSheet("QLabel{color:white; font:20px;}") #self.layout.addWidget(label, 3, 1, 1,1) fill = pg.PlotWidget() fill.getPlotItem().hideAxis("bottom") fill.getPlotItem().hideAxis("left") fill.setBackground(background=None) self.layout.addWidget(fill, 4,0,1,6) # get the node positions x, y, nodeList = EEGArray() # set cmap colormap = cm.get_cmap("jet") #getting colormap from matplotlib colormap._init() lut = (colormap._lut * 255).view(np.ndarray) #convert to numpy array ticks = [] colors = [] # pos = [] # mapColors = [] self.gradient = pg.GradientWidget(allowAdd=False) for i in range(len(lut)-3): #adding colors to a gradient r=int(lut[i][0]) g=int(lut[i][1]) b=int(lut[i][2]) a=255 ticks.append(i/255) colors.append((r,g,b,a)) # pos.append(i/255) # mapColors.append((r,g,b,a)) if i%15 == 0: self.gradient.addTick(x=ticks[i], color=QColor(r,g,b,a), movable=False) if i == 0: self.gradient.setTickColor(0,QColor(r,g,b,a)) elif i == 255: self.gradient.addTick(1,QColor(r,g,b,a)) #self.pgCM = pg.ColorMap(np.array(ticks), colors) self.pgCM = self.gradient.colorMap() # self.layout.addWidget(self.gradient, 3, 4, 1, 2) ########################################################################## #creating a groupbox for the gradient and labels self.gradientBox = gradientLayout(self.gradient) ##################################### self.layout.addWidget(self.gradientBox, 3,0,1,8) ########################################################################## self.n = 64 # initialize newdata self.newdata = np.zeros(self.n) # initialize 64 by 64 data array self.data = np.zeros((self.n, self.n)) # get global max for normalization self.aglobalMax = -(sys.maxsize) - 1 self.tglobalMax = -(sys.maxsize) - 1 self.dglobalMax = -(sys.maxsize) - 1 self.setLayout(self.layout) # Open StreamInlet streams = resolve_stream() self.inlet = StreamInlet(streams[0]) # create timer self.timer = QTimer(self) # # self.timer.setInterval(10000) self.timer.timeout.connect(self.UpdateNodes) self.timer.start(20)
tes = [] con = 0 for d in range(len(prediction)): final.append(np.argmax(prediction[d])) for d in range(len(y2)): tes.append(np.argmax(y2[d])) for d in range(len(final)): if final[d] == tes[d]: con += 1 print("test accuracy is", (con * 100) / len(final)) matrix = met.confusion_matrix(prediction.argmax(axis=1), y2.argmax(axis=1)) print(matrix) # code for character control time.sleep(5) print("starting...") streams = resolve_stream('type', 'EEG') inlet = StreamInlet(streams[0]) duration = 0.1 def predictit(): print("relax") time.sleep(3) def sample_extract(): start = time.time() with open('openbci.csv', 'w', newline='') as csvfile: writer = csv.writer(csvfile, delimiter=',') while time.time() <= start + duration: samples, timestamp = inlet.pull_chunk() if samples:
import sys sys.path.append("..") # help python find pylsl relative to this example program from pylsl import StreamInlet, resolve_stream # first resolve a marker stream on the lab network print("looking for a marker stream...") streams = resolve_stream("type", "Markers") # 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("got ", sample[0], " at time ", timestamp)
def run(self): # Create a window self.window = tk.Tk(className='\n' + self.type + ' Plot') self.window.protocol("WM_DELETE_WINDOW", self.terminate) self.window.configure(bg='black') self.window.tk_setPalette(background='#282820', foreground='black', activeBackground='black', activeForeground='#282820') self.fig, self.ax = plt.subplots(1, 1) self.fig.set_facecolor('#282820') self.canvas = FigureCanvasTkAgg(self.fig, master=self.window) self.canvas.get_tk_widget().pack(side='top', fill='both', expand=1) self.canvas._tkcanvas.pack(side='top', fill='both', expand=1) # Beautify: self.ax.spines["top"].set_visible(False) self.ax.spines["bottom"].set_visible(False) self.ax.spines["right"].set_visible(False) self.ax.spines["left"].set_visible(False) self.ax.set_axis_bgcolor('black') self.ax.set_xlabel("Seconds", fontsize=14, color='white', alpha=0.3) self.ax.set_xlim(0, self.liveWindowTime) # self.ax.set_ylim(-1.5, 2.5) xlist = range(0, int(self.liveWindowTime + 1)) self.ax.set_xticks(xlist) self.ax.set_xticklabels([str(x) for x in xlist], fontsize=14, color='white') self.ax.set_autoscaley_on(True) self.ax.tick_params(axis="both", which="both", bottom="off", top="off", labelbottom="on", left="off", right="off", labelleft="on", labelsize=14, labelcolor='white') self.canvas.show() # Initial Data: ##################### self.t = np.linspace(0, self.liveWindow * self.INTERVAL, self.liveWindow) # # Centreline: # self.ax.plot(self.t, [0, ] * len(self.t), # color='white', alpha=0.3, linewidth=2.0) # Set colour colDict = {'gold':'#b0c050', 'red':'red', 'blue':'skyblue', 'gray':'dimgray', 'grey':'dimgray', 'silver':'lightgrey'} try: tempCol = colDict[self.col] except: tempCol = colDict['gold'] # Initialise line self.line, = self.ax.plot(self.t, [0, ] * len(self.t), color=tempCol, linewidth=self.thickness, zorder=0) # Text display (top right corner): if self.valueText != "": self.label = self.ax.text(0.98, 0.97, # Coordinates (percentage) "", fontweight='bold', verticalalignment='top', horizontalalignment='right', transform=self.ax.transAxes, fontsize=14, color=tempCol) # LSL: # first resolve a stream on the lab network print"looking for a(n)", self.type, "stream..." peakStream = resolve_stream('type', self.type) print"found a(n)", self.type, "stream..." # create a new inlet to read from the stream self.peakInlet = StreamInlet(peakStream[0]) # Run the animation: self.updateplot() # Maintain the window even when not updated: self.window.mainloop() self.terminate() return
import sys sys.path.append('..') from pylsl import StreamInlet, resolve_stream # first resolve a marker stream on the lab network print("looking for a marker stream...") streams = resolve_stream('type', 'Markers') # 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("Event: ", sample[0], " at time: ", timestamp)