class Airtrack: """Airtrack system interface.""" def __init__(self): self.__bpod = None self._bpod_closed = True self._subject = AirtrackSubject() # Register exit handler atexit.register(self.close) @property def _bpod(self): if self.__bpod is None: self._create_bpod() if self._bpod_closed: self._open_bpod() return self.__bpod @handle_error def _create_bpod(self): self.__bpod = Bpod(emulator_mode=True) @handle_error def _open_bpod(self): self.__bpod.open() self._bpod_closed = False @handle_error def _close(self): self.__bpod.close(ignore_emulator=True) self._bpod_closed = True @handle_error def _run(self): self._sma = AirtrackStateMachine(self._bpod, self._subject) self._sma.setup() self._bpod.send_state_machine(self._sma, ignore_emulator=True) self._bpod.run_state_machine(self._sma) @handle_error def _clean_up(self): self._subject.clean_up() self._sma.clean_up() def run(self, trials=None): """Run the system. :keyword trials (optional): Number of trials to run the system for. :type trials (optional): ``int`` """ iterator = range(trials or 0) or itertools.count() for i in iterator: trial = i + 1 logger.debug(f'Starting trial #{trial}...') self._run() logger.debug(f'End of trial #{trial}.') def close(self): """Close the system.""" self._clean_up() self._close()
def bpod_modules_ok() -> bool: # List bpod modules # figure out if RE is in Module 1, Ambient sensore in port 2 and # if ephys in board name if SoundCard in port 3 ephys_rig = "ephys" in _grep_param_dict("NAME") if ephys_rig: expected_modules = [ "RotaryEncoder1", "AmbientModule1", "SoundCard1", ] else: expected_modules = [ "RotaryEncoder1", "AmbientModule1", ] out = False try: comport = _grep_param_dict("COM_BPOD") bpod = Bpod(serial_port=comport) mods = [x.name for x in bpod.modules] bpod.close() oks = [x in mods for x in expected_modules] if all(oks): out = True else: missing = set(expected_modules) - set(mods) log.warning(f"Missing modules: {missing}") except BaseException as e: log.warning(f"{e} \nCan't check modules from Bpod.") return out
from pybpodapi.protocol import Bpod from confapp import conf my_bpod = Bpod(emulator_mode=True) my_bpod.close() print("Target Bpod firmware version: ", conf.TARGET_BPOD_FIRMWARE_VERSION) print("Firmware version (read from device): ", my_bpod.hardware.firmware_version) print("Machine type version (read from device): ", my_bpod.hardware.machine_type)
from pybpodapi.protocol import Bpod, StateMachine import task_settings import user_settings from session_params import SessionParamHandler log = logging.getLogger('iblrig') log.setLevel(logging.INFO) global sph sph = SessionParamHandler(task_settings, user_settings) # ============================================================================= # CONNECT TO BPOD # ============================================================================= bpod = Bpod() log.info('Listening...') # ============================================================================= # Start state machine definition # ============================================================================= sma = StateMachine(bpod) sma.add_state(state_name='trial_start', state_timer=0, state_change_conditions={'Tup': 'listen'}, output_actions=[]) sma.add_state(state_name='listen', state_change_conditions={}, output_actions=[])
log = logging.getLogger('iblrig') log.setLevel(logging.INFO) PARAMS = params.load_params_file() # start sph sph = SessionParamHandler(task_settings, user_settings) # frame2TTL seg thresholds if frame2TTL.get_and_set_thresholds() == 0: sph.F2TTL_GET_AND_SET_THRESHOLDS = True # Rotary encoder re = MyRotaryEncoder(sph.ALL_THRESHOLDS, sph.STIM_GAIN, sph.PARAMS['COM_ROTARY_ENCODER']) sph.ROTARY_ENCODER = re # get bpod bpod = Bpod(serial_port=PARAMS['COM_BPOD']) # Build messages msg = BpodMessageCreator(bpod) sc_play_tone = msg.sound_card_play_idx(sph.GO_TONE_IDX) sc_play_noise = msg.sound_card_play_idx(sph.WHITE_NOISE_IDX) bpod = msg.return_bpod() # get soundcard card = usb.core.find(idVendor=0x04d8, idProduct=0xee6a) card_play_tone = bytes(np.array([2, 6, 32, 255, 2, 2, 0, 43], dtype=np.int8)) card_play_noise = bytes(np.array([2, 6, 32, 255, 2, 3, 0, 44], dtype=np.int8)) def do_gabor(osc_client, pcs_idx, pos, cont, phase): # send pcs to Bonsai bonsai.send_stim_info(sph.OSC_CLIENT,
global sph if data == 0: sph.stop_sound() elif data == 1: sph.play_tone() elif data == 2: sph.play_noise() elif data == 3: sph.start_camera_recording() # sph.OSC_CLIENT.send_message("/e", data) # ============================================================================= # CONNECT TO BPOD # ============================================================================= bpod = Bpod() # Loop handler function is used to flush events for the online plotting bpod.loop_handler = bpod_loop_handler # Soft code handler function can run arbitrary code from within state machine bpod.softcode_handler_function = softcode_handler # Rotary Encoder State Machine handler rotary_encoder = [x for x in bpod.modules if x.name == 'RotaryEncoder1'][0] # ROTARY ENCODER SEVENTS # Set RE position to zero 'Z' + eneable all RE thresholds 'E' # re_reset = rotary_encoder.create_resetpositions_trigger() re_reset = 1 bpod.load_serial_message( rotary_encoder, re_reset, [
log = logging.getLogger('iblrig') log.setLevel(logging.INFO) global sph sph = SessionParamHandler(task_settings, user_settings) def bpod_loop_handler(): f.canvas.flush_events() # 100µs # ============================================================================= # CONNECT TO BPOD # ============================================================================= bpod = Bpod() # Loop handler function is used to flush events for the online plotting bpod.loop_handler = bpod_loop_handler # Rotary Encoder State Machine handler rotary_encoder = [x for x in bpod.modules if x.name == 'RotaryEncoder1'][0] sound_card = [x for x in bpod.modules if x.name == 'SoundCard1'][0] # ROTARY ENCODER SEVENTS # Set RE position to zero 'Z' + eneable all RE thresholds 'E' # re_reset = rotary_encoder.create_resetpositions_trigger() re_reset = 1 bpod.load_serial_message(rotary_encoder, re_reset, [RotaryEncoder.COM_SETZEROPOS, # ord('Z') RotaryEncoder.COM_ENABLE_ALLTHRESHOLDS]) # ord('E') # Stop the stim re_stop_stim = re_reset + 1
# !/usr/bin/python3 # -*- coding: utf-8 -*- """ Demonstration of AddTrialEvents used in a simple visual 2AFC session. AddTrialEvents formats each trial's data in a human-readable struct, and adds to myBpod.data (to save to disk later) Connect noseports to ports 1-3. Example adapted from Josh Sanders' original version on Sanworks Bpod repository """ import random from pybpodapi.protocol import Bpod, StateMachine my_bpod = Bpod() nTrials = 5 trialTypes = [1, 2] # 1 (rewarded left) or 2 (rewarded right) for i in range(nTrials): # Main loop print('Trial: ', i + 1) thisTrialType = random.choice(trialTypes) # Randomly choose trial type if thisTrialType == 1: stimulus = Bpod.OutputChannels.PWM1 # set stimulus channel for trial type 1 leftAction = 'Reward' rightAction = 'Punish' rewardValve = 1 elif thisTrialType == 2: stimulus = Bpod.OutputChannels.PWM3 # set stimulus channel for trial type 1 leftAction = 'Punish'
print("----PLAY-----") soundStream.playSound() start = timeit.default_timer() if not camOK: cam.record() camOK = True elif data == 66: soundStream.stopSound() print(':::::::::Time to stop:::::::::', timeit.default_timer() - start) # ------------------------------------------------------------------ START_APP = timeit.default_timer() my_bpod = Bpod() my_bpod.softcode_handler_function = my_softcode_handler nTrials = 2 for i in range(nTrials): # Main loop print('Trial: ', i + 1) sma = StateMachine(my_bpod) soundStream.load(s1) # load the sound <----------------- sma.add_state(state_name='WaitForPort2Poke', state_timer=1, state_change_conditions={Bpod.Events.Tup: 'PlaySound'}, output_actions=[(Bpod.OutputChannels.PWM1, 255)])
# !/usr/bin/python3 # -*- coding: utf-8 -*- """ Get hardware info from Bpod """ from pybpodapi.protocol import Bpod from confapp import conf my_bpod = Bpod() my_bpod.close() print("Target Bpod firmware version: ", conf.TARGET_BPOD_FIRMWARE_VERSION) print("Firmware version (read from device): ", my_bpod.hardware.firmware_version) print("Machine type version (read from device): ", my_bpod.hardware.machine_type)
log = logging.getLogger("iblrig") log.setLevel(logging.INFO) PARAMS = params.load_params_file() # start sph sph = SessionParamHandler(task_settings, user_settings) # frame2TTL seg thresholds if frame2TTL.get_and_set_thresholds() == 0: sph.F2TTL_GET_AND_SET_THRESHOLDS = True # Rotary encoder re = MyRotaryEncoder(sph.ALL_THRESHOLDS, sph.STIM_GAIN, sph.PARAMS["COM_ROTARY_ENCODER"]) sph.ROTARY_ENCODER = re # get bpod bpod = Bpod() # Build messages msg = BpodMessageCreator(bpod) sc_play_tone = msg.sound_card_play_idx(sph.GO_TONE_IDX) sc_play_noise = msg.sound_card_play_idx(sph.WHITE_NOISE_IDX) bpod = msg.return_bpod() # get soundcard card = usb.core.find(idVendor=0x04D8, idProduct=0xEE6A) card_play_tone = bytes(np.array([2, 6, 32, 255, 2, 2, 0, 43], dtype=np.int8)) card_play_noise = bytes(np.array([2, 6, 32, 255, 2, 3, 0, 44], dtype=np.int8)) def do_gabor(osc_client, pcs_idx, pos, cont, phase): # send pcs to Bonsai bonsai.send_stim_info(
# !/usr/bin/python3 # -*- coding: utf-8 -*- """ Example adapted from Josh Sanders' original version on Sanworks Bpod repository """ import time from pybpodapi.protocol import Bpod my_bpod = Bpod() print("Send byte 65 on UART port 1 - by default, this is ASCII 'A'") my_bpod.manual_override(Bpod.ChannelTypes.OUTPUT, Bpod.ChannelNames.SERIAL, 1, 65) time.sleep(1) # Wait 1s print("Set byte 65 ('A') on UART port 1 to trigger a 3-byte message: 'BCD'") my_bpod.load_serial_message(1, 65, [66, 67, 68]) # Now, the same command has a different result my_bpod.manual_override(Bpod.ChannelTypes.OUTPUT, Bpod.ChannelNames.SERIAL, channel_number=1, value=65) time.sleep(1) # Wait 1s print("Reset the serial message library. Bytes will now pass through again.") my_bpod.reset_serial_messages() # Back to 'A' my_bpod.manual_override(Bpod.ChannelTypes.OUTPUT, Bpod.ChannelNames.SERIAL,
PARAMS = params.load_params_file() # start sph sph = SessionParamHandler(task_settings, user_settings) # frame2TTL seg thresholds if frame2TTL.get_and_set_thresholds() == 0: sph.F2TTL_GET_AND_SET_THRESHOLDS = True # Rotary encoder re = MyRotaryEncoder( sph.ALL_THRESHOLDS, sph.STIM_GAIN, sph.PARAMS["COM_ROTARY_ENCODER"] ) sph.ROTARY_ENCODER = re # Turn bpod lights off bpod_lights(PARAMS["COM_BPOD"], 0) # get bpod bpod = Bpod(serial_port=PARAMS["COM_BPOD"]) # Build messages msg = BpodMessageCreator(bpod) sc_play_tone = msg.sound_card_play_idx(sph.GO_TONE_IDX) sc_play_noise = msg.sound_card_play_idx(sph.WHITE_NOISE_IDX) bpod = msg.return_bpod() # get soundcard card = usb.core.find(idVendor=0x04D8, idProduct=0xEE6A) card_play_tone = bytes(np.array([2, 6, 32, 255, 2, 2, 0, 43], dtype=np.int8)) card_play_noise = bytes(np.array([2, 6, 32, 255, 2, 3, 0, 44], dtype=np.int8)) def do_gabor(osc_client, pcs_idx, pos, cont, phase): # send pcs to Bonsai bonsai.send_stim_info(
import time from pybpodapi.protocol import Bpod import examples.emulator_settings as settings my_bpod = Bpod(emulator_mode=True) wait_active_time_ms = 2 # INPUTS - BNC (1, 2) print("Set BNC1 (Input) to a value") my_bpod.manual_override(Bpod.ChannelTypes.INPUT, Bpod.ChannelNames.BNC, channel_number=1, value=12) time.sleep(wait_active_time_ms) print("Set BNC2 (Input) to a value") my_bpod.manual_override(Bpod.ChannelTypes.INPUT, Bpod.ChannelNames.BNC, channel_number=2, value=15) time.sleep(wait_active_time_ms) # INPUTS - PWM (1..4) print("Set PWM1 (Input) to a value") my_bpod.manual_override(Bpod.ChannelTypes.INPUT, 'Port', channel_number=1, value=12) time.sleep(wait_active_time_ms) print("Set PWM2 (Input) to a value") my_bpod.manual_override(Bpod.ChannelTypes.INPUT, 'Port', channel_number=2, value=13) time.sleep(wait_active_time_ms) print("Set PWM3 (Input) to a value") my_bpod.manual_override(Bpod.ChannelTypes.INPUT, 'Port', channel_number=3, value=14) time.sleep(wait_active_time_ms) print("Set PWM3 (Input) to a value") my_bpod.manual_override(Bpod.ChannelTypes.INPUT, 'Port', channel_number=4, value=15) time.sleep(wait_active_time_ms)
1 : go_tone 2 : white_noise """ global sph if data == 0: sph.stop_sound() elif data == 1: sph.play_tone() elif data == 3: sph.start_camera_recording() # ============================================================================= # CONNECT TO BPOD # ============================================================================= bpod = Bpod() # Soft code handler function can run arbitrary code from within state machine bpod.softcode_handler_function = softcode_handler # Rotary Encoder State Machine handle rotary_encoder = [x for x in bpod.modules if x.name == "RotaryEncoder1"][0] # ROTARY ENCODER EVENTS rotary_encoder_reset = 1 bpod.load_serial_message( rotary_encoder, rotary_encoder_reset, [RotaryEncoder.COM_SETZEROPOS, RotaryEncoder.COM_ENABLE_ALLTHRESHOLDS ], # ord('Z') ) # ord('E') # Stop the stim re_stop_stim = rotary_encoder_reset + 1 bpod.load_serial_message(rotary_encoder, re_stop_stim, [ord("#"), 1])
""" Manually set values on Bpod channels via serial instructions. Example adapted from Josh Sanders' original version on Sanworks Bpod repository """ import time from pybpodapi.protocol import Bpod import examples.settings as settings my_bpod = Bpod() wait_active_time_ms = 2 ### INPUTS - BNC (1, 2) ### print("Set BNC1 (Input) to a value") my_bpod.manual_override(Bpod.ChannelTypes.INPUT, Bpod.ChannelNames.BNC, channel_number=1, value=12) time.sleep(wait_active_time_ms) print("Set BNC2 (Input) to a value") my_bpod.manual_override(Bpod.ChannelTypes.INPUT, Bpod.ChannelNames.BNC, channel_number=2, value=15) time.sleep(wait_active_time_ms) ### INPUTS - PWM (1..4) ### print("Set PWM1 (Input) to a value") my_bpod.manual_override(Bpod.ChannelTypes.INPUT, 'Port', channel_number=1, value=12)
def _create_bpod(self): self.__bpod = Bpod(emulator_mode=True)
from pybpodapi.protocol import Bpod, StateMachine import random my_bpod = Bpod(serial_port='COM14') nTrials = 5 trialTypes = [1, 2] for i in range(nTrials): print('Trial: ', i + 1) thisTrialType = random.choice(trialTypes) # Randomly choose trial type sma = StateMachine(my_bpod) sma.add_state(state_name='WaitForLick', state_timer=0, state_change_conditions={Bpod.Events.Port1In: 'Reward'}, output_actions=[]) sma.add_state(state_name='Reward', state_timer=0.1, state_change_conditions={Bpod.Events.Tup: 'Delay'}, output_actions=[(Bpod.OutputChannels.Valve, 1)]) sma.add_state(state_name='Delay', state_timer=2, state_change_conditions={Bpod.Events.Tup: 'exit'}, output_actions=[]) my_bpod.send_state_machine(sma)
} if save_to is not None: data = {k: v.tolist() for k, v in Measures.items()} with open( os.path.join(save_to, "_iblrig_ambientSensorData.raw.jsonable"), "a") as f: f.write(json.dumps(data)) f.write("\n") f.flush() return {k: v.tolist()[0] for k, v in Measures.items()} if __name__ == "__main__": from pybpodgui_api.models import project root = "/home/nico/Projects/IBL/github/iblrig/scratch" path = root + "/test_iblrig_params/IBL" p = project.Project() try: p.load(path) except TypeError as blabla: print("PyBpod says:", blabla) pass my_bpod = Bpod(serial_port=p.boards[0].serial_port) data = get_reading(my_bpod) print(data) my_bpod.close()
from pybpodapi.protocol import Bpod, StateMachine my_bpod = Bpod(emulator_mode=True) sma = StateMachine(my_bpod) # Set global timer 1 for 3 seconds, following a 1.5 second onset delay after # trigger. Link to LED of port 2. sma.set_global_timer(timer_id=1, timer_duration=3, on_set_delay=1.5, channel=Bpod.OutputChannels.PWM2, on_message=255) sma.add_state( state_name='TimerTrig', # Trigger global timer state_timer=0, state_change_conditions={Bpod.Events.Tup: 'Port1Lit_Pre'}, output_actions=[('GlobalTimerTrig', 1)]) sma.add_state( state_name='Port1Lit_Pre', state_timer=.25, state_change_conditions={Bpod.Events.Tup: 'Port3Lit_Pre', Bpod.Events.GlobalTimer1_Start: 'Port1Lit_Post'}, output_actions=[(Bpod.OutputChannels.PWM1, 16)]) sma.add_state( state_name='Port3Lit_Pre', state_timer=.25, state_change_conditions={Bpod.Events.Tup: 'Port1Lit_Pre', Bpod.Events.GlobalTimer1_Start: 'Port3Lit_Post'}, output_actions=[(Bpod.OutputChannels.PWM3, 16)]) sma.add_state( state_name='Port1Lit_Post', state_timer=.25, state_change_conditions={ Bpod.Events.Tup: 'Port3Lit_Post', Bpod.Events.GlobalTimer1_End: 'exit'}, output_actions=[(Bpod.OutputChannels.PWM1, 255)])
log = logging.getLogger('iblrig') log.setLevel(logging.INFO) global sph sph = SessionParamHandler(task_settings, user_settings) def bpod_loop_handler(): f.canvas.flush_events() # 100µs # ============================================================================= # CONNECT TO BPOD # ============================================================================= bpod = Bpod() # Loop handler function is used to flush events for the online plotting bpod.loop_handler = bpod_loop_handler # Bpod message creator msg = BpodMessageCreator(bpod) re_reset = msg.rotary_encoder_reset() bonsai_hide_stim = msg.bonsai_hide_stim() bonsai_show_stim = msg.bonsai_show_stim() bonsai_close_loop = msg.bonsai_close_loop() bonsai_freeze_stim = msg.bonsai_freeze_stim() sc_play_tone = msg.sound_card_play_idx(sph.GO_TONE_IDX) sc_play_noise = msg.sound_card_play_idx(sph.WHITE_NOISE_IDX) bpod = msg.return_bpod()
bonsai_data_lengths_file = folder / 'bonsai_ts_data_lengths.jsonable' def softcode_handler(data): if data: # Launch the workflow bonsai.start_frame2ttl_test(bonsai_data_file, bonsai_data_lengths_file) return # Set the thresholds for Frame2TTL iblrig.frame2TTL.get_and_set_thresholds() # ============================================================================= # CONNECT TO BPOD # ============================================================================= bpod = Bpod() # Soft code handler function can run arbitrary code from within state machine bpod.softcode_handler_function = softcode_handler log.info(f'Starting 1000 iterations of 1000 sync square pulses @60Hz') sys.stdout.flush() NITER = 500 # ============================================================================= # Start state machine definition # ============================================================================= for i in range(NITER): log.info(f"Starting iteration {i+1} of {NITER}") sma = StateMachine(bpod) sma.add_state(state_name='start', state_timer=2, output_actions=[('SoftCode', 1)],
import random import time from pybpodapi.protocol import Bpod, StateMachine from concurrent.futures import ThreadPoolExecutor my_bpod = Bpod(emulator_mode=True) nTrials = 5 graceTime = 5 port_numbers = [1, 2, 3] trialTypes = [1, 2] # 1 (rewarded left) or 2 (rewarded right) for i in range(nTrials): # Main loop print('Trial: ', i + 1) thisTrialType = random.choice(trialTypes) # Randomly choose trial type if thisTrialType == 1: # set stimulus channel for trial type 1 stimulus = Bpod.OutputChannels.PWM1 leftAction = 'Reward' rightAction = 'Punish' rewardValve = 1 elif thisTrialType == 2: # set stimulus channel for trial type 1 stimulus = Bpod.OutputChannels.PWM3 leftAction = 'Punish' rightAction = 'Reward' rewardValve = 3 sma = StateMachine(my_bpod) sma.set_global_timer_legacy(timer_id=1, timer_duration=graceTime) # Set timeout sma.add_state( state_name='WaitForPort2Poke', state_timer=1,
# !/usr/bin/python3 # -*- coding: utf-8 -*- """ Light Chasing Loop example Follow light on 3 pokes and repeat states until a timeout occurs. Connect noseports to ports 1-3. """ from pybpodapi.protocol import Bpod, StateMachine my_bpod = Bpod() sma = StateMachine(my_bpod) # Set global timer 1 for 3 seconds sma.set_global_timer_legacy(timer_id=1, timer_duration=10) sma.add_state( state_name='TimerTrig', # Trigger global timer state_timer=0, state_change_conditions={Bpod.Events.Tup: 'Port1Active1'}, output_actions=[(Bpod.OutputChannels.GlobalTimerTrig, 1)]) # Infinite loop (with next state). Only a global timer can save us. sma.add_state( state_name='Port1Active1', state_timer=0, state_change_conditions={Bpod.Events.Port1In: 'Port2Active1', Bpod.Events.GlobalTimer1_End: 'exit'},
# !/usr/bin/python3 # -*- coding: utf-8 -*- """ Example adapted from Josh Sanders' original version on Sanworks Bpod repository """ from pybpodapi.protocol import Bpod, StateMachine bpod = Bpod() bpod.manual_override(2, 'Valve', 1, 0) """ sma = StateMachine(bpod) sma.set_global_timer( timer_id=1, timer_duration=1.5, on_set_delay=0, channel=Bpod.OutputChannels.PWM1, #PulseWidthByte=255 ) sma.set_condition(2, 'GlobalTimer1', 1) sma.add_state( state_name='Port2Light', state_timer=1, state_change_conditions={ Bpod.Events.Tup: 'Port2Off', Bpod.Events.Port1In: 'TriggerGlobalTimer' },