Command Line Interfaces

This package provides the Command Line Interfaces (CLIs) for interfacing with all user-facing library components, exposed by installing the library into a Python environment.

sl-run

Runs data acquisition and system maintenance sessions supported by the data acquisition system managed by the host-machine.

Usage

sl-run [OPTIONS] COMMAND [ARGS]...

maintenance

Runs the data acquisition system maintenance session.

Calling this command exposes a GUI for directly interfacing with a small subset of the managed data acquisition system’s components that require frequent maintenance. It does not collect any data during runtime and does not interface with the remote data storage infrastructure accessible to the data acquisition system. It is designed to perform minor (day-to-day) maintenance tasks that do not require disassembling the system’s components.

Usage

sl-run maintenance [OPTIONS]

session

Runs the specified data acquisition session for the target animal and project combination.

Usage

sl-run session [OPTIONS] COMMAND [ARGS]...

Options

-u, --user <user>

Required The ID of the user supervising the session.

-p, --project <project>

Required The name of the project to which the animal belongs.

-a, --animal <animal>

Required The ID of the animal undergoing the session.

-w, --animal_weight <animal_weight>

Required The weight of the animal, in grams, at the beginning of the session.

check-window

Runs the cranial window quality checking session.

The primary purpose of the cranial window quality checking session is to ensure that the animal is suitable for collecting high-quality brain activity data. Additionally, the session is used to generate the animal-specific data acquisition system configuration reused during all future data acquisition sessions to fine-tune the system to work for the target animal.

Usage

sl-run session check-window [OPTIONS]

experiment

Runs the specified experiment session.

Experiment runtimes are carried out after the lick and run training sessions. This command allows running any valid Sun lab experiment supported by the data acquisition system managed by the host-machine. To create a new experiment configuration for the local data-acquisition system, use the ‘sl-configure experiment’ CLI command.

Usage

sl-run session experiment [OPTIONS]

Options

-e, --experiment <experiment>

Required The name of the experiment to carry out during runtime.

-ur, --unconsumed_rewards <unconsumed_rewards>

The maximum number of rewards that can be delivered without the animal consuming them. If the unconsumed reward count exceeds this threshold, the system stops delivering new water rewards until the animal consumes the already delivered rewards. Setting this argument to 0 disables the reward consumption tracking.

lick-training

Runs the lick training session.

Lick training is the first phase of preparing the animal for experiment sessions, and is usually carried out over the first two days of the pre-experiment training sequence. This session teaches the animal to operate the lick-port and associate licking at the port with water delivery.

Usage

sl-run session lick-training [OPTIONS]

Options

-t, --maximum_time <maximum_time>

The maximum time to run the training session, in minutes. Defaults to 20 minutes.

-min, --minimum_delay <minimum_delay>

The minimum number of seconds that has to pass between two consecutive reward deliveries during training. Defaults to 6 seconds.

-max, --maximum_delay <maximum_delay>

The maximum number of seconds that can pass between two consecutive reward deliveries during training. Defaults to 18 seconds.

-v, --maximum_volume <maximum_volume>

The maximum volume of water, in milliliters, that can be delivered during training. Defaults to 1.0 mL.

-ur, --unconsumed_rewards <unconsumed_rewards>

The maximum number of rewards that can be delivered without the animal consuming them. If the unconsumed reward count exceeds this threshold, the system stops delivering new water rewards until the animal consumes the already delivered rewards. Setting this argument to 0 disables the reward consumption tracking. Defaults to 1.

run-training

Runs the run training session.

Run training is the second phase of preparing the animal for experiment sessions, and is usually carried out over the five days following the lick training sessions. This session teaches the animal to run on the wheel treadmill while being head-fixed and associate getting water rewards with running on the treadmill. Over the course of training, the task requirements are adjusted to prepare the animal to perform as many laps as possible during experiment sessions lasting ~60 minutes.

Usage

sl-run session run-training [OPTIONS]

Options

-t, --maximum_time <maximum_time>

The maximum time to run the training session, in minutes. Defaults to 40 minutes.

-is, --initial_speed <initial_speed>

The initial speed, in centimeters per second, the animal must maintain to obtain water rewards. Defaults to 0.8 cm/s.

-id, --initial_duration <initial_duration>

The initial duration, in seconds, the animal must maintain above-threshold running speed to obtain water rewards. Defaults to 1.5 seconds.

-it, --increase_threshold <increase_threshold>

The volume of water delivered to the animal, in milliliters, after which the speed and duration thresholds are increased by the specified step-sizes. This is used to make the training progressively harder for the animal over the course of the training session. Defaults to 0.1 mL.

-ss, --speed_step <speed_step>

The amount, in centimeters per second, to increase the speed threshold each time the animal receives the volume of water specified by the ‘increase-threshold’ parameter. Defaults to 0.05 cm/s.

-ds, --duration_step <duration_step>

The amount, in seconds, to increase the duration threshold each time the animal receives the volume of water specified by the ‘increase-threshold’ parameter. Defaults to 0.1 seconds.

-v, --maximum_volume <maximum_volume>

The maximum volume of water, in milliliters, that can be delivered during training. Defaults to 1.0 mL.

-mit, --maximum_idle_time <maximum_idle_time>

The maximum time, in seconds, the animal is allowed to maintain the speed that is below the speed threshold and still receive the water reward. Setting this argument to 0 forces the animal to maintain the above-threshold speed at all times. Defaults to 0.3 seconds.

-ur, --unconsumed_rewards <unconsumed_rewards>

The maximum number of rewards that can be delivered without the animal consuming them. If the unconsumed reward count exceeds this threshold, the system stops delivering new water rewards until the animal consumes the already delivered rewards. Setting this argument to 0 disables the reward consumption tracking. Defaults to 1.

