Data processors

Methods for manipulating classification and pose-estimation data

Aggregate classifier statistics calculator

class simba.data_processors.agg_clf_calculator.AggregateClfCalculator(config_path: Union[str, PathLike], data_measures: List[typing_extensions.Literal['Bout count', 'Total event duration (s)', 'Mean event bout duration (s)', 'Median event bout duration (s)', 'First event occurrence (s)', 'Mean event bout interval duration (s)', 'Median event bout interval duration (s)']], classifiers: List[str], detailed_bout_data: bool = False, transpose: bool = False, video_meta_data: Optional[List[typing_extensions.Literal['Frame count', 'Video length (s)']]] = None)[source]

Bases: ConfigReader

Compute aggregate descriptive statistics from classification data.

Parameters
  • config_path (str) – path to SimBA project config file in Configparser format

  • data_measures (List[str]) – Aggregate statistics measures to calculate. OPTIONS: [‘Bout count’, ‘Total event duration (s)’, ‘Mean event bout duration (s)’, ‘Median event bout duration (s)’, ‘First event occurrence (s)’, ‘Mean event bout interval duration (s)’, ‘Median event bout interval duration (s)’]

  • classifiers (List[str]) – Classifiers to calculate aggregate statistics for. E.g.,: [‘Attack’, ‘Sniffing’]

  • video_meta_data (Optional[List[str]]) – Video metadata to include in the output. Options: ‘Frame count’, ‘Video length (s)’.

  • detailed_bout_data (bool) – If True, save detailed data for each bout in each video (start frame, end frame, bout time etc.)

  • transpose (bool) – If True, then one video per row. Else, one meassure per row. Default: False.

Examples

>>> clf_log_creator = AggregateClfCalculator(config_path="MyConfigPath", data_measures=['Bout count', 'Total event duration (s)'], classifiers=['Attack', 'Sniffing'])
>>> clf_log_creator.run()
>>> clf_log_creator.save()
save() None[source]

Method to save classifier aggregate statistics created in analyze_data() to disk. Results are stored in the project_folder/logs directory of the SimBA project

Directing-other-animals calculator

class simba.data_processors.directing_other_animals_calculator.DirectingOtherAnimalsAnalyzer(config_path: Union[str, PathLike], data_paths: Optional[Union[str, PathLike]] = None, bool_tables: Optional[bool] = True, summary_tables: Optional[bool] = False, append_bool_tables_to_features: Optional[bool] = False, aggregate_statistics_tables: Optional[bool] = False)[source]

Bases: ConfigReader, FeatureExtractionMixin

Calculate when animals are directing towards body-parts of other animals. Results are stored in the project_folder/logs/directionality_dataframes directory of the SimBA project.

Important

Requires the pose-estimation data for the left ear, right ear and nose of each individual animals. Github Tutorial. Expected output.

Parameters
  • config_path (str) – path to SimBA project config file in Configparser format.

  • bool_tables (bool) – If True, creates boolean output tables.

  • summary_tables (bool) – If True, creates summary tables including approximate location of eye of observer and the location of observed body-parts and frames when observation was detected.

  • aggregate_statistics_tables (bool) – If True, summary statistics tables of how much time each animal spent observation the other animals.

Examples

>>> directing_analyzer = DirectingOtherAnimalsAnalyzer(config_path='MyProjectConfig')
>>> directing_analyzer.run()

Forward-spike-time-tiling coefficient calculator

class simba.data_processors.fsttc_calculator.FSTTCCalculator(config_path: Union[str, PathLike], time_window: int, behavior_lst: List[str], time_delta_at_onset: Optional[bool] = False, join_bouts_within_delta: Optional[bool] = False, create_graphs: Optional[bool] = False)[source]

Bases: ConfigReader, PlottingMixin

Compute forward spike-time tiling coefficients between pairs of classified behaviors.

Parameters
  • config_path (str) – path to SimBA project config file in Configparser format.

  • time_window (int) – FSTTC hyperparameter; Integer representing the time window in seconds.

  • behavior_lst (List[str]) – Behaviors to calculate FSTTC between. FSTTC will be computed for all combinations of behaviors.

  • create_graphs (bool) – If True, created violin plots (as below) representing each FSTTC. Default: False.

Parameter

Optional[bool] join_bouts_within_delta: If several bouts onsets (of the same classifier) occurs within a single time-delta, then join the bouts into a single bout.

Parameter

Optional[bool] time_delta_at_onset: If True, time delta is initatiated at bout onset. If False, then initated at bout offset and includes bout duration. Default: False.

_images/fsttc_violin.png

Note

Tutorial.

Examples

>>> fsttc_calculator = FSTTCCalculator(config_path='MyConfigPath', time_window=2, behavior_lst=['Attack', 'Sniffing'], create_graphs=True)
>>> fsttc_calculator.run()

References

1

Lee et al., Temporal microstructure of dyadic social behavior during relationship formation in mice, PLOS One, 2019.

2

Cutts et al., Detecting Pairwise Correlations in Spike Trains: An Objective Comparison of Methods and Application to the Study of Retinal Waves, J Neurosci, 2014.

find_sequences()[source]

Method to create list of dataframes holding information on the sequences of behaviors including inter-temporal distances.

Returns

Attribute – vide_df_sequence_lst

Return type

list

run()[source]

Method to calculate forward spike-time tiling coefficients (FSTTC) using the data computed in :meth: find_sequences().

Returns

Attribute – results_dict

Return type

dict

save()[source]

Method to save forward spike-time tiling coefficients (FSTTC) to disk within the project_folder/logs directory.

Return type

None

Pose interpolator calculator

class simba.data_processors.interpolate_pose.Interpolate(config_file_path: str, in_file: DataFrame)[source]

Bases: ConfigReader

Interpolate missing body-parts in pose-estimation data.

Parameters
  • config_file_path (str) – path to SimBA project config file in Configparser format

  • in_file (pd.DataFrame) – Pose-estimation data

Notes

Interpolation tutorial.

Examples

>>> body_part_interpolator = Interpolate(config_file_path='MyProjectConfig', in_file=input_df)
>>> body_part_interpolator.detect_headers()
>>> body_part_interpolator.fix_missing_values(method_str='Body-parts: Nearest')
>>> body_part_interpolator.reorganize_headers()
detect_headers()[source]

Method to detect multi-index headers and set values to numeric in input dataframe

fix_missing_values(method_str: str)[source]

Method to interpolate missing values in pose-estimation data.

Parameters

method_str (str) – String representing interpolation method. OPTIONS: ‘None’,’Animal(s): Nearest’, ‘Animal(s): Linear’, ‘Animal(s): Quadratic’,’Body-parts: Nearest’, ‘Body-parts: Linear’, ‘Body-parts: Quadratic’

reorganize_headers()[source]

Method to re-insert original multi-index headers

Pose interpolator and smoothing calculators

class simba.data_processors.interpolation_smoothing.AdvancedInterpolator(data_dir: Union[str, PathLike], config_path: Union[str, PathLike], type: typing_extensions.Literal['animal', 'body-part'], settings: Dict[str, Any], initial_import_multi_index: Optional[bool] = False, overwrite: Optional[bool] = True)[source]

Bases: ConfigReader

Interpolation method that allows different interpolation parameters for different animals or body-parts. For example, interpolate some body-parts of animals using linear interpolation, and other body-parts of animals using nearest interpolation.

Parameters
  • data_dir (str) – path to pose-estimation data in CSV or parquet format

  • config_path (str) – path to SimBA project config file in Configparser format.

  • type (Literal) – Type of interpolation: animal or body-part.

  • settings (Dict) – Interpolation rules for each animal or each animal body-part.

  • initial_import_multi_index (bool) – If True, the incoming data is multi-index columns dataframes. Use of input data is the project_folder/csv/input_csv directory. Default: False.

  • overwrite (bool) – If True, overwrites the input data. If False, then saves input data in datetime-stamped sub-directory.

Examples

