Mesoscope-VR Acquisition System¶
Provides the assets for acquiring and preprocessing data via the Mesoscope-VR data acquisition system.
- class sollertia_experiment.mesoscope_vr.MesoscopePositions(mesoscope_x=0.0, mesoscope_y=0.0, mesoscope_roll=0.0, mesoscope_z=0.0, mesoscope_fast_z=0.0, mesoscope_tip=0.0, mesoscope_tilt=0.0, laser_power_mw=0.0, red_dot_alignment_z=0.0)¶
Bases:
YamlConfigStores the positions of real and virtual Mesoscope imaging axes reused between experiment sessions that use the Mesoscope-VR system.
- laser_power_mw: float = 0.0¶
The laser excitation power at the sample, in milliwatts.
- mesoscope_fast_z: float = 0.0¶
The ScanImage’s FastZ (virtual Z-axis) position, in micrometers.
- mesoscope_roll: float = 0.0¶
The Mesoscope objective’s Roll-axis position, in degrees.
- mesoscope_tilt: float = 0.0¶
The ScanImage’s Tilt position, in degrees.
- mesoscope_tip: float = 0.0¶
The ScanImage’s Tip position, in degrees.
- mesoscope_x: float = 0.0¶
The Mesoscope objective’s X-axis position, in micrometers.
- mesoscope_y: float = 0.0¶
The Mesoscope objective’s Y-axis position, in micrometers.
- mesoscope_z: float = 0.0¶
The Mesoscope objective’s Z-axis position, in micrometers.
- red_dot_alignment_z: float = 0.0¶
The Mesoscope objective’s Z-axis position, in micrometers, used for the red-dot alignment procedure.
- class sollertia_experiment.mesoscope_vr.MesoscopeSystemConfiguration(name='mesoscope', filesystem=<factory>, sheets=<factory>, cameras=<factory>, microcontrollers=<factory>, acquisition=<factory>, assets=<factory>, video_tracking=<factory>)¶
Bases:
SystemConfigurationDefines the hardware and software asset configuration for the Mesoscope-VR data acquisition system.
- acquisition: MesoscopeAcquisition¶
Stores the Mesoscope motion-estimation and z-stack acquisition configuration.
- assets: MesoscopeVRAssets¶
Stores the Virtual Reality task asset configuration.
- cameras: MesoscopeCameras¶
Stores the video cameras configuration.
- filesystem: _MesoscopeFileSystem¶
Stores the filesystem configuration.
- microcontrollers: MesoscopeMicroControllers¶
Stores the microcontrollers configuration.
- name: str = 'mesoscope'¶
The descriptive name of the data acquisition system.
- save(path)¶
Saves the instance’s data to disk as a .yaml file.
Notes
Path and Enum fields are serialized automatically by YamlConfig. The valve_calibration_data tuple is temporarily converted to a dict for serialization so that existing .yaml files retain their mapping layout for the calibration table, then restored after the write.
- Parameters:
path (
Path) – The destination .yaml file path.- Return type:
None
- sheets: MesoscopeGoogleSheets¶
Stores the identifiers for the Google Sheets.
- video_tracking: MesoscopeVideoTracking¶
Stores the DeepLabCut face-camera eye-tracking inference configuration.
- class sollertia_experiment.mesoscope_vr.ZaberPositions(headbar_z=0, headbar_pitch=0, headbar_roll=0, lickport_z=0, lickport_y=0, lickport_x=0, wheel_x=0)¶
Bases:
YamlConfigStores Zaber motor positions reused between data acquisition sessions that use the Mesoscope-VR system.
- headbar_pitch: int = 0¶
The absolute position, in native motor units, of the HeadBar pitch-axis motor.
- headbar_roll: int = 0¶
The absolute position, in native motor units, of the HeadBar roll-axis motor.
- headbar_z: int = 0¶
The absolute position, in native motor units, of the HeadBar z-axis motor.
- lickport_x: int = 0¶
The absolute position, in native motor units, of the LickPort x-axis motor.
- lickport_y: int = 0¶
The absolute position, in native motor units, of the LickPort y-axis motor.
- lickport_z: int = 0¶
The absolute position, in native motor units, of the LickPort z-axis motor.
- wheel_x: int = 0¶
The absolute position, in native motor units, of the running wheel platform x-axis motor.
- sollertia_experiment.mesoscope_vr.build_filesystem_paths_report(configuration)¶
Builds a per-path diagnostic report for the filesystem configuration of the Mesoscope-VR system.
Notes
Long-term storage destinations whose root is left unset are reported as not configured rather than as errors, since configuring them is optional. The optional input files follow the same convention, so a host that runs without stored camera configurations or without face-camera inference still reports a healthy filesystem. The mesoscope acquisition directory is required by this acquisition system, so an unset value there is reported as both not configured and not ok.
- Parameters:
configuration (
MesoscopeSystemConfiguration) – The Mesoscope-VR system configuration whose filesystem paths the report covers.- Return type:
dict[str,Any]- Returns:
A dictionary mapping each configuration path name to its diagnostic report.
- sollertia_experiment.mesoscope_vr.check_dlc_project_task(project_path)¶
Checks that the configured DeepLabCut project is able to produce predictions accepted by preprocessing.
Notes
DeepLabCut embeds the project’s ‘Task’ field verbatim in the scorer string it appends to every prediction filename. Session preprocessing accepts a prediction only when that filename carries the eye-tracking token, so a project whose ‘Task’ field omits the token aborts the data transfer at the very end of a session’s preprocessing. Reporting the mismatch here surfaces it before any session is acquired.
- Parameters:
project_path (
Path) – The path to the DeepLabCut project’s config.yaml file.- Return type:
str|None- Returns:
The description of why the project is unable to satisfy the eye-tracking token requirement, or None when it satisfies the requirement.
- sollertia_experiment.mesoscope_vr.check_mesoscope_bridge()¶
Probes whether the ScanImagePC’s runAcquisition control loop is reachable over the shared MQTT broker.
Notes
Loads the active Mesoscope-VR system configuration to resolve the shared broker address, connects to the broker, issues a single bounded liveness probe, and disconnects. An unreachable interface means the operator has not launched the runAcquisition function on the ScanImagePC.
- Return type:
tuple[bool,str]- Returns:
A two-element tuple whose first element is True when the ScanImagePC acknowledged the probe within the timeout and whose second element is a one-line human-readable status summary.
- sollertia_experiment.mesoscope_vr.create_experiment_configuration_file(project, experiment, template, state_count, reward_size, reward_tone_duration, puff_duration, *, overwrite=False)¶
Creates a Mesoscope-VR experiment configuration file from a task template under the configured data root.
Resolves the target project directory under the local data root and instantiates the named task template from the configured task templates directory. The resulting Mesoscope-VR experiment configuration carries the provided trial defaults and the requested number of default-valued runtime states, and it is written to the project’s configuration directory.
- Parameters:
project (
str) – The name of the project under which to create the experiment configuration file.experiment (
str) – The name of the experiment, used as the stem of the created configuration file.template (
str) – The name of the task template to instantiate, given as the template filename without the .yaml extension.state_count (
int) – The number of default-valued runtime states to generate.reward_size (
float) – The default water reward volume, in microliters, for lick-type trials.reward_tone_duration (
int) – The default reward tone duration, in milliseconds, for lick-type trials.puff_duration (
int) – The default gas puff duration, in milliseconds, for occupancy-type trials.overwrite (
bool, default:False) – Determines whether to replace an existing experiment configuration file at the destination.
- Raises:
ValueError – If the target project does not exist under the data root.
FileNotFoundError – If the named task template does not exist in the configured task templates directory.
FileExistsError – If the destination configuration file exists and overwrite is False.
- Return type:
None
- sollertia_experiment.mesoscope_vr.create_system_configuration_file()¶
Creates the .yaml configuration file for the Mesoscope-VR data acquisition system and configures the local machine (PC) to use this file for all future acquisition-system-related calls.
- Return type:
None
- sollertia_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 defined 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.
- Raises:
FileNotFoundError – If the target project does not carry an experiment configuration file named after the requested experiment.
ValueError – If the experiment configuration uses a Mesoscope-VR system state code outside the supported set, or if the maximum number of unconsumed rewards is negative.
- Return type:
None
- sollertia_experiment.mesoscope_vr.get_system_configuration()¶
Loads the local system configuration file and verifies that the host-machine belongs to the Mesoscope-VR data acquisition system.
- Return type:
- Returns:
The initialized MesoscopeSystemConfiguration instance that stores the loaded configuration parameters.
- Raises:
FileNotFoundError – If the local working directory does not contain exactly one system configuration file.
ValueError – If the local configuration file does not belong to any registered acquisition system.
TypeError – If the host-machine does not belong to the Mesoscope-VR data acquisition system.
- sollertia_experiment.mesoscope_vr.get_system_configuration_path()¶
Resolves the path to the local machine’s data acquisition system configuration file.
A host-machine belongs to exactly one acquisition system, so its working directory must contain exactly one
*_system_configuration.yamlfile.- Return type:
Path- Returns:
The path to the single local system configuration file.
- Raises:
FileNotFoundError – If the local working directory does not contain exactly one system configuration file.
- sollertia_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.
- Raises:
ValueError – If the maximum number of unconsumed rewards is negative, or if the maximum water volume is not greater than zero milliliters. Also raised if that volume cannot fund a single reward of the requested size, or if the maximum training time is shorter than the minimum reward delay.
- Return type:
None
- sollertia_experiment.mesoscope_vr.maintenance_logic()¶
Encapsulates the logic used to maintain a subset of the Mesoscope-VR system’s hardware components.
- Raises:
RuntimeError – If the maintenance GUI process terminates without requesting the runtime shutdown, which leaves the runtime without a way to control the managed hardware.
- Return type:
None
- sollertia_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.
Notes
The migration strategy depends on whether the host-machine is configured with any long-term storage destinations. Systems with at least one configured destination treat the preferred (first configured) destination as the source of truth. They preprocess any sessions that still reside only on the host machine, then pull, re-preprocess, and purge each session. Systems without any configured destination keep all data on the acquisition host machine, so the migration reduces to an on-premises operation that relocates each locally stored session to the target project directory and reassigns it. The persistent data relocation and the cleanup of redundant directories apply to both modes.
The migration fails with an error if any session cannot be preprocessed or migrated. In the destination-backed mode, each session is handled as an isolated unit that removes its in-flight source-project directory on failure, so re-running the migration after resolving the error resumes from the failed session without manual intervention. The on-premises mode relocates each session with a move that is not rolled back. A failure after the move leaves that session under the target project while its record still names the source project, and a re-run no longer sees it. That case requires manual repair.
- 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.
- Raises:
FileNotFoundError – If the target project does not exist on the host machine.
- Return type:
None
- sollertia_experiment.mesoscope_vr.preprocess_session_data(session_data)¶
Aggregates the session’s data on the VRPC, compresses it for efficient network transmission, transfers the data to all configured long-term storage destinations, and removes the local data copy from the VRPC.
Notes
If no long-term storage destinations are configured for the host-machine, the data transfer and the local data removal are skipped, and the preprocessing is limited to on-premises data conversion and aggregation steps.
A session that still carries the ‘nk.bin’ uninitialized-session marker never finished initialization and holds no valid data. Such a session is purged from all storage locations instead of being preprocessed.
- Parameters:
session_data (
SessionData) – The SessionData instance that defines the processed session.- Return type:
None
- sollertia_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
- sollertia_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.
- Raises:
ValueError – If the maximum number of unconsumed rewards is negative, or if the maximum training time is not greater than zero minutes.
- Return type:
None
- sollertia_experiment.mesoscope_vr.window_checking_logic(experimenter, project_name, animal_id)¶
Guides the user through verifying the quality of the implanted cranial window and generating the animal’s initial Zaber and Mesoscope position snapshots.
- 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
- sollertia_experiment.mesoscope_vr.data_preprocessing.EYE_TRACKING_PROJECT_NAME: str = 'eye_tracking'¶
The DeepLabCut project name token that has to appear in the eye-tracking prediction filename. DeepLabCut names each prediction after the analyzed video’s stem followed by its scorer string, and the scorer embeds the project’s ‘Task’ field verbatim. The project that the acquisition system is configured to use therefore has to carry this name for sollertia-forgery’s locate_mesoscope_pose_predictions to resolve the prediction downstream.
Virtual Reality Task Interface¶
Provides the acquisition-system-agnostic interface for the Unity Virtual Reality tasks.
- class sollertia_experiment.vr_task.StimulusCause(*values)¶
Bases:
StrEnumDefines the cause of a trial’s stimulus outcome as reported by Unity.
Unity stamps this on every Stimulus message so the acquisition system can distinguish a self-driven success from a guidance-driven outcome without knowing the appetitive-or-aversive stimulus valence.
- BEHAVIOR = 'behavior'¶
The animal’s own action produced the outcome.
- GUIDANCE = 'guidance'¶
The guidance fallback produced the outcome.
- class sollertia_experiment.vr_task.UnityBridgeClient(host='127.0.0.1', port=8090)¶
Bases:
objectDrives Unity Editor scene activation and play-mode transitions over the editor-only MCP Bridge.
Wraps the bridge’s HTTP JSON tool protocol exposed by McpBridge.cs in sollertia-virtual-reality. Every call POSTs a single short-timeout localhost request and raises UnityBridgeError on a connection failure or a failed tool response, letting the caller decide between retrying, surfacing the error, or probing reachability.
Notes
Methods raise UnityBridgeError directly rather than through console.error because reachability probing catches the error as part of normal control flow. Logging every probe failure as an error would be misleading when the editor is simply closed, so error reporting is deferred to the driver layer.
- Parameters:
host (
str, default:'127.0.0.1') – The loopback host on which the bridge listens.port (
int, default:8090) – The TCP port on which the bridge listens.
- _url¶
The fully-formed bridge endpoint to which every tool call is POSTed.
- _client¶
The httpx2 client that issues bridge requests.
- close()¶
Closes the underlying httpx2 client and releases its connection pool.
- Return type:
None
- describe_status()¶
Returns a one-line human-readable summary of the bridge’s reachability, active scene, and play state.
- Return type:
str
- enter_play_mode()¶
Requests the editor to enter Play Mode.
- Return type:
str- Returns:
The post-request play state reported by the bridge, either “playing” when the editor was already playing or “entering_play_mode” when the transition was just triggered.
- Raises:
UnityBridgeError – If the bridge is unreachable or the response omits the play state.
- exit_play_mode()¶
Requests the editor to exit Play Mode.
- Return type:
str- Returns:
The post-request play state reported by the bridge, either “edit” when the editor was not playing or “exiting_play_mode” when the transition was just triggered.
- Raises:
UnityBridgeError – If the bridge is unreachable or the response omits the play state.
- get_active_controller()¶
Returns the GameObject name of the motion controller currently bound to the active scene’s actor.
Notes
The read runs in Edit Mode and does not modify the scene, so the caller can probe the bound controller before deciding whether a corrective write is necessary.
- Return type:
str- Returns:
The name of the controller the scene’s actor currently references.
- Raises:
UnityBridgeError – If the bridge is unreachable or omits the actor controller from its response.
- get_play_state()¶
Requests the editor’s current play state and active scene name.
- Return type:
tuple[str,str]- Returns:
A two-element tuple whose first element is the play state (“playing”, “compiling”, or “edit”) and whose second element is the active scene’s name without its file extension.
- Raises:
UnityBridgeError – If the bridge is unreachable or the response omits the expected fields.
- is_reachable()¶
Returns True when the bridge responds to a play-state probe and False when it raises UnityBridgeError.
- Return type:
bool
- open_scene(scene_path, unsaved_changes='save')¶
Opens the scene at the given project-relative path, applying the unsaved-changes policy.
- Parameters:
scene_path (
str) – The project-relative path of the scene to open.unsaved_changes (
Literal['','save','discard'], default:'save') – The policy applied when the active scene has unsaved edits. A “save” value persists them before switching, “discard” abandons them, and an empty value leaves the policy unspecified.
- Raises:
UnityBridgeError – If the bridge is unreachable or refuses to open the scene.
- Return type:
None
- resolve_scene_path(scene_name)¶
Resolves a scene name to its project-relative path using the project’s scene listing.
- Parameters:
scene_name (
str) – The scene name to resolve, matched against each scene path’s stem.- Return type:
str- Returns:
The project-relative path of the scene whose file stem equals the given name.
- Raises:
UnityBridgeError – If the bridge is unreachable or no scene with a matching name exists in the project.
- set_active_controller(controller_name)¶
Sets the active scene actor’s motion controller and returns the controller the scene reports afterward.
Notes
The write only marks the scene dirty, so the caller must issue it while the editor is in Edit Mode for the change to take effect on the next Play Mode entry.
- Parameters:
controller_name (
str) – The GameObject name of the controller to bind to the scene’s actor, matched against the controllers present in the scene by the bridge.- Return type:
str- Returns:
The name of the controller the scene’s actor references after the write. A value that differs from the requested name indicates the write did not take effect.
- Raises:
UnityBridgeError – If the bridge is unreachable, rejects the controller name, or omits the actor controller from its response.
- class sollertia_experiment.vr_task.VRTaskConfiguration(ip='127.0.0.1', port=1883)¶
Bases:
objectStores the configuration used to connect to the Unity game engine that runs the Virtual Reality task.
Notes
This configuration only stores the MQTT broker discovery fields used to reach Unity. The geometric VR parameters (cue catalog, corridor geometry, cm-per-unity-unit conversion) are resolved at experiment-start from the matching TaskTemplate YAML in the shared VR task templates directory.
- ip: str¶
The IP address of the MQTT broker used to communicate with the Unity game engine.
- port: int¶
The port number of the MQTT broker used to communicate with the Unity game engine.
- class sollertia_experiment.vr_task.VRTaskDriver(configuration, *, task_template, expected_scene_name)¶
Bases:
objectDrives the Unity game engine that runs the Virtual Reality task implemented in sollertia-virtual-reality.
Encapsulates the MQTT contract with Unity: connection lifecycle, scene handshake, VR display verification, wall cue sequence retrieval, per-cycle stimulus pump, guidance toggling, and resume-after-Unity-restart. The driver is hardware-agnostic, and per-cycle Unity events are surfaced as typed _VRTaskEvent values that the caller dispatches to acquisition system hardware.
- Parameters:
configuration (
VRTaskConfiguration) – The runtime configuration that defines the MQTT broker discovery fields.task_template (
TaskTemplate) – The VR TaskTemplate that defines the cue catalog, corridor geometry, per-trial spatial cue sequences, and per-trial trigger types for the active Unity scene.expected_scene_name (
str) – The Unity scene name the driver enforces during the setup handshake.
- _configuration¶
The VRTaskConfiguration instance that defines the MQTT broker discovery fields.
- _task_template¶
The VR TaskTemplate consumed during cue sequence decomposition.
- _expected_scene_name¶
The Unity scene name enforced during the setup handshake.
- _mqtt¶
The MQTTCommunication instance that bidirectionally transfers data between this driver and Unity.
- _state¶
The _VRTaskState instance that tracks the Virtual Reality task environment state.
- _motif_decomposer¶
The CachedMotifDecomposer used to flatten and cache trial motif data between decomposition runs.
- _decomposed_trials¶
The DecomposedTrials produced by the most recent cue sequence decomposition.
- _polling_timer¶
The PrecisionTimer used to delay between consecutive Unity buffer polls during the setup sequence.
- _bridge¶
The UnityBridgeClient used to drive Unity scene activation and Play Mode through the editor MCP Bridge.
- connect()¶
Establishes the MQTT connection to the Unity game engine.
- Return type:
None
- property cue_sequence_distances: NDArray[float64]¶
Returns the cumulative distances, in centimeters, the animal must travel to complete each decomposed trial.
- cycle()¶
Consumes the next pending Unity message and returns it as a typed event.
Notes
The driver consumes at most one message from the MQTT buffer per cycle.
- Return type:
_VRTaskEvent- Returns:
The _VRTaskEvent describing the Unity message that was just parsed. When the MQTT buffer is empty, the event kind is NONE. The event kind is also NONE when the consumed message is on a non-surfaced (handshake) topic, such as SESSION_START, SCENE_NAME, or CUE_SEQUENCE.
- disconnect()¶
Stops the active Unity scene and closes the MQTT and bridge connections to the Unity game engine.
- Return type:
None
Notes
Exits Play Mode through the bridge before tearing down the connections so the Unity scene does not keep running after the session ends. Every step is isolated, so an unreachable editor or broker still leaves the remaining connections closed.
- push_lick_event()¶
Notifies Unity that the animal engaged the interaction sensor.
- Return type:
None
Notes
The Mesoscope-VR system’s interaction sensor is the lick port, so this method retains the lick name the system layer uses. It publishes on Unity’s generic Interaction topic.
- push_position(absolute_position)¶
Forwards the latest animal position to Unity as a movement delta.
Notes
The driver internally tracks the last absolute position passed to this method and only emits an MQTT message when the position has changed.
- Parameters:
absolute_position (
float64) – The current absolute position of the animal, in Unity units, relative to the origin of the Virtual Reality task environment’s track.- Return type:
None
- resume_after_unity_restart()¶
Re-arms Unity through the bridge after an emergency pause and re-fetches the wall cue sequence.
- Return type:
None
Notes
An emergency pause occurs when Unity reports that its runtime terminated. This method ensures the editor is reachable, re-arms Unity via the bridge, re-publishes the tracked guidance modes, re-queries the regenerated wall cue sequence so the animal’s Virtual Reality position is tracked accurately after the reset, and clears the termination flag.
A fresh Play Mode session reloads Unity’s interaction and wait requirements from the values serialized into the task prefab, and Unity never queries the driver for them. Re-publishing both guidance modes restores the requirements the operator selected for the session.
- set_aversive_guidance(*, enabled)¶
Sets the aversive trial guidance mode.
- Parameters:
enabled (
bool) – Determines whether to enable or disable aversive guidance.- Return type:
None
- set_reinforcing_guidance(*, enabled)¶
Sets the reinforcing trial guidance mode.
- Parameters:
enabled (
bool) – Determines whether to enable or disable reinforcing guidance.- Return type:
None
- setup()¶
Carries out the Unity setup sequence used at the start of a session.
- Return type:
None
Notes
Requires the Unity Editor MCP Bridge to be reachable. The sequence opens the expected scene, arms Unity, verifies the active scene matches the expected one, prompts the operator to verify the VR display, and requests the wall cue sequence used by the task. Scene activation and Play Mode control are issued through the bridge, and the operator only confirms that the VR display renders correctly.
The caller must enable the VR screens before invoking this method and disable them once it returns, as the display verification stage relies on the screens rendering the active scene.
- property state: _VRTaskState¶
Returns the current Virtual Reality task state tracked by the driver.
- property trial_names: tuple[str, ...]¶
Returns the name of each decomposed trial, in sequence order.
- class sollertia_experiment.vr_task.VRTaskEventKind(*values)¶
Bases:
IntEnumDefines the kinds of Virtual Reality task events produced by the VRTaskDriver per runtime cycle.
Notes
This enumeration intentionally covers only the asynchronous Unity messages surfaced by cycle() for the caller to dispatch. Messages that arrive as synchronous handshake replies are resolved internally by the driver and are deliberately excluded.
- NONE = 0¶
either the MQTT buffer was empty, or the consumed message was on a topic that cycle() does not surface (a handshake topic).
- Type:
No dispatchable Unity event was produced this cycle
- STIMULUS_TRIGGERED = 1¶
A trial resolved its stimulus outcome. The event’s trial_name, delivered, and cause carry the result.
- TRIGGER_DELAY_REQUESTED = 2¶
Unity requested the acquisition system to apply a brake pulse for the specified duration.
- UNITY_TERMINATED = 3¶
Unity reported that its runtime has been terminated, so the acquisition system must enter an emergency pause.
- sollertia_experiment.vr_task.load_vr_task_template(unity_scene_name)¶
Loads the VR TaskTemplate that corresponds to the given Unity scene name.
Notes
Templates are resolved from the task templates directory persisted by the sollertia-shared-assets ‘slsa configure templates’ CLI command. The template file name is expected to match the Unity scene name with a ‘.yaml’ suffix.
- Parameters:
unity_scene_name (
str) – Stem of a YAML template file stored in the configured task templates directory.- Return type:
TaskTemplate- Returns:
The TaskTemplate parsed from the matching YAML file.
- Raises:
FileNotFoundError – If the configured task templates directory is unset or missing on disk. The same error is raised when that directory holds no YAML file whose stem matches the given Unity scene name.
Command Line Interface¶
sle¶
Serves as the consolidated entry point for the sollertia-experiment command-line interface.
Exposes two operational command groups: ‘get’ for general, hardware-agnostic acquisition system discovery, and ‘mesoscope’ for configuring, running, and managing the Mesoscope-VR data acquisition system. The ‘mcp’ command starts a single MCP server that exposes the tools backing both groups to AI agents.
Usage
sle [OPTIONS] COMMAND [ARGS]...
get¶
Evaluates the composition of the data acquisition system managed by the host-machine.
Usage
sle get [OPTIONS] COMMAND [ARGS]...
cameras¶
Identifies the cameras accessible to the data acquisition system.
Usage
sle get cameras [OPTIONS]
checksum¶
Calculates the CRC32-XFER checksum for the input string.
Usage
sle 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
sle get controllers [OPTIONS]
ports¶
Identifies the serial communication ports accessible to the data acquisition system.
Usage
sle get ports [OPTIONS]
unity¶
Checks whether the Unity Editor MCP Bridge is reachable for Virtual Reality task sessions.
Usage
sle get unity [OPTIONS]
zaber¶
Identifies the Zaber devices accessible to the data acquisition system.
Usage
sle get zaber [OPTIONS]
mcp¶
Starts the MCP server for agentic access to the ‘sle get’ and ‘sle mesoscope’ tools.
Usage
sle mcp [OPTIONS]
Options
- -t, --transport <transport>¶
The MCP transport type to use.
- Default:
'stdio'- Options:
stdio | streamable-http
mesoscope¶
Configures, runs, and manages the Mesoscope-VR data acquisition system.
This command group exposes every Mesoscope-VR-specific runtime: generating the system and experiment configuration files, performing system maintenance, checking the system configuration, the filesystem paths, and the mesoscope control bridge, running data acquisition sessions, and managing the data collected by the system.
Usage
sle mesoscope [OPTIONS] COMMAND [ARGS]...
check-bridge¶
Checks whether the ScanImagePC’s runAcquisition control loop is reachable for Mesoscope imaging sessions.
The runAcquisition function is a lock-in command loop the operator launches once on the ScanImagePC, and it arms and commands the Mesoscope over MQTT for the entire runtime. An unreachable bridge means it is not running.
Usage
sle mesoscope check-bridge [OPTIONS]
check-mounts¶
Verifies every filesystem path declared in the Mesoscope-VR system configuration file.
The check covers the platform data root, the mesoscope acquisition directory, every configured long-term storage destination, the two stored camera configuration files, and the DeepLabCut project that drives face-camera inference. A path belonging to a feature the host leaves switched off passes the check as not configured.
Usage
sle mesoscope check-mounts [OPTIONS]
configure¶
Generates Mesoscope-VR configuration files.
Exposes two configuration targets: ‘system’ creates the data acquisition system configuration file that binds the host-machine to the Mesoscope-VR system, and ‘experiment’ creates per-experiment configuration files from Unity task templates.
Usage
sle mesoscope configure [OPTIONS] COMMAND [ARGS]...
experiment¶
Creates a Mesoscope-VR experiment configuration from a task template under the configured data root.
Usage
sle mesoscope configure experiment [OPTIONS]
Options
- -p, --project <project>¶
Required The name of the project for which to generate the new experiment configuration file.
- -e, --experiment <experiment>¶
Required The name of the experiment for which to create the configuration file.
- -t, --template <template>¶
Required The name of the task template to use (filename without .yaml extension).
- -sc, --state-count <state_count>¶
The number of runtime states supported by the experiment.
- Default:
1
- --reward-size <reward_size>¶
Default water reward volume in microliters for lick-type trials.
- Default:
5.0
- --reward-tone-duration <reward_tone_duration>¶
Default reward tone duration in milliseconds for lick-type trials.
- Default:
300
- --puff-duration <puff_duration>¶
Default gas puff duration in milliseconds for occupancy-type trials.
- Default:
100
- -f, --force¶
Determines whether to overwrite the experiment configuration file if it already exists.
- Default:
False
system¶
Creates the Mesoscope-VR data acquisition system configuration file under the working directory.
Usage
sle mesoscope configure system [OPTIONS]
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
sle mesoscope delete [OPTIONS]
Options
- -sp, --session-path <session_path>¶
Required The path to the data acquisition session’s directory to remove.
maintain¶
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. The session operates against the local hardware alone, writing nothing to the session tree or to long-term storage. It is designed to perform minor (day-to-day) maintenance tasks that do not require disassembling the system’s components.
Usage
sle mesoscope maintain [OPTIONS]
migrate¶
Transfers all sessions for the specified animal from the source project to the target project.
Usage
sle mesoscope 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
sle mesoscope preprocess [OPTIONS]
Options
- -sp, --session-path <session_path>¶
Required The path to the data acquisition session’s directory to preprocess.
run¶
Runs the specified data acquisition session for the target animal and project combination.
The user, project, animal, and animal weight are parsed on this group and shared by every subcommand, so they must be given before the subcommand name.
Usage
sle mesoscope run [OPTIONS] COMMAND [ARGS]...
Options
- -u, --user <user>¶
The ID of the user supervising the session.
- -p, --project <project>¶
The name of the project to which the animal belongs.
- -a, --animal <animal>¶
The ID of the animal undergoing the session.
- -w, --animal-weight <animal_weight>¶
The weight of the animal, in grams, at the beginning of the session.
experiment¶
Runs the specified experiment session.
Experiment runtimes are carried out after the lick and run training sessions. This command runs any experiment configuration 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 ‘sle mesoscope configure experiment’ subcommand.
Usage
sle mesoscope run 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 reaches this threshold, the system stops delivering new water rewards until the animal consumes the already delivered rewards. Setting this argument to 0 removes the limit, so any number of rewards can remain unconsumed. When omitted, reuses the previous session’s value for this animal, or 1 if there is none.
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
sle mesoscope run lick-training [OPTIONS]
Options
- -t, --maximum-time <maximum_time>¶
The maximum time to run the training session, in minutes. When omitted, reuses the previous session’s value for this animal, or 20 minutes if there is none.
- -min, --minimum-delay <minimum_delay>¶
The minimum number of seconds that has to pass between two consecutive reward deliveries during training. When omitted, reuses the previous session’s value for this animal, or 6 seconds if there is none.
- -max, --maximum-delay <maximum_delay>¶
The maximum number of seconds that can pass between two consecutive reward deliveries during training. When omitted, reuses the previous session’s value for this animal, or 18 seconds if there is none.
- -v, --maximum-volume <maximum_volume>¶
The maximum volume of water, in milliliters, that can be delivered during training. When omitted, reuses the previous session’s value for this animal, or 1.0 mL if there is none.
- -ur, --unconsumed-rewards <unconsumed_rewards>¶
The maximum number of rewards that can be delivered without the animal consuming them. If the unconsumed reward count reaches this threshold, the system stops delivering new water rewards until the animal consumes the already delivered rewards. Setting this argument to 0 removes the limit, so any number of rewards can remain unconsumed. When omitted, reuses the previous session’s value for this animal, or 1 if there is none.
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
sle mesoscope run run-training [OPTIONS]
Options
- -t, --maximum-time <maximum_time>¶
The maximum time to run the training session, in minutes. Must be greater than 0. When omitted, reuses the previous session’s value for this animal, or 40 minutes if there is none.
- -is, --initial-speed <initial_speed>¶
The initial speed, in centimeters per second, the animal must maintain to obtain water rewards. When omitted, reuses the previous session’s value for this animal, or 0.8 cm/s if there is none.
- -id, --initial-duration <initial_duration>¶
The initial duration, in seconds, the animal must maintain above-threshold running speed to obtain water rewards. When omitted, reuses the previous session’s value for this animal, or 1.5 seconds if there is none.
- -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. When omitted, reuses the previous session’s value for this animal, or 0.1 mL if there is none.
- -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. When omitted, reuses the previous session’s value for this animal, or 0.05 cm/s if there is none.
- -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. When omitted, reuses the previous session’s value for this animal, or 0.1 seconds if there is none.
- -v, --maximum-volume <maximum_volume>¶
The maximum volume of water, in milliliters, that can be delivered during training. When omitted, reuses the previous session’s value for this animal, or 1.0 mL if there is none.
- -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. When omitted, reuses the previous session’s value for this animal, or 0.3 seconds if there is none.
- -ur, --unconsumed-rewards <unconsumed_rewards>¶
The maximum number of rewards that can be delivered without the animal consuming them. If the unconsumed reward count reaches this threshold, the system stops delivering new water rewards until the animal consumes the already delivered rewards. Setting this argument to 0 removes the limit, so any number of rewards can remain unconsumed. When omitted, reuses the previous session’s value for this animal, or 1 if there is none.
window-checking¶
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
sle mesoscope run window-checking [OPTIONS]
validate-config¶
Validates the Mesoscope-VR system configuration file and reports every issue it carries.
Beyond checking each filesystem path the configuration declares, this command verifies that a configured DeepLabCut project is able to produce the eye-tracking predictions accepted by session preprocessing.
Usage
sle mesoscope validate-config [OPTIONS]
Cross-System Acquisition Tools¶
Provides the assets shared by multiple data acquisition systems.
- class sollertia_experiment.cross_system.BrakeInterface(minimum_brake_strength, maximum_brake_strength)¶
Bases:
ModuleInterfaceInterfaces 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 brake-engage (kToggleOn) module command.
- _disengage¶
The code for the brake-disengage (kToggleOff) 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()¶
Returns immediately, because the module keeps no assets in the communication process.
- 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)¶
Discards the received message, because the module carries no real-time processing stage.
- 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) – Determines whether to engage the brake.- Return type:
None
- terminate_remote_assets()¶
Returns immediately, because the module holds no remote assets to release.
- Return type:
None
- class sollertia_experiment.cross_system.CRCCalculator¶
Bases:
objectExposes 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 sollertia_experiment.cross_system.EncoderInterface(encoder_ppr, wheel_diameter, polling_frequency)¶
Bases:
ModuleInterfaceInterfaces with EncoderModule instances running on the Encoder MicroController.
Notes
Type code 2.
The encoder is constructed without a Unity scale and reports zero Unity motion until
set_unity_scaleis called.- 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.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. Zero until
set_unity_scaleis called.
- _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 in the main runtime process.
- 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
- set_unity_scale(cm_per_unity_unit)¶
Updates the encoder pulse to Unity unit conversion factor used to report animal motion to Unity.
Notes
The factor is stored on the main process and scales the signed encoder displacement when the absolute_position property is read, so it can be updated after the communication process that fills the shared memory buffer has started.
- Parameters:
cm_per_unity_unit (
float) – The length of one Virtual Reality environment distance unit (Unity unit) in centimeters.- 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 sollertia_experiment.cross_system.GasPuffValveInterface¶
Bases:
ModuleInterfaceInterfaces with specialized ValveModule instances designed to operate gas valves.
Notes
Type code 5.
Controls the valve by pulse duration directly, because gas puff delivery tolerates the volume spread an uncalibrated valve produces.
- _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 instance’s shared memory buffer in the main runtime process.
- Return type:
None
- initialize_remote_assets()¶
Connects to the instance’s shared memory buffer.
- 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.
- property puff_tracker: SharedMemoryArray¶
Returns the SharedMemoryArray that exports the delivered puff count to other processes.
- set_state(*, state)¶
Sets the managed valve to the desired state.
- Parameters:
state (
bool) – Determines whether to open the gas-puff valve.- Return type:
None
- terminate_remote_assets()¶
Disconnects from the instance’s shared memory buffer.
- Return type:
None
- class sollertia_experiment.cross_system.LickInterface(lick_threshold, polling_frequency)¶
Bases:
ModuleInterfaceInterfaces 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 in the main runtime process.
- 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 sollertia_experiment.cross_system.MesoscopeFrameTTLInterface(polling_frequency)¶
Bases:
ModuleInterfaceInterfaces with the TTLModule instance that monitors the Mesoscope frame-acquisition pulses, running on the Sensor MicroController.
Notes
Type code 1.
- 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 in the main runtime process.
- 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 sollertia_experiment.cross_system.ScreenInterface¶
Bases:
ModuleInterfaceInterfaces 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()¶
Returns immediately, because the module keeps no assets in the communication process.
- Return type:
None
- process_received_data(_message)¶
Discards the received message, because the module carries no real-time processing stage.
- 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) – Determines whether the screens are powered on.- Return type:
None
- property state: bool¶
Returns True when the screens are currently powered on.
- terminate_remote_assets()¶
Returns immediately, because the module holds no remote assets to release.
- Return type:
None
- class sollertia_experiment.cross_system.StorageDestination(name, session_path)¶
Bases:
objectDefines a single long-term storage destination resolved for a particular data acquisition session.
- name: str¶
The human-readable name of the storage destination, used in progress and status messages.
- session_path: Path¶
The absolute path to the session’s data directory on this storage destination.
- class sollertia_experiment.cross_system.StorageDestinations(destinations=())¶
Bases:
objectDefines the ordered collection of long-term storage destinations resolved for a data acquisition session.
- destinations: tuple[StorageDestination, ...]¶
The storage destinations to which the session’s data is transferred and from which it can be removed.
- class sollertia_experiment.cross_system.SurgeryLog(project_name, animal_id, credentials_path, sheet_id)¶
Bases:
objectInterfaces with the Sollertia platform’s surgery log Google Sheet.
Notes
This class is purpose-built to work with the specific surgery log format used by the Sollertia platform.
- 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 Sollertia platform surgery log, or if the target animal’s identifier is not present in the sheet’s ‘ID’ column.
- close()¶
Closes the underlying HTTP connection to the processed surgery log, releasing its SSL socket.
- Return type:
None
Notes
Callers should invoke this method (typically from a try/finally block) as soon as they finish using the instance. Relying on garbage collection to release the connection leaves the SSL socket open until an unpredictable finalization point, which surfaces as a ResourceWarning during interpreter shutdown.
- extract_animal_data()¶
Extracts and returns the processed animal’s surgical intervention data as a SurgeryData object.
- Return type:
SurgeryData- Returns:
The subject, procedure, drug, implant, and injection records read from the animal’s row.
- Raises:
ValueError – If the animal’s date or time cells are empty, or if the date, time, identifier, weight, cage, surgery quality, ‘<stem> (ml)’ drug volume, ‘<base> volume (nl)’ injection volume, or ‘<base> coordinates’ cells contain malformed values. Date and time cells are parsed via _convert_date_time_to_timestamp, the coordinate cells via _parse_stereotactic_coordinates, and the remaining cells via int() and float().
- update_surgery_quality(quality)¶
Updates the processed animal’s surgery quality value to the input value.
Notes
In addition to writing the value, this method issues a second batchUpdate request that applies CENTER horizontal and MIDDLE vertical cell alignment formatting to the updated cell.
- 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). The 0-3 scale is advisory, and this method does not validate that the input falls within that range.- Return type:
None
- class sollertia_experiment.cross_system.SystemConfiguration¶
Bases:
YamlConfigDefines the shared type and save behavior of every Sollertia data acquisition system configuration.
Each acquisition system defines a concrete subclass (e.g. MesoscopeSystemConfiguration) that composes its per-subsystem configuration sections and registers it via register_system_configuration(). Subclassing provides a common type for the cross-system configuration registry and helpers below, plus a default save() that subclasses override when the on-disk YAML representation must differ from the in-memory representation.
- save(path)¶
Saves the configuration instance to disk as a .yaml file.
Subclasses override this method when the YAML representation must differ from the in-memory representation (e.g., to convert a calibration tuple to a mapping for a stable on-disk layout).
- Parameters:
path (
Path) – The destination .yaml file path.- Return type:
None
- class sollertia_experiment.cross_system.TorqueInterface(baseline_voltage, maximum_voltage, sensor_capacity, polling_frequency)¶
Bases:
ModuleInterfaceInterfaces 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()¶
Returns immediately, because the module keeps no assets in the communication process.
- Return type:
None
- process_received_data(_message)¶
Discards the received message, because the module carries no real-time processing stage.
- 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()¶
Returns immediately, because the module holds no remote assets to release.
- 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 sollertia_experiment.cross_system.WaterLog(animal_id, session_date, credentials_path, sheet_id)¶
Bases:
objectInterfaces with the Sollertia platform’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 by the Sollertia platform.
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.
- _animal_id¶
The unique identifier of the target animal.
- _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 session start time converted to the host machine’s local 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 Sollertia platform water restriction and animal interaction log. If the session_date cannot be parsed as a Sollertia session timestamp, or if the log does not contain a row for the session’s local date.
- close()¶
Closes the underlying HTTP connection to the processed water restriction and animal interaction log, releasing its SSL socket.
- Return type:
None
Notes
Callers should invoke this method (typically from a try/finally block) as soon as they finish using the instance. Relying on garbage collection to release the connection leaves the SSL socket open until an unpredictable finalization point, which surfaces as a ResourceWarning during interpreter shutdown.
- 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
- class sollertia_experiment.cross_system.WaterValveInterface(valve_calibration_data)¶
Bases:
ModuleInterfaceInterfaces with the ValveModule instance that controls the water reward valve 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. This value is also sent as the firmware calibration_count parameter on every reward and simulated-reward command.
- _scale_coefficient¶
The scale coefficient derived from fitting the power-law model to the valve’s calibration data.
- _nonlinearity_exponent¶
The nonlinearity exponent derived from 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.
- _transmitted_parameters¶
The pulse duration, calibration count, and tone duration triple last transmitted to the module, or None before the first transmission.
- _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 or referencing 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.
Notes
The firmware silences the buzzer no earlier than the valve closes, so a non-zero tone shorter than the valve pulse is extended to the pulse duration. A zero-length tone requests a silent reward and is delivered as one.
- 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.
- Raises:
ValueError – If the requested volume is too small to be reliably dispensed by the valve.
- 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.- Return type:
uint32- Returns:
The duration, in microseconds, the valve needs to stay open to deliver the specified volume.
- Raises:
ValueError – If the desired water volume is too small to be reliably dispensed by the valve, based on its calibration data.
- initialize_local_assets()¶
Connects to the instance’s shared memory buffer in the main runtime process.
- 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 the configured number of calibration pulses, each delivering 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) – Determines whether to open the valve.- Return type:
None
- simulate_reward(tone_duration=300)¶
Simulates delivering water reward by emitting an audible ‘reward’ tone without opening the valve.
Notes
A zero-length tone is a no-op. A simulated reward delivers no water, so a tone of no duration leaves the animal with nothing to perceive.
- Parameters:
tone_duration (
int, default:300) – The duration of the auditory tone, in milliseconds, to emit while simulating the water reward delivery.- Raises:
ValueError – If the fallback reference volume is too small to be reliably dispensed by the valve.
- Return type:
None
- terminate_remote_assets()¶
Disconnects from the instance’s shared memory buffer and releases the cycle PrecisionTimer.
- Return type:
None
Notes
Dropping the PrecisionTimer reference frees its nanobind-bound C++ object before the communication subprocess interpreter is finalized. Otherwise, nanobind reports a spurious ‘leaked instance’ warning when the subprocess shuts down.
- property valve_tracker: SharedMemoryArray¶
Returns the SharedMemoryArray that exports the valve’s delivered volume and state to other processes.
- class sollertia_experiment.cross_system.ZaberAxis(motor)¶
Bases:
objectInterfaces with a Zaber motor (axis).
Notes
This class represents the lowest level of the tri-class hierarchy used to control Zaber motors during runtime.
- Parameters:
motor (
Axis) – The Axis class instance that interfaces with the motor’s hardware.
- _motor¶
The Axis class instance that physically controls the motor’s hardware through Zaber ASCII protocol.
- _park_position¶
The absolute position, in native motor units, where the motor should be moved to before parking and shutting down.
- _maintenance_position¶
The absolute position, in native motor units, where the motor should be moved as part of the preparation for the system’s maintenance.
- _mount_position¶
The absolute position, in native motor units, where the motor should be moved before mounting the animal into the system’s enclosure.
- _maximum_limit¶
The maximum absolute position relative to the home sensor position, in native motor units, the motor is allowed to reach during runtime. Read from the configurable ‘limit.max’ axis setting.
- _minimum_limit¶
The minimum absolute position relative to the home sensor position, in native motor units, the motor is allowed to reach during runtime. Read from the configurable ‘limit.min’ axis setting.
- _shutdown_flag¶
Tracks whether the motor has been shut down.
- _pacing_guard¶
A Timeout class instance that is used to ensure that communication with the motor is carried out at a pace that does not overwhelm the connection interface with too many successive calls.
- Raises:
ValueError – If any parameter read from the motor’s non-volatile memory is outside the expected range of values.
- get_position()¶
Returns the current absolute position of the motor, in native motor units, relative to its home position.
- Return type:
float
- home()¶
Homes the motor by moving it towards the home sensor position until it triggers the sensor.
- Return type:
None
Notes
This method establishes a stable reference point used to execute all other motion commands.
The method initializes the homing procedure but does not block until it is over. This feature is designed to support homing multiple motors in parallel.
- property is_busy: bool¶
Returns True if the motor is currently executing a command (is moving).
- property is_homed: bool¶
Returns True if the motor has been homed (has a motion reference point).
- property is_parked: bool¶
Returns True if the motor is parked.
- property maintenance_position: int¶
Returns the absolute position, in native motor units, where the motor needs to be moved as part of preparing the system for maintenance.
- property mount_position: int¶
Returns the absolute position, in native motor units, where the motor needs to be moved before mounting the animal into the system’s enclosure.
- move(position)¶
Moves the motor to the requested absolute position.
Notes
This method initiates the movement, but does not wait until it is completed. This behavior is designed to enable parallel operation of multiple motors.
- Parameters:
position (
int) – The exact position, in native motor units, to move the motor to.- Return type:
None
- park()¶
Parks the motor, making it unresponsive to motor commands, and stores the current absolute position of the motor in its non-volatile memory.
- Return type:
None
- property park_position: int¶
Returns the absolute position, in native motor units, where the motor needs to be moved as part of the system’s shutdown procedure.
- shutdown()¶
Prepares the motor for shutting down by seizing any ongoing movement and parking it to cache its current position to the non-volatile memory.
- Return type:
None
- stop()¶
Decelerates and stops the motor.
- Return type:
None
Notes
This method can be called to interrupt other currently running methods, which is primarily used in the case of an emergency.
Calling this method once instructs the motor to decelerate and stop. Per the Zaber ASCII protocol manual, a second stop command issued while the motor is still decelerating halts it immediately. That is controller firmware behavior and is not implemented by this wrapper.
This command does not block until the motor stops to allow stopping multiple motors (axes) in rapid succession.
- unpark()¶
Unparks a parked motor, which allows the motor to accept and execute motion commands.
- Return type:
None
- class sollertia_experiment.cross_system.ZaberConnection(port)¶
Bases:
objectInterfaces with a serial USB port and all Zaber devices (controllers) and axes (motors) available through that port.
Notes
This class represents the highest level of the tri-class Zaber binding hierarchy.
This class does not automatically initialize the connection with the port. Call the connect() method to establish connection before calling other class methods.
- Parameters:
port (
str) – The name of the USB port the connection targets.
- _port¶
The name of the target serial port.
- _connection¶
The Connection class instance that manages the specified serial port and all Zaber devices using the port.
- _devices¶
The tuple of _ZaberDevice instances used to interface with Zaber devices available through the connected port.
- _is_connected¶
Tracks whether the instance is currently connected to the managed serial port.
- Raises:
TypeError – If the provided ‘port’ argument value is not a string.
- connect()¶
Opens the serial port and detects and connects to any available Zaber devices (controllers).
- Raises:
NoDeviceFoundException – If no Zaber devices are discovered using the target serial port.
- Return type:
None
- disconnect()¶
Shuts down all managed Zaber devices and closes the connection.
- Return type:
None
- get_device(index)¶
Returns the _ZaberDevice instance for the requested Zaber controller (device).
- Parameters:
index (
int) – The index of the controller for which to retrieve the interface. The controllers are indexed based on their position in the daisy-chain of Zaber devices relative to the USB port, with the device directly connected to the port having an index of 0.- Return type:
_ZaberDevice- Returns:
The interface to the controller occupying the requested position in the daisy-chain.
- Raises:
ConnectionError – If the instance is not connected to the managed serial port.
- property is_connected: bool¶
Returns True if the class has established connection with the managed serial port.
- sollertia_experiment.cross_system.assemble_session_logs(session_data, processes)¶
Assembles all .npy log entries stored in the session’s temporary log directory into .npz archives, one for each data source recorded during the session’s runtime.
- Parameters:
session_data (
SessionData) – The SessionData instance that defines the processed session.processes (
int) – The number of processes to use while archiving the log entries.
- Raises:
RuntimeError – If the target log directory contains both unprocessed and processed log entries.
- Return type:
None
- sollertia_experiment.cross_system.create_system_configuration_file(system)¶
Creates the default .yaml configuration file for the specified data acquisition system and configures the local machine (PC) to use it for all future acquisition-system-related calls.
The file is written into the local working directory’s configuration folder, and any other system configuration file in that folder is removed once the write succeeds, so the machine belongs to exactly one acquisition system.
- Parameters:
system (
AcquisitionSystems|str) – The acquisition system whose configuration file is created.- Raises:
FileNotFoundError – If the local Sollertia platform working directory has not been configured for the host-machine or no longer exists.
ValueError – If the requested acquisition system is not registered.
- Return type:
None
- sollertia_experiment.cross_system.delete_session_directories(candidates, session_name, *, require_confirmation)¶
Removes the target session’s data directories from all provided storage locations.
Notes
This function is destructive and irreversible. When confirmation is requested, it locks the runtime until the user explicitly confirms or aborts the deletion.
- Parameters:
candidates (
tuple[Path,...]) – The directories to remove, typically the session’s directory on the host machine and on every long-term storage destination.session_name (
str) – The name of the session whose data is being removed, used in the confirmation prompt.require_confirmation (
bool) – Determines whether to prompt the user to confirm the deletion before proceeding.
- Return type:
bool- Returns:
True if the directories were removed, False if the user aborted the deletion.
- sollertia_experiment.cross_system.discover_zaber_devices()¶
Scans all available serial ports and displays information about connected Zaber devices.
- Return type:
None
Notes
Connection errors encountered during scanning are logged at DEBUG level and do not interrupt the discovery process. Ports the scan cannot open are listed as having “No Devices”.
- sollertia_experiment.cross_system.get_project_experiments(project_directory)¶
Discovers the available experiment configuration files for the target project.
- Parameters:
project_directory (
Path) – The path to the project directory for which to discover the experiment configurations.- Return type:
tuple[str,...]- Returns:
A tuple of naturally-sorted experiment configurations available for the target project.
- sollertia_experiment.cross_system.get_system_configuration_data()¶
Loads the local machine’s data acquisition system configuration file.
Resolves the single configuration file on the local machine, maps it to the registered SystemConfiguration subclass for its acquisition system, and returns the loaded instance.
Notes
The return type is the shared
SystemConfigurationbase.- Return type:
- Returns:
The loaded SystemConfiguration instance.
- Raises:
FileNotFoundError – If the local working directory does not contain exactly one system configuration file.
ValueError – If the configuration file does not belong to a registered acquisition system.
- sollertia_experiment.cross_system.get_system_configuration_path()¶
Resolves the path to the local machine’s data acquisition system configuration file.
A host-machine belongs to exactly one acquisition system, so its working directory must contain exactly one
*_system_configuration.yamlfile.- Return type:
Path- Returns:
The path to the single local system configuration file.
- Raises:
FileNotFoundError – If the local working directory does not contain exactly one system configuration file.
- sollertia_experiment.cross_system.get_version_data()¶
Returns the current Python and sollertia-experiment versions.
- Return type:
tuple[str,str]- Returns:
The Python version first, then the sollertia-experiment version.
- sollertia_experiment.cross_system.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:
The device’s labels, park, maintenance and mount positions, shutdown and unsafe flags, motion limits, and current position, read from its non-volatile memory.
- Raises:
ConnectionError – If unable to connect to the specified port.
IndexError – If device_index is out of range for the connected devices.
- sollertia_experiment.cross_system.get_zaber_devices_info()¶
Scans all available serial ports for Zaber devices and returns formatted device information.
Notes
Connection errors encountered during scanning are logged at DEBUG level and do not interrupt the discovery process.
- 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”.
- sollertia_experiment.cross_system.migrate_session_directory(remote_session_path, local_session_path, old_session_data_path, target_project, threads)¶
Pulls a single session from a remote storage destination to the host machine and reassigns it to the target project.
Notes
This function copies the pulled session_data.yaml file to the source project’s host-machine location so the caller can later remove the obsolete data from all storage destinations. It also recreates the source project’s per-session raw_data directory (which preprocessing removed) so the copied session_data.yaml has a valid destination on the host machine.
- Parameters:
remote_session_path (
Path) – The path to the session’s directory on the remote storage destination.local_session_path (
Path) – The path to the session’s directory on the host machine, under the target project.old_session_data_path (
Path) – The path to the session_data.yaml file under the source project on the host machine.target_project (
str) – The name of the project to which the session is reassigned.threads (
int) – The number of worker threads used to parallelize the data transfer.
- Return type:
SessionData- Returns:
The reloaded SessionData instance that reflects the session’s reassignment to the target project.
- sollertia_experiment.cross_system.probe_writable(path)¶
Probes write access to a directory by creating and removing a uniquely-named temporary file.
- Parameters:
path (
Path) – The directory whose write access is probed.- Return type:
str|None- Returns:
None when the directory is writable, or a human-readable reason describing why it is not.
- sollertia_experiment.cross_system.push_session_data(session_data, destinations, threads)¶
Moves the preprocessed session’s raw data from the acquisition host machine to all long-term storage destinations.
Notes
This function computes the data integrity checksum before the transfer and removes the entire local session directory, including any processed_data not transferred, after the raw data is successfully transferred to all destinations.
If the input collection contains no storage destinations, the function aborts early with a warning and leaves the local copy of the session’s data intact, since there is no destination to which the data can be backed up.
- Parameters:
session_data (
SessionData) – The SessionData instance that defines the processed session.destinations (
StorageDestinations) – The StorageDestinations collection that defines the long-term storage destinations resolved for the processed session.threads (
int) – The number of worker threads used by each transfer process to parallelize the data transfer.
- Return type:
None
- sollertia_experiment.cross_system.register_system_configuration(system, configuration_class)¶
Registers the SystemConfiguration subclass used by the specified data acquisition system.
Each acquisition system calls this function at import time so that the cross-system configuration helpers below can create, resolve, and load that system’s configuration file. Registration is the only system-specific wiring the file lifecycle requires, and everything else is shared.
- Parameters:
system (
AcquisitionSystems|str) – The acquisition system that owns the configuration class.configuration_class (
type[SystemConfiguration]) – The system’s SystemConfiguration subclass.
- Return type:
None
- sollertia_experiment.cross_system.rename_session_videos(session_data)¶
Renames the .MP4 video files generated during the processed session’s runtime to use human-friendly names instead of the numeric camera source ID codes.
Notes
The mapping between source IDs and human-friendly names is resolved from the camera manifest written by the ataraxis-video-system library during acquisition.
- Parameters:
session_data (
SessionData) – The SessionData instance that defines the processed session.- Return type:
None
- sollertia_experiment.cross_system.request_confirmation(message, *, default=False)¶
Prompts the user to confirm or decline an action, requiring the Enter key to submit the response.
- Parameters:
message (
str) – The yes-or-no question presented to the user.default (
bool, default:False) – Determines whether an empty answer is treated as a confirmation.
- Return type:
bool- Returns:
True if the user confirmed the action, False if the user declined it.
- sollertia_experiment.cross_system.request_required_confirmation(message)¶
Prompts the user to confirm or decline an action, re-prompting until an explicit yes or no is entered.
Unlike request_confirmation, this prompt has no default response. Submitting an empty or unrecognized answer re-displays the question instead of falling back to a default, which forces the user to make a deliberate choice.
- Parameters:
message (
str) – The yes-or-no question presented to the user.- Return type:
bool- Returns:
True if the user confirmed the action, False if the user declined it.
- sollertia_experiment.cross_system.request_selection(message, choices)¶
Prompts the user to select one option from a list, requiring the Enter key to submit the selection.
- Parameters:
message (
str) – The instruction presented to the user.choices (
Sequence[Choice|str]) – The options offered to the user, provided as questionary choices or plain strings.
- Return type:
Any- Returns:
The value associated with the option selected by the user.
- sollertia_experiment.cross_system.request_text(message, *, default='', multiline=False, validate=None)¶
Prompts the user to enter free-form text, requiring the Enter key to submit the response.
- Parameters:
message (
str) – The instruction presented to the user.default (
str, default:'') – The text pre-filled into the response field.multiline (
bool, default:False) – Determines whether the user can enter multiple lines of text before submitting the response.validate (
Callable[[str],bool|str] |Validator|type[Validator] |None, default:None) – An optional questionary validator applied to the response before it is accepted.
- Return type:
str- Returns:
The text entered by the user.
- sollertia_experiment.cross_system.run_shutdown_step(description, step)¶
Executes a single shutdown callable, isolating it so that an error or interrupt does not propagate.
Acquisition system shutdown sequences tear down several subprocess-backed assets in turn. Allowing an exception or a repeated KeyboardInterrupt from one asset to propagate would skip the remaining teardown steps. This would leave the orphaned subprocesses to be collected by the garbage collector, which tears down their shared-memory managers out of order and cascades into multiprocessing errors. This helper contains each failure so the remaining steps still run, while the originally propagating exception (if any) resumes once the shutdown sequence completes.
- Parameters:
description (
str) – A short gerund phrase naming the step, used to contextualize an error encountered while running it.step (
Callable[[],None]) – The zero-argument callable that performs the shutdown step.
- Return type:
None
- sollertia_experiment.cross_system.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. Device label changes automatically update the checksum (USER_DATA_0) to maintain device validation, and axis label changes do not. 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.
TypeError – If the value type does not match the setting (a non-string label, or a non-integer position or flag).
ValueError – If the setting name is invalid, if the value is out of range, or if a device_label write succeeded but the matching USER_DATA_0 checksum write failed, leaving the label and the checksum possibly out of agreement.
- sollertia_experiment.cross_system.snapshot_surgery_data(session_data, animal_id, credentials_path, surgery_sheet_id)¶
Caches a copy of the animal’s surgical intervention record to the session’s data directory as the surgery_metadata.yaml file.
Notes
Returns the SurgeryLog handle so callers can reuse the established Google Sheets connection. The caller owns the returned handle and must close it (typically from a try/finally block) once it is no longer needed to release the underlying SSL socket.
- Parameters:
session_data (
SessionData) – The SessionData instance that defines the processed session.animal_id (
int) – The unique identifier code of the animal that participated in the processed session.credentials_path (
Path) – The path to the Google service account credentials file.surgery_sheet_id (
str) – The identifier of the Google Sheet that stores the animals’ surgical intervention records.
- Return type:
- Returns:
The SurgeryLog instance connected to the surgery log Google Sheet.
- sollertia_experiment.cross_system.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:
The pass or fail outcome of the check, the identity of the validated device, and the error and warning messages the check produced.
- Raises:
ConnectionError – If unable to connect to the specified port.
IndexError – If device_index is out of range for the connected devices.
- sollertia_experiment.cross_system.wait_for_enter(message='Press Enter to continue')¶
Blocks runtime execution until the user presses the Enter key.
Requiring the Enter key, rather than any keystroke, ensures the user deliberately resumes the runtime, because a single-key prompt consumes key presses buffered ahead of time.
- Parameters:
message (
str, default:'Press Enter to continue') – The message displayed to the user while the runtime waits for the Enter key.- Return type:
None
- sollertia_experiment.cross_system.data_preprocessing.BEHAVIOR_LOGGER_NAME: str = 'behavior'¶
The instance name assigned to the DataLogger that records the behavior data of every acquisition system.