sl-manage

Manages the data accessible to the data acquisition system managed by the local host-machine.

Usage

sl-manage [OPTIONS] COMMAND [ARGS]...

delete

Removes the target session’s data from all destinations accessible to the data acquisition system.

This is an extremely dangerous command that can potentially delete valuable data if used carelessly. This command removes the session’s data from all machines of the data acquisition system and all long-term storage destinations accessible to the data acquisition system.

Usage

sl-manage delete [OPTIONS]

Options

-sp, --session-path <session_path>

Required The path to the data acquisition session’s directory to remove.

mcp

Starts the MCP server for agentic access to sl-manage tools.

Usage

sl-manage mcp [OPTIONS]

Options

-t, --transport <transport>

The MCP transport type (‘stdio’, ‘sse’, or ‘streamable-http’).

Default:

'stdio'

migrate

Transfers all sessions for the specified animal from the source project to the target project.

Usage

sl-manage migrate [OPTIONS]

Options

-s, --source <source>

Required The name of the project from which to migrate the data.

-d, --destination <destination>

Required The name of the project to which to migrate the data.

-a, --animal <animal>

Required The ID of the animal whose data to migrate.

preprocess

Preprocesses the target session’s data stored on the data acquisition system’s host-machine.

Usage

sl-manage preprocess [OPTIONS]

Options

-sp, --session-path <session_path>

Required The path to the data acquisition session’s directory to preprocess.

sl-get

Evaluates the composition of the data acquisition system managed by the host-machine.

Usage

sl-get [OPTIONS] COMMAND [ARGS]...

cameras

Identifies the cameras accessible to the data acquisition system.

Usage

sl-get cameras [OPTIONS]

checksum

Calculates the CRC32-XFER checksum for the input string.

Usage

sl-get checksum [OPTIONS]

Options

-i, --input_string <input_string>

The string for which to compute the checksum.

controllers

Identifies the microcontrollers accessible to the data acquisition system.

Usage

sl-get controllers [OPTIONS]

experiments

Identifies the target project’s experiment configurations accessible to the data acquisition system.

Usage

sl-get experiments [OPTIONS]

Options

-p, --project <project>

Required The name of the project for which to discover the available experiment configurations.

mcp

Starts the MCP server for agentic access to sl-get tools.

Usage

sl-get mcp [OPTIONS]

Options

-t, --transport <transport>

The MCP transport type (‘stdio’, ‘sse’, or ‘streamable-http’).

Default:

'stdio'

ports

Identifies the serial communication ports accessible to the data acquisition system.

Usage

sl-get ports [OPTIONS]

projects

Identifies the projects accessible to the data acquisition system.

Usage

sl-get projects [OPTIONS]

zaber

Identifies the Zaber devices accessible to the data acquisition system.

Usage

sl-get zaber [OPTIONS]

Mesoscope-VR Acquisition System

This package provides the assets for acquiring and preprocessing data via the Mesoscope-VR data acquisition system.

class sl_experiment.mesoscope_vr.CRCCalculator

Bases: object

Exposes methods for calculating CRC32-XFER checksums for ASCII strings.

_calculator

The configured Calculator instance used to calculate the checksums.

string_checksum(string)

Calculates the CRC32-XFER checksum for the input string.

Parameters:

string (str) – The string for which to calculate the CRC checksum.

Return type:

int

Returns:

The integer CRC32-XFER checksum.

class sl_experiment.mesoscope_vr.ZaberDeviceSettings(device_label, axis_label, checksum, shutdown_flag, unsafe_flag, park_position, maintenance_position, mount_position, limit_min, limit_max, current_position)

Bases: object

Stores configuration settings read from a Zaber device’s non-volatile memory.

axis_label: str

The user-assigned name of the axis.

checksum: int

The CRC32-XFER checksum stored in USER_DATA_0.

current_position: float

The current absolute position of the motor in native motor units.

device_label: str

The user-assigned name of the device.

limit_max: float

The maximum allowed position relative to home in native motor units.

limit_min: float

The minimum allowed position relative to home in native motor units.

maintenance_position: int

The maintenance position in native motor units stored in USER_DATA_12.

mount_position: int

The mount position in native motor units stored in USER_DATA_13.

park_position: int

The park position in native motor units stored in USER_DATA_11.

shutdown_flag: int

The shutdown flag stored in USER_DATA_1 (1 = proper shutdown, 0 = abnormal).

unsafe_flag: int

The unsafe flag stored in USER_DATA_10 (1 = requires safe position for homing).

class sl_experiment.mesoscope_vr.ZaberValidationResult(is_valid, checksum_valid, positions_valid, errors, warnings)

Bases: object

Stores the results of validating a Zaber device’s configuration.

checksum_valid: bool

Determines whether the stored checksum matches the calculated checksum for the device label.

errors: tuple[str, ...]

Contains critical issues that prevent the device from being used with the binding library.

is_valid: bool

Determines whether the device configuration is valid for use with the binding library.

positions_valid: bool

Determines whether all predefined positions are within the device motion limits.

warnings: tuple[str, ...]

Contains non-critical issues that may affect device operation.

sl_experiment.mesoscope_vr.discover_zaber_devices()

Scans all available serial ports and displays information about connected Zaber devices.

Note

Connection errors encountered during scanning are logged at DEBUG level and do not interrupt the discovery process. Ports that cannot be connected are listed as having “No Devices”.

Return type:

None

sl_experiment.mesoscope_vr.experiment_logic(experimenter, project_name, experiment_name, animal_id, animal_weight, maximum_unconsumed_rewards=None)

Runs experiments using the Virtual Reality task environments and collects the brain activity data via the mesoscope.

Notes