>>> interpolator = AdvancedInterpolator(data_dir='/Users/simon/Desktop/envs/troubleshooting/two_black_animals_14bp/project_folder/csv/input_csv',
>>>                                     config_path='/Users/simon/Desktop/envs/troubleshooting/two_black_animals_14bp/project_folder/project_config.ini',
>>>                                     type='animal',
>>>                                     settings={'Simon': 'linear', 'JJ': 'quadratic'}, initial_import_multi_index=True)
>>> interpolator.run()
class simba.data_processors.interpolation_smoothing.AdvancedSmoother(data_dir: Union[str, PathLike], config_path: Union[str, PathLike], type: typing_extensions.Literal['animal', 'body-part'], settings: Dict[str, Any], initial_import_multi_index: Optional[bool] = False, overwrite: Optional[bool] = True)[source]

Bases: ConfigReader

Smoothing method that allows different smoothing parameters for different animals or body-parts. For example, smooth some body-parts of animals using Savitzky-Golay smoothing, and other body-parts of animals using Gaussian smoothing.

Parameters
  • data_dir (str) – path to pose-estimation data in CSV or parquet format

  • config_path (str) – path to SimBA project config file in Configparser format.

  • type (Literal) – Level of smoothing: animal or body-part.

  • settings (Dict) – Smoothing rules for each animal or each animal body-part.

  • initial_import_multi_index (bool) – If True, the incoming data is multi-index columns dataframes. Use of input data is the project_folder/csv/input_csv directory. Default: False.

  • overwrite (bool) – If True, overwrites the input data. If False, then saves a copy input data in datetime-stamped sub-directory.

Examples

>>> smoother = AdvancedSmoother(data_dir='/Users/simon/Desktop/envs/troubleshooting/two_black_animals_14bp/project_folder/csv/input_csv',
>>>                             config_path='/Users/simon/Desktop/envs/troubleshooting/two_black_animals_14bp/project_folder/project_config.ini',
>>>                             type='animal',
>>>                             settings={'Simon': {'method': 'Savitzky Golay', 'time_window': 200},
>>>                                       'JJ': {'method': 'Savitzky Golay', 'time_window': 200}},
>>>                             initial_import_multi_index=True,
>>>                             overwrite=False)
>>> smoother.run()
class simba.data_processors.interpolation_smoothing.Interpolate(input_path: Union[str, PathLike], config_path: Union[str, PathLike], method: typing_extensions.Literal['Animal(s): Nearest', 'Animal(s): Linear', 'Animal(s): Quadratic', 'Body-parts: Nearest', 'Body-parts: Linear', 'Body-parts: Quadratic'], initial_import_multi_index: bool = False)[source]

Bases: ConfigReader

Interpolate missing body-parts in pose-estimation data. “Missing” is defined as either (i) when a single body-parts is None, or when all body-parts belonging to an animal are identical (i.e., the same 2D coordinate or all None).

Parameters
  • input_path (str) – Directory or file path to pose-estimation data in CSV or parquet format

  • config_path (str) – path to SimBA project config file in Configparser format.

  • str (Literal) – Type of interpolation. OPTIONS: ‘Animal(s): Nearest’, ‘Animal(s): Linear’, ‘Animal(s): Quadratic’,’Body-parts: Nearest’, ‘Body-parts: Linear’, ‘Body-parts: Quadratic’] See tutorial for info/images of the different interpolation types.

  • initial_import_multi_index (bool) – If True, the incoming data is multi-index columns dataframes. Default: False.

_images/interpolation_comparison.png

Examples

>>> _ = Interpolate(input_path=data_path, config_path=SimBaProjectConfigPath, method='Animal(s): Nearest')
class simba.data_processors.interpolation_smoothing.Smooth(config_path: str, input_path: str, time_window: int, smoothing_method: typing_extensions.Literal['Gaussian', 'Savitzky-Golay'], initial_import_multi_index: bool = False)[source]

Bases: ConfigReader

Smooth pose-estimation data according to user-defined method.

