def main(): parser = argparse.ArgumentParser() # 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-port', type=int, help='ip port', required=False, default=0) parser.add_argument('--ip-protocol', type=int, help='ip protocol, check IpProtocolType enum', required=False, default=0) parser.add_argument('--ip-address', type=str, help='ip address', required=False, default='') parser.add_argument('--serial-port', type=str, help='serial port', required=False, default='') parser.add_argument('--mac-address', type=str, help='mac address', required=False, default='') parser.add_argument('--other-info', type=str, help='other info', required=False, default='') parser.add_argument('--streamer-params', type=str, help='streamer params', required=False, default='') parser.add_argument('--serial-number', type=str, help='serial number', 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('--file', type=str, help='file', required=False, default='') parser.add_argument('--log', action='store_true') args = parser.parse_args() params = BrainFlowInputParams() params.ip_port = args.ip_port params.serial_port = args.serial_port params.mac_address = args.mac_address params.other_info = args.other_info params.serial_number = args.serial_number params.ip_address = args.ip_address params.ip_protocol = args.ip_protocol params.timeout = args.timeout params.file = args.file if (args.log): BoardShim.enable_dev_board_logger() else: BoardShim.disable_board_logger() board = BoardShim(args.board_id, params) board.prepare_session() # board.start_stream () # use this for default options board.start_stream(45000, args.streamer_params) data = np.empty(shape=(31, 0)) print('Started streaming') start_time = time.time() while True: try: # data = board.get_current_board_data (256) # get latest 256 packages or less, doesnt remove them from internal buffer new_data = board.get_board_data() print('new data shape is ' + str(new_data.shape)) data = np.concatenate( (data, new_data), axis=-1) # get all data and remove it from internal buffer except KeyboardInterrupt: f_sample = data.shape[-1] / (time.time() - start_time) print('Stopped streaming, sampling rate = ' + str(f_sample)) break board.stop_stream() board.release_session() print(data) return data
def main(): parser = argparse.ArgumentParser() # use docs to check which parameters are required for specific board, e.g. for Cyton - set serial port, parser.add_argument('--ip-port', type=int, help='ip port', required=False, default=0) parser.add_argument('--ip-protocol', type=int, help='ip protocol, check IpProtocolType enum', required=False, default=0) parser.add_argument('--ip-address', type=str, help='ip address', required=False, default='') parser.add_argument('--serial-port', type=str, help='serial port', required=False, default='') parser.add_argument('--mac-address', type=str, help='mac address', required=False, default='') parser.add_argument('--other-info', type=str, help='other info', 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('--log', action='store_true') args = parser.parse_args() params = BrainFlowInputParams() params.ip_port = args.ip_port params.serial_port = args.serial_port params.mac_address = args.mac_address params.other_info = args.other_info params.ip_address = args.ip_address params.ip_protocol = args.ip_protocol if (args.log): BoardShim.enable_dev_board_logger() else: BoardShim.disable_board_logger() # demo how to read data as 2d numpy array board = BoardShim(args.board_id, params) board.prepare_session() board.start_stream() BoardShim.log_message(LogLevels.LEVEL_INFO.value, 'start sleeping in the main thread') time.sleep(10) # data = board.get_current_board_data (256) # get latest 256 packages or less, doesnt remove them from internal buffer data = board.get_board_data( ) # get all data and remove it from internal buffer board.stop_stream() board.release_session() # demo how to convert it to pandas DF and plot data eeg_channels = BoardShim.get_eeg_channels(args.board_id) df = pd.DataFrame(np.transpose(data)) print('Data From the Board') print(df.head()) plt.figure() df[eeg_channels].plot(subplots=True) plt.savefig('before_processing.png') # demo for data serialization DataFilter.write_file(data, 'test.csv', 'w') restored_data = DataFilter.read_file('test.csv') restored_df = pd.DataFrame(np.transpose(restored_data)) print('Data From the File') print(restored_df.head()) # demo how to perform signal processing for count, channel in enumerate(eeg_channels): if count == 0: DataFilter.perform_bandpass( data[channel], BoardShim.get_sampling_rate(args.board_id), 15.0, 6.0, 4, FilterTypes.BESSEL.value, 0) elif count == 1: DataFilter.perform_bandstop( data[channel], BoardShim.get_sampling_rate(args.board_id), 5.0, 1.0, 3, FilterTypes.BUTTERWORTH.value, 0) elif count == 2: DataFilter.perform_lowpass( data[channel], BoardShim.get_sampling_rate(args.board_id), 9.0, 5, FilterTypes.CHEBYSHEV_TYPE_1.value, 1) elif count == 3: DataFilter.perform_highpass( data[channel], BoardShim.get_sampling_rate(args.board_id), 3.0, 4, FilterTypes.BUTTERWORTH.value, 0) df = pd.DataFrame(np.transpose(data)) print('Data After Processing') print(df.head()) plt.figure() df[eeg_channels].plot(subplots=True) plt.savefig('after_processing.png')
def main(): parser = argparse.ArgumentParser() # 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-port', type=int, help='ip port', required=False, default=0) parser.add_argument('--ip-protocol', type=int, help='ip protocol, check IpProtocolType enum', required=False, default=0) parser.add_argument('--ip-address', type=str, help='ip address', required=False, default='') parser.add_argument('--serial-port', type=str, help='serial port', required=False, default='') parser.add_argument('--mac-address', type=str, help='mac address', required=False, default='') parser.add_argument('--other-info', type=str, help='other info', required=False, default='') parser.add_argument('--streamer-params', type=str, help='streamer params', required=False, default='') parser.add_argument('--serial-number', type=str, help='serial number', 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('--log', action='store_true') args = parser.parse_args() params = BrainFlowInputParams() params.ip_port = args.ip_port params.serial_port = args.serial_port params.mac_address = args.mac_address params.other_info = args.other_info params.serial_number = args.serial_number params.ip_address = args.ip_address params.ip_protocol = args.ip_protocol params.timeout = args.timeout if (args.log): BoardShim.enable_dev_board_logger() else: BoardShim.disable_board_logger() board = BoardShim(args.board_id, params) board.prepare_session() # board.start_stream () # use this for default options board.start_stream(45000, args.streamer_params) time.sleep(10) # data = board.get_current_board_data (256) # get latest 256 packages or less, doesnt remove them from internal buffer data = board.get_board_data( ) # get all data and remove it from internal buffer board.stop_stream() board.release_session() print(data) df = pd.DataFrame(np.transpose(data)) upload(df)
def main(): # =========================================== Boiler Plate Code BoardShim.enable_dev_board_logger() parser = argparse.ArgumentParser() # 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-port', type=int, help='ip port', required=False, default=0) parser.add_argument('--ip-protocol', type=int, help='ip protocol, check IpProtocolType enum', required=False, default=0) parser.add_argument('--ip-address', type=str, help='ip address', required=False, default='') parser.add_argument('--serial-port', type=str, help='serial port', required=False, default='') parser.add_argument('--mac-address', type=str, help='mac address', required=False, default='') parser.add_argument('--other-info', type=str, help='other info', required=False, default='') parser.add_argument('--streamer-params', type=str, help='streamer params', required=False, default='') parser.add_argument('--serial-number', type=str, help='serial number', 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('--file', type=str, help='file', required=False, default='') args = parser.parse_args() params = BrainFlowInputParams() params.ip_port = args.ip_port params.serial_port = args.serial_port params.mac_address = args.mac_address params.other_info = args.other_info params.serial_number = args.serial_number params.ip_address = args.ip_address params.ip_protocol = args.ip_protocol params.timeout = args.timeout params.file = args.file # =========================================== Experiment Setup # Change the resolution based on your machine: (height x width x channels) window_size = (960, 1920, 3) # Define the points that form the polygons of the arrow up_body_pts = [(870, 350), (870, 900), (1050, 900), (1050, 350)] up_head_pts = [(960, 50), (745, 350), (1175, 350)] # (x,y) coordinates of the center of the screen center = (960, 480) # Make an image of an arrow pointing up up_arrow = np.zeros(window_size, np.uint8) body = np.array(up_body_pts, np.int32) head = np.array(up_head_pts, np.int32) make_arrow(up_arrow, head, body) # Make an image of an arrow pointing down down_arrow = np.zeros(window_size, np.uint8) body = np.array(rotate(up_body_pts, center, 180), np.int32) head = np.array(rotate(up_head_pts, center, 180), np.int32) make_arrow(down_arrow, head, body) # Make an image of an arrow pointing left left_arrow = np.zeros(window_size, np.uint8) body = np.array(rotate(up_body_pts, center, 270), np.int32) head = np.array(rotate(up_head_pts, center, 270), np.int32) make_arrow(left_arrow, head, body) # Make an image of an arrow pointing right right_arrow = np.zeros(window_size, np.uint8) body = np.array(rotate(up_body_pts, center, 90), np.int32) head = np.array(rotate(up_head_pts, center, 90), np.int32) make_arrow(right_arrow, head, body) # Make a blank screen with black background blank_screen = np.zeros(window_size, np.uint8) # Make an image of a fixation cross on a black background blank_cross = np.copy(blank_screen) make_cross(blank_cross, 10) # Organize all images in a list visual_cues = [blank_screen, up_arrow, down_arrow, left_arrow, right_arrow] # Generate a random sequence of 48 visual cues ensuring that the cues are uniformly distributed: rand_seq = [1, 2, 3, 4] rand_seq = np.repeat(rand_seq, 4) rand_seq = np.random.permutation(rand_seq) # Show a blank screen and immediately move the window to the upper left corner so that it occupies the entire screen cv.imshow('window', blank_screen) cv.moveWindow('window', 0, 0) cv.waitKey(1) # Make a board object and let the API initialize the board board = BoardShim(args.board_id, params) board.prepare_session() # 50 trials/session * 8 sec/trial * 250 samples/sec = 100 000 * SF = 1.25 = 125000 samples in buffer board.start_stream(125000, args.streamer_params) # =========================================== Running the Experiment for code in rand_seq: # Display blank screen for 2 seconds board.insert_marker(6) cv.imshow('window', blank_screen) cv.waitKey(2000) # Display blank screen with fixation cross for 2 seconds board.insert_marker(5) cv.imshow('window', blank_cross) cv.waitKey(2000) # Display visual cue with fixation cross for 1.25 seconds followed by fixation cross for 2.75 seconds board.insert_marker(code) cv.imshow('window', visual_cues[code]) cv.waitKey(1250) cv.imshow('window', blank_cross) cv.waitKey(2750) cv.destroyAllWindows() # Get all the data stored in the buffer and terminate all background processes data = board.get_board_data() board.stop_stream() board.release_session()
def return_prediction(): #ms = post_id # Lines 27-65 copied from https://brainflow.readthedocs.io/en/stable/Examples.html # use docs to check which parameters are required for specific board, e.g. for Cyton - set serial port parser = argparse.ArgumentParser() parser.add_argument('--ip-port', type=int, help='ip port', required=False, default=0) parser.add_argument('--ip-protocol', type=int, help='ip protocol, check IpProtocolType enum', required=False, default=0) parser.add_argument('--ip-address', type=str, help='ip address', required=False, default='') parser.add_argument('--serial-port', type=str, help='serial port', required=False, default='') parser.add_argument('--mac-address', type=str, help='mac address', required=False, default='') parser.add_argument('--other-info', type=str, help='other info', required=False, default='') parser.add_argument('--streamer-params', type=str, help='other info', 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('--log', action='store_true') args = parser.parse_args() params = BrainFlowInputParams() params.ip_port = args.ip_port params.serial_port = args.serial_port params.mac_address = args.mac_address params.other_info = args.other_info params.ip_address = args.ip_address params.ip_protocol = args.ip_protocol if (args.log): BoardShim.enable_dev_board_logger() else: BoardShim.disable_board_logger() board = BoardShim(args.board_id, params) board.prepare_session() board.start_stream() # use this for default options board.start_stream(ms, args.streamer_params) time.sleep(3000 / 1000) data = board.get_current_board_data( 256 ) # get latest 256 packages or less, doesnt remove them from internal buffer data = board.get_board_data( ) # get all data and remove it from internal buffer board.stop_stream() board.release_session() # CONNECT THE DATA TO THE MODEL FOR PREDICTIONS # Test Sample Data #data = 'https://archlife.org/wp-content/uploads/2020/03/OpenBCI-RAW-right0.txt' column_names = [ 'index', 'channel1', 'channel2', 'channel3', 'channel4', 'accel1', 'accel2', 'accel3', 'timestamp', 'aux' ] dropped_row_indices = [0, 1, 2, 3, 4, 5] df = pd.read_csv(data, sep=',', header=None, names=column_names) df = df.drop(dropped_row_indices, axis=0).reset_index() df = df.drop(['level_0', 'index', 'timestamp'], axis=1) df = df.dropna(axis=0) model = joblib.load('flask_test/rfc.joblib') commands_proba = model.predict_proba(df) commands_pred = model.predict(df) commands_df = pd.DataFrame({ 'index': df.index, 'predictions': commands_pred }) commands_df['predictions'] = commands_df['predictions'].astype('int64') command_count = commands_df['predictions'].value_counts() ccdf = pd.DataFrame({ 'index': command_count.index, 'predictions': command_count }) preds = ccdf['index'].values command_pred = preds[0] return str(command_pred)
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)
def main(): BoardShim.enable_dev_board_logger() logging.basicConfig(level=logging.DEBUG) parser = argparse.ArgumentParser() # 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-port', type=int, help='ip port', required=False, default=0) parser.add_argument('--ip-protocol', type=int, help='ip protocol, check IpProtocolType enum', required=False, default=0) parser.add_argument('--ip-address', type=str, help='ip address', required=False, default='') parser.add_argument('--serial-port', type=str, help='serial port', required=False, default='') parser.add_argument('--mac-address', type=str, help='mac address', required=False, default='') parser.add_argument('--other-info', type=str, help='other info', required=False, default='') parser.add_argument('--streamer-params', type=str, help='streamer params', required=False, default='') parser.add_argument('--serial-number', type=str, help='serial number', required=False, default='') parser.add_argument( '--board-id', type=int, help='board id, check docs to get a list of supported boards', required=False, default=BoardIds.SYNTHETIC_BOARD) parser.add_argument('--file', type=str, help='file', required=False, default='') args = parser.parse_args() params = BrainFlowInputParams() params.ip_port = args.ip_port params.serial_port = args.serial_port params.mac_address = args.mac_address params.other_info = args.other_info params.serial_number = args.serial_number params.ip_address = args.ip_address params.ip_protocol = args.ip_protocol params.timeout = args.timeout params.file = args.file try: board_shim = BoardShim(args.board_id, params) board_shim.prepare_session() board_shim.start_stream(450000, args.streamer_params) g = Graph(board_shim) except BaseException as e: logging.warning('Exception', exc_info=True) finally: if board_shim.is_prepared(): logging.info('Releasing session') board_shim.release_session()
def __init__(self, debug=False, display=True, num_channels=None, wifi=True): # make audio stream self.audio_stream = sd.InputStream(device=None, channels=1, samplerate=16000) # make emg stream params = BrainFlowInputParams() if debug: board_id = -1 # synthetic sample_rate = 256 elif not wifi: board_id = BoardIds.CYTON_BOARD.value params.serial_port = '/dev/ttyUSB0' sample_rate = 250 else: board_id = BoardIds.CYTON_WIFI_BOARD.value params.ip_port = 8001 params.ip_address = '192.168.4.1' sample_rate = 1000 self.emg_channels = BoardShim.get_emg_channels(board_id) if num_channels is not None: self.emg_channels = self.emg_channels[:num_channels] board = BoardShim(board_id, params) board.prepare_session() board.config_board('/3') # configure for digital read board.start_stream() self.board = board # config and make data holders audio_multiplier = int(16000 / sample_rate) window = sample_rate * 5 self.audio_data = [] self.emg_data = [] self.button_data = [] self.debug = debug self.previous_sample_number = -1 # plot setup self.display = display if display: plt.ion() fig, (audio_ax, emg_ax) = plt.subplots(2) audio_ax.axis((0, window * audio_multiplier, -1, 1)) emg_ax.axis((0, window, -300, 300)) audio_lines = audio_ax.plot(np.zeros(window * audio_multiplier)) emg_lines = emg_ax.plot(np.zeros((window, len(self.emg_channels)))) for l, c in zip(emg_lines, [ 'grey', 'mediumpurple', 'blue', 'green', 'yellow', 'orange', 'red', 'sienna' ]): l.set_color(c) text = emg_ax.text(50, -250, 'RMS: 0') for ax in (audio_ax, emg_ax): ax.set_yticks([0]) ax.yaxis.grid(True) ax.tick_params(bottom=False, top=False, labelbottom=False, right=False, left=False, labelleft=False) fig.tight_layout(pad=0) def update_plot(frame): """ This is called by matplotlib for each plot update. """ audio_to_plot = get_last_sequence(self.audio_data, window * audio_multiplier, 1, False, sample_rate) audio_to_plot = audio_to_plot.squeeze(1) audio_lines[0].set_ydata(audio_to_plot) emg_to_plot = get_last_sequence(self.emg_data, window, len(self.emg_channels), True, sample_rate) for column, line in enumerate(emg_lines): line.set_ydata(emg_to_plot[:, column]) text.set_text('RMS: ' + str(emg_to_plot[-sample_rate * 2:-sample_rate // 2].std())) return audio_lines + emg_lines self.ani = FuncAnimation(fig, update_plot, interval=30)
def main(): parser = argparse.ArgumentParser() # use docs to check which parameters are required for specific board, e.g. for Cyton - set serial port parser.add_argument('--ip-port', type=int, help='ip port', required=False, default=0) parser.add_argument('--ip-protocol', type=int, help='ip protocol, check IpProtocolType enum', required=False, default=0) parser.add_argument('--ip-address', type=str, help='ip address', required=False, default='') parser.add_argument('--serial-port', type=str, help='serial port', required=False, default='') parser.add_argument('--mac-address', type=str, help='mac address', required=False, default='') parser.add_argument('--other-info', type=str, help='other info', required=False, default='') parser.add_argument('--streamer-params', type=str, help='other info', 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('--log', action='store_true') parser.add_argument('--run-time', type=int, help='run time for one iteration in sec', required=True) parser.add_argument('--num-iters', type=int, help='number of iterations', default=1) parser.add_argument( '--channels', type=str, help='channels to plot in format 0,1,2 by default plot all channels', default=None) args = parser.parse_args() params = BrainFlowInputParams() params.ip_port = args.ip_port params.serial_port = args.serial_port params.mac_address = args.mac_address params.other_info = args.other_info params.ip_address = args.ip_address params.ip_protocol = args.ip_protocol if (args.log): BoardShim.enable_dev_board_logger() else: BoardShim.disable_board_logger() # for streaming board need to use master board id master_board_id = args.board_id if args.board_id == BoardIds.STREAMING_BOARD.value: master_board_id = int(params.other_info) board = BoardShim(args.board_id, params) board.prepare_session() buffer_size = int( BoardShim.get_sampling_rate(master_board_id) * args.run_time * 1.2) # + 20% for safety if master_board_id in (BoardIds.CYTON_BOARD.value, BoardIds.CYTON_WIFI_BOARD.value, BoardIds.GANGLION_WIFI_BOARD.value): bytes_per_package = 33 elif master_board_id in (BoardIds.CYTON_DAISY_BOARD, BoardIds.CYTON_DAISY_WIFI_BOARD.value): bytes_per_package = 66 elif master_board_id == BoardIds.SYNTHETIC_BOARD.value: bytes_per_package = 104 elif master_board_id == BoardIds.NOVAXR_BOARD.value: bytes_per_package = 72 else: raise ValueError('unsupported board') timestamp_channel = BoardShim.get_timestamp_channel(master_board_id) package_num_channel = BoardShim.get_package_num_channel(master_board_id) try: cur_id = 0 for i in range(args.num_iters): # wait for an input input('Press Enter to continue...') BoardShim.log_message( LogLevels.LEVEL_INFO.value, '\nRunning iteration %d/%d\n' % (i, args.num_iters)) # start stream and get data board.start_stream(buffer_size, args.streamer_params) time.sleep(args.run_time) board.stop_stream() data = board.get_board_data() if data.shape[1] == 0: BoardShim.log_message(LogLevels.LEVEL_WARN.value, '\nNo data received!\n') continue # calculate some metrics total_bytes_received = bytes_per_package * data.shape[1] packages_per_sec = float(data.shape[1]) / float(args.run_time) timestamp_array = data[timestamp_channel] time_diff_array = list() for i in range(0, timestamp_array.size - 1): time_diff_array.append(timestamp_array[i + 1] - timestamp_array[i]) package_num_array = data[package_num_channel] lost_packages = 0 expected = package_num_array[0] while cur_id < package_num_array.size: if expected == 256: expected = 0 if package_num_array[cur_id] != expected: BoardShim.log_message( LogLevels.LEVEL_WARN.value, 'package loss detected: position %d package_num value %d expected value %d' % (cur_id, package_num_array[cur_id], expected)) lost_packages = lost_packages + 1 else: cur_id = cur_id + 1 expected = expected + 1 package_loss = (lost_packages / data.shape[1]) * 100 # provide results for iteration BoardShim.log_message(LogLevels.LEVEL_INFO.value, '\nResults:\n') BoardShim.log_message(LogLevels.LEVEL_INFO.value, 'package loss percent %f' % package_loss) BoardShim.log_message( LogLevels.LEVEL_INFO.value, 'average time delta %f' % statistics.mean(time_diff_array)) BoardShim.log_message( LogLevels.LEVEL_INFO.value, 'std deviation of time delta %f' % statistics.pstdev(time_diff_array)) BoardShim.log_message(LogLevels.LEVEL_INFO.value, 'total packages received %d' % data.shape[1]) BoardShim.log_message(LogLevels.LEVEL_INFO.value, 'packages per sec %f' % packages_per_sec) BoardShim.log_message( LogLevels.LEVEL_INFO.value, 'total bytes received %d' % total_bytes_received) # plot data eeg_channels = BoardShim.get_eeg_channels(master_board_id) emg_channels = BoardShim.get_emg_channels(master_board_id) total_channels = list() if args.channels is not None: selected_channels = [int(x) for x in args.channels.split(',')] temp_channels = eeg_channels for ch in emg_channels: if ch not in temp_channels: temp_channels.append(ch) for i in range(len(temp_channels)): if i in selected_channels: total_channels.append(temp_channels[i]) else: # for cyton/ganglion eeg_channels and emg_channels are the same array because we can not split it # for novaxr its 2 different arrays, join them total_channels = eeg_channels for ch in emg_channels: if ch not in total_channels: total_channels.append(ch) df = pd.DataFrame(np.transpose(data)) df[total_channels].to_csv('selected_data_%d.csv' % i) df.to_csv('all_data_%d.csv' % i) df[total_channels].plot(subplots=True) plt.show() finally: # release session in the end board.release_session()
def main(): parser = argparse.ArgumentParser() # use docs to check which parameters are required for specific board, e.g. for Cyton - set serial port parser.add_argument('--ip-port', type=int, help='ip port', required=False, default=0) parser.add_argument('--ip-protocol', type=int, help='ip protocol, check IpProtocolType enum', required=False, default=0) parser.add_argument('--ip-address', type=str, help='ip address', required=False, default='') parser.add_argument('--serial-port', type=str, help='serial port', required=False, default='') parser.add_argument('--mac-address', type=str, help='mac address', required=False, default='') parser.add_argument('--other-info', type=str, help='other info', 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('--log', action='store_true') args = parser.parse_args() # in fact it can be CytonDaisy or Wifi Shield based boards, limit it to only Cyton in demo if args.board_id != BoardIds.CYTON_BOARD.value: raise ValueError('wrong board id, should be Cyton') params = BrainFlowInputParams() params.ip_port = args.ip_port params.serial_port = args.serial_port params.mac_address = args.mac_address params.other_info = args.other_info params.ip_address = args.ip_address params.ip_protocol = args.ip_protocol if (args.log): BoardShim.enable_dev_board_logger() else: BoardShim.disable_board_logger() board = BoardShim(args.board_id, params) board.prepare_session() board.config_board('/2') # enable analog mode only for Cyton Based Boards! board.start_stream() time.sleep(10) data = board.get_board_data() board.stop_stream() board.release_session() other_channels = BoardShim.get_other_channels(args.board_id) accel_channels = BoardShim.get_accel_channels(args.board_id) analog_channels = BoardShim.get_analog_channels(args.board_id) """ data format for cyton with analog and accel data, data[get_other_channels(board_id)[0]] contains cyton end byte if end byte is 0xC0 there are accel data in data[get_accel_channels(board_id)[....]] else there are zeros if end byte is 0xC1 there are analog data in data[get_analog_channels(board_id)[....]] else there are zeros """ if not other_channels: raise ValueError('no cyton end byte foud') print('end bytes for first 20 packages:') print(data[other_channels[0]][0:20]) # we send /2 to enable analog mode so here we will see zeroes print('accel data for first 20 packages:') for count, channel in enumerate(accel_channels): print(data[channel][0:20]) # analog data are in int32 format but we return single array fron low level api so it was casted to double wo any changes print('analog data for first 20 packages:') for count, channel in enumerate(analog_channels): print(data[channel][0:20])
def main(): parser = argparse.ArgumentParser () # 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-port', type = int, help = 'ip port', required = False, default = 0) parser.add_argument ('--ip-protocol', type = int, help = 'ip protocol, check IpProtocolType enum', required = False, default = 0) parser.add_argument ('--ip-address', type = str, help = 'ip address', required = False, default = '') parser.add_argument ('--serial-port', type = str, help = 'serial port', required = False, default = '') parser.add_argument ('--mac-address', type = str, help = 'mac address', required = False, default = '') parser.add_argument ('--other-info', type = str, help = 'other info', required = False, default = '') parser.add_argument ('--streamer-params', type = str, help = 'streamer params', required = False, default = '') parser.add_argument ('--serial-number', type = str, help = 'serial number', 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 ('--log', action = 'store_true') args = parser.parse_args () params = BrainFlowInputParams () params.ip_port = args.ip_port params.serial_port = args.serial_port params.mac_address = args.mac_address params.other_info = args.other_info params.serial_number = args.serial_number params.ip_address = args.ip_address params.ip_protocol = args.ip_protocol params.timeout = args.timeout if (args.log): BoardShim.enable_dev_board_logger () else: BoardShim.disable_board_logger () board = BoardShim (args.board_id, params) board.prepare_session () board.start_stream (45000, args.streamer_params) model = P300ClassifierLDA() model.load("test-model") figlet = Figlet(font='slant') stopped = True raw = None time.sleep(3) while stopped: try: with mne.utils.use_log_level('error'): # time.sleep(MICROSECONDS_BEFORE_STIMULUS / 1000) # show_stimulus() # time.sleep(MICROSECONDS_AFTER_STIMULUS / 1000) data = board.get_current_board_data(SAMPLES_TOTAL) # TODO constant from model raw = create_raw(data, model) prediction = prepare_raw(raw, model) print_prediction(figlet, prediction) except KeyboardInterrupt: print("Got keyboard interrupt, stopping...") break board.stop_stream () board.release_session ()
def main(): parser = argparse.ArgumentParser() # use docs to check which parameters are required for specific board, e.g. for Cyton - set serial port parser.add_argument('--ip-port', type=int, help='ip port', required=False, default=0) parser.add_argument('--ip-protocol', type=int, help='ip protocol, check IpProtocolType enum', required=False, default=0) parser.add_argument('--ip-address', type=str, help='ip address', required=False, default='') parser.add_argument('--serial-port', type=str, help='serial port', required=False, default='') parser.add_argument('--mac-address', type=str, help='mac address', required=False, default='') parser.add_argument('--other-info', type=str, help='other info', 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('--log', action='store_true') args = parser.parse_args() params = BrainFlowInputParams() params.ip_port = args.ip_port params.serial_port = args.serial_port params.mac_address = args.mac_address params.other_info = args.other_info params.ip_address = args.ip_address params.ip_protocol = args.ip_protocol if (args.log): BoardShim.enable_dev_board_logger() else: BoardShim.disable_board_logger() board = BoardShim(args.board_id, params) board.prepare_session() # disable 2nd channel for cyton use real board to check it, emulator ignores commands if args.board_id == brainflow.board_shim.BoardIds.CYTON_BOARD.value: board.config_board('x2100000X') board.start_stream() time.sleep(10) data = board.get_board_data() board.stop_stream() board.release_session() print(data)
def main(): BoardShim.enable_dev_board_logger() parser = argparse.ArgumentParser() # 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-port', type=int, help='ip port', required=False, default=0) parser.add_argument('--ip-protocol', type=int, help='ip protocol, check IpProtocolType enum', required=False, default=0) parser.add_argument('--ip-address', type=str, help='ip address', required=False, default='') parser.add_argument('--serial-port', type=str, help='serial port', required=False, default='') parser.add_argument('--mac-address', type=str, help='mac address', required=False, default='') parser.add_argument('--other-info', type=str, help='other info', required=False, default='') parser.add_argument('--streamer-params', type=str, help='streamer params', required=False, default='') parser.add_argument('--serial-number', type=str, help='serial number', 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('--file', type=str, help='file', required=False, default='') args = parser.parse_args() params = BrainFlowInputParams() params.ip_port = args.ip_port params.serial_port = args.serial_port params.mac_address = args.mac_address params.other_info = args.other_info params.serial_number = args.serial_number params.ip_address = args.ip_address params.ip_protocol = args.ip_protocol params.timeout = args.timeout params.file = args.file board = BoardShim(args.board_id, params) board.prepare_session() board.start_stream(45000, args.streamer_params) for i in range(10): time.sleep(1) board.insert_marker(i + 1) data = board.get_board_data() board.stop_stream() board.release_session() print(data)
def initialise_brainflow(): BoardShim.enable_dev_board_logger() parser = ArgumentParser() # 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-port', type=int, help='ip port', required=False, default=0) parser.add_argument('--ip-protocol', type=int, help='ip protocol, check IpProtocolType enum', required=False, default=0) parser.add_argument('--ip-address', type=str, help='ip address', required=False, default='') parser.add_argument('--serial-port', type=str, help='serial port', required=False, default='') parser.add_argument('--mac-address', type=str, help='mac address', required=False, default='') parser.add_argument('--other-info', type=str, help='other info', required=False, default='') parser.add_argument('--streamer-params', type=str, help='streamer params', required=False, default='') parser.add_argument('--serial-number', type=str, help='serial number', 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('--file', type=str, help='file', required=False, default='') args = parser.parse_args() params = BrainFlowInputParams() params.ip_port = args.ip_port params.serial_port = args.serial_port params.mac_address = args.mac_address params.other_info = args.other_info params.serial_number = args.serial_number params.ip_address = args.ip_address params.ip_protocol = args.ip_protocol params.timeout = args.timeout params.file = args.file params.board_id = args.board_id return params, args
def main(): BoardShim.enable_board_logger() DataFilter.enable_data_logger() MLModel.enable_ml_logger() parser = argparse.ArgumentParser() # 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-port', type=int, help='ip port', required=False, default=0) parser.add_argument('--ip-protocol', type=int, help='ip protocol, check IpProtocolType enum', required=False, default=0) parser.add_argument('--ip-address', type=str, help='ip address', required=False, default='') parser.add_argument('--serial-port', type=str, help='serial port', required=False, default='') parser.add_argument('--mac-address', type=str, help='mac address', required=False, default='') parser.add_argument('--other-info', type=str, help='other info', required=False, default='') parser.add_argument('--streamer-params', type=str, help='streamer params', required=False, default='') parser.add_argument('--serial-number', type=str, help='serial number', 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('--file', type=str, help='file', required=False, default='') args = parser.parse_args() params = BrainFlowInputParams() params.ip_port = args.ip_port params.serial_port = args.serial_port params.mac_address = args.mac_address params.other_info = args.other_info params.serial_number = args.serial_number params.ip_address = args.ip_address params.ip_protocol = args.ip_protocol params.timeout = args.timeout params.file = args.file board = BoardShim(args.board_id, params) master_board_id = board.get_board_id() sampling_rate = BoardShim.get_sampling_rate(master_board_id) board.prepare_session() board.start_stream(45000, args.streamer_params) BoardShim.log_message(LogLevels.LEVEL_INFO.value, 'start sleeping in the main thread') time.sleep( 5 ) # recommended window size for eeg metric calculation is at least 4 seconds, bigger is better data = board.get_board_data() board.stop_stream() board.release_session() eeg_channels = BoardShim.get_eeg_channels(int(master_board_id)) bands = DataFilter.get_avg_band_powers(data, eeg_channels, sampling_rate, True) feature_vector = np.concatenate((bands[0], bands[1])) print(feature_vector) # calc concentration concentration_params = BrainFlowModelParams( BrainFlowMetrics.CONCENTRATION.value, BrainFlowClassifiers.KNN.value) concentration = MLModel(concentration_params) concentration.prepare() print('Concentration: %f' % concentration.predict(feature_vector)) concentration.release() # calc relaxation relaxation_params = BrainFlowModelParams( BrainFlowMetrics.RELAXATION.value, BrainFlowClassifiers.REGRESSION.value) relaxation = MLModel(relaxation_params) relaxation.prepare() print('Relaxation: %f' % relaxation.predict(feature_vector)) relaxation.release()
def main(argv): '''Takes args and initiates streaming''' if argv: # manage settings read form a yaml file if argv[0] == '--set': file_settings = argv[1] data = read_settings(file_settings) if not data: print('The end') sys.exit() args, arduino, chan_commands = manage_settings_data(data) else: print(CRED + "Use --set *.yml to load settings" + CEND, "\nThe end", sep='') sys.exit() # debug / check data from settings #print(f"args:\n{args}\narduino:\n{arduino}\ncommands:\n{chan_commands}\n") # open serial port for external triggers (arduino/serial) ser = None if arduino: print("Connecting to serial port...") try: ser = serial.Serial(arduino["serial_port"], arduino['baud'], write_timeout=0) time.sleep(3) # minimum 2 sec to wake device up! except (serial.SerialException, ValueError) as err: print(CRED + f"Error: {err}" + CEND) if ser: ser_data = ser.readline().decode( 'utf-8', errors='ignore').strip().split(",") ser.write("a".encode()) # message for arduino to give "on" sound time.sleep( 0.5) # must be longer than time of "on" sound from arduino print(100 * '-') print( CGREEN + f'Established serial connection to Arduino on port: {arduino["serial_port"]} as {arduino["name"]}' + CEND + f"\nMessage from board: {ser_data[0]}, reading sensor at {ser_data[1]} Hz" ) ping_time = ping( ser, 10) # estimate mean ping time between pc and arduino # LSL external outlet (stream form arduino/serial) configuration and initialization if ser: marker_delay = arduino.get( 'delay', 0) + ping_time / 2 # half the two way transfer time info = StreamInfo(name=arduino['name'], type=arduino['type'], channel_count=arduino['channel_count'], channel_format=arduino['channel_format'], source_id=arduino['source_id']) outlet_ext = StreamOutlet(info) print(50 * '-') print(CGREEN + f'LSL Stream: {info.name()} initialized' + CEND) user_choice("Initiate? 'y' -> yes, 'q' -> quit\n--> ", serial=ser) BoardShim.enable_dev_board_logger() # brainflow initialization params = BrainFlowInputParams() params.serial_port = args['serial_port'] params.ip_address = args['ip_address'] board = BoardShim(args['board_id'], params) # LSL internal outlet (stream form board) configuration and initialization channel_names = {} n_channels = {} srate = {} info = {} outlet_int = {} fw_delay = {} for type in args['data_type']: channel_names[type] = args['channel_names'][type].split(',') n_channels[type] = len(channel_names[type]) srate[type] = board.get_sampling_rate(args['board_id']) name = args['name'] + "_" + type uid = args['uid'] + "_" + type info[type] = StreamInfo(name, type, n_channels[type], srate[type], 'double64', uid) # add channel labels chans = info[type].desc().append_child("channels") for label in channel_names[type]: chan = chans.append_child("channel") chan.append_child_value("label", label) outlet_int[type] = StreamOutlet(info[type]) fw_delay[type] = args['delay'] # prepare session; exit if board is not ready try: board.prepare_session() except brainflow.board_shim.BrainFlowError as e: print(CRED + f"Error: {e}" + CEND) if ser: ser.write("c".encode()) # message for arduino to stop streaming time.sleep(1) ser.close() print("The end") time.sleep(1) sys.exit() # remove daisy if attached, when using only Cyton if (args['board_id'] == 0) and (args['daisy_attached']): res_query = board.config_board("c") time.sleep(0.5) print(f"Response to query register settings:\n{res_query}") # wait until user accepts user_choice("Send commands to board? 'y' -> yes, 'q' -> quit\n--> ", board=board, serial=ser) # iterate over channel commands, send one and wait for a response from board # to restore default channel settings 'd' can be sent for chan, command in chan_commands.items(): res_string = board.config_board(command) time.sleep(0.1) if res_string.find('Success') != -1: res = CGREEN + res_string + CEND else: res = CRED + res_string + CEND print(f"Response from {chan}: {res}") # show stream configuration and wait until user accepts or quits print(50 * "-") for type in args['data_type']: print( f"{type}:\nNumber of channels: {n_channels[type]}\nSampling rate: {srate[type]}\n" f"Time limit: {args['max_time'] // 60} min. {args['max_time'] % 60} sec.\n" ) user_choice("Start streaming? 'y' -> yes, 'q' -> quit\n--> ", board=board, serial=ser) # board starts streaming board.start_stream(45000, args['streamer_params']) time.sleep(1) # define threads which will collect continuous data (e.g. EEG) and markers (if arduino/serial is set up) thread_cont = threading.Thread( target=collect_cont, args=[board, args, srate, outlet_int, fw_delay]) thread_cont.start() if ser: thread_markers = threading.Thread(target=collect_markers, args=[ser, outlet_ext, marker_delay]) thread_markers.start() # wait for stop message from user while running data collecting threads time.sleep(2) user_choice("To stop streaming and quit press 'q' + ENTER\n--> ", board=board, serial=ser, thread_initiated=True)