Each experiment is conceptualized as a sequence of experiment states (phases), which define the task and the types of data being collected while the system maintains the state. During the session, the system executes the predefined sequence of states defines in the experiment’s configuration file. Once all states are executed, the experiment session ends.

During the session’s runtime, the task logic and the Virtual Reality world are resolved by the Unity game engine. This function handles the data collection and the overall runtime management.

The maximum_unconsumed_rewards argument is an optional override. If not provided, the system loads the argument’s value used during a previous session (if available) or uses a system-defined default value.

Parameters:
  • experimenter (str) – The unique identifier of the experimenter conducting the experiment session.

  • project_name (str) – The name of the project in which the experimental animal participates.

  • experiment_name (str) – The name of the experiment to be conducted.

  • animal_id (str) – The unique identifier of the animal participating in the experiment.

  • animal_weight (float) – The weight of the animal, in grams, at the beginning of the session.

  • maximum_unconsumed_rewards (int | None, default: None) – The maximum number of rewards that can be delivered without the animal consuming them, before the system suspends delivering water rewards until the animal consumes all available rewards. Setting this argument to 0 disables forcing reward consumption.

Return type:

None

sl_experiment.mesoscope_vr.get_zaber_device_settings(port, device_index)

Reads configuration settings from a Zaber device’s non-volatile memory.

Parameters:
  • port (str) – Serial port path (e.g., “/dev/ttyUSB0”).

  • device_index (int) – Zero-based index in the daisy-chain (0 = closest to USB port).

Return type:

ZaberDeviceSettings

Returns:

A ZaberDeviceSettings instance containing the device configuration including labels, positions, flags, and motion limits.

Raises:
  • ConnectionError – If unable to connect to the specified port.

  • IndexError – If device_index is out of range for the connected devices.

sl_experiment.mesoscope_vr.get_zaber_devices_info()

Scans all available serial ports for Zaber devices and returns formatted device information.

Return type:

str

Returns:

A formatted table string containing port, device, and axis information for all discovered Zaber devices. Ports with connection errors are listed as having “No Devices”.

Notes

This function is designed for programmatic access to Zaber device information, such as from MCP tools. Connection errors encountered during scanning are logged at DEBUG level and do not interrupt the discovery process.

sl_experiment.mesoscope_vr.lick_training_logic(experimenter, project_name, animal_id, animal_weight, reward_size=None, reward_tone_duration=None, minimum_reward_delay=None, maximum_reward_delay=None, maximum_water_volume=None, maximum_training_time=None, maximum_unconsumed_rewards=None)

Trains the animal to operate the lickport used by the Mesoscope-VR data acquisition system.

Notes

The training consists of delivering water rewards via the lickport at pseudorandom intervals to teach the animal that rewards come out of the lick port. The training continues either until the valve delivers the ‘maximum_water_volume’ in milliliters or until the ‘maximum_training_time’ in minutes is reached, whichever comes first.

Most arguments to this function are optional overrides. If an argument is not provided, the system loads the argument’s value used during a previous runtime (if available) or uses a system-defined default value.

Parameters:
  • experimenter (str) – The unique identifier of the experimenter conducting the training session.

  • project_name (str) – The name of the project in which the trained animal participates.

  • animal_id (str) – The unique identifier of the animal being trained.

  • animal_weight (float) – The weight of the animal, in grams, at the beginning of the session.

  • reward_size (float | None, default: None) – The volume of water, in microliters, to use when delivering water rewards to the animal.

  • reward_tone_duration (int | None, default: None) – The duration, in milliseconds, of the auditory tone played to the animal when it receives water rewards.

  • minimum_reward_delay (int | None, default: None) – The minimum time, in seconds, that has to pass between delivering two consecutive rewards.

  • maximum_reward_delay (int | None, default: None) – The maximum time, in seconds, that can pass between delivering two consecutive rewards.

  • maximum_water_volume (float | None, default: None) – The maximum volume of water, in milliliters, that can be delivered to the animal during the session.

  • maximum_training_time (int | None, default: None) – The maximum training time, in minutes.

  • maximum_unconsumed_rewards (int | None, default: None) – The maximum number of rewards that can be delivered without the animal consuming them, before the system suspends delivering water rewards until the animal consumes all available rewards. Setting this argument to 0 disables forcing reward consumption.

Return type:

None

sl_experiment.mesoscope_vr.maintenance_logic()

Encapsulates the logic used to maintain a subset of the Mesoscope-VR system’s hardware components.

Return type:

None

sl_experiment.mesoscope_vr.migrate_animal_between_projects(animal, source_project, target_project)

Transfers all sessions performed by the specified animal from the source project to the target project across all storage locations.

Parameters:
  • animal (str) – The animal for which to migrate the data.

  • source_project (str) – The name of the project from which to migrate the data.

  • target_project (str) – The name of the project to which the data should be migrated.

Return type:

None

sl_experiment.mesoscope_vr.preprocess_session_data(session_data)

Aggregates all session’s data on VRPC, compresses it for efficient network transmission, transfers the data to the BioHPC server and the Synology NAS, and removes the local data copy from the VRPC.

Parameters:

session_data (SessionData) – The SessionData instance that defines the processed session.

Return type:

None

sl_experiment.mesoscope_vr.purge_session(session_data)

Removes all data and directories associated with the input session from all Mesoscope-VR system machines and long-term storage destinations.

Notes

This function is extremely dangerous and should be used with caution. It is designed to remove all data from failed or no longer necessary sessions from all storage locations. Never use this function on sessions that contain valid scientific data.

Parameters:

session_data (SessionData) – The SessionData instance that defines the session whose data needs to be removed.

Return type:

None

sl_experiment.mesoscope_vr.run_training_logic(experimenter, project_name, animal_id, animal_weight, reward_size=None, reward_tone_duration=None, initial_speed_threshold=None, initial_duration_threshold=None, speed_increase_step=None, duration_increase_step=None, increase_threshold=None, maximum_water_volume=None, maximum_training_time=None, maximum_idle_time=None, maximum_unconsumed_rewards=None)

