def simulate_bci_signal(fs, chunk_size=8, verbose=False): # setup stream info = StreamInfo(name='NFBLab_data', type='', channel_count=1, nominal_srate=fs) channels = info.desc().append_child("channels") channels.append_child("channel").append_child_value("name", 'BCI') print('Stream info:\n\tname: {}, fs: {}Hz, channels: {}'.format( info.name(), int(info.nominal_srate()), ['BCI'])) outlet = StreamOutlet(info) print('Now sending data...') # prepare main loop start = time() counter = chunk_size x = x_base = np.ones((chunk_size, 1)) n_chunks = 0 # main loop while True: while time() - start < counter / fs: sleep(1 / fs) if np.random.randint(0, fs / chunk_size / 2) == 0: x = x_base * np.random.randint(0, 2 + 1) outlet.push_chunk(x) n_chunks += 1 counter += chunk_size if verbose: # print('counter time: {:.2f}\ttime: {:.2f}'.format(counter/fs, time() - start)) if n_chunks % 50 == 0: print('Chunk {} was sent'.format(n_chunks))
class BetaGeneratorOutlet(object): def __init__(self, Fs=2**14, FreqBeta=20.0, AmpBeta=100.0, AmpNoise=20.0, NCyclesPerChunk=4, channels=["RAW1", "SPK1", "RAW2", "SPK2", "RAW3", "SPK3"]): """ :param Fs: Sampling rate :param FreqBeta: Central frequency of beta band :param AmpBeta: Amplitude of beta (uV) :param AmpNoise: Amplitude of pink noise (uV) :param NCyclesPerChunk: Minimum number of cycles of beta in a chunk. :param channels: List of channel names """ # Saved arguments self.FreqBeta = FreqBeta self.AmpBeta = AmpBeta # Amplitude of Beta (uV) self.AmpNoise = AmpNoise # Amplitude of pink noise self.channels = channels # Derived variables chunk_dur = NCyclesPerChunk / self.FreqBeta # Duration, in sec, of one chunk chunk_len = int(Fs * chunk_dur) # Number of samples in a chunk self.tvec = 1.0 * (np.arange(chunk_len) + 1) / Fs # time vector for chunk (sec) # Pink noise generator self.pinkNoiseGen = PinkNoiseGenerator(nSampsPerBlock=chunk_len) # Create a stream of fake 'raw' data raw_info = StreamInfo(name='BetaGen', type='EEG', channel_count=len(self.channels), nominal_srate=Fs, channel_format='float32', source_id='betagen1234') raw_xml = raw_info.desc() chans = raw_xml.append_child("channels") for channame in self.channels: chn = chans.append_child("channel") chn.append_child_value("label", channame) chn.append_child_value("unit", "microvolts") chn.append_child_value("type", "generated") self.eeg_outlet = StreamOutlet(raw_info) print("Created outlet with name BetaGen and type EEG") self.last_time = local_clock() def update(self, task={'phase': 'precue', 'class': 1}): # Convert phase and class_id into beta_amp if task['phase'] in ['cue', 'go']: beta_amp = 0 if task['class'] == 3 else self.AmpBeta else: beta_amp = self.AmpBeta / 5.0 this_tvec = self.tvec + self.last_time # Sample times # Put the signal together this_sig = self.AmpNoise * np.asarray(self.pinkNoiseGen.generate(), dtype=np.float32) # Start with some pink noise this_sig += beta_amp * np.sin(this_tvec * 2 * np.pi * self.FreqBeta) # Add our beta signal this_sig = np.atleast_2d(this_sig).T * np.ones((1, len(self.channels)), dtype=np.float32) # Tile across channels time_to_sleep = max(0, this_tvec[-1] - local_clock()) time.sleep(time_to_sleep) print("Beta outlet pushing signal with shape {},{} and Beta amp {}".format(this_sig.shape[0], this_sig.shape[1], beta_amp)) self.eeg_outlet.push_chunk(this_sig, timestamp=this_tvec[-1]) self.last_time = local_clock()
def main(): model = load_model('RNN') while True: try: print("looking for an EEG stream...") streams = resolve_stream('name', 'NER_2015_BCI_Challenge_Samples') # create a new inlet to read from the stream inlet = StreamInlet(streams[0]) # Pred stream info_pred = StreamInfo('NER_2015_BCI_Challenge_PRED', 'PRED', 1, IRREGULAR_RATE, 'float32', 'PREDID') outlet_pred = StreamOutlet(info_pred) while True: sample = np.empty((0, 56)) timestamps = [] while len(sample) < 2001: chunk, ts = inlet.pull_chunk() if ts: ts = timestamps + ts sample = np.concatenate([sample, chunk], axis=0) pred = model.predict( np.expand_dims(sample[:2001].transpose(), axis=0)) outlet_pred.push_chunk(pred[0, :, 0].tolist()) print('Pushed inference results') except LostError: pass
class lsl_outlet(po): def __init__(self, info): self.outlet = StreamOutlet(info) def process(self, frames): if frames.chann_cnt is not self.outlet.channel_count: return -1 self.outlet.push_chunk(frames.buffer.tolist()) return frames
class SignalsOutlet: def __init__(self, signals, fs, name='NFBLab_data1'): self.info = StreamInfo(name=name, type='', channel_count=len(signals), source_id='nfblab42', nominal_srate=fs) self.info.desc().append_child_value("manufacturer", "BioSemi") channels = self.info.desc().append_child("channels") for c in signals: channels.append_child("channel").append_child_value("name", c) self.outlet = StreamOutlet(self.info) def push_sample(self, data): self.outlet.push_sample(data) def push_repeated_chunk(self, data, n=1): #chunk = repeat(data, n).reshape(-1, n).T.tolist() #self.outlet.push_chunk(chunk) for k in range(n): self.outlet.push_sample(data) def push_chunk(self, data, n=1): self.outlet.push_chunk(data)
class SignalsOutlet: def __init__(self, signals, fs): self.info = StreamInfo(name='NFBLab_data', type='', channel_count=len(signals), source_id='nfblab42', nominal_srate=fs) self.info.desc().append_child_value("manufacturer", "BioSemi") channels = self.info.desc().append_child("channels") for c in signals: channels.append_child("channel").append_child_value("name", c) self.outlet = StreamOutlet(self.info) def push_sample(self, data): self.outlet.push_sample(data) def push_repeated_chunk(self, data, n=1): #chunk = repeat(data, n).reshape(-1, n).T.tolist() #self.outlet.push_chunk(chunk) for k in range(n): self.outlet.push_sample(data) def push_chunk(self, data, n=1): self.outlet.push_chunk(data)
class BetaGeneratorOutlet(object): def __init__(self, Fs=2**14, FreqBeta=20.0, AmpBeta=100.0, AmpNoise=20.0, NCyclesPerChunk=4, channels=["RAW1", "SPK1", "RAW2", "SPK2", "RAW3", "SPK3"]): """ :param Fs: Sampling rate :param FreqBeta: Central frequency of beta band :param AmpBeta: Amplitude of beta (uV) :param AmpNoise: Amplitude of pink noise (uV) :param NCyclesPerChunk: Minimum number of cycles of beta in a chunk. :param channels: List of channel names """ # Saved arguments self.FreqBeta = FreqBeta self.AmpBeta = AmpBeta # Amplitude of Beta (uV) self.AmpNoise = AmpNoise # Amplitude of pink noise self.channels = channels # Derived variables chunk_dur = NCyclesPerChunk / self.FreqBeta # Duration, in sec, of one chunk chunk_len = int(Fs * chunk_dur) # Number of samples in a chunk self.tvec = 1.0 * (np.arange(chunk_len) + 1) / Fs # time vector for chunk (sec) # Pink noise generator self.pinkNoiseGen = PinkNoiseGenerator(nSampsPerBlock=chunk_len) # Create a stream of fake 'raw' data raw_info = StreamInfo(name='BetaGen', type='EEG', channel_count=len(self.channels), nominal_srate=Fs, channel_format='float32', source_id='betagen1234') raw_xml = raw_info.desc() chans = raw_xml.append_child("channels") for channame in self.channels: chn = chans.append_child("channel") chn.append_child_value("label", channame) chn.append_child_value("unit", "microvolts") chn.append_child_value("type", "generated") self.eeg_outlet = StreamOutlet(raw_info) print("Created outlet with name BetaGen and type EEG") self.last_time = local_clock() def update(self, task={'phase': 'precue', 'class': 1}): # Convert phase and class_id into beta_amp if task['phase'] in ['cue', 'go']: beta_amp = 0 if task['class'] == 3 else self.AmpBeta else: beta_amp = self.AmpBeta / 5.0 this_tvec = self.tvec + self.last_time # Sample times # Put the signal together this_sig = self.AmpNoise * np.asarray( self.pinkNoiseGen.generate(), dtype=np.float32) # Start with some pink noise this_sig += beta_amp * np.sin( this_tvec * 2 * np.pi * self.FreqBeta) # Add our beta signal this_sig = np.atleast_2d(this_sig).T * np.ones( (1, len(self.channels)), dtype=np.float32) # Tile across channels time_to_sleep = max(0, this_tvec[-1] - local_clock()) time.sleep(time_to_sleep) print("Beta outlet pushing signal with shape {},{} and Beta amp {}". format(this_sig.shape[0], this_sig.shape[1], beta_amp)) self.eeg_outlet.push_chunk(this_sig, timestamp=this_tvec[-1]) self.last_time = local_clock()
opt_detrend=1, HP=0, LP=40, phase='zero-double') if exp_marker == ['a'] and behavior_marker == ['1']: target_epochs = np.append(target_epochs, [epoch], axis=0) target_markers = np.append(target_markers, 1) target_RT = np.append(target_RT, RT) # Check if user wants to visualize epochs of data if expInfo['Visualize Epochs']: label = np.ndarray.tolist(1 * np.ones((1, fs_new))) y = np.ndarray.tolist(epoch) + label outlet_viz.push_chunk(y, pushthrough=True) # meanEpoch = np.mean([lastEpoch, epoch], axis=0) # lastEpoch = epoch elif exp_marker == ['l'] and behavior_marker == ['1']: nontarget_epochs = np.append(nontarget_epochs, [epoch], axis=0) nontarget_markers = np.append(nontarget_markers, 0) nontarget_RT = np.append(nontarget_RT, RT) # Check if user wants to visualize epochs of data if expInfo['Visualize Epochs']: label = np.ndarray.tolist(-1 * np.ones( (1, fs_new))) y = np.ndarray.tolist(epoch) + label outlet_viz.push_chunk(y, pushthrough=True)
def fft_backend(input_stream, output_stream, window_length=256, pow2=True, window_type=np.hamming): ################################# ## Stream Inlet and Outlet Creation ################################# #streams = resolve_byprop("name",input_stream.name(),timeout= 10) #input_stream = streams[0] #print(input_stream.channel_count()) #print(input_stream) #print(input_stream.name()) inlet = StreamInlet(input_stream, max_chunklen=12, recover=True) inlet.open_stream() # Stream is opened implicitely on first call of pull chunk, but opening now for clarity # Create StreamOutlet to push data to output stream outlet = StreamOutlet(output_stream, chunk_size=129) ################################### ## FFT ################################### buffer = np.empty((0,5)) window = window_type(window_length) g = True while(True): input_chunk = inlet.pull_chunk() # Pull Chunk #print(np.shape(input_chunk)) if input_chunk[0] and np.shape(input_chunk)[1] > 0: # Check for available chunk #print("output samples") buffer = np.append(buffer, input_chunk[0], axis=0) if (len(buffer) >= window_length): # Take data from buffer data = buffer[0:window_length] data = np.transpose(data) # Get frequency labels/bins freq_labels = np.fft.rfftfreq(window_length, 1/input_stream.nominal_srate()) # Take FFT of data for each channel data_windowed = [] data_fft = [] psd = [] for i in range(0, output_stream.channel_count()): # Multiply data by window data_windowed.append(data[i] - np.mean(data[i], axis=0)) data_windowed[i] = data_windowed[i] * window # Get FFT data_fft.append(np.fft.rfft(data_windowed[i], n=window_length, axis=0)) data_fft[i] = data_fft[i]/window_length # Convert FFT to PSD psd.append(abs(data_fft[i])) # Take absolute value # Assume input signal is real-valued and double power to account for negative frequencies # DC power (psd[i][0]) only occurs once and does not need to be doubled) psd[i][1:] = 2*psd[i][1:] # Create Output Data Packet in shape 2 x N (Where N is the # of discrete frequencies) # The first dimension of output sample contains the data of shape CHANNELS x N # The second dimension contains the N labels for the frequencies in Hz psd = np.transpose(psd) psd = psd.tolist() if(g==True): #print(psd) g=False #print(np.shape(psd)) #freq_labels = freq_labels.tolist() #output_sample = (psd, freq_labels) #print(np.shape(output_sample)) #print(output_sample) # Push fft transform for each channel using outlet outlet.push_chunk(psd)
chns = info_eeg.desc().append_child("channels") for label in ["AFp1", "AFp2", "C3", "C4", "P7", "P8", "O1", "O2"]: ch = chns.append_child("channel") ch.append_child_value("label", label) info_aux = StreamInfo('OpenBCIAUX', 'AUX', 3, 250, 'float32', 'OpenBCItestAUX') chns = info_aux.desc().append_child("channels") for label in ["X", "Y", "Z"]: ch = chns.append_child("channel") ch.append_child_value("label", label) outlet_aux = StreamOutlet(info_aux) outlet_eeg = StreamOutlet(info_eeg) # construct a numpy array that contains only eeg channels and aux channels with correct scaling # this streams to lsl while True: data = board.get_board_data() # this gets data continiously # don't send empty data if len(data[0]) < 1 : continue eeg_data = data[eeg_chan] aux_data = data[aux_chan] #print(scaled_eeg_data) #print(scaled_aux_data) #print('------------------------------------------------------------------------------------------') eegchunk = [] for i in range(len(eeg_data[0])): eegchunk.append((eeg_data[:,i]).tolist()) #scale data here outlet_eeg.push_chunk(eegchunk) auxchunk = [] for i in range(len(aux_data[0])): auxchunk.append((aux_data[:,i]).tolist()) #scale data here outlet_aux.push_chunk(auxchunk)
# you can use the python API of labstreaminglayer to fix things there # https://github.com/labstreaminglayer/liblsl-Python/tree/b158b57f66bc82230ff5ad0433fbd4480766a849 # make a new LSL stream to send data away: # 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) info = StreamInfo('Python', 'EEG', nbchan, fs, 'float32', 'corrected') outlet = StreamOutlet(info) amp.start() while True: time.sleep(0.01) data, marker = amp.get_data() # it doesn't make sense to do stuff, if theere is no data if data.shape[0] > 0: data, marker = amp.get_data() data2 = hpf.handle(data) data3 = mr.handle(data2) # send it away - you'd need to figure out whether to seond data # or transposed data (i.e. data.T) # pdb.set_trace() outlet.push_chunk(data3)
class LslServer: """Class for LabStreamingLayer integration""" def __init__(self, device_info): n_chan = device_info['adc_mask'].count(1) self.exg_fs = device_info['sampling_rate'] orn_fs = 20 info_exg = StreamInfo(name=device_info["device_name"] + "_ExG", type='ExG', channel_count=n_chan, nominal_srate=self.exg_fs, channel_format='float32', source_id=device_info["device_name"] + "_ExG") info_exg.desc().append_child_value("manufacturer", "Mentalab") channels = info_exg.desc().append_child("channels") for i, mask in enumerate(device_info['adc_mask']): if mask == 1: channels.append_child("channel")\ .append_child_value("name", EXG_CHANNELS[i])\ .append_child_value("unit", EXG_UNITS[i])\ .append_child_value("type", "ExG") info_orn = StreamInfo(name=device_info["device_name"] + "_ORN", type='ORN', channel_count=9, nominal_srate=orn_fs, channel_format='float32', source_id=device_info["device_name"] + "_ORN") info_orn.desc().append_child_value("manufacturer", "Mentalab") channels = info_exg.desc().append_child("channels") for chan, unit in zip(ORN_CHANNELS, ORN_UNITS): channels.append_child("channel") \ .append_child_value("name", chan) \ .append_child_value("unit", unit) \ .append_child_value("type", "ORN") info_marker = StreamInfo(name=device_info["device_name"] + "_Marker", type='Markers', channel_count=1, nominal_srate=0, channel_format='int32', source_id=device_info["device_name"] + "_Markers") logger.info( "LSL Streams have been created with names/source IDs as the following:\n" + "\t\t\t\t\t" + device_info["device_name"] + "_ExG\n" + "\t\t\t\t\t" + device_info["device_name"] + "_ORN\n" + "\t\t\t\t\t" + device_info["device_name"] + "_Markers\n") self.orn_outlet = StreamOutlet(info_orn) self.exg_outlet = StreamOutlet(info_exg) self.marker_outlet = StreamOutlet(info_marker) def push_exg(self, packet): """Push data to ExG outlet Args: packet (explorepy.packet.EEG): ExG packet """ _, exg_data = packet.get_data(self.exg_fs) self.exg_outlet.push_chunk(exg_data.T.tolist()) def push_orn(self, packet): """Push data to orientation outlet Args: packet (explorepy.packet.Orientation): Orientation packet """ _, orn_data = packet.get_data() self.orn_outlet.push_sample(orn_data) def push_marker(self, packet): """Push data to marker outlet Args: packet (explorepy.packet.EventMarker): Event marker packet """ _, code = packet.get_data() self.marker_outlet.push_sample(code)
class LslServer: """Class for LabStreamingLayer integration""" def __init__(self, device_info): n_chan = device_info['adc_mask'].count(1) self.exg_fs = device_info['sampling_rate'] orn_fs = 20 info_exg = StreamInfo(device_info["device_name"] + "_ExG", 'ExG', n_chan, self.exg_fs, 'float32', 'ExG') info_exg.desc().append_child_value("manufacturer", "Mentalab") channels = info_exg.desc().append_child("channels") for i, mask in enumerate(device_info['adc_mask']): if mask == 1: channels.append_child("channel")\ .append_child_value("name", EXG_CHANNELS[i])\ .append_child_value("unit", EXG_UNITS[i])\ .append_child_value("type", "ExG") info_orn = StreamInfo(device_info["device_name"] + "_ORN", 'Orientation', 9, orn_fs, 'float32', 'ORN') info_orn.desc().append_child_value("manufacturer", "Mentalab") channels = info_exg.desc().append_child("channels") for chan, unit in zip(ORN_CHANNELS, ORN_UNITS): channels.append_child("channel") \ .append_child_value("name", chan) \ .append_child_value("unit", unit) \ .append_child_value("type", "ORN") info_marker = StreamInfo(device_info["device_name"] + "_Marker", 'Markers', 1, 0, 'int32', 'Marker') self.orn_outlet = StreamOutlet(info_orn) self.exg_outlet = StreamOutlet(info_exg) self.marker_outlet = StreamOutlet(info_marker) def push_exg(self, packet): """Push data to ExG outlet Args: packet (explorepy.packet.EEG): ExG packet """ _, exg_data = packet.get_data(self.exg_fs) self.exg_outlet.push_chunk(exg_data.T.tolist()) def push_orn(self, packet): """Push data to orientation outlet Args: packet (explorepy.packet.Orientation): Orientation packet """ _, orn_data = packet.get_data() self.orn_outlet.push_sample(orn_data) def push_marker(self, packet): """Push data to marker outlet Args: packet (explorepy.packet.EventMarker): Event marker packet """ _, code = packet.get_data() self.marker_outlet.push_sample(code)
def main(): BoardShim.enable_dev_board_logger() parser = argparse.ArgumentParser() # brainflow params - use docs to check which parameters are required for specific board, e.g. for Cyton set serial port parser.add_argument('--timeout', type=int, help='timeout for device discovery or connection', required=False, default=0) parser.add_argument('--ip-address', type=str, help='ip address', required=False, default='') parser.add_argument('--board-id', type=int, help='board id, check docs to get a list of supported boards', required=True) parser.add_argument('--serial-port', type=str, help='serial port', required=False, default='') parser.add_argument('--streamer-params', type=str, help='streamer params', required=False, default='') # LSL params parser.add_argument('--name', type=str, help='name', required=True) parser.add_argument('--data-type', type=str, help='data type', required=True) parser.add_argument('--channel-names', type=str, help='channel names', required=True) parser.add_argument('--uid', type=str, help='uid', required=True) args = parser.parse_args() # brainflow initialization params = BrainFlowInputParams() params.serial_port = args.serial_port params.ip_address = args.ip_address board = BoardShim(args.board_id, params) # LSL initialization channel_names = args.channel_names.split(',') n_channels = len(channel_names) srate = board.get_sampling_rate(args.board_id) info = StreamInfo(args.name, args.data_type, n_channels, srate, 'double64', args.uid) outlet = StreamOutlet(info) fw_delay = 0 # prepare session board.prepare_session() # send commands to the board for every channel. Cyton has 8 Channels. Here, we turn off every channel except for 1 and 8. # This is here for testing purposes. #board.config_board("x1000110X") #Lower the gain to 1x on channel 1 #board.config_board("x1061000X") #board.config_board("x2161000X") #board.config_board("x3161000X") #board.config_board("x4161000X") #board.config_board("x5161000X") #board.config_board("x6161000X") #board.config_board("x7161000X") #board.config_board("x8060110X") # start stream board.start_stream(45000, args.streamer_params) time.sleep(1) start_time = local_clock() sent_samples = 0 queue = Queue(maxsize = 5*srate) chans = channel_select(board, args.board_id, args.data_type) # Vars for filters applyBandStop = True applyBandPass = True bandStopFrequency = 60.0 bp_lowerBound = 5.0 bp_upperBound = 50.0 bp_centerFreq = (bp_upperBound + bp_lowerBound) / 2.0; bp_bandWidth = bp_upperBound - bp_lowerBound # read data with brainflow and send it via LSL print("Now sending data...") while True: data = board.get_board_data()[chans] # It's best to apply filters on the receiving end, but this is here just for testing purposes. """ for chan in range(len(chans)): if applyBandStop: DataFilter.perform_bandstop(data[chan], BoardShim.get_sampling_rate(args.board_id), bandStopFrequency, 4.0, 2, FilterTypes.BUTTERWORTH.value, 0); if applyBandPass: DataFilter.perform_bandpass( data[chan], BoardShim.get_sampling_rate(args.board_id), bp_centerFreq, bp_bandWidth, 2, FilterTypes.BUTTERWORTH.value, 0); """ for i in range(len(data[0])): queue.put(data[:,i].tolist()) elapsed_time = local_clock() - start_time required_samples = int(srate * elapsed_time) - sent_samples if required_samples > 0 and queue.qsize() >= required_samples: mychunk = [] for i in range(required_samples): mychunk.append(queue.get()) stamp = local_clock() - fw_delay outlet.push_chunk(mychunk, stamp) sent_samples += required_samples time.sleep(1)
p=time.time() t=0 startTime = time.time() while (time.time() - startTime < exptime): # make a new random 8-channel sample; this is converted into a # pylsl.vectorf (the data type that is expected by push_sample) startwhile = time.time(); t+=startwhile-p if(t>1): pbar.update(round(t)) t=0 p=startwhile chunk = myoData[pos:pos+chunksize,:].tolist() outletMyo.push_chunk(chunk) chunk = pnData[pos:pos+chunksize,:].tolist() outletPn.push_chunk(chunk) pos=pos+chunksize dif = dt_rate - time.time() + startwhile; if(dif > 0): time.sleep(dif) pbar.close() del(myoData) del(pnData)
#channels = info.desc().append_child("channels") #for c in ["C3", "C4", "Cz", "FPz", "POz", "CPz", "O1", "O2"]: # channels.append_child("channel") \ # .append_child_value("label", c) \ # .append_child_value("unit", "microvolts") \ # .append_child_value("type", "EEG") # next make an outlet; we set the transmission chunk size to 32 samples and # the outgoing buffer size to 360 seconds (max.) # outlet = StreamOutlet(info, 32, 360) outlet = StreamOutlet(info, 100, 30) amp.start() while True: # time.sleep(0.01) data, marker = amp.get_data() # it doesn't make sense to do stuff, if theere is no data if data.shape[0] > 0: #data, marker = amp.get_data() data2 = hpf.handle(data) data3 = mr.handle(data2) # send it away - you'd need to figure out whether to seond data # or transposed data (i.e. data.T) # pdb.set_trace() outlet.push_chunk(data.tolist())
def stream(socket, address, resp_enabled, ecg_enabled, acc_enabled, log_enabled, sum_enabled): print('Streaming...') if ecg_enabled: # ECG LSL outlet ecg_info = StreamInfo('ZephyrECG', 'ECG', 1, 250, 'float32') ecg_info.desc().append_child_value("manufacturer", "Zephyr") ecg_channels = ecg_info.desc().append_child("channels") ecg_channels.append_child("channel").append_child_value( "label", "ECG").append_child_value("unit", "microvolts").append_child_value( "type", "ECG") ecg_outlet = StreamOutlet(ecg_info, 12) if resp_enabled: # RESP LSL outlet resp_info = StreamInfo('ZephyrRESP', 'RESP', 1, 18, 'float32') resp_info.desc().append_child_value("manufacturer", "Zephyr") resp_channels = resp_info.desc().append_child("channels") resp_channels.append_child("channel").append_child_value( "label", "RESP").append_child_value( "unit", "microvolts").append_child_value("type", "RESP") resp_outlet = StreamOutlet(resp_info, 12) if acc_enabled: # ACC LSL outlet acc_info = StreamInfo('ZephyrACC', 'ACC', 3, 250, 'float32', 'Zephyr%s' % address) acc_info.desc().append_child_value("manufacturer", "Zephyr") acc_channels = acc_info.desc().append_child("channels") for c in ['X', 'Y', 'Z']: acc_channels.append_child("channel").append_child_value( "label", c).append_child_value("unit", "g").append_child_value("type", "ACC") acc_outlet = StreamOutlet(acc_info, 12) try: while True: data = socket.recv(1024) decoded_data = data.hex() stream_type = decoded_data[2:4] pay_len = 2 * int(decoded_data[4:6], 16) curr_payload = decoded_data[6:pay_len + 6] if stream_type == '21': # RESP #timestamp = util.get_timestamp(curr_payload) sample_set = util.get_sample_set(curr_payload) sample_list = util.parser_10bit(sample_set) resp_outlet.push_chunk(sample_list) if stream_type == '22': # ECG #timestamp = util.get_timestamp(curr_payload) sample_set = util.get_sample_set(curr_payload) sample_list = util.parser_10bit(sample_set) ecg_outlet.push_chunk(sample_list) if stream_type == '25': # ACC #timestamp = util.get_timestamp(curr_payload) sample_set = util.get_sample_set(curr_payload) sample_list = util.parser_acc(sample_set) acc_outlet.push_chunk(sample_list) socket.send('\x02#\x00\x00\x03') #Prevents a connection timeout. except IOError: pass
# pass # while Buffer_thread.hold(): # infinite Loop """ This is the main part of the code, and will run infinitely. The buffer is filled and stored as Live_Matrix Live_matrix is then High passed, Normalized, and PSD feature calculated and returned finally the buffer is deleted, and then reinitialized to be sent back in to be filled """ print(("Filling Buffer please wait, Buffer size = %d s" % window)) fullbuff = Q.get() # Get 9x128 Matrix from LSL fullbuff = np.nan_to_num(fullbuff) for i in range(0, x): fullbuff[i, :] = (fullbuff[i, :] - base[i]) """ Open and Write JSON object """ fullsum = np.sum(fullbuff, axis=0) #NomLSL.push_sample(fullsum) NomLSL.push_chunk(fullsum) # with open('./buffer.json', 'w') as f_buffer: # # collapse buffer channels to 1 # f_buffer.write('{\n\"Buffer\":[') # for n in fullsum: # f_buffer.write(str(n)) # f_buffer.write(',') # f_buffer.write(']\n}') # np.save('./Data/Training/Raw/BR8/buffer_W{0}'.format(window),fullbuff) print("Buffer filled Preprocessing") live_M = Feature_calc.DEAP_process(fullbuff, Fs) Normalized, psdf, psdx = Feature_calc.process_live(live_M, Fs) alpha, beta, delta, gamma, theta = Feature_calc.Band_PSD( Normalized, Fs)
pnbuff[i] = t else: print('empty pn chunk encountered') if chunk_size > 0: chunk = chunk[:, :numCh] chunk = emgfilter.filterEMG(chunk) WienerCoords, KalmanCoords = emgdecoder.decodeEMG(chunk) #getting the last samples prediction = KalmanCoords[-1, :len(fingersrange)] fact = np.copy(pnbuff) print(prediction.reshape(1, -1)) outletEMG.push_chunk(prediction.reshape(1, -1)) avatarBuffer[fsendrange] = prediction avatarBuffer[fsendrange + 3] = prediction avatarBuffer[fsendrange + 6] = prediction / 2 avatarBuffer[fsendrange + 48] = fact avatarBuffer[fsendrange + 3 + 48] = fact avatarBuffer[fsendrange + 6 + 48] = fact / 2 #sending to the Avatar data2 = struct.pack('%df' % len(avatarBuffer), *list(map(float, avatarBuffer))) sock.sendto(data2, client_address) else:
def main(argv): srate = 100 name = 'LSLExampleAmp' type = 'EEG' channel_names = ["C3", "C4", "Cz", "FPz", "POz", "CPz", "O1", "O2"] n_channels = len(channel_names) help_string = 'SendData.py -s <sampling_rate> -n <stream_name> -t <stream_type>' try: opts, args = getopt.getopt(argv, "hs:n:t:", longopts=["srate=", "name=", "type"]) except getopt.GetoptError: print(help_string) sys.exit(2) for opt, arg in opts: if opt == '-h': print(help_string) sys.exit() elif opt in ("-s", "--srate"): srate = float(arg) elif opt in ("-n", "--name"): name = arg elif opt in ("-t", "--type"): type = arg # 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). info = StreamInfo(name, type, n_channels, srate, 'float32', 'myuid2424') # append some meta-data info.desc().append_child_value("manufacturer", "LSLExampleAmp") chns = info.desc().append_child("channels") for label in channel_names: ch = chns.append_child("channel") ch.append_child_value("label", label) ch.append_child_value("unit", "microvolts") ch.append_child_value("type", "EEG") info.desc().append_child_value("manufacturer", "LSLExamples") cap = info.desc().append_child("cap") cap.append_child_value("name", "ComfyCap") cap.append_child_value("size", "54") cap.append_child_value("labelscheme", "10-20") # next make an outlet; we set the transmission chunk size to 32 samples and # the outgoing buffer size to 360 seconds (max.) outlet = StreamOutlet(info, 32, 360) print("now sending data...") start_time = local_clock() sent_samples = 0 while True: elapsed_time = local_clock() - start_time required_samples = int(srate * elapsed_time) - sent_samples if required_samples > 0: # make a chunk==array of length required_samples, where each element in the array # is a new random n_channels sample vector mychunk = [[rand() for chan_ix in range(n_channels)] for samp_ix in range(required_samples)] # get a time stamp in seconds (we pretend that our samples are actually # 125ms old, e.g., as if coming from some external hardware) stamp = local_clock() - 0.125 # now send it and wait for a bit outlet.push_chunk(mychunk, stamp) sent_samples += required_samples time.sleep(0.02)
j = np.abs(np.sin(2 * np.pi * i / 50)) pacgen = PACGenerator(16, 130, 1, .25, sample_rate=2**14, phase_amp=np.pi, seed=False) mysample = pacgen.simulate(tdur, j, nch=1, noise=False) tstart += 500 n = np.arange(tstart, tstart + tdur) # now send it and wait for a bit # time.sleep(0.001) outlet.push_chunk(mysample) tmp = fb.analysis(mysample, window='hanning') print(mysample.shape, tmp.shape) i += 1 # try: # # ax1.clear() # # ax1.plot(n, mysample.T) # # ax1.set_ylim([-3, 3]) # # for (i,), ax in np.ndenumerate(ax2): # ax.clear() # ax.plot(n, tmp[:,i,:].T) #