Parameters
  • input_path (str) – path to pose-estimation data in CSV or parquet format

  • config_path (str) – path to SimBA project config file in Configparser format.

  • str (Literal) – Type of smoothing_method. OPTIONS: Gaussian, Savitzky-Golay.

  • time_window (int) – Rolling time window in millisecond to use when smoothing. Larger time-windows and greater smoothing.

  • initial_import_multi_index (bool) – If True, the incoming data is multi-index columns dataframes. Default: False.

_images/smoothing.gif
References
1

Video expected putput.

Examples

>>> _ = Smooth(input_path=data_path, config_path=SimBaProjectConfigPath, smoothing_method='Savitzky-Golay', time_window=300)

Kleinberg calculator

class simba.data_processors.kleinberg_calculator.KleinbergCalculator(config_path: Union[str, PathLike], classifier_names: List[str], sigma: Optional[int] = 2, gamma: Optional[float] = 0.3, hierarchy: Optional[int] = 1, hierarchical_search: Optional[bool] = False, input_dir: Optional[Union[str, PathLike]] = None, output_dir: Optional[Union[str, PathLike]] = None)[source]

Bases: ConfigReader

Smooth classification data using the Kleinberg burst detection algorithm.

Note

Tutorial.

_images/kleinberg.png
Parameters
  • config_path (str) – path to SimBA project config file in Configparser format

  • classifier_names (List[str]) – Classifier names to apply Kleinberg smoothing to.

  • sigma (float) – Burst detection sigma value. Higher sigma values and fewer, longer, behavioural bursts will be recognised. Default: 2.

  • gamma (float) – Burst detection gamma value. Higher gamma values and fewer behavioural bursts will be recognised. Default: 0.3.

  • hierarchy (int) – Burst detection hierarchy level. Higher hierarchy values and fewer behavioural bursts will to be recognised. Default: 1.

  • hierarchical_search (bool) – See Tutorial Default: False.

  • input_dir (Optional[Union[str, os.PathLike]]) – The directory with files to perform kleinberg smoothing on. If None, defaults to project_folder/csv/machine_results

  • output_dir (Optional[Union[str, os.PathLike]]) – Location to save smoothened data in. If None, defaults to project_folder/csv/machine_results

Example I

>>> kleinberg_calculator = KleinbergCalculator(config_path='MySimBAConfigPath', classifier_names=['Attack'], sigma=2, gamma=0.3, hierarchy=2, hierarchical_search=False)
>>> kleinberg_calculator.run()
Example 2

>>> output_dir = r'/Users/simon/Desktop/envs/troubleshooting/two_black_animals_14bp/project_folder/csv/kleinberg_gridsearch_test'
>>> input_dir = r'/Users/simon/Desktop/envs/troubleshooting/two_black_animals_14bp/project_folder/csv/kleinberg_gridsearch_test'
>>> kleinberg_calculator = KleinbergCalculator(config_path=r'/Users/simon/Desktop/envs/troubleshooting/two_black_animals_14bp/project_folder/project_config.ini', classifier_names=['Attack', 'Sniffing', 'Rear'], sigma=2, gamma=0.3, hierarchy=3, hierarchical_search=False, input_dir=input_dir, output_dir=output_dir)

References

1

Kleinberg, Bursty and Hierarchical Structure in Streams, Data Mining and Knowledge Discovery, vol. 7, pp. 373–397, 2003.

2

Lee et al., Temporal microstructure of dyadic social behavior during relationship formation in mice, PLOS One, 2019.

3

Bordes et al., Automatically annotated motion tracking identifies a distinct social behavioral profile following chronic social defeat stress, bioRxiv, 2022.

Movement calculator

class simba.data_processors.movement_calculator.MovementCalculator(config_path: str, body_parts: List[str], threshold: float = 0.0, file_paths: Optional[List[str]] = None)[source]

Bases: ConfigReader, FeatureExtractionMixin

Compute aggregate movement statistics from pose-estimation data in SimBA project.

Parameters str config_path

path to SimBA project config file in Configparser format

Parameters
  • body_parts (List[str]) – Body-parts to use for movement calculations OR Animal_name CENTER OF GRAVITY. If Animal_name CENTER OF GRAVITY, then SimBA will approximate animal centroids through convex hull.

  • threshold (float) – Filter body-part detection below set threshold (Value 0-1). Default: 0.00

  • file_paths (List[str] or None) – Files to calucalte movements for. If None, then all files in project_folder/csv/outlier_corrected_movement_location directory.

Note

Tutorial.

Examples

>>> body_parts=['Animal_1 CENTER OF GRAVITY']
>>> movement_processor = MovementCalculator(config_path='project_folder/project_config.ini', body_parts=body_parts)
>>> movement_processor.run()
>>> movement_processor.save()

Pup-retrieval calculator

class simba.data_processors.pup_retrieval_calculator.PupRetrieverCalculator(config_path: str, settings: Dict[str, Union[float, str, bool]])[source]

Bases: ConfigReader

Pup retreival calculator used in Winters et al., `Sci Reports`, 2022

Parameters
  • config_path (str) – path to SimBA project config file in Configparser format

  • settings (dict) – user-defined setting for pup retrieval.

Examples

>>> settings = {'pup_track_p': 0.025, 'dam_track_p': 0.5, 'start_distance_criterion': 80.0, 'carry_frames': 90.0, 'core_nest': 'corenest', 'nest': 'nest', 'dam_name': '1_mother', 'pup_name': '2_pup', 'smooth_function': 'gaussian', 'smooth_factor': 5, 'max_time': 90.0, 'clf_carry': 'carry', 'clf_approach': 'approach', 'clf_dig': 'digging', 'distance_plots': True, 'log': True, 'swarm_plot': True}
>>> config_path = '/Users/simon/Downloads/Automated PRT_test/project_folder/project_config.ini'
>>> calculator = PupRetrieverCalculator(config_path=config_path, settings=settings)
>>> calculator.run()

References

1

Winters et al., Automated procedure to assess pup retrieval in laboratory mice, Sci Reports, 2022.

SimBA pyburst calculator

simba.data_processors.pybursts_calculator.kleinberg_burst_detection(offsets: ndarray, s: float, gamma: float)[source]

Burst detection using pyburst. Private method called by simba.data_processors.kleinberg_calculator.KleinbergCalculator.

Severity calculator

class simba.data_processors.severity_calculator.SeverityCalculator(config_path: Union[str, PathLike], settings: Dict)[source]

Bases: ConfigReader

Computes the “severity” of classification frame events based on how much the animals are moving. Frames are scored as less or more severe at lower and higher movements, respectively.

Parameters
  • config_path (str) – path to SimBA project config file in Configparser format.

  • settings (dict) – how to calculate the severity. E.g., {‘brackets’: 10, ‘clf’: ‘Attack’, ‘animals’: [‘Simon’, ‘JJ’], ‘time’: True, ‘frames’: False}.

Note

Tutorial.

Examples

>>> settings = {'brackets': 10, 'clf': 'Attack', 'animals': ['Simon', 'JJ'], 'time': True, 'frames': False}
>>> processor = SeverityCalculator(config_path='project_folder/project_config.ini', settings=settings)
>>> processor.run()
>>> processor.save()

Classifier time-bins calculator

class simba.data_processors.timebins_clf_calculator.TimeBinsClfCalculator(config_path: str, bin_length: int, measurements: List[typing_extensions.Literal['First occurrence (s)', 'Event count', 'Total event duration (s)', 'Mean event duration (s)', 'Median event duration (s)', 'Mean event interval (s)', 'Median event interval (s)']], classifiers: List[str])[source]

Bases: ConfigReader