Trains the animal to run on the wheel treadmill while being head-fixed.

Notes

The run training consists of making the animal run on the wheel with a desired speed, in centimeters per second, maintained for the desired duration of time, in seconds. Each time the animal satisfies the speed and duration thresholds, it receives a water reward, and the speed and duration trackers reset for the next training ‘epoch’. Each time the animal receives ‘increase_threshold’ of water, the speed and duration thresholds increase to make the task progressively more challenging. The training continues either until the training time exceeds the ‘maximum_training_time’, or the animal receives the ‘maximum_water_volume’ of water, whichever happens earlier.

Most arguments to this function are optional overrides. If an argument is not provided, the system loads the argument’s value used during a previous session (if available) or uses a system-defined default value.

Parameters:
  • experimenter (str) – The unique identifier of the experimenter conducting the training session.

  • project_name (str) – The name of the project in which the trained animal participates.

  • animal_id (str) – The unique identifier of the animal being trained.

  • animal_weight (float) – The weight of the animal, in grams, at the beginning of the session.

  • reward_size (float | None, default: None) – The volume of water, in microliters, to use when delivering water rewards to the animal.

  • reward_tone_duration (int | None, default: None) – The duration, in milliseconds, of the auditory tone played to the animal when it receives water rewards.

  • initial_speed_threshold (float | None, default: None) – The initial running speed threshold, in centimeters per second, that the animal must maintain to receive water rewards.

  • initial_duration_threshold (float | None, default: None) – The initial duration threshold, in seconds, that the animal must maintain above-threshold running speed to receive water rewards.

  • speed_increase_step (float | None, default: None) – The step size, in centimeters per second, by which to increase the speed threshold each time the animal receives ‘increase_threshold’ milliliters of water.

  • duration_increase_step (float | None, default: None) – The step size, in seconds, by which to increase the duration threshold each time the animal receives ‘increase_threshold’ milliliters of water.

  • increase_threshold (float | None, default: None) – The volume of water received by the animal, in milliliters, after which the speed and duration thresholds are increased by one step.

  • maximum_water_volume (float | None, default: None) – The maximum volume of water, in milliliters, that can be delivered to the animal during the session.

  • maximum_training_time (int | None, default: None) – The maximum training time, in minutes.

  • maximum_idle_time (float | None, default: None) – The maximum time, in seconds, the animal’s speed can be below the speed threshold to still receive water rewards. This parameter is designed to help animals with a distinct ‘step’ pattern to not lose water rewards due to taking many large steps, rather than continuously running at a stable speed. Setting this argument to 0 disables this functionality.

  • maximum_unconsumed_rewards (int | None, default: None) – The maximum number of rewards that can be delivered without the animal consuming them, before the system suspends delivering water rewards until the animal consumes all available rewards. Setting this argument to 0 disables forcing reward consumption.

Return type:

None

sl_experiment.mesoscope_vr.set_zaber_device_setting(port, device_index, setting, value)

Writes a configuration setting to a Zaber device’s non-volatile memory.

Notes

Position values are validated against device motion limits before writing. Label changes automatically update the checksum (USER_DATA_0) to maintain device validation. The checksum setting cannot be modified directly as it is managed by the binding library.

Parameters:
  • port (str) – Serial port path (e.g., “/dev/ttyUSB0”).

  • device_index (int) – Zero-based index in the daisy-chain (0 = closest to USB port).

  • setting (str) – Setting name. Valid options are park_position, maintenance_position, mount_position, unsafe_flag, shutdown_flag, device_label, and axis_label.

  • value (int | str) – Value to write. Use integers for positions and flags, strings for labels.

Return type:

str

Returns:

A success message containing the old and new values.

Raises:
  • ConnectionError – If unable to connect to the specified port.

  • IndexError – If device_index is out of range for the connected devices.

  • ValueError – If the setting name is invalid, the value type is incorrect, or the value is out of range.

sl_experiment.mesoscope_vr.validate_zaber_device_configuration(port, device_index)

Validates a Zaber device’s configuration for use with the binding library.

Notes

Performs comprehensive validation including checksum verification against the device label, position bounds checking against motion limits, and configuration completeness verification.

Parameters:
  • port (str) – Serial port path (e.g., “/dev/ttyUSB0”).

  • device_index (int) – Zero-based index in the daisy-chain (0 = closest to USB port).

Return type:

ZaberValidationResult

Returns:

A ZaberValidationResult instance containing validation status, error messages, and warnings.

Raises:
  • ConnectionError – If unable to connect to the specified port.

  • IndexError – If device_index is out of range for the connected devices.

sl_experiment.mesoscope_vr.window_checking_logic(experimenter, project_name, animal_id)

Guides the user though verifying the quality of the implanted cranial window and generating the initial Mesoscope-VR system configuration for the target animal.

Parameters:
  • experimenter (str) – The unique identifier of the experimenter conducting the window checking session.

  • project_name (str) – The name of the project in which the evaluated animal participates.

  • animal_id (str) – The unique identifier of the animal being evaluated.

Return type:

None

Shared Acquisition Tools And Assets

This package provides the assets shared by multiple data acquisition systems.

class sl_experiment.shared_components.BrakeInterface(minimum_brake_strength, maximum_brake_strength)

Bases: ModuleInterface

Interfaces with BrakeModule instances running on the Actor MicroController.

Notes

Type code 3.

Parameters:
  • minimum_brake_strength (float) – The torque, in gram centimeter, applied by the brake when it is fully disengaged.

  • maximum_brake_strength (float) – The torque, in gram centimeter, applied by the brake when it is maximally engaged.

