bpod_core.bpod¶
Module for interfacing with the Bpod Finite State Machine.
Submodules¶
Exceptions¶
Classes¶
- class bpod_core.bpod.Bpod ¶
Bases:
SerialDevice,AbstractBpodInterface to a Bpod Finite State Machine.
Connects to the Bpod hardware over USB. If neither port nor serial_number is given, the first idle Bpod found on any USB port is used.
- Parameters:
port (
str|None, default:None) – USB serial port of the device (e.g., ‘/dev/ttyACM0’ or ‘COM3’). Mutually exclusive with serial_number.serial_number (
str|None, default:None) – Serial number of the device to connect to. Mutually exclusive with port.remote (
bool, default:False) – Advertise the ZeroMQ service via Zeroconf so that other processes can connect to this Bpod instance remotely.
- Raises:
BpodError – If no idle Bpod is found, the indicated port does not exist, or the device is not a supported Bpod model.
Examples
Connect to a Bpod on
COM3:with Bpod(port='COM3') as bpod: # do things
- close() ¶
Close the connection to the Bpod.
Waits for any running trial to finish before closing the serial port.
Note
Prefer using
Bpodas a context manager, which opens and closes the connection automatically.- Raises:
SerialException – If the port could not be closed.
- get_data(*, concat=True, rechunk=False, lazy=False) ¶
Return trial data from the data queue.
- Parameters:
concat (
bool, default:True) – IfTrue, pop and concatenate all DataFrames currently in the queue into a single DataFrame, blocking until at least one is available. IfFalse, pop and return one DataFrame, blocking until one is available.rechunk (
bool, default:False) – IfTrue, make sure that the result data is in contiguous memory. Only applies whenconcat=True.lazy (
bool, default:False) – IfTrue, return apolars.LazyFrame. IfFalse, return apolars.DataFrame.
- Returns:
One trial’s data, or all available trials concatenated when
concat=True.Columns:
time (
Datetime) – absolute Bpod timestamp.trial (
UInt16) – zero-based trial index.state machine (
Categorical) – state machine hash, seehash().state (
Categorical) – state name.type (
Enum) – event type.event (
Categorical) – input event name.channel (
Categorical) – channel name.value (
UInt8) – channel value.
- Return type:
- Raises:
BpodError – If the queue is empty and no state machine is currently running.
- open() ¶
Open the connection to the Bpod and perform a handshake.
Note
Prefer using
Bpodas a context manager, which opens and closes the connection automatically.- Raises:
SerialException – If the port could not be opened.
BpodError – If the handshake fails.
- peek_data(trigger_states=None, *, lazy=False) ¶
Return a snapshot of the current trial’s data.
- Parameters:
trigger_states (
Collection[str] |None, default:None) – Block until at least one of the given states has been entered, then return the snapshot. IfNone(default), returns immediately.lazy (
bool, default:False) – IfTrue, return apolars.LazyFrame. IfFalse(default), return apolars.DataFrame.
- Returns:
Events recorded so far in the current trial. Returns an empty DataFrame if no trial is running.
- Return type:
- Raises:
ValueError – If one or several of the trigger states are not part of the state machine.
- reset_session_clock() ¶
Reset the Bpod session clock.
- run(state_machine=None, *, trial_number=None, validate=True) ¶
Run a state machine on the Bpod.
Validates, compiles, sends, and queues a state machine for immediate execution. If the Bpod is currently running a state machine, the new one is queued to run as soon as the current one finishes, with no inter-trial gap.
If called without an argument, the previously sent state machine is re-sent from the compilation cache and queued for immediate back-to-back execution.
- Parameters:
state_machine (
StateMachine|None, default:None) – The state machine to run. If not provided, the previously sent state machine is repeated.trial_number (
int|None, default:None) – The trial number to assign to the state machine. If not provided, the trial number is automatically incremented with each run.validate (
bool, default:True) – If False, the state machine will not be validated prior to compilation. This will speed up the process, but may result in errors or unexpected behavior if the state machine is invalid. Use with caution.
- Raises:
RuntimeError – If called without an argument and no state machine has been run yet.
ValueError – If the state machine is invalid or exceeds hardware limitations.
ValidationError – If function arguments don’t match type hints.
Notes
This method returns once the state machine has been queued on the Bpod. The Bpod will then begin executing the state machine as soon as possible — immediately if the device is idle or right after the current state machine finishes. Subsequent calls of this method will result in continuous acquisition and zero inter-trial downtime (as long as the Bpod’s run queue stays filled).
- send_softcode(softcode) ¶
Send a softcode to the state machine.
Can be used to trigger transitions.
- Parameters:
softcode (
int) – The softcode value to send.- Raises:
ValueError – If
softcodeis out of range.
- set_softcode_handler(softcode_handler=None) ¶
Set the handler function for softcodes sent from the Bpod.
- set_status_led(enable) ¶
Enable or disable the Bpod status LED.
- stop_state_machine() ¶
Stop the currently running state machine.
- update_modules() ¶
Update the list of connected modules and their configurations.
- validate_state_machine(state_machine) ¶
Validate the provided state machine for compatibility with the hardware.
- Parameters:
state_machine (
StateMachine) – The state machine to validate.- Raises:
ValueError – If the state machine is invalid or not compatible with the hardware.
- wait() ¶
Wait for the currently running state machine to finish.
Blocks until the state machine thread completes. If no state machine is currently running, this method returns immediately.
- property port: str ¶
The name of the serial port.
- Returns:
The device path of the serial port (e.g., ‘/dev/ttyACM0’).
- Return type:
- property serial0: ExtendedSerial ¶
Primary serial device for communication with the Bpod.
- serial1: ExtendedSerial | None = None¶
Secondary serial device for communication with the Bpod.
- serial2: ExtendedSerial | None = None¶
Tertiary serial device for communication with the Bpod - used by Bpod 2+ only.
- property version: VersionInfo ¶
Version information of the Bpod’s firmware and hardware.
- class bpod_core.bpod.Input ¶
Bases:
ChannelInput channel class representing a digital input channel.
- enable(enable) ¶
Enable or disable the input channel.
- override(state) ¶
Override the state of the input channel.
- Parameters:
state (
bool) – The state to set for the input channel.
- read() ¶
Read the state of the input channel.
- Returns:
True if the input channel is active, False otherwise.
- Return type:
- class bpod_core.bpod.Module ¶
Bases:
objectRepresents a Bpod module with its configuration and event names.
- load_serial_message(message_id, message_bytes) ¶
Load a serial message targeting the module.
Serial messages are byte sequences targeting a specific module that can be triggered as output actions during a state machine run. Each message is identified by a
message_id.- Parameters:
- Returns:
- Return type:
- Raises:
ValidationError – If the provided parameters cannot be validated or coerced to the expected type.
ValueError – If
message_id, ormessage_byteslength is out of range.
- class bpod_core.bpod.Output ¶
Bases:
ChannelOutput channel class representing a digital output channel.
- class bpod_core.bpod.RemoteBpod ¶
Bases:
AbstractBpodProxy for a
Bpodinstance running in another process.Use this when the Bpod hardware is managed by a separate process that was started with
remote=True.RemoteBpoddiscovers that process via Zeroconf and forwards all method calls over ZeroMQ.Note
This class is not yet fully functional. Some methods may be missing or incomplete.
- Parameters:
address (
str|None, default:None) – ZeroMQ address of the remote Bpod service. Discovered automatically if not given.name (
str|None, default:None) – Zeroconf service name to filter by during discovery.serial_number (
str|None, default:None) – Serial number of the target Bpod to filter by during discovery.location (
str|None, default:None) – Zeroconf location string to filter by during discovery.timeout (
float, default:10.0) – Discovery timeout in seconds.
- Raises:
TimeoutError – If no matching remote Bpod is found within timeout seconds.
- close() ¶
Close the connection to the remote Bpod.
- get_data(*, concat=True, rechunk=False, lazy=False) ¶
Return trial data from the data queue.
- Parameters:
concat (
bool, default:True) – IfTrue, pop and concatenate all DataFrames currently in the queue into a single DataFrame, blocking until at least one is available. IfFalse, pop and return one DataFrame, blocking until one is available.rechunk (
bool, default:False) – IfTrue, make sure that the result data is in contiguous memory. Only applies whenconcat=True.lazy (
bool, default:False) – IfTrue, return apolars.LazyFrame. IfFalse, return apolars.DataFrame.
- Returns:
One trial’s data, or all available trials concatenated when
concat=True.Columns:
time (
Datetime) – absolute Bpod timestamp.trial (
UInt16) – zero-based trial index.state machine (
Categorical) – state machine hash, seehash().state (
Categorical) – state name.type (
Enum) – event type.event (
Categorical) – input event name.channel (
Categorical) – channel name.value (
UInt8) – channel value.
- Return type:
- Raises:
BpodError – If the queue is empty and no state machine is currently running.
- reset_session_clock() ¶
Reset the Bpod session clock.
- run(state_machine=None, *, trial_number=None, validate=True) ¶
Run a state machine on the Bpod.
Validates, compiles, sends, and queues a state machine for immediate execution. If the Bpod is currently running a state machine, the new one is queued to run as soon as the current one finishes, with no inter-trial gap.
If called without an argument, the previously sent state machine is re-sent from the compilation cache and queued for immediate back-to-back execution.
- Parameters:
state_machine (
StateMachine|None, default:None) – The state machine to run. If not provided, the previously sent state machine is repeated.trial_number (
int|None, default:None) – The trial number to assign to the state machine. If not provided, the trial number is automatically incremented with each run.validate (
bool, default:True) – If False, the state machine will not be validated prior to compilation. This will speed up the process, but may result in errors or unexpected behavior if the state machine is invalid. Use with caution.
- Raises:
RuntimeError – If called without an argument and no state machine has been run yet.
ValueError – If the state machine is invalid or exceeds hardware limitations.
ValidationError – If function arguments don’t match type hints.
Notes
This method returns once the state machine has been queued on the Bpod. The Bpod will then begin executing the state machine as soon as possible — immediately if the device is idle or right after the current state machine finishes. Subsequent calls of this method will result in continuous acquisition and zero inter-trial downtime (as long as the Bpod’s run queue stays filled).
- set_status_led(enable) ¶
Enable or disable the Bpod’s status LED.
- stop_state_machine() ¶
Stop the currently running state machine.
- update_modules() ¶
Update the list of connected modules and their configurations.
- property version: VersionInfo ¶
Version information of the Bpod’s firmware and hardware.
Functions¶
- bpod_core.bpod.discover_bpod(port=None, serial_number=None) ¶
Identify available Bpod devices connected via USB.
Scans for USB serial ports matching Bpod vendor/product IDs and verifies each device responds to a discovery message. Yields information about identified devices.
- Parameters:
- Yields:
BpodInfo– Information structure describing a Bpod device.- Return type:
Examples
Iterate over available Bpods:
for device in discover_bpod(): print(f"Found Bpod at {device}")
Get as a list:
devices = list(discover_bpod())
- bpod_core.bpod.discover_remote_bpod(name=None, serial_number=None, location=None, timeout=10.0, poll_interval=1.0, *, local=True, remote=True) ¶
Identify available Bpod devices connected via ZeroMQ.
- Parameters:
serial_number (
str|None, default:None) – Serial number of the Bpod device.location (
str|None, default:None) – Location of the Bpod device.timeout (
float|None, default:10.0) – How many seconds to monitor. PassNoneto monitor indefinitely until the iterator is closed.poll_interval (
float, default:1.0) – How often to poll for local service changes, in seconds. Default is 1.local (
bool, default:True) – Whether to search for services on the local machine.remote (
bool, default:True) – Whether to also search for services on the network.
- Yields:
ServiceEvent– A named tuple with the following fields:kind: str, either ‘added’ or ‘removed’
address: str, the service address, e.g., ‘tcp://192.168.1.10:1234’
properties: dict, the service properties, e.g., {‘name’: ‘MyDevice’}
- Return type: