Bruker Control’s Functions and Classes¶
video_utils.py¶
Module contains functions for configuring GenICam compliant cameras as well as grabbing, displaying, and writing video frames the cameras acquire. It has been written with flexibility of number of cameras in mind, but has only been tested using one camera so far.
- exception video_utils.CameraNotFound(*args)¶
Exception class for if Python cannot find a connected GENTL camera.
- video_utils.calculate_frames(session_len_s, framerate)¶
Calculates number of images to collect during the experiment.
Converts imaging session length into number of frames to collect by microscope and, therefore, camera. Currently, the camera takes an image each time the microscope does via its TTLs.
- Parameters
session_len_s (
int
) – Experimental session length in secondsframerate (
float
) – Framerate of microscope.
- Return type
int
- Returns
num_frames
- video_utils.capture_preview(project, subject_id)¶
Capture frames generated by camera object and display them in preview mode.
Takes values from init_camera_preview() to capture images delivered by camera buffer, reshapes the image to appropriate height and width, draws a grid upon the preview
When user hits the ‘Esc’ key, the window closes and the camera object is destroyed. Finally, the preview content is saved as an image that is timestamped with the day’s date and placed into the subject’s metadata directory.
- Parameters
project – The team and project conducting the experiment
subject_id – The subject being recorded
- video_utils.capture_recording(framerate, num_frames, current_plane, imaging_plane, project, subject_id)¶
Capture frames generated by camera object, display them in recording mode, and write frames to .mp4 file.
Takes values from init_camera_recording() to capture images delivered by camera buffer, reshapes the image to appropriate height and width, displays the image to an opencv window, and writes the image to a .mp4 file. When the camera acquires the specified number of frames for an experiment, the window closes, the camera object is destroyed, and the video is written to disk.
- Parameters
framerate (
float
) – Microscope’s framerate from prairieview_utils used in the video codecnumber_frames – Number of frames specified to collect for the video recording
current_plane (
int
) – Current plane being imaged as in 1st, 2nd, 3rd, etcimaging_plane (
str
) – Plane the 2P image is currently being taken acquired from Prairie Viewproject (
str
) – The team and project conducting the experiment (ie teamname_projectname)subject_id (
str
) – The subject being recorded
- Return type
list
- Returns
dropped_frames
- video_utils.init_camera_preview()¶
Creates, configures, describes, and starts harvesters camera object in preview setting.
Initializes harvester camera, sets camera properties appropriate for preview, gathers the camera’s width and height in pixels, and starts video acquisition. The function takes no arguments.
- Return type
Tuple
[Harvester
,Harvester
,int
,int
]- Returns
Harvester object
Camera object
Camera’s height (pixels)
Camera’s width (pixels)
- video_utils.init_camera_recording()¶
Creates, configures, describes, and starts harvesters camera object in recording setting.
Initializes harvester camera, sets camera properties appropriate for behavior recording, gathers the camera’s width and height in pixels, and starts video acquisition. There are no arguments.
- Return type
Tuple
[Harvester
,Harvester
,int
,int
]- Returns
Harvester object
Camera object
Camera’s height (pixels)
Camera’s width (pixels)
- video_utils.shutdown_camera(camera, harvester)¶
Deactivates and resets both harvester and camera after acquisition.
Turns off camera, resets its configuration values, and resets the harvester object once acquisition is done. The function does not return anything
- Parameters
camera (
Harvester
) – Harverster camera objectharvester (
Harvester
) – Haverster object
trial_utils.py¶
Module contains functions for interpreting configuration file parameters and using them for generating pseudorandom trial arrays following user defined rules with the capability of producing catch trials in given subsets of the trial order, for generating ITIs from a uniform random distribution between bounds defined by the user, and tone durations that vary between user defined bounds.
- trial_utils.calculate_punish_seconds(punish_delivery_ms, trialArray)¶
Calculates number of seconds punishments are delivered.
Uses configuration values to calculate how many seconds rewards are present for a given session.
- Parameters
punish_delivery_ms (
int
) – Amount of time punishments are delivered in milliseconds from the config file.trialArray (
list
) – Experimental runtime trial order gathered from the experimental_array_list at index 0
- Return type
int
- Returns
punish_seconds
- trial_utils.calculate_reward_seconds(reward_delivery_ms, reward_prsnt_ms, trialArray, vacuum)¶
Calculates number of seconds rewards are presented and removed.
Uses configuration values to calculate how many seconds rewards are present for a given session as well as how many seconds the vacuum is active if used. Returns number of seconds rewards are present.
- Parameters
reward_delivery_ms (
int
) – Amount of time reward is delivered in milliseconds from the config filereward_prsnt_ms (
int
) – Amount of time reward is presented to mouse in milliseconds from the config filetrialArray (
list
) – Experimental runtime trial order gathered from the experimental_array_list at index 0vacuum (
bool
) – Status of whether or not the vacuum is being used for a project
- Return type
int
- Returns
reward_seconds
- trial_utils.calculate_session_length(experiment_arrays)¶
Calculates number of imaging frames to collect for experimental session.
Iterates through experiment runtime arrays to calculate amount of time and, therefore, the total number of frames that the microscope and camera should collect for the experiment.
- Parameters
experiment_arrays (
list
) – List of experiment runtime arrays generated from generate_arrays().- Return type
int
- Returns
Session length in seconds.
- trial_utils.check_session_punishments(trialArray, max_seq_punish)¶
Check if too many punish trials happen sequentially
Takes in trialArray after punish trial flips and determines if more than user defined max number of punish trials occur in a row. If so, the punish_check is returned True.
- Parameters
trialArray (
ndarray
) – Trial array post punish trial flipsmax_seq_punish (
int
) – Maximum number of sequential punishment trials from config_template
- Return type
bool
- Returns
punish_check
- trial_utils.check_session_rewards(trialArray, max_seq_reward)¶
Check if too many reward trials happen sequentially.
Takes in trialArray after punish trial flips and determines if more than user defined max number of reward trials occur in a row. If so, the reward_check is returned True.
- Parameters
trialArray (
ndarray
) – Trial array post punish trial flipsmax_seq_reward (
int
) – Maximum number of sequential reward trials from config_template
- Return type
bool
- Returns
punish_check_status
- trial_utils.check_session_stim_only(tmp_array, max_seq_stim_only=2)¶
Checks if there are more than 2 stimulation only trials that occur in a row.
- Parameters
tmp_array (
ndarray
) – Trial array containing newly flipped stimulation only trials.max_seq_stim_only – Maximim number of stimulation only trials allowed to occur in order.
- Returns
Boolean value encoding if the check passed or failed.
- Return type
stim_only_status
- trial_utils.flip_catch(trialArray, config_template, catch_check)¶
Flips trials to catches in checked trialArray.
Flips subset of trials depending on user specified offset and selected number of reward/punish catch trials.
- Parameters
trialArray (
ndarray
) – Checked trialArray returned by flip_punishments()config_template (
dict
) – Configuration template value dictionary gathered from team’s configuration .json file.catch_check (
bool
) – Boolean status for catch trials being flipped or not.
- Return type
Tuple
[ndarray
,bool
]- Returns
- trialArray
trialArray with catch trials added
- catch_check
Boolean status for catch trials being flipped or not.
- trial_utils.flip_punishments(tmp_array, potential_flips, num_punish, max_seq_punish)¶
Flips user specified number of trials to punishments over trialArray copy.
Takes in a copy of the fresh trialArray called tmp_array, takes a random sample of potential flip positions for punishment trials, and flips their value from 1, reward, to 0, punishment.
- Parameters
tmp_array (
ndarray
) – Copy of fresh trialArray consisting of all reward trialspotential_flips (
ndarray
) – Array of potential indexes to flip to punishmentsnum_punish (
int
) – Integer of number of punishment trials to flip for session
- Returns
Modified array containing flipped values, to be saved as trialArray
- punish_check:
Boolean status of whether the array meets experimenter defined criteria. False if successful, True if failed.
- Return type
tmp_array
- trial_utils.flip_stim_only(tmp_array, remaining_flips, num_stim_alone)¶
Flips user specified number of trials to stimulation only trials.
- Parameters
tmp_array (
ndarray
) – trialArray consisting of trials that have had flips performed for punishment stimulation.remaining_flips (
ndarray
) – Array of indexes that can be switched to stimulation only trialsnum_stim_alone (
int
) – Number of trials where only LED stimulation occurs
- Return type
Tuple
[ndarray
,bool
]- Returns
trialArray
stim_only_check
- trial_utils.flip_stim_trials(fresh_array, total_stim_trials, num_stim_punish, num_stim_alone, stim_start_position, max_seq_punish)¶
Flips fresh array of all reward trials into stimulation trials for both reward and punish trials.
Stimulation trials are defined by the user as part of the configuration template file. The fresh array containing all reward trials has a subset of trials flipped to stimulation trial types (4, 5, or 6) that starts at the specified position in the trial structure. It first flips the subset of trials to reward, punish, and stimulation alone trials and then performs multiple shuffles of the subset. A check for sequential punish trials is conducted next and, if it fails, it will reshuffle until it succeeds. Returns a trialArray that has stimulation trials.
- Parameters
fresh_array (
ndarray
) – Array composed entirely of reward trials to be flipped pseudo-randomlytotal_stim_trials (
int
) – Total number of photo-stimulation trials (reward, punish, and stim only)num_stim_punish (
int
) – User specified number of photo-stimulation trials with airpuffnum_stim_alone (
int
) – User specified number of trials with only photo-stimulationstim_start_position (
int
) – User specified position for where photo-stimulation block startsmax_seq_punish (
int
) – Maximum number of punishment trials permitted in a row
- Returns
Intermediate Trial Array that contains stimulation trials per user’s rules
- Return type
stimulated_array
- trial_utils.gen_ITIArray(config_template)¶
Generate ITIArray for experimental runtime from configuration.
Generates ITIArray from users configuration file. Generates either static or jittered ITIs depending on user’s selection.
- Parameters
config_template (
dict
) – Configuration template value dictionary gathered from team’s configuration .json file.- Return type
list
- Returns
ITIArray
- trial_utils.gen_LEDArray(config_template, trialArray, ITIArray)¶
Generates LED stimulation timepoints if necessary.
Stimulation arrays have been incorporated into the Arduino scripts by default to avoid having several scripts per team to maintain. Therefore, for now at least, LEDArray is is a required part of array generation. This may change in the future where stimulation and no-stimulation experiments have their own Arduino scripts that are used.
- Parameters
config_template (
dict
) – Configuration template value dictionary gathered from team’s configuration .json filetrialArray (
ndarray
) – Completed trial array containing trial typesITIArray (
ndarray
) – Array of ITIs for the experiment
- Return type
list
- Returns
LEDArray
- trial_utils.gen_jitter_ITIArray(config_template)¶
Generate jittered ITIArray for given experiment from user specified bounds.
Generates array of ITIs from configuration the user provides. Uses a random uniform distribution bounded by the lower and upper ITIs as defined in the configuration file.
- Parameters
config_template (
dict
) – Configuration template value dictionary gathered from team’s configuration .json file.- Return type
list
- Returns
Jittered ITIArray.
- trial_utils.gen_jitter_toneArray(config_template)¶
Generate jittered toneArray for given experiment from user specified bounds.
Generates array of tones from configuration the user provides. Uses a random uniform distribution bounded by the lower and upper ITIs as defined in the configuration file.
- Parameters
config_template (
dict
) – Configuration template value dictionary gathered from team’s configuration .json file.- Return type
list
- Returns
Jittered toneArray.
- trial_utils.gen_static_ITIArray(config_template)¶
Generate static, or without jitter, ITIArray.
Generates array of ITIs using baseITI from configuration file for the number of trials specified by the user.
- Parameters
config_template (
dict
) – Configuration template value dictionary gathered from team’s configuration .json file.- Return type
list
- Returns
Static ITIArray
- trial_utils.gen_static_toneArray(config_template)¶
Generate static, or without jitter, toneArray.
Generates array of tones durations using baseTone from configuration file for the number of trials specified by the user.
- Parameters
config_template (
dict
) – Configuration template value dictionary gathered from team’s configuration .json file.- Return type
list
- Returns
Static toneArray
- trial_utils.gen_toneArray(config_template)¶
Generate toneArray for experimental runtime from configuration.
Generates toneArray from user’s configuration file. Generates either static or jittered tones depending on user’s selection.
- Parameters
config_template (
dict
) – Configuration template value dictionary gathered from team’s configuration .json file.- Return type
list
- Returns
toneArray
- trial_utils.gen_trialArray_nostim(config_template)¶
Creates pseudorandom trial structure for binary discrimination task without stimulation.
Generates array of stimuli and catch trials from configuration file the user provides. 1 and 0 encode stimuli where 1 is reward and 0 is punishment. 2 and 3 encode catch trials where 2 is aversive catch and 3 is reward catch.
- Parameters
config_template (
dict
) – Configuration template value dictionary gathered from team’s configuration .json file.- Return type
ndarray
- Returns
- trialArray
Trial array with user specified trial structure.
- trial_utils.gen_trialArray_stim(config_template)¶
Creates pseudorandom trial structure for binary discrimination task with LED stimulation.
Generates array of stimuli and catch trials from configuration file the user provides. 1 and 0 encode stimuli where 1 is reward and 0 is punishment. 2 and 3 encode catch trials where 2 is aversive catch and 3 is reward catch. 4, 5, and 6 encode LED stimulation where 4 is aversive stim, 5 is reward stim, and 6 is stim alone.
- Parameters
config_template (
dict
) – Configuration template value dictionary gathered from team’s configuration .json file.- Return type
ndarray
- Returns
- trialArray
Trial array with user specified trial structure using LED stimulation.
- trial_utils.generate_arrays(config_template)¶
Generates all necessary arrays for Bruker experimental runtime.
Creates arrays as specified by user’s configuration file. Builds the trialArray, ITIArray, toneArray, and LEDArray according to user defined rules.
- Parameters
config_template (
dict
) – Configuration template value dictionary gathered from team’s configuration .json file- Return type
list
- Returns
- experiment_arrays
List of experimental arrays to be sent via pySerialTransfer
- trial_utils.punish_catch_sample(punish_trials, num_catch_punish)¶
Generate random sample of punish trial indexes to flip.
Randomly select trials out of possible punish positions to flip to catch trials depending on the number of catch trials specified by the user.
- Parameters
punish_trials (
list
) – List of reward trial indexes past specified offset contained in the trialArray.num_catch_punish (
int
) – Number of punish catch trials to implement as specified by the user
- Return type
list
- Returns
Sampled punish catch trial index list.
- trial_utils.reward_catch_sample(reward_trials, num_catch_reward)¶
Generate random sample of reward trial indexes to flip.
Randomly select trials out of possible reweard positions to flip to catch trials depending on the number of catch trials specified by the user.
- Parameters
reward_trials (
list
) – List of reward trial indexes past specified offset contained in the trialArray.num_catch_reward (
int
) – Number of reward catch trials to implement as specified by the user
- Return type
list
- Returns
Sampled reward catch trial index list.
config_utils.py¶
Module contains functions for reading, writing, and passing configuration information to different modules or files including NWB files.
- exception config_utils.SubjectError(*args)¶
Exception for when there’s an error when parsing information for a subject.
- exception config_utils.TemplateError(*args)¶
Exception for when there’s an error when parsing templates.
- config_utils.build_server_directory(project, subject_id, config_template)¶
Builds directories for copying files to server at the end of the day.
Directories are not automatically built for different subjects on different days because dates and times might change. Therefore, they’re built during runtime. The directory for a given animal in the 2P folder for a given project will already exist, so this function creates the appropriate structure.
- Parameters
project (
str
) – The team and project conducting the experiment (ie teamname_projectname)subject_id (
str
) – Subject ID value from metadata_args[“project”]config_template (
dict
) – Configuration template gathered for the project by get_template()
- Returns
Path that files should be written to after experiment is finished.
- Return type
session_path
- config_utils.check_yoked_config(subject_type, current_plane, project)¶
Checks to see if a yoked trialset already exists for a session.
If a user wants yoked trial sessions, a check is performed to see if a trial set for the given experimental group and given plane has been generated yet. If no file is available, a None object is returned and trialsets are generated with trial_utils as normal. If a file is available, those experimental arrays are loaded and saved as the expeirment_arrays.
- Parameters
subject_type (
str
) – Type of group the subject is a part of, either “experimental” or “control”.current_plane (
int
) – Which plane number is being currently imaged (i.e. 1, 2, 3)project (
str
) – The team and project conducting the experiment (ie teamname_projectname)
- Return type
list
- Returns
experiment_arrays
- config_utils.get_arduino_metadata(config_template)¶
Grabs metadata relevent to Arduino runtime
Parses the template configuration supplied by the user and grabs only the metadata that is relevant for the Arduino’s function using dictionary comprehension. Finally converts dictionary to json object for transfer.
- Parameters
config_template (
dict
) – Configuration template value dictionary gathered from team’s configuration .json file.- Return type
dict
- Returns
- arduino_metadata
Dictionary of relevant Arduino metadata for experiment.
- config_utils.get_subject_metadata(project, subject_id)¶
Parses imaging subject’s .yml metadata file for NWB fields
Locates and then uses ruamel.yaml to parse the metadata fields with safe loading. Gathers yaml data and places it into a dictionary for use later in the NWB file.
- Parameters
project (
str
) – The team and project conducting the experiment (ie teamname_projectname)subject_id (
str
) – Subject ID from metadata_args[“subject”]
- Return type
dict
- Returns
subject_metadata
- config_utils.get_surgery_metadata(subject_metadata)¶
Grabs surgery information from subject’s metadata file.
Implant information and virus information for stimulation and recording is contained within the subject’s metadata file. This information is used for filenaming purposes particularly in the Z-Stack files as well as the NWB files’ metadata sections.
- Parameters
subject_metadata (
dict
) – Metadata obtained from get_subject_metadata()- Return type
dict
- Returns
surgery_metadata
- config_utils.get_template(project)¶
Grab team’s template configuration file for experiment runtime.
Uses the metadata_args values “team” and “project” found in bruker_control to select the specific 2-Photon configuration file that will run the experiment for a session.
- Parameters
project (
str
) – The team and project conducting the experiment (ie teamname_projectname)- Return type
dict
- Returns
template_config
- config_utils.get_zstack_metadata(config_template)¶
Grabs metadata relevant for generating Z-stacks
Parses template configuration supplied by the user and grabs only the metadata that is relevant for Prairie View executing a Z-stack.
- Parameters
config_template (
dict
) – Configuration template value dictionary gathered from team’s configuration .json file.- Return type
dict
- Returns
- zstack_metadata
Dictionary of relevant Prairie View Z-Stack for experiment
- config_utils.read_config(config_path)¶
Utility function for reading config files
General purpose function for reading .json files containing configuration values for an experiment.
- Parameters
config_path (
Path
) – Pathlib path to the template configuration file.- Return type
dict
- Returns
Dictionary of contents inside the configuration .json file
- config_utils.weight_check(project, subject_id)¶
Checks subject’s weight file for current measurement.
Some teams want to ensure that their recordings have a weight gathered that day. In practice, it can be something that users could forget to do accidentally and then be left without that data when they need it. If the project’s configuration requires users to gather a weight for that day, this function will search for the subject’s weight file and check if a measurement has been taken.
- Parameters
project (
str
) – The team and project conducting the experiment (ie teamname_projectname)subject_id (
str
) – Subject ID value from metadata_args[“project”]
- config_utils.write_experiment_config(config_template, experiment_arrays, dropped_frames, project, subject_id, imaging_plane, current_plane)¶
Writes experiental configuration file to Raw Data drive.
Takes the configuration template and appends on the experimental arrays and dropped frames from the experiment. Then writes the configuration to disk.
- Parameters
config_template (
dict
) – Configuration template value dictionary gathered from team’s configuration .json file.experiment_arrays (
list
) – List of arrays used for experimental runtime. [0] is trialArray, [1] is ITIArray, [2] is toneArray, [3] is LEDArray. These must always be in this order.dropped_frames (
list
) – List of dropped frames from the camera during the experimentproject (
str
) – The team and project conducting the experiment (ie teamname_projectname)subject_id (
str
) – Subject ID from metadata_args[“subject_id”]imaging_plane (
str
) – Plane 2P images were acquired at, the Z-axis valuecurrent_plane (
int
) – Current plane being imaged as in 1st, 2nd, 3rd, etc
- config_utils.write_yoked_config(subject_type, current_plane, project, experiment_arrays)¶
Write out yoked configurations for unique plane/subject combinations.
Yoked trial sets indicate that an entire experimental group will receive the same pseudorandom trials. This generates sessions that are far easier to compare between mice and also larger N for each dataset for statistical analysis of neural activity later. These are written to the local filesystem first and will be copied to the server at the end of the day.
- Parameters
subject_type (
str
) – Type of group the subject is a part of, either “experimental” or “control”.current_plane (
int
) – Which plane number is being currently imaged (i.e. 1, 2, 3)project (
str
) – The team and project conducting the experiment (ie teamname_projectname)experiment_arrays (
list
) – List of experimental arrays to be sent via pySerialTransfer
prairieview_utils.py¶
Module contains functions for interacting with Prairie View’s API to set data directories, filenames, and gathering imaging plane information. Also sets microscope laser values according to user presets and initiates image acquisition.
- exception prairieview_utils.PrairieLinkPasswordError(*args)¶
Exception for when there’s an error when parsing prairelink password.
- prairieview_utils.configure_zseries(project, subject_id, current_plane, imaging_plane, indicator_name, stack, zstack_delta, zstack_step)¶
Readies the Bruker 2-Photon microscope for a Z-Series
Sets directories and filenames for Z-stack recording as well as defines the distance a z-stack should be taken as well as the step distance for the Piezo motor. Transitions Galvo mode to Galvo from Resonant Galvo.
- Parameters
project (
str
) – The team and project conducting the experiment (ie teamname_projectname)subject_id (
str
) – Name of the experimental subjectcurrent_plane (
int
) – Current plane being imaged as in 1st, 2nd, 3rd, etcimaging_plane (
float
) – Current Z-Motor position for given recording planeindicator_name (
str
) – Name of the fluorophore being imaged during the Z-seriesstack (
int
) – The current stack number from the total number of stacks requestedzstack_delta (
float
) – Delta both above and below current imaging plane to collect per stackzstack_step (
float
) – Step size to go between individual planes
- prairieview_utils.end_tseries()¶
Ends T-Series Microscopy recording
Once the number of frames specified is collected, a signal to abort the microscopy session is sent to Prairie View. This function takes no arguments and returns nothing.
- prairieview_utils.get_imaging_indicators(surgery_metadata)¶
Gets imaging indicators from surgery metadata.
Only a subset of metadata from the surgery information is requried for changing laser values and filenames. This builds a dictionary of those indicators and relevant values.
- Parameters
surgery_metdata – Surgical information for a given subject including virus data describing excitation and emission wavelengths.
- Return type
dict
- Returns
indicator_metadata
- prairieview_utils.get_imaging_plane()¶
Gets current position of Z-axis motor from Prairie View
Gathers what plane is being imaged for the microscopy session for use in file naming and Z-Stack movement.
- Return type
float
- Returns
imaging_plane
- prairieview_utils.get_laser_power()¶
Queries Prairie View for the microscope’s current laser power.
The function will query Prairie View for the scope’s current laser power setting.
- Return type
int
- Returns
laser_power
- prairieview_utils.get_microscope_framerate()¶
Queries Prairie View for the microscope’s framerate before a recording is started.
The scope appears to have slightly different framerates between starts of Prairie View on the orders of 0.01FPS. To ensure that the video codec for the facial recording is using the same timescale, getting the scope’s state for framerate is necessary. This will query Prairie View for the scope’s current framerate setting, round the framerate UP to the nearest hundreth, and return it so the video codec uses the correct FPS.
- Return type
float
- Returns
microscope_framerate
- prairieview_utils.get_pmt_gain(channel_number)¶
Queries Prairie View for the microscope’s channel number.
The function will query Prairie View for the scope’s current channel number setting, and returns it as the correct value of each PMT’s gain.
- Parameters
channel_number (
int
) – channel the software will monitor for data collection- Returns
pmt_gain
- prairieview_utils.get_pv_password()¶
Load Prairie View Password from file or obtain it from user.
Prairie View has placed a password on their API that’s unique to each user account on the system. Per Michael Fox, this was done not because of worries about malicious intent but because sometimes IT systems will be HTTP address sniffing (basically looking for computers to talk to) and start trying to talk to the scope on accident. This can keep the scope’s software either busy or, more likely, will raise errors from Bruker’s API that interferes with the experiment as the API will interpret the communications as (malformed) PrairieLink commands.
Since it’s different per user, a local file must be stored in the repo that contains the correct password. This password is found by going to: Tools -> Scripts -> Edit Scripts … dialog in the bottom left corner of the window. It is 4 characters long, all uppercase. The default password will be the string “0000” and must be updated by the user the first time they install bruker_control OR likely when there’s a Prairie View Update. If the password isn’t the default, it’s passed onto the connect function.
- Return type
str
- Returns
password
- prairieview_utils.prepare_tseries(project, subject_id, current_plane, imaging_plane, surgery_metadata)¶
Readies the Bruker 2-Photon microscope for a T-Series experiment
Sets directories and filenames for recording. Ensures that Resonant Galvo mode is selected. Sets Prairie View to only use the gcamp indicator channel (Channel 2). Initializes Bruker T-Series for imaging, Voltage Recording for behavior data, and Mark Points Series as a work around for stimulation trials.
- Parameters
project (
str
) – The team and project conducting the experiment (ie teamname_projectname)subject_id (
str
) – Name of the experimental subjectcurrent_plane (
int
) – Current plane being imaged as in 1st, 2nd, 3rd, etcimaging_plane (
float
) – Current Z-Motor position for given recording planesurgery_metadata (
dict
) – Surgical information for a given subject including virus data describing excitation and emission wavelengths.
- prairieview_utils.pv_connect()¶
Connect to Prairie View
First grabs machin hostname and IP address for connecting to Prairie Link. Used to connect to Prairie View at the beginning of each session with their API. This function takes no arguments and returns nothing.
- prairieview_utils.pv_disconnect()¶
Disconnect from Prairie View
Used to disconnect from Prairie View at the end of each session with their API. This function takes no arguments and returns nothing.
- prairieview_utils.set_galvo_galvo()¶
Sets Acquisition Mode to Galvo Galvo.
Z-Series recordings are performed in Galvo Galvo mode. This ensures that the mode is switched before the recording starts. Sleeps the program for 1 second to make sure Prairie View has enough tim to switch. This function takes no arguments and returns nothing
- prairieview_utils.set_laser_lambda(indicator_lambda)¶
Sets laser lambda to appropriate wavelength for indicator.
Each indicator has its own optimal excitation wavelength equal to two times the value found in the surgical metadata for the subject. This update is performed in this function before setting the laser wavelength for the series of Z-stacks that are being collected. Sleeps the program for 3 seconds to ensure switch occurs.
- Parameters
indicator_lambda (
float
) – Excitation wavelength for the indicator being imaged
- prairieview_utils.set_one_channel_zseries(indicator_emission)¶
Sets proper recording channel to use (1: Red 2: Green) in the z-stack.
Different indicators have different channels that should be recorded from depending on the emission wavelengths of the indicators being imaged.
- Parameters
indicator_emission (
float
) – Wavelength fluorescent indicator emits when cell is active and being stimulated by light
- prairieview_utils.set_resonant_galvo()¶
Sets acquisition mode to Resonant Galvo.
Not having resonant galvo mode engaged during T-Series recordings gathers insufficient data and does not trigger the facial recording camera correctly. This ensures that it is enabled before the recording starts. Sleeps the program for 1 second to make sure Prairie View has enough time to switch. This function takes no arguments and returns nothing.
- prairieview_utils.set_tseries_filename(project, subject_id, current_plane, imaging_plane)¶
Sets T-Series and Behavior recording filenames and directories.
Generates appropriately named imaging and behavior directories and filenames for data coming off the microscope.
- Parameters
project (
str
) – The team and project conducting the experiment (ie teamname_projectname)subject_id (
str
) – The subject being recordedcurrent_plane (
int
) – The plane being imaged as in 1st, 2nd, 3rd, etcimaging_plane (
float
) – Current Z-Motor position for given recording plane
- prairieview_utils.set_tseries_parameters(surgery_metadata)¶
Changes laser lambda to correct wavelength for t-series.
The laser may or may not be set to use the appropriate wavelength for imaging. This ensures that the laser is set to the correct wavelength for the functional indicator specified in the surgical metadata.
- prairieview_utils.set_zseries_filename(project, subject_id, current_plane, imaging_plane, indicator_name, stack)¶
Sets Z-Series filename and directory.
Generates appropriately named Z-Series filenames for data coming off the microscope.
- Parameters
project (
str
) – The team and project conducting the experiment (ie teamname_projectname)subject_id (
str
) – The subject being recordedcurrent_plane (
int
) – Current plane being imaged as in 1st, 2nd, 3rd, etcimaging_plane (
float
) – Current Z-Motor position for given recording planeindicator_name (
str
) – Name of the fluorophore being imaged during the Z-seriesstack (
int
) – The stack being imaged as in 1st, 2nd, 3rd, etc
- prairieview_utils.set_zseries_parameters(imaging_plane, zstack_delta, zstack_step)¶
Set Z-Series depth and step sizes.
Sets Prairie View’s Z-Series parameters for the depth of the stack as well as the step size between imaging planes
- Parameters
imaging_plane – Current Z-Motor position for given recording plane
zstack_delta – Z-Stack distance to move above and below imaging_plane
zstack_step – Step size to go between individual planes
- prairieview_utils.tseries(project, subject_id, current_plane, imaging_plane, surgery_metadata=None)¶
Starts Prairie View 2-P T-Series Experiment
Function unites t-series preparation function with starting the recording with an input trigger. Starting with an input trigger is done within the Prairie View GUI.
- Parameters
project (
str
) – The team and project conducting the experiment (ie teamname_projectname)subject_id (
str
) – Name of the experimental subjectcurrent_plane (
int
) – Current plane being imaged as in 1st, 2nd, 3rd, etcimaging_plane (
float
) – Current Z-Motor position for given recording planesurgery_metadata –
- prairieview_utils.zstack(zstack_metadata, project, subject_id, current_plane, imaging_plane, surgery_metadata)¶
Starts Prairie View Z-Series 2P Recording
Starts Z-stack recording at the start of a given session for a subject and moves through configuration specific planes with configuration specific step sizes. Writes out the raw stack to team’s microscopy folder.
- Parameters
zstack_metadata (
dict
) – Information about depth for Z-Stack and step distanceproject (
str
) – The team and project conducting the experiment (ie teamname_projectname)subject_id (
str
) – Name of the experimental subjectcurrent_plane (
int
) – Current plane being imaged as in 1st, 2nd, 3rd, etcimaging_plane (
float
) – Current Z-Motor position for given recording planesurgery_metdata – Surgical information for a given subject including virus data describing excitation and emission wavelengths.
serialtransfer_utils.py¶
Module contains functions for sending, receiving, and checking trial information to the Arduino delivering stimuli via pySerialTransfer.
- class serialtransfer_utils.Arduino(sketch_path, idx=0)¶
Generic Arduino class for interacting with arbitrary Arduino boards.
Class for discovering boards available on the system with ability to select arbitrary Arduino boards discovered on the machine. Compiles and uploads sketches to the board before the experiment starts.
- compile_sketch()¶
Use the CLI to compile the project’s Arduino sketch
- classmethod list_boards()¶
Query CLI for finding available Arduinos on the machine.
- Return type
List
[tuple
]
- upload_sketch()¶
Use the CLI to upload the sketch to the Arduino.
- exception serialtransfer_utils.SketchError(*args)¶
Exception for when there’s an error finding or using an Arduino sketch.
- serialtransfer_utils.array_error_check(transmitted_array, received_array)¶
Performs Python side error checking for array transmission.
While pySerialTransfer performs error checking for different errors, this allows for something simple that is independent of the package for error checking.
- Parameters
transmitted_array (
list
) – Array that was sent to the Arduinoreceived_array (
list
) – Array that was received by the Arduino
- serialtransfer_utils.onepacket_transfer(experiment_arrays, link)¶
Function for completing experiment arrays one packet transfers to Arduino.
Iterates over transfer_packet() function for each experiment array and invoked if the session length is less than or equal to 60 trials. Finally invokes the update_python_status() function to say transmission is complete.
- Parameters
experiment_arrays (
list
) – List of arrays generated for a given microscopy session’s behavior. 0th index is trialArray, 1st is ITIArray, 2nd is toneArray.link (
SerialTransfer
) – pySerialTransfer transmission object
- serialtransfer_utils.transfer_data(arduino_metadata, experiment_arrays)¶
Sends metadata and trial information to the Arduino.
Takes each array assembled for transmission to the Arduino and stuffs it into packets to be sent via pySerialTransfer. Unites several functions used for transmitting, receiving, and checking data during transfer.
- Parameters
arduino_metadata (
str
) – Metadata gathered from config_template that’s relevant for Arduino runtime. Formatted as a json string.experiment_arrays (
list
) – List of arrays generated for a given microscopy session’s behavior. 0th index is trialArray, 1st is ITIArray, 2nd is toneArray, and 3rd is the LEDArray.
- serialtransfer_utils.transfer_experiment_arrays(experiment_arrays, link)¶
Transfers experimental arrays to Arduino via pySerialTransfer.
Determines what type of packet transfer is required (single or multi) for the generated trials. If the number of trials is greater than 60, then multiple packets are required for transferring each array. If less, then only one packet is required for each array.
- Parameters
experiment_arrays (
list
) – List of arrays generated for a given microscopy session’s behavior. 0th index is trialArray, 1st is ITIArray, 2nd is toneArray, 3rd is the LEDArray.link (
SerialTransfer
) – pySerialTransfer transmission object
- serialtransfer_utils.transfer_metadata(arduino_metadata, link)¶
Transfers arduino_metadata to the Arduino.
Arduino metadata collected from config_template is formatted into a json string that the Arduino knows how to interpret. Each variable is encoded according to a specific byte size depending on the variable type.
- Parameters
arduino_metadata (
str
) – Metadata gathered from config_template that’s relevant for Arduino runtime. Formatted as a json string.link (
SerialTransfer
) – pySerialTransfer transmission object
- serialtransfer_utils.transfer_packet(array, packet_id, link)¶
Transfers an individual packet to the Arduino.
Each packet is given a unique ID the Arduino can identify and transmitted through the pySerialTransfer link. While the link is unavailable, that is there’s an active transfer, the function passes. When finished transmitting, the function receives what the Arduino encoded and an error check is performed. If it passes, the program continues. If it fails, an exception is raised and the program exits.
- Parameters
array (
list
) – Experimental array to be transferredpacket_id (
int
) – Unique ID for encoding an arraylink (
SerialTransfer
) – pySerialTransfer transmission object
- serialtransfer_utils.update_python_status(packet_id, link)¶
Updates python side of program as ready to continue post serial transfer.
Once the packets have all been transmitted to the Arduino, this final step is performed to ensure that all information has made it across the link. Once this check is passed, the connection to the Arduino closes and the experiment will start!
- Parameters
packet_id (
int
) – Unique ID for encoding an arraylink (
SerialTransfer
) – pySerialTransfer transmission object
- serialtransfer_utils.upload_arduino_sketch(project)¶
Takes project name running experiment and finds sketch, uploads to board.
Uses project name to grab .ino file for given team, compiles it, and finally sends it to the Arduino using the arduino-cli.
- Parameters
project (
Path
) – The team and project conducting the experiment (ie teamname_projectname)
flight_manifest.py¶
GUI for selecting which mice are scheduled to be run in a given day’s imaging. Thank you to Dr. Jonny Saunders for showing me how to do it! <3