_minimum_brake_strength

The minimum torque, in N cm, the brake delivers at minimum voltage.

_maximum_brake_strength

The maximum torque, in N cm, the brake delivers at maximum voltage.

_engage

The code for the EnableBrake module command.

_disengage

The code for the DisableBrake module command.

_pulse

The code for the SendPulse module command.

_enabled

Tracks the current state of the managed brake.

_previous_pulse_duration

Tracks the pulse duration used during the previous send_pulse() call.

initialize_remote_assets()

Not used.

Return type:

None

property maximum_brake_strength: float64

Returns the torque, in Newton centimeters, produced by the brake when it is maximally engaged.

property minimum_brake_strength: float64

Returns the torque, in Newton centimeters, produced by the brake when it is fully disengaged.

process_received_data(_message)

Not used, as the module currently does not require any real-time data processing.

Return type:

None

send_pulse(duration_ms)

Briefly engages the brake at full strength for the specified duration then automatically disengages.

Parameters:

duration_ms (int) – The duration, in milliseconds, to engage the brake.

Return type:

None

set_state(*, state)

Sets the brake to the desired state.

Parameters:

state (bool) – The desired state of the brake. True means the brake is engaged; False means the brake is disengaged.

Return type:

None

terminate_remote_assets()

Not used.

Return type:

None

class sl_experiment.shared_components.EncoderInterface(encoder_ppr, wheel_diameter, cm_per_unity_unit, polling_frequency)

Bases: ModuleInterface

Interfaces with EncoderModule instances running on the Encoder MicroController.

Notes

Type code 2.

Parameters:
  • encoder_ppr (int) – The resolution of the module’s quadrature encoder, in Pulses Per Revolution (PPR).

  • wheel_diameter (float) – The diameter of the running wheel attached to the encoder, in centimeters.

  • cm_per_unity_unit (float) – The length of one Virtual Reality environment distance unit (Unity unit) in centimeters.

  • polling_frequency (int) – The frequency, in microseconds, at which to check the encoder’s state when monitoring the encoder.

_ppr

The resolution of the managed quadrature encoder.

_wheel_diameter

The diameter of the running wheel connected to the encoder.

_cm_per_pulse

The conversion factor that translates encoder pulses into centimeters.

_unity_unit_per_pulse

The conversion factor that translates encoder pulses into Unity units.

_polling_frequency

The frequency, in microseconds, at which to check the encoder’s state when monitoring the encoder.

_distance_tracker

The SharedMemoryArray instance that transfers the distance data collected by the module from the communication process to other runtime processes.

_check_state

The code for the CheckState module command.

_reset_encoder

The code for the ResetEncoder module command.

_monitoring

Tracks whether the instance is currently configured to monitor the managed encoder’s state.

property absolute_position: float64

Returns the absolute position of the animal, in Unity units, relative to the runtime onset.

property cm_per_pulse: float64

Returns the conversion factor that translates the raw encoder pulse counts to traveled centimeters.

initialize_local_assets()

Connects to the instance’s shared memory buffer and enables buffer cleanup at shutdown.

Return type:

None

initialize_remote_assets()

Connects to the instance’s shared memory buffer.

Return type:

None

process_received_data(message)

Updates the distance data stored in the instance’s shared memory buffer based on the messages received from the microcontroller.

Return type:

None

reset_distance_tracker()

Resets the traveled distance trackers to zero.

Return type:

None

set_monitoring_state(*, state)

Configures the module to start or stop continuously monitoring the managed sensor’s state.

Parameters:

state (bool) – Determines whether to start or stop monitoring the managed sensor’s state.

Return type:

None

set_parameters(report_ccw, report_cw, delta_threshold)

Sets the module’s PC-addressable runtime parameters to the input values.

Parameters:
  • report_ccw (bool) – Determines whether to report rotation in the counterclockwise (CCW; positive) direction.

  • report_cw (bool) – Determines whether to report rotation in the clockwise (CW; negative) direction.

  • delta_threshold (uint32) – The minimum displacement change (delta) between any two consecutive readouts for reporting the rotation to the PC.

Return type:

None

terminate_remote_assets()

Disconnects from the instance’s shared memory buffer.

Return type:

None

property traveled_distance: float64

Returns the total distance, in centimeters, traveled by the animal since the runtime onset.

class sl_experiment.shared_components.GasPuffValveInterface

Bases: ModuleInterface

Interfaces with specialized ValveModule instances designed to operate gas valves.

Notes

Type code 5.

Unlike the water reward valve, gas valves do not require calibration as precise gas volume control is not critical. This interface provides direct duration-based control without volume conversion.

_pulse

The code for the Pulse module command.

_open

The code for the Open module command.

_close

The code for the Close module command.

_configured_state

Tracks the current state of the valve (Open or Closed) set through this interface instance.

_previous_module_state

Tracks the valve’s state reported by the last received message from the microcontroller.

_previous_duration

Tracks the pulse duration used during the previous deliver_puff() call.

_puff_tracker

The SharedMemoryArray instance that transfers puff data from the communication process to other runtime processes.

deliver_puff(duration_ms=100)

Opens the valve for the specified duration to deliver a gas puff.

Parameters:

duration_ms (int, default: 100) – The duration, in milliseconds, to keep the valve open.

Return type:

None

initialize_local_assets()

Connects to the puff tracker shared memory array from the local process.

Return type:

None

initialize_remote_assets()

Connects to the puff tracker shared memory array from the remote process.

Return type:

None

process_received_data(message)

Updates the puff data stored in the instance’s shared memory buffer based on the messages received from the microcontroller.

Return type:

None

property puff_count: int

Returns the total number of gas puffs delivered since runtime onset.

set_state(*, state)

Sets the managed valve to the desired state.

