for stream in streams: print('results >>', stream) print("stream_name", stream.name()) print("/--------------/") # first resolve an EEG stream on the lab network print("looking for an EEG stream...") name1 = 'obci_eeg' name2 = 'obci_aux' mac1 = 'EEG' mac2 = 'AUX' stream1 = resolve_stream('name', name1) #stream2 = resolve_stream('type', mac2) # create a new inlet to read from the stream inlet1 = StreamInlet(stream1[0]) #inlet2 = StreamInlet(stream2[0]) stream_info = inlet1.info() stream_name = stream_info.name() stream_mac = stream_info.type() stream_host = stream_info.hostname() stream_n_channels = stream_info.channel_count() print(stream_info) print(stream_name) print(stream_mac) print(stream_host) print(stream_n_channels) #wait before streaming time.sleep(10) while True:
help="Name of the recording file.") # dejitter timestamps dejitter = False (options, args) = parser.parse_args() print("looking for an EEG stream...") streams = resolve_byprop('type', 'EEG', timeout=2) if len(streams) == 0: raise(RuntimeError, "Can't find EEG stream") print("Start acquiring data") inlet = StreamInlet(streams[0], max_chunklen=12) eeg_time_correction = inlet.time_correction() print("looking for a Markers stream...") marker_streams = resolve_byprop('name', 'Markers', timeout=2) if marker_streams: inlet_marker = StreamInlet(marker_streams[0]) marker_time_correction = inlet_marker.time_correction() else: inlet_marker = False print("Can't find Markers stream") info = inlet.info() description = info.desc()
Also, the # Chan should match the data type (Examples: 1 for Focus, 3 for Accel) """ from pylsl import StreamInlet, resolve_stream import time numStreams = 3 # first resolve an EEG stream on the lab network print("looking for an EEG stream...") stream1 = resolve_stream('type', 'EEG') stream2 = resolve_stream('type', 'AUX') stream3 = resolve_stream('type', 'FFT') # create a new inlet to read from the stream inlet = StreamInlet(stream1[0]) inlet2 = StreamInlet(stream2[0]) inlet3 = StreamInlet(stream3[0]) def testLSLSamplingRates(): print( "Testing Sampling Rates..." ) start = time.time() numSamples1 = 0 numSamples2 = 0 numSamples3 = 0 while time.time() < start + 5: # get a new sample (you can also omit the timestamp part if you're not # interested in it) for i in range(numStreams): if i == 0: chunk, timestamps = inlet.pull_chunk()
# Connect to read EEG stream_name = 'LSLoutlet-EEG' streams = resolve_stream('type', 'EEG') try: for i in range (len(streams)): print(streams[i].name()) if (streams[i].name() == stream_name): index = i print ("NIC stream available") print ("Connecting to NIC stream... \n") inlet = StreamInlet(streams[index]) except NameError: print ("Error: NIC stream not available\n\n\n") else: raise ValueError('Invalid EEG device number') # Ensure EEG is connected [clock, initial_timestamp] = connectEEG(EEGdevice, outlet) # Load our classifier # clf, X_loaded = loadModel(subjID) # Save task parameters taskParameters = {'initial_timestamp':initial_timestamp, \ 'column_count':COLUMN_COUNT,'row_count':ROW_COUNT,'width':WIDTH,\
def present(duration=120): print('Looking for an EEG stream...') streams = resolve_byprop('type', 'EEG', timeout=2) if len(streams) == 0: raise RuntimeError('Can\'t find EEG stream.') #EEG Data Aquisition print("Start acquiring data") inlet = StreamInlet(streams[0], max_chunklen=12) #outlet = StreamOutlet(info) eeg_time_correction = inlet.time_correction() markernames = [1, 2] start = time() # Set up trial parameters n_trials = 2010 iti = 0.3 soa = 0.2 jitter = 0.2 record_duration = np.float32(120) duration = 120 subject = 1 session = 1 recording_path = os.path.join(os.path.expanduser("~"), "eeg-notebooks", "data", "visual", "P300", "subject" + str(subject), "session" + str(session), ("recording_%s.csv" % strftime("%Y-%m-%d-%H.%M.%S", gmtime())) + ".csv") stimulus = Process(target=.present, args=(duration,)) recording = Process(target=record, args=(duration, recording_path)) stimulus.start() recording.start() # Initialize stimuli aud1 = sound.Sound('C', octave=5, sampleRate=44100, secs=0.2) aud1.setVolume(0.8) aud2 = sound.Sound('D', octave=6, sampleRate=44100, secs=0.2) aud2.setVolume(0.8) auds = [aud1, aud2] # Setup trial list sound_ind = np.random.binomial(1, 0.25, n_trials) trials = DataFrame(dict(sound_ind=sound_ind, timestamp=np.zeros(n_trials))) # Setup graphics mon = monitors.Monitor('test')#fetch the most recent calib for this monitor mon.setDistance(114)#further away than normal? mywin = visual.Window(size=[1024,768], monitor=mon) fixation = visual.GratingStim(win=mywin, size=0.2, pos=[0, 0], sf=0, rgb=[1, 0, 0]) fixation.setAutoDraw(True) mywin.flip() for ii, trial in trials.iterrows(): # Intertrial interval core.wait(iti + np.random.rand() * jitter) # Select and play sound ind = trials['sound_ind'].iloc[ii] auds[ind].play() # Send marker timestamp = time() #outlet.push_sample([markernames[ind]], timestamp) # offset core.wait(soa) if len(event.getKeys()) > 0 or (time() - start) > record_duration: break event.clearEvents() # Cleanup mywin.close()
import numpy as np from pylsl import StreamInlet, resolve_stream, local_clock import pyqtgraph as pg from pyqtgraph.Qt import QtCore, QtGui plot_duration = 2.0 # 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 = StreamInlet(resolve_stream('type', 'Markers')[0]) # Create the pyqtgraph window win = pg.GraphicsWindow() win.setWindowTitle('LSL Plot ' + inlet.info().name()) plt = win.addPlot() plt.setLimits(xMin=0.0, xMax=plot_duration, yMin=-1.0 * (inlet.channel_count - 1), yMax=1.0) t0 = [local_clock()] * inlet.channel_count curves = [] for ch_ix in range(inlet.channel_count): curves += [plt.plot()] def update():
def main(): print("Waiting for inference sample data stream " + config.INFERENCE_LSL_NAME + '...') streams = resolve_byprop('type', config.INFERENCE_LSL_NAME) # create a new inlet to read from the stream ###################################################################### inlet = StreamInlet(streams[0]) print('number of streams is ' + str(len(streams))) # create a outlet to relay the inference results ################################################################## print('Sample stream found, creating inference results out stream ...') lsl_data_type = config.INFERENCE_LSL_RESULTS_TYPE lsl_data_name = config.INFERENCE_LSL_RESULTS_NAME info = StreamInfo(lsl_data_name, lsl_data_type, channel_count=config.INFERENCE_CLASS_NUM, channel_format='float32', source_id='myuid1234') info.desc().append_child_value("apocalyvec", "RealityNavigation") chns = info.desc().append_child("inference") channel_names = [ 'class' + str(i) for i in range(config.INFERENCE_CLASS_NUM) ] for label in channel_names: ch = chns.append_child("channel") ch.append_child_value("label", label) outlet = StreamOutlet(info, max_buffered=360) start_time = local_clock() # Load inference parameters ######################################################################################## model, y_encoder, data_downsampled_min, data_downsampled_max = load_model_params( ) # data buffers ##################################################################### timestamp_accumulated = [] print('Entering inference loop') while True: # get a new sample (you can also omit the timestamp part if you're not # interested in it) try: data, timestamp = inlet.pull_sample(timeout=1e-2) if data: timestamp_accumulated.append( timestamp) # accumulate timestamps samples = np.reshape( data, newshape=(config.EYE_SAMPLES_PER_INFERENCE, config.EYE_INFERENCE_WINDOW_TIMESTEPS, 2)) # take the most recent samples # conduct inference samples_preprocessed = preprocess_eye_samples( samples, data_downsampled_max, data_downsampled_min) results, results_decoded = inference(samples_preprocessed, model, y_encoder) # send the inference results via LSL, only send out the not-decoded results results_moving_average = np.mean(results, axis=0) print(results_moving_average) outlet.push_sample(results_moving_average) inference_per_second = len(timestamp_accumulated) / ( timestamp_accumulated[-1] - timestamp_accumulated[0]) if timestamp_accumulated[ -1] - timestamp_accumulated[0] != 0. else 0. print('Inference per second is ' + str(inference_per_second)) print() except KeyboardInterrupt: pass
def connect(self, prop='type', value='EEG'): streams = resolve_byprop(prop, value, timeout=5) self.inlet = StreamInlet(streams[0], max_chunklen=12) return self.inlet is not None
# -*- coding: utf-8 -*- """ Created on Thu Jul 9 14:01:59 2020 @author: AlexVosk """ from pylsl import StreamInlet, resolve_stream import time #streams = resolve_stream() streams = resolve_stream('name', 'EBNeuro_BePLusLTM_192.168.171.81') print(streams) time.sleep(1) stream = streams[0] ecogInlet = StreamInlet(stream, 2048) print(stream.name()) time.sleep(1) a = ecogInlet.pull_sample() print(a)
stdsmooth = [ 0, ] * len(trims) # stdsmooth = [plotThresh, ] * len(trims) """ Initialise LSL: """ if online: """ INLET """ # First resolve an RR stream on the lab network print "\nlooking for an RR stream..." RRStream = resolve_stream('type', 'RR') print "found an RR stream." # create a new inlet to read from the stream # (Don't attempt to recover if data lost) RRInlet = StreamInlet(RRStream[0], recover=False) """ OUTLET """ # Now create a new stream info object: # (here we set the name to Faros, the content-type to ECG, 1 channel, frequency = rate, # float-valued data, and the MAC address) # The last value, the MAC address of the device, is a local identifier for the stream # (you could also omit it but interrupted connections wouldn't auto-recover). # streamConfig = StreamInfo('Emulator', streamType, 1, rate, 'float32', 'Emulator'); streamID = 'RR_STD_CALC_' + environ['COMPUTERNAME'] channel_count = len(trims) print "Created outlet with ID:", streamID, 'with', channel_count, 'channel(s)' streamConfig = StreamInfo('RR_STD_CALC', 'HRV_STD', channel_count, 100, 'float32', streamID) # next add an outlet to the list RRoutlet = StreamOutlet(streamConfig) print "LSL channels opened\n"
def record_to_CSV_experiment_data(EXPERIMENT_TIME=5, SAVE_FILE_NAME='recorded_signal_data', SHOW_PLT_DATA=False, DO_PRINT_SAMPLE=False): """ Resolve a pylsl stream coming from the plugin streamer lsl that can be activate by starting the user.py function (in OPENBCI) with the command -add (ex: for Windows: python user.py -p=COM3 --add streamer_lsl). Then append this data to a list that is converted to a numpy array to then save as a CSV file Parameters: EXPERIMENT_TIME : int The duration of streaming of the electrical signal SAVE_FILE_NAME : str The name of the file where you want to save the electrical signal data SHOW_PLT_DATA : bool To indicate if you want to plot the acquired data with matplotlib DO_PRINT_SAMPLE : bool Toggle this bool if you want to show all the pulled sample Returns: all_eeg : np.array Array containing all the 8 channel data recorded from the OPENBCI board. These are the same value saved by the function in the CSV file timestamps : np.array Array containing the timestamps for all the acquiered signal values """ print("Looking for an EEG stream...") # Create a new inlet to read from the outlet stream streams = resolve_stream('type', 'EEG') inlet = StreamInlet(streams[0]) # Initialisation of values all_eeg = [] timestamps = [] time_init = time.time() # Collect data for the duration of the experiment while time.time() - time_init < EXPERIMENT_TIME: sample, timestamp = inlet.pull_sample() if timestamp: if DO_PRINT_SAMPLE: print('chunk: ', sample) timestamps.append(timestamp) all_eeg.append(sample) # Show the data for all the cython chanels all_eeg = np.array(all_eeg) timestamps = np.array(timestamps) timestamps_and_eeg = np.concatenate((all_eeg.T, timestamps[:, None].T)) # Show matplotlib of the acquiered data if SHOW_PLT_DATA: for i in range(all_eeg.shape[1]): plt.figure(i) # Use int(len(all_eeg) * 0.2) avoid showing the noise # at the beginning # HINT: this should be remove if real testing plt.plot(all_eeg[int(len(all_eeg) * 0.2):, i]) plt.plot() # Save as csv np.savetxt('{SAVE_FILE_NAME}.csv'.format(SAVE_FILE_NAME=SAVE_FILE_NAME), timestamps_and_eeg.T, delimiter=',') return timestamps, all_eeg
def record(duration, filename=None, dejitter=False, data_source="EEG"): print('dgafsjkfsdgajkp') chunk_length = LSL_EEG_CHUNK if data_source == "PPG": chunk_length = LSL_PPG_CHUNK if data_source == "ACC": chunk_length = LSL_ACC_CHUNK if data_source == "GYRO": chunk_length = LSL_GYRO_CHUNK if not filename: filename = os.path.join( os.getcwd(), "%s_recording_%s.csv" % (data_source, strftime('%Y-%m-%d-%H.%M.%S', gmtime()))) print("Looking for a %s stream..." % (data_source)) streams = resolve_byprop('type', data_source, timeout=LSL_SCAN_TIMEOUT) if len(streams) == 0: print("Can't find %s stream." % (data_source)) return print("Started acquiring data.") inlet = StreamInlet(streams[0], max_chunklen=chunk_length) # eeg_time_correction = inlet.time_correction() print("Looking for a Markers stream...") marker_streams = resolve_byprop('name', 'Markers', timeout=LSL_SCAN_TIMEOUT) if marker_streams: inlet_marker = StreamInlet(marker_streams[0]) else: inlet_marker = False print("Can't find Markers stream.") info = inlet.info() description = info.desc() Nchan = info.channel_count() ch = description.child('channels').first_child() ch_names = [ch.child_value('label')] for i in range(1, Nchan): ch = ch.next_sibling() ch_names.append(ch.child_value('label')) res = [] timestamps = [] markers = [] t_init = time() time_correction = inlet.time_correction() print('Start recording at time t=%.3f' % t_init) print('Time correction: ', time_correction) print('dgafsjkfsdgajkp') while (time() - t_init) < duration: try: data, timestamp = inlet.pull_chunk(timeout=1.0, max_samples=chunk_length) print('data = ', data, timestamp) if timestamp: res.append(data) timestamps.extend(timestamp) if inlet_marker: marker, timestamp = inlet_marker.pull_sample(timeout=0.0) if timestamp: markers.append([marker, timestamp]) except KeyboardInterrupt: break time_correction = inlet.time_correction() print('Time correction: ', time_correction) res = np.concatenate(res, axis=0) timestamps = np.array(timestamps) + time_correction if dejitter: y = timestamps X = np.atleast_2d(np.arange(0, len(y))).T lr = LinearRegression() lr.fit(X, y) timestamps = lr.predict(X) res = np.c_[timestamps, res] data = pd.DataFrame(data=res, columns=['timestamps'] + ch_names) if inlet_marker: n_markers = len(markers[0][0]) for ii in range(n_markers): data['Marker%d' % ii] = 0 # process markers: for marker in markers: # find index of markers ix = np.argmin(np.abs(marker[1] - timestamps)) for ii in range(n_markers): data.loc[ix, 'Marker%d' % ii] = marker[0][ii] directory = os.path.dirname(filename) if not os.path.exists(directory): os.makedirs(directory) data.to_csv(filename, float_format='%.3f', index=False) print('Done - wrote file: ' + filename + '.')
cap.append_child_value("name", "EasyCap") cap.append_child_value("size", "54") cap.append_child_value("labelscheme", "10-20") # create outlet for the stream outlet = StreamOutlet(info) # (...normally here one might start sending data into the outlet...) # === the following could run on another computer === # 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 inf = inlet.info() print("The stream's XML meta-data is: ") print(inf.as_xml()) print("The manufacturer is: %s" % inf.desc().child_value("manufacturer")) print("Cap circumference is: %s" % 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)
def main(): inlet = None timestamp_accumulated = None data_accumulated = None no_data_duration = None # Create a outlet to relay the inference results ################################################################## if len( resolve_byprop( 'name', config.INFERENCE_LSL_RESULTS_NAME, timeout=0.5)) > 0: print( 'Inference stream with name {0} alreayd exists, cannot start. Check if there are other same script running' .format(config.INFERENCE_LSL_RESULTS_NAME)) raise Exception('Inference stream already exists') lsl_data_type = config.INFERENCE_LSL_RESULTS_TYPE lsl_data_name = config.INFERENCE_LSL_RESULTS_NAME info = StreamInfo(lsl_data_name, lsl_data_type, channel_count=inference_chann_count, channel_format='float32', source_id=(''.join( random.choice(string.digits) for i in range(8))), nominal_srate=110) info.desc().append_child_value("apocalyvec", "RealityNavigation") chns = info.desc().append_child("inference") channel_names = ['class' + str(i) for i in range(inference_chann_count)] for label in channel_names: ch = chns.append_child("channel") ch.append_child_value("label", label) outlet = StreamOutlet(info, max_buffered=360) print('Created inference results out stream ...') # Main Loop ################################################################################## while True: if inlet: data, timestamp = inlet.pull_sample(timeout=1e-2) if data: no_data_duration = 0 # received data, timestamp_accumulated.append( timestamp) # accumulate timestamps data_accumulated = np.concatenate( [data_accumulated, np.expand_dims(data, axis=-1)], axis=-1) # take the most recent samples # conduct inference # simply take the tail of data if data_accumulated.shape[-1] > f_data * time_window: try: _frame_min_max_adaptive = [ interp_negative(x) for x in data_accumulated[ use_channels, -int(f_data * adaptive_min_max_time_window):] ] data_downsampled_min = np.min(_frame_min_max_adaptive) data_downsampled_max = np.max(_frame_min_max_adaptive) except ValueError: # use default data_downsampled_min = 2. data_downsampled_max = 8. samples = np.expand_dims( data_accumulated[use_channels, -int(f_data * time_window):], axis=0) samples_preprocessed = preprocess_eye_samples( samples, f_resample=f_resample, data_downsampled_min=data_downsampled_min, data_downsampled_max=data_downsampled_max) results, _ = inference(samples_preprocessed) # send the inference results via LSL, only send out the not-decoded results outlet.push_sample(results) inference_per_second = len(timestamp_accumulated) / ( timestamp_accumulated[-1] - timestamp_accumulated[0]) if timestamp_accumulated[-1] - \ timestamp_accumulated[ 0] != 0. else 0. print('Inference per second is ' + str(inference_per_second), end='\r', flush=True) else: no_data_duration += time.time() - current_time if no_data_duration > reconnect_patience: print( 'No data seen on data stream with name {0}. Assume it is lost, trying to reconnect' .format(data_stream_name)) inlet = None else: print('Waiting for data stream with name {0} ...'.format( data_stream_name)) streams = resolve_byprop('name', data_stream_name) if len(streams) < 0: print('No stream found with name {0}, cannot start.'.format( data_stream_name)) raise Exception('No stream found for given name') # create a new inlet to read from the stream ###################################################################### inlet = StreamInlet(streams[0]) print('Found data stream with name {0}'.format(data_stream_name)) # model, y_encoder, data_downsampled_min, data_downsampled_max = load_model_params() # data buffers ##################################################################### timestamp_accumulated = [] data_accumulated = np.empty(shape=(data_chann_count, 0)) no_data_duration = 0. print('Entering inference loop') current_time = time.time() current_time = time.time()
def __init__(self, stream, fig, axes, window, scale, filter_data=True, dejitter=True): """Init""" self.stream = stream self.window = window self.scale = scale self.dejitter = dejitter self.inlet = StreamInlet(stream, max_chunklen=buf) self.filt = filter_data info = self.inlet.info() description = info.desc() self.sfreq = info.nominal_srate() self.n_samples = int(self.sfreq * self.window) self.n_chan = info.channel_count() ch = description.child('channels').first_child() ch_names = [ch.child_value('label')] for i in range(self.n_chan): ch = ch.next_sibling() ch_names.append(ch.child_value('label')) self.ch_names = ch_names fig.canvas.mpl_connect('key_press_event', self.OnKeypress) fig.canvas.mpl_connect('button_press_event', self.onclick) self.fig = fig self.axes = axes sns.despine(left=True) self.data = np.zeros((self.n_samples, self.n_chan)) self.times = np.arange(-self.window, 0, 1. / self.sfreq) impedances = np.std(self.data, axis=0) lines = [] for ii in range(self.n_chan): line, = axes.plot(self.times[::subsample], self.data[::subsample, ii] - ii, lw=1) lines.append(line) self.lines = lines axes.set_ylim(-self.n_chan + 0.5, 0.5) ticks = np.arange(0, -self.n_chan, -1) axes.set_xlabel('Time (s)') axes.xaxis.grid(False) axes.set_yticks(ticks) ticks_labels = [ '%s - %.1f' % (ch_names[ii], impedances[ii]) for ii in range(self.n_chan) ] axes.set_yticklabels(ticks_labels) self.display_every = int(0.2 / (12 / self.sfreq)) # self.bf, self.af = butter(4, np.array([1, 40])/(self.sfreq/2.), # 'bandpass') self.bf = firwin(32, np.array([1, 40]) / (self.sfreq / 2.), width=0.05, pass_zero=False) self.af = [1.0] zi = lfilter_zi(self.bf, self.af) self.filt_state = np.tile(zi, (self.n_chan, 1)).transpose() self.data_f = np.zeros((self.n_samples, self.n_chan))
INDEX_CHANNEL_JAW = [2] INDEX_CHANNELS = [INDEX_CHANNEL_BLINK, INDEX_CHANNEL_JAW] if __name__ == "__main__": """ 1. CONNECT TO EEG STREAM """ # Search for active LSL streams 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) # Get the stream info info = inlet.info() # Get the sampling frequency # This is an important value that represents how many EEG data points are # collected in a second. This influences our frequency band calculation. # for the Muse 2016, this should always be 256 fs = int(info.nominal_srate()) """ 2. INITIALIZE BUFFERS """ # Initialize raw EEG data buffer eeg_buffer = np.zeros((int(fs * BUFFER_LENGTH), 1)) filter_state = None # for use with the notch filter
def ReceiveAndDisplayEEG(self, lowfreq=1, highfreq=81, band=[10, 20]): if self.currentObj is None: print("no mesh") return try: invMat = scipy.io.loadmat( '/home/neuropsynov/hugHackathon/Manik_actiCHamp64_5000.mat') except: print("can't open the inv mat") return try: spi2gii = np.load('/home/neuropsynov/hugHackathon/spi2fullGii.npy') except: print("can't open the spi2gii file") return print("looking for an EEG stream...") streams = resolve_byprop('type', 'EEG', timeout=5.0) if len(streams) == 0: print("no eeg signal found") return #check number of contact match invMat size if streams[0].channel_count() != invMat["x"].shape[1]: print("invMat and channel_count doesn't match") #check if we have EOG for eye artefact removal #prepare the texture object if self.aimsMesh is None: self.aimsMesh = self.a.toAimsObject(self.mesh) self.texture[0].assign([0] * len(self.aimsMesh.vertex())) currentIndex = 0 buffSize = 500 buff = np.zeros([buffSize, streams[0].channel_count()]) #est-ce qu'on fait un buffer "normalisation" avec le signal en degageant du signal tout ce qui est >5 la MAD ? self.EEGAnalysisParam = {} nyq = 0.5 * streams[0].nominal_srate() low = lowfreq / nyq high = highfreq / nyq paramFil = scipy.signal.butter(6, [low, high], btype='band') # create a new inlet to read from the stream inlet = StreamInlet(streams[0]) self.mustStop = False self.TextObj.setPalette(palette='Blue-Red') while not self.mustStop: print(currentIndex) np.roll(buff, -1, 0) buff[buffSize - 1, :], timestamp = inlet.pull_sample() if currentIndex >= 500: filtSample = scipy.signal.filtfilt(paramFil[0], paramFil[1], buff, method="gust", axis=0) #il faudrait faire une fastICA ici #on prend juste le milieu du signal ? f_welch, S_xx_welch = scipy.signal.welch( filtSample[math.floor(buffSize / 4):math.floor(buffSize / 4) * 3, :], fs=streams[0].nominal_srate(), nfft=math.floor(2 * streams[0].nominal_srate() / 2.5), nperseg=math.floor(streams[0].nominal_srate() / 5.0), axis=0, scaling="density") freqKept = (f_welch >= band[0]) & (f_welch <= band[1]) DataToProject = np.mean(S_xx_welch[freqKept, :], axis=0) #DataToProject = buff[250,:] invsolmat = np.sqrt( np.multiply(np.dot(invMat["x"], DataToProject), np.dot(invMat["x"], DataToProject)) + np.multiply(np.dot(invMat["y"], DataToProject), np.dot(invMat["y"], DataToProject)) + np.multiply(np.dot(invMat["z"], DataToProject), np.dot(invMat["z"], DataToProject))) #if currentIndex % 500 == 0: # plt.plot(filtSample[:,5], 'b-') # plt.plot(buff[:,5], 'r-') # plt.show() fullTexture = np.dot(spi2gii, invsolmat) self.texture2[0].assign(fullTexture) self.TextObj.setTexture(self.texture2, True) self.TextObj.notifyObservers() self.app.processEvents() #mapping avec les leds currentIndex += 1 pdb.set_trace()
def create_streams(self, recursion_meter=0, max_recursion_depth=3): ''' Opens two LSL streams: one for EEG, another for markers, If error, tries to reconnect several times ''' if self.device == 'Enobio': stream_type_eeg = 'EEG' stream_name_markers = 'CycleStart' elif self.device == 'NVX52': stream_type_eeg = 'Data' stream_name_markers = 'CycleStart' stream_name_events = 'NVX52_Events' STREAM_NVX_PHOTOCELL = True else: print 'I don\'t know device {}!s\n\n\nWill now exit!'.format( self.device) sys.exit() if recursion_meter == 0: recursion_meter += 1 elif 0 < recursion_meter < max_recursion_depth: print 'Trying to reconnect for the %i time \n' % (recursion_meter + 1) recursion_meter += 1 else: print 'exiting' sys.exit() inlet_eeg = [] inlet_markers = [] if self.StreamEeg == True: print("Connecting to %s stream..." % self.device) if stream_type_eeg in [ stream.type() for stream in resolve_stream() ]: streams_eeg = resolve_stream('type', stream_type_eeg) inlet_eeg = StreamInlet(streams_eeg[0]) try: inlet_eeg self.sampling_rate = streams_eeg[0].nominal_srate() # print inlet_eeg.info().as_xml() print '...done \n' except NameError: print("Error: Cannot conect to %s stream\n" % self.device) sys.exit() else: print 'Error: %s stream is not available\n' % self.device sys.exit() else: inlet_eeg = [] if STREAM_NVX_PHOTOCELL == True: print("Connecting to %s photocell stream..." % self.device) if stream_name_events in [ stream.name() for stream in resolve_stream() ]: streams_eeg = resolve_stream('name', stream_name_events) inlet_photocell = StreamInlet(streams_eeg[0]) try: inlet_photocell # print inlet_eeg.info().as_xml() print '...done \n' except NameError: print("Error: Cannot conect to %s photocell stream\n" % self.device) sys.exit() else: print 'Error: %s stream is not available\n' % self.device sys.exit() else: inlet_photocell = [] if self.StreamMarkers == True: print("Connecting to Psychopy stream...") if stream_name_markers in [ stream.name() for stream in resolve_stream() ]: sterams_markers = resolve_stream('name', stream_name_markers) inlet_markers = StreamInlet(sterams_markers[0]) try: inlet_markers print '...done \n' except NameError: print("Error: Cannot conect to Psychopy stream\n") sys.exit() else: print 'Error: Psychopy stream is not available\n' return self.create_streams(stream_type_eeg, stream_name_markers, StreamEeg, StreamMarkers, recursion_meter) else: inlet_markers = [] return inlet_eeg, inlet_markers, inlet_photocell
from collections import deque import os import random ACTION = 'idle' FFT_MAX_HZ = 60 HM_SECONDS = 10 # this is approximate. Not 100%. do not depend on this. TOTAL_ITERS = HM_SECONDS * 25 # ~25 iters/sec last_print = time.time() fps_counter = deque(maxlen=150) # first resolve an EEG stream on the lab network print("looking for an EEG stream...") streams = resolve_stream('type', 'EEG') # create a new inlet to read from the stream inlet = StreamInlet(streams[-1]) total = 0 left = 0 right = 0 none = 0 correct = 0 channel_datas = [] for i in range(TOTAL_ITERS ): # how many iterations. Eventually this would be a while True channel_data = [] for i in range(60): sample, timestamp = inlet.pull_sample() channel_data.append(sample[:FFT_MAX_HZ]) fps_counter.append(time.time() - last_print) last_print = time.time() cur_raw_hz = 1 / (sum(fps_counter) / len(fps_counter))
from threading import Thread # Enough for 1 sec at 256 Hz BUFFER = 256 print("looking for an EEG stream...") streams = resolve_byprop('type', 'EEG', timeout=2) if len(streams) == 0: raise(RuntimeError("Cant find EEG stream")) print("Start aquiring data") stream = streams[0] inlet = StreamInlet(stream, max_chunklen=BUFFER) def alpha(data): #data.filter(8, 12, n_jobs=1, l_trans_bandwidth=1, h_trans_bandwidth=1, fir_design='firwin') #data.apply_hilbert(n_jobs=1, envelope=False) #epochs = mne.Epochs(data, events, 1, -1.0, 3.0, baseline=None, reject=dict(grad=4000e-13, eog=350e-6)) return np.average([math.sqrt(part.real**2 + part.imag**2) for part in data]) class CircularBuffer: def __init__(self, chunks): self.window = np.zeros((5, 256*chunks)) self.chunks = chunks self.window_read = self.chunks // 2 self.window_write = 0
import win32api def doSaneThing(sig, func=None): print("END") Drone.send('end') raise KeyboardInterrupt if __name__ == "__main__": #%% catching the control-C event win32api.SetConsoleCtrlHandler(doSaneThing, 1) #%% Access stream streams = resolve_stream('type', 'EEG') inlet = StreamInlet(streams[0], max_buflen=1000) info = inlet.info() NAME = inlet.info().name() SAMPLE_RATE = int(info.nominal_srate()) CHANNEL_COUNT = int(info.channel_count()) print("Name: {:s}".format(NAME)) print("Channel Count: {:d}".format(CHANNEL_COUNT)) print("Sample Rate: {:d}".format(SAMPLE_RATE)) #%% Initialize of the Drone interface Drone = TELLO() #List of stimulus frequencies list_freqs = np.arange(8.0, 13.0 + 1, 1) COMMAND = [ 'takeoff', 'land', 'forward 10', 'back 10', 'left 10', 'right 10'
samplingRate = 256 numSensors = 4 dataBuffer = np.zeros([numSensors, windowLength]) # api parser parser = argparse.ArgumentParser() parser.add_argument('-k', '--api_key', type=str, required=True, help='API key for the Petal Metrics API') args = parser.parse_args() print("looking for an EEG stream...") streams = resolve_stream('type', 'EEG') inlet = StreamInlet(streams[0]) while True: sample, timestamp = inlet.pull_chunk(timeout=2, max_samples=chunkLength) sample = np.asarray(sample).T for channel in range(0, numSensors): dataBuffer[channel] = np.roll(dataBuffer[channel], -chunkLength) for newSample in range(0, chunkLength): dataBuffer[channel][len(dataBuffer[channel]) - chunkLength + newSample] = sample[channel][newSample] finalDataAPI = np.asarray(dataBuffer).tolist() #call api apiOutput = request_metrics( api_key=args.api_key, eeg_data=finalDataAPI,
def plotNodes(i): # define all global variables global data global globalMax global line1 global line2 # Create an inlet inlet = StreamInlet(streams[0]) # Pull data into the inlet amplitudes = inlet.pull_sample() # create a new numpy array called new_data for amplitudes new_data = np.asarray(amplitudes[0][:n]) # get the frequency via delta band or by accessing individual frequencies temp, localMax, data = getFreqBandOrValue(data, new_data, 0, globalMax) # Initialize row and column dimensions for the 64 x 64 list # initialize row dimension to 64 i = 64 # initialize column dimension to 64 j = 64 # Create and initialize a 2-dimensional list with zeros to store differences between amplitudes differences = [[0] * j for i in range(64)] # Compute the differences between the amplitudes at every given xth, yth position for x in range(63): for y in range(63): # Compute the difference between the amplitudes at every given xth, yth position difference = abs(temp[x] - temp[y]) # Store the current difference in the differences list at the given xth, yth position differences[x][y] = difference # Convert the differences list into a (64 x 64)-element Numpy array differences_data = np.asarray(differences) # print the shape/size of the differences_data array print(np.shape(differences_data)) # Compute the z-score of the differences z_scores = np.zeros([64, 64]) # print the shape/size of the z-scores array print(np.shape(z_scores)) # calculate the z-scores for each row and column in the differences_data array for i in range(63): # calculate the z-scores z_scores[:n][i] = stats.zscore(differences_data[:n][i]) # print the z-scores print(z_scores[:n][i]) # set the x-axis limits for plot ax1 ax1.set_xlim(-6, 6) # set the y-axis limits for plot ax1 ax1.set_ylim(-6, 6) # Plot z-scores of differences in amplitudes ax1.scatter(x, y) # Plot a red line between electrodes where z-score > 2.3 # Plot a blue line between electrodes where z-score < -2.3 # Dimensions of z-scores numpy array is not acceptable in scatter function # remove every line in ax1 for line in ax1.lines: line.remove() # for every pair of electrodes: # - plot a red line where the z-scores of the differences is > 2.3 # - plot a blue line where the z-scores of the differences is < -2.3 for i in range(64): for j in range(64): if j <= i: continue # if z-scores is > 2.3, plot a red line on ax1 if z_scores[i, j] > 2.3: Red_Lines(list[i], list[j], ax1) # if z-scores is < -2.3, plot a blue line on ax1 elif z_scores[i, j] < -2.3: Blue_Lines(list[i], list[j], ax1) # else, continue else: continue