Computes aggregate classification results in user-defined time-bins. Results are stored in the project_folder/logs directory of the SimBA project`

Parameters
  • config_path (str) – path to SimBA project config file in Configparser format.

  • bin_length (int) – Integer representing the time bin size in seconds

  • measurements (List[str]) – Aggregate statistic measures calculated for each time bin. OPTIONS: [‘First occurrence (s)’, ‘Event count’, Total event duration (s)’, ‘Mean event duration (s)’, ‘Median event duration (s)’, ‘Mean event interval (s)’, ‘Median event interval (s)’]

  • classifiers (List[str]) – Names of classifiers to calculate aggregate statistics in time-bins for. EXAMPLE: [‘Attack’, ‘Sniffing’]

Tutorial.

Example

>>> timebin_clf_analyzer = TimeBinsClfCalculator(config_path='MyConfigPath', bin_length=15, measurements=['Event count', 'Total event duration (s)'])
>>> timebin_clf_analyzer.run()
run()[source]

Method for running the classifier time-bin analysis. Results are stored in the project_folder/logs directory of the SimBA project.

Return type

None

Movement time-bins calculator

class simba.data_processors.timebins_movement_calculator.TimeBinsMovementCalculator(config_path: str, bin_length: Union[int, float], body_parts: List[str], plots: Optional[bool] = False)[source]

Bases: ConfigReader, FeatureExtractionMixin

Computes aggregate movement statistics in user-defined time-bins.

Parameters
  • config_path (str) – path to SimBA project config file in Configparser format

  • bin_length (int) – Integer representing the time bin size in seconds.

  • plots (bool) – If True, creates time-bin line plots representing the movement in each time-bin per video. Results are saved in the project_folder/logs/ sub-directory.

Note

Tutorial.

_images/TimeBinsMovementCalculator.png
Example

>>> calculator = TimeBinsMovementCalculator(config_path='/Users/simon/Desktop/envs/simba/troubleshooting/two_black_animals_14bp/project_folder/project_config.ini', bin_length=0.04,plots=True, body_parts=['Nose_1', 'Nose_2'])
>>> calculator.run()

Mutual exclusivity refactorer

class simba.data_processors.mutual_exclusivity_corrector.MutualExclusivityCorrector(rules: dict, config_path: Union[str, PathLike])[source]

Bases: ConfigReader

Refactor classification results according to user-defined mutual exclusivity rules.

Note

Tutorial.

Examples

>>> rules = {1: {'rule_type': 'threshold_determinator','determinator': 'Attack', 'threshold': 0.5, 'subordinates': ['Sniffing']}, 2: {'rule_type': 'threshold_determinator', 'determinator': 'Attack', 'threshold': 0.0, 'subordinates': ['Sniffing', 'Rear']}}
>>> exclusivity_corrector = MutualExclusivityCorrector(config_path='/Users/simon/Desktop/envs/troubleshooting/two_black_animals_14bp/project_folder/project_config.ini', rules=rules)
>>> exclusivity_corrector.run()
>>> rules = {1: {'rule_type': 'highest_probability', 'subordinates': ['body', 'face'], 'winner': 'body', 'skip_files_with_identical': True}}
>>> exclusivity_corrector = MutualExclusivityCorrector(config_path='/Users/simon/Desktop/envs/troubleshooting/two_black_animals_14bp/project_folder/project_config.ini', rules=rules)
>>> exclusivity_corrector.run()

Boolean conditional calculator

class simba.data_processors.boolean_conditional_calculator.BooleanConditionalCalculator(config_path: Union[str, PathLike], rules: Dict[str, bool], data_paths: Optional[Union[str, PathLike]] = None)[source]

Bases: ConfigReader

Compute descriptive statistics (e.g., the time in seconds and number of frames) of multiple Boolean fields fullfilling user-defined conditions.

For example, computedescriptive statistics for when Animal 1 is inside the shape Rectangle_1 while at the same time directing towards shape Polygon_1, while at the same time Animal 2 is outside shape Rectangle_1 and directing towards Polygon_1.

Parameters
  • config_path (str) – path to SimBA project config file in Configparser format.

  • rules (Dict[str, bool]) – Rules with field names as keys and bools as values.

Examples

>>> rules = {'Rectangle_1 Simon in zone': 'TRUE', 'Polygon_1 JJ in zone': 'TRUE'}
>>> conditional_bool_rule_calculator = BooleanConditionalCalculator(rules=rules, config_path='/Users/simon/Desktop/envs/troubleshooting/two_animals_16bp_032023/project_folder/project_config.ini')
>>> conditional_bool_rule_calculator.run()
>>> conditional_bool_rule_calculator.save()

Gibbs sampling

class simba.data_processors.gibbs_sampler.GibbsSampler(config_path: Union[str, PathLike], data: DataFrame, pseudo_number: int = 0.001, sequence_length: int = 4, iterations: int = 1500, epochs: int = 2, stop_val: float = 0.001, plateau_val: int = 50)[source]

Bases: ConfigReader

Gibbs sampling for finding “motifs” in categorical sequences.

Parameters
  • config_path (str) – path to SimBA project config file in Configparser format

  • data (pd.DataFrame) – Dataframe where each row represents videos and each column represents behavior sequence.

  • pseudo_number (float) – Small error value for fuzzy search. Default: 0.001.

  • sequence_length (int) – The length of the motif sequence searched for.

  • iterations (int) – Number of iterations per epoch. Default: 1000.

  • epochs (int) – Number of epochs of iterations. Default: 5.

  • plateau_val (int) – Terminate epoch when error rate has remained unchanged for plateau_val count of interations.

Example

>>> df = pd.read_csv('/tests/data/gibbs_sample_data/gibbs_sample_ver_7.csv', index_col=0)
>>> gibbs_sampler = GibbsSampler(data=df)
>>> gibbs_sampler.run()
References

1

Lawrence et.al, Detecting Subtle Sequence Signals: a Gibbs Sampling Strategy for Multiple Alignment, Science, vol. 262, pp. 208-214, 1993.

2

Great YouTube course by Xiaole Shirley Liu.

Spontaneous alternation calculator

class simba.data_processors.spontaneous_alternation_calculator.SpontaneousAlternationCalculator(config_path: Union[str, PathLike], arm_names: List[str], center_name: str, animal_area: Optional[int] = 80, threshold: Optional[float] = 0.0, buffer: Optional[int] = 2, verbose: Optional[bool] = False, detailed_data: Optional[bool] = False, data_path: Optional[Union[str, PathLike]] = None)[source]

Bases: ConfigReader

Compute spontaneous alternations based on specified ROIs and animal detection parameters.

Note

This method computes spontaneous alternation by fitting the smallest viable geometry (a.k.a. shape, polygon) that encompasses the animal key-points (but see buffer parameter below). It then checks the percent overlap between the animal geometry and the defined arm and center geometries in each frame. If the percent overlap is more or equal to the specified threshold, then the animal considered to visiting the relevant arm. The animal is considered exiting an arm when the percent overlap with a different ROI is above the threshold.

Attention

Requires SimBA project with (i) only one tracked animal, (ii) at least three pose-estmated body-parts, and (iii) defined ROIs representing the arms and the center of the maze.

Parameters
  • config_path (Union[str, os.PathLike]) – Path to SimBA project config file.

  • arm_names (List[str]) – List of ROI names representing the arms.

  • center_name (str) – Name of the ROI representing the center of the maze

  • animal_area (Optional[int]) – Value between 51 and 100, representing the percent of the animal body that has to be situated in a ROI for it to be considered an entry.

  • threshold (Optional[float]) – Value between 0.0 and 1.0. Body-parts with detection probabilities below this value will be (if possible) filtered when constructing the animal geometry.

  • buffer (Optional[int]) – Millimeters area for which the animal geometry should be increased in size. Useful if the animal geometry does not fully cover the animal.

  • detailed_data (Optional[bool]) – If True, saves an additional CSV for each analyzed video with detailed data pertaining each error type and alternation sequence.

  • data_path (Optional[Union[str, os.PathLike]]) – Directory of path to the file to be analyzed. If None, then project_folder/outlier_corrected_movement_location directory.

Example

>>> x = SpontaneousAlternationCalculator(config_path='/Users/simon/Desktop/envs/simba/troubleshooting/spontenous_alternation/project_folder/project_config.ini', arm_names=['A', 'B', 'C'], center_name='Center', threshold=0.0, animal_area=100, buffer=2, detailed_data=True)
>>> x.run()
>>> x.save()