Parameters:

state (bool) – The desired state of the valve. True means the valve is open; False means the valve is closed.

Return type:

None

terminate_remote_assets()

Disconnects from and destroys the puff tracker shared memory array.

Return type:

None

class sl_experiment.shared_components.LickInterface(lick_threshold, polling_frequency)

Bases: ModuleInterface

Interfaces with LickModule instances running on the Sensor MicroController.

Notes

Type code 4.

Parameters:
  • lick_threshold (int) – The threshold voltage, in raw analog units measured by a 3.3 Volt 12-bit Analog-to-Digital-Converter module, for interpreting the signal received from the sensor as a lick event.

  • polling_frequency (int) – The frequency, in microseconds, at which to check the lick sensor’s state when monitoring the sensor.

_lick_threshold

The threshold voltage for detecting lick events.

_polling_frequency

The frequency, in microseconds, at which to check the lick sensor’s state when monitoring the sensor.

_lick_tracker

The SharedMemoryArray instance that transfers the lick data collected by the module from the communication process to other runtime processes.

_previous_readout_zero

Tracks whether the previous voltage readout reported by the sensor was 0 (no contact).

_check_state

The code for the CheckState module command.

_monitoring

Tracks whether the instance is currently configured to monitor the managed lick sensor’s state.

initialize_local_assets()

Connects to the instance’s shared memory buffer and enables buffer cleanup at shutdown.

Return type:

None

initialize_remote_assets()

Connects to the instance’s shared memory buffer.

Return type:

None

property lick_count: uint64

Returns the total number of licks detected by the module since the runtime onset.

property lick_threshold: uint16

Returns the voltage threshold, in raw ADC units of a 12-bit Analog-to-Digital voltage converter, interpreted as the animal licking at the sensor.

process_received_data(message)

Updates the lick event data stored in the instance’s shared memory buffer based on the messages received from the microcontroller.

Return type:

None

set_monitoring_state(*, state)

Configures the module to start or stop continuously monitoring the managed sensor’s state.

Parameters:

state (bool) – Determines whether to start or stop monitoring the managed sensor’s state.

Return type:

None

set_parameters(signal_threshold, delta_threshold, average_pool_size)

Sets the module’s PC-addressable runtime parameters to the input values.

Parameters:
  • signal_threshold (uint16) – The minimum voltage level, in raw analog units of a 3.3 Volt 12-bit Analog-to-Digital-Converter (ADC), reported to the PC as a significant sensor interaction. Note: signals below the threshold are pulled to 0.

  • delta_threshold (uint16) – The minimum difference between two consecutive voltage level readouts for reporting the new signal value to the PC.

  • average_pool_size (uint8) – The number of analog pin readouts to average together when checking the sensor’s state.

Return type:

None

terminate_remote_assets()

Disconnects from the instance’s shared memory buffer.

Return type:

None

class sl_experiment.shared_components.ScreenInterface

Bases: ModuleInterface

Interfaces with ScreenModule instances running on the Actor MicroController.

Notes

Type code 7.

This interface expects that the managed screens are turned OFF when the interface is initialized.

_toggle

The code for the Toggle module command.

_enabled

Tracks the current state of the managed screens.

initialize_remote_assets()

Not used.

Return type:

None

process_received_data(_message)

Not used, as the module currently does not require any real-time data processing.

Return type:

None

set_parameters(pulse_duration)

Sets the module’s PC-addressable runtime parameters to the input values.

Parameters:

pulse_duration (uint32) – The duration, in microseconds, of each emitted screen state toggle TTL pulse.

Return type:

None

set_state(*, state)

Sets the screens to the desired power state.

Parameters:

state (bool) – The desired screen power state. True means the screens are powered on; False means the screens are powered off.

Return type:

None

property state: bool

Returns True if the screens are currently powered on; False otherwise.

terminate_remote_assets()

Not used.

Return type:

None

class sl_experiment.shared_components.SurgeryLog(project_name, animal_id, credentials_path, sheet_id)

Bases: object

Interfaces with the Sun lab’s surgery log Google Sheet.

Notes

This class is purpose-built to work with the specific surgery log format used in the Sun lab.

Parameters:
  • project_name (str) – The name of the project for which to access the surgery log data.

  • animal_id (int) – The unique identifier of the animal for which to access the surgery log data.

  • credentials_path (Path) – The path to the .JSON file containing the service account credentials for accessing the surgery log.

  • sheet_id (str) – The unique identifier of the Google Sheet that contains the surgery log data.

_project_name

The name of the target project.

_animal_id

The unique identifier of the target animal.

_sheet_id

The unique identifier of the surgery log Google Sheet.

_service

The API service instance that bidirectionally interfaces with the surgery log.

_headers

Maps the surgery log headers (column names) to the Excel-style Google Sheet column letters (A, B, etc.).

_animals

Stores the unique identifiers of all animals whose data is stored in the surgery log.

Raises:

ValueError – If the target Google Sheet is not a valid Sun lab surgery log.

extract_animal_data()

Extracts and returns the processed animal’s surgical intervention data as a SurgeryData object.

Return type:

SurgeryData

Returns:

A SurgeryData instance that stores the extracted data.

update_surgery_quality(quality)

Updates the processed animal’s surgery quality value to the input value.

Parameters:

quality (int) – The integer value that reflects the quality of the animal’s surgical intervention for scientific data acquisition on a scale from 0 (unusable) to 3 (high-grade scientific publication).

Return type:

None

class sl_experiment.shared_components.TTLInterface(polling_frequency)

Bases: ModuleInterface

Interfaces with TTLModule instances running on the Sensor MicroController.

Parameters:

polling_frequency (int) – The frequency, in microseconds, at which to check for incoming TTL signals when monitoring the TTL sensor.

_polling_frequency

The frequency, in microseconds, at which to check for incoming TTL signals when monitoring the TTL sensor.

_pulse_tracker

The SharedMemoryArray instance that transfers the TTL pulse data collected by the module from the communication process to other runtime processes.

_check_state

The code for the CheckState module command.

_monitoring

Tracks whether the instance is currently configured to monitor the incoming TTL signals.

initialize_local_assets()

Connects to the instance’s shared memory buffer and enables buffer cleanup at shutdown.

Return type:

None

initialize_remote_assets()

Connects to the instance’s shared memory buffer.

Return type:

None

process_received_data(message)

Updates the TTL pulse count stored in the instance’s shared memory buffer based on the messages received from the microcontroller.

Return type:

None

property pulse_count: uint64

Returns the number of received TTL pulses recorded by the module since runtime onset.

reset_pulse_count()

Resets the TTL pulse tracker to zero.

Return type:

None

set_monitoring_state(*, state)

Configures the module to start or stop continuously monitoring the managed sensor’s state.

Parameters:

state (bool) – Determines whether to start or stop monitoring the managed sensor’s state.

Return type:

None

set_parameters(averaging_pool_size)

Sets the module’s PC-addressable runtime parameters to the input values.

Parameters:

averaging_pool_size (uint8) – The number of sensor readouts to average together when checking the incoming TTL signal state.

Return type:

None

terminate_remote_assets()

Disconnects from the instance’s shared memory buffer.

Return type:

None

class sl_experiment.shared_components.TorqueInterface(baseline_voltage, maximum_voltage, sensor_capacity, polling_frequency)

Bases: ModuleInterface

Interfaces with TorqueModule instances running on the Sensor MicroController.

Notes

Type code 6.

Parameters:
  • baseline_voltage (int) – The voltage level, in raw analog units measured by a 3.3 Volt 12-bit Analog-to-Digital-Converter module, that corresponds to no torque (0) readout.

  • maximum_voltage (int) – The voltage level, in raw analog units measured by a 3.3 Volt 12-bit Analog-to-Digital-Converter module, that corresponds to the absolute maximum torque detectable by the sensor.

  • sensor_capacity (float) – The maximum torque level, in grams centimeter (g cm) detectable by the sensor.

  • polling_frequency (int) – The frequency, in microseconds, at which to check the torque sensor’s state when monitoring the sensor.

_polling_frequency

The frequency, in microseconds, at which to check the torque sensor’s state when monitoring the sensor.

_torque_per_adc_unit

The conversion factor that translates the raw analog units of a 3.3 Volt 12-bit ADC to torque in Newtons centimeter.

_check_state

The code for the CheckState module command.

_monitoring

Tracks whether the instance is currently configured to monitor the managed torque sensor’s state.

initialize_remote_assets()

Not used.

Return type:

None

process_received_data(_message)

Not used, as the module currently does not require real-time data processing.

Return type:

None

set_monitoring_state(*, state)

Configures the module to start or stop continuously monitoring the managed sensor’s state.

Parameters:

state (bool) – Determines whether to start or stop monitoring the managed sensor’s state.

Return type:

None

set_parameters(report_ccw, report_cw, signal_threshold, delta_threshold, averaging_pool_size)

Sets the module’s PC-addressable runtime parameters to the input values.

Parameters:
  • report_ccw (bool) – Determines whether the sensor should report torques in the counterclockwise (CCW; positive) direction.

  • report_cw (bool) – Determines whether the sensor should report torque in the clockwise (CW; negative) direction.

  • signal_threshold (uint16) – The minimum torque level, in raw analog units of 12-bit Analog-to-Digital-Converter (ADC), reported to the PC as a significant torque signal. Note: signals below the threshold are pulled to 0.

  • delta_threshold (uint16) – The minimum difference between two consecutive torque level readouts for reporting the new signal value to the PC.

  • averaging_pool_size (uint8) – The number of analog pin readouts to average together when checking the sensor’s state.

Return type:

None

terminate_remote_assets()

Not used.

Return type:

None

property torque_per_adc_unit: float64

Returns the conversion factor that translates the raw analog values recorded by the 3.3 Volt 12-bit ADC into torque in Newton centimeter.

class sl_experiment.shared_components.ValveInterface(valve_calibration_data)

Bases: ModuleInterface

Interfaces with ValveModule instances running on the Actor MicroController.

Notes

Type code 5.

Parameters:

valve_calibration_data (tuple[tuple[int | float, int | float], ...]) – Maps the valve open durations to delivered fluid volumes.

_calibration_count

The number of reward delivery cycles to use during calibration and referencing procedures.

_scale_coefficient

The scale coefficient derived from the fitting the power law model to the valve’s calibration data.

_nonlinearity_exponent

The intercept derived from the fitting the power law model to the valve’s calibration data.

_valve_tracker

The SharedMemoryArray instance that transfers the reward data collected by the module from the communication process to other runtime processes.

_reward

The code for the Pulse module command.

_open

The code for the Open module command.

_close

The code for the Close module command.

_calibrate

The code for the Calibrate module command.

_tone

The code for the Tone module command.

_previous_module_state

Tracks the valve’s state reported by the last received message sent from the microcontroller.

_configured_valve_state

Tracks the current state of the valve (Open or Closed) set through this interface instance.

_previous_volume

Tracks the volume of water the valve was instructed to dispense during the previous reward delivery.

_previous_tone_duration

Tracks the tone duration used during the previous reward delivery or simulation.

_cycle_timer

A PrecisionTimer instance that tracks how long the valve stays open during reward delivery.

calibrate_valve(pulse_duration)

Repeatedly opens the valve for the requested number of milliseconds to determine the volume of fluid dispensed through the valve during this period of time.

Parameters:

pulse_duration (int) – The duration, in milliseconds, to keep the valve open at each calibration cycle.

Return type:

None

property calibrating: bool

Returns True if the module is currently performing a valve calibration cycle and False otherwise.

deliver_reward(volume=5.0, tone_duration=300)

Opens the valve for the duration of time necessary to deliver the requested volume of water.

Parameters:
  • volume (float, default: 5.0) – The volume of water to deliver, in microliters.

  • tone_duration (int, default: 300) – The duration of the auditory tone, in milliseconds, to emit while delivering the water reward.

Return type:

None

property delivered_volume: float64

Returns the total volume of water, in microliters, delivered by the valve since the runtime onset.

get_duration_from_volume(target_volume)

Converts the input volume of water, in microliters, to the required period of time, in microseconds, the managed valve must stay open to deliver the specified volume.

Parameters:

target_volume (float) – The volume of water, in microliters, to deliver.

Raises:

ValueError – If the desired water volume is too small to be reliably dispensed by the valve, based on its calibration data.

Return type:

uint32

Returns:

The duration, in microseconds, the valve needs to stay open to deliver the specified volume.

initialize_local_assets()

Connects to the instance’s shared memory buffer and enables buffer cleanup at shutdown.

Return type:

None

initialize_remote_assets()

Connects to the instance’s shared memory buffer and initializes the cycle PrecisionTimer.

Return type:

None

property nonlinearity_exponent: float64

Returns the nonlinearity exponent (B) of the power-law model fitted to the valve’s calibration data.

process_received_data(message)

Updates the reward data stored in the instance’s shared memory buffer based on the messages received from the microcontroller.

Return type:

None

reference_valve()

Opens the valve 200 times for the duration necessary to deliver 5 microliters of water to verify the valve’s calibration.

Return type:

None

Notes

A well-calibrated valve is expected to deliver 1.0 milliliter of water during this procedure.

property scale_coefficient: float64

Returns the scale coefficient (A) of the power-law model fitted to the valve’s calibration data.

set_state(*, state)

Sets the managed valve to the desired state.

Parameters:

state (bool) – The desired state of the valve. True means the valve is open; False means the valve is closed.

Return type:

None

simulate_reward(tone_duration=300)

Simulates delivering water reward by emitting an audible ‘reward’ tone without opening the valve.

Parameters:

tone_duration (int, default: 300) – The duration of the auditory tone, in milliseconds, to emit while simulating the water reward delivery.

Return type:

None

terminate_remote_assets()

Disconnects from the instance’s shared memory buffer.

Return type:

None

class sl_experiment.shared_components.WaterLog(animal_id, session_date, credentials_path, sheet_id)

Bases: object

Interfaces with the Sun lab’s water restriction and animal interaction log Google Sheet.

Notes

This class is purpose-built to work with the specific water restriction and animal interaction log format used in the Sun lab.

This class is specifically designed to access the log data in a ‘session-oriented’ format. Specifically, it assumes that the log is accessed as part of a data acquisition session that uses a specific row to store all session-specific data.

Parameters:
  • animal_id (int) – The unique identifier of the animal for which to access the log data.

  • session_date (str) – The date of the data acquisition session for which to access the log data, in the format YYYY-MM-DD-HH-MM-SS-US.

  • credentials_path (Path) – The path to the .JSON file containing the service account credentials for accessing the water restriction and animal interaction log.

  • sheet_id (str) – The unique identifier of the Google Sheet that contains the water restriction and animal interaction data.

_sheet_id

The unique identifier of the water restriction and animal interaction log Google Sheet.

_service

The API service instance that bidirectionally interfaces with the log.

_animals

Stores the unique identifiers of all animals whose data is stored in the log.

_headers

Maps the water restriction and animal interaction log headers (column names) to the Excel-style Google Sheet column letters (A, B, etc.).

_animal_tab_id

The unique identifier of the log’s tab that stores the target animal’s data.

_current_time

The current ETC/EDT time in the HH:MM format.

_session_row_index

The index of the log’s row that stores the processed session’s data.

Raises:

ValueError – If the target Google Sheet is not a valid Sun lab water restriction and animal interaction log.

update_water_log(weight, water_ml, experimenter_id, session_type)

Updates the processed data acquisition session’s row in the processed log file with the input animal’s data.

Notes

For this method to work as intended, the processed log tab must be pre-filled to contain the processed session’s date.

Parameters:
  • weight (float) – The weight of the animal, in grams, at the onset of the data acquisition session.

  • water_ml (float) – The combined volume of water, in milliliters, given to the animal by the acquisition system during runtime and by the experimenter after the runtime.

  • experimenter_id (str) – The unique identifier of the experimenter supervising the data acquisition session.

  • session_type (str) – The type of the data acquisition session.

Return type:

None

sl_experiment.shared_components.get_animal_project(animal_id)

Scans the local project directory and returns the names of all projects that use the target animal.

Parameters:

animal_id (str) – The unique identifier of the animal for which to discover the projects that use this animal.

Return type:

tuple[str, ...]

Returns:

A tuple of project names that use the target animal.

sl_experiment.shared_components.get_project_experiments(project, filesystem_configuration)

Discovers the available experiment configuration files for the target project.

Parameters:
  • project (str) – The name of the project for which to discover the experiment configurations.

  • filesystem_configuration (MesoscopeFileSystem) – The MesoscopeFileSystem instance that stores the filesystem configuration of the data acquisition system used to acquire the specified project’s data.

Return type:

tuple[str, ...]

Returns:

A tuple of naturally-sorted experiment configurations available for the target project.

sl_experiment.shared_components.get_version_data()

Returns the current Python and sl-experiment versions.

Return type:

tuple[str, str]

Returns:

A tuple of two strings. The first string stores the Python version, and the second string stores the sl-experiment version.