Analysis

Functions:

get_syllable_names(project_dir, model_name, ...)

Get syllable names from syll_info.csv file.

generate_index(project_dir, model_name, ...)

Write index.csv with a row for every recording in the model's results.

interactive_group_setting(project_dir, ...)

Start the interactive group setting widget.

compute_moseq_df(project_dir, model_name[, ...])

Compute moseq dataframe from results dict that contains all kinematic values by frame.

compute_stats_df(moseq_df[, min_frequency, ...])

Summary statistics for syllable frequencies and kinematic values.

label_syllables(project_dir, model_name, ...)

Label syllables in the syllable grid movie.

get_tie_correction(x, N_m)

Assign tied rank values to the average of the ranks they would have received if they had not been tied for Kruskal-Wallis helper function.

run_manual_KW_test(df_usage, ...[, n_perm, seed])

Run a manual Kruskal-Wallis test compare the results agree with the scipy.stats.kruskal function.

dunns_z_test_permute_within_group_pairs(...)

Run Dunn's z-test statistic on combinations of all group pairs, handling pre- computed tied ranks.

compute_pvalues_for_group_pairs(...[, ...])

Adjust the p-values from Dunn's z-test statistics and computes the resulting significant syllables with the adjusted p-values.

run_kruskal(stats_df[, statistic, n_perm, ...])

Run Kruskal-Wallis test on syllable usage data.

sort_syllables_by_stat_difference(stats_df, ...)

Sort syllables by the difference in the stat between the control and experimental group.

sort_syllables_by_stat(stats_df[, stat])

Sort syllables by the stat and return the ordering and label mapping.

save_analysis_figure(fig, plot_name, ...)

Save an analysis figure.

plot_syll_stats_with_sem(stats_df, ...[, ...])

Plot syllable statistics with 68% bootstrap confidence intervals.

get_transitions(label_sequence)

Get the syllable transitions and their locations.

n_gram_transition_matrix(labels[, n, max_label])

The transition matrix for n-grams.

normalize_transition_matrix(init_matrix, ...)

Normalize the transition matrices.

get_transition_matrix(labels[, ...])

Compute the transition matrix for the syllable labels.

get_group_trans_mats(labels, label_group, ...)

Get the transition matrices for each group.

visualize_transition_bigram(project_dir, ...)

Visualize the transition matrices for each group.

generate_transition_matrices(project_dir, ...)

Generate a transition matrix for each group.

plot_transition_graph_group(project_dir, ...)

Plot the transition graph for each group.

plot_transition_graph_difference(...[, ...])

Plot the difference of transition graph between groups.

keypoint_moseq.analysis.get_syllable_names(project_dir, model_name, syllable_ixs)[source]

Get syllable names from syll_info.csv file. Labels consist of the syllable index, followed by the syllable label, if it exists.

Parameters:
  • project_dir (str) – the path to the project directory

  • model_name (str) – the name of the model directory

  • syllable_ixs (list) – list of syllable indices to get names for

Returns:

names – list of syllable names

Return type:

list of str

keypoint_moseq.analysis.generate_index(project_dir, model_name, index_filepath)[source]

Write index.csv with a row for every recording in the model’s results.

Recordings already in index.csv keep their rows and groups; recordings that are not, such as ones added with apply_model, are appended in the group “default”. The file is only rewritten when rows are added.

Parameters:
  • project_dir (str) – path to project directory

  • model_name (str) – model directory name

  • index_filepath (str) – path to index file

keypoint_moseq.analysis.interactive_group_setting(project_dir, model_name)[source]

Start the interactive group setting widget.

Clicking “Save group info” writes the groups to {project_dir}/index.csv. The message next to the button confirms the save and shows how many recordings are in each group.

Parameters:
  • project_dir (str) – the path to the project directory

  • model_name (str) – the name of the model directory

keypoint_moseq.analysis.compute_moseq_df(project_dir, model_name, results_dict=None, *, fps=None, smooth_heading=True)[source]

Compute moseq dataframe from results dict that contains all kinematic values by frame.

Velocities are converted from per-frame to per-second with the frame rate, which is also stored in the “fps” column so that keypoint_moseq.analysis.compute_stats_df() converts syllable durations with the same rate.

Parameters:
  • project_dir (str) – the path to the project directory

  • model_name (str) – the name of the model directory

  • results_dict (dict) – dictionary of results from model fitting. If None, loaded from {project_dir}/{model_name}/results.h5.

  • fps (float, optional) – The frame rate of the recordings. By default, the fps in the project’s config.yml.

  • smooth_heading (bool, optional) – boolean flag whether smooth the computed heading, by default True

Returns:

moseq_df – the dataframe that contains kinematic data for each frame. onset marks the first frame of each syllable instance. A recording’s first frame is never an onset, since its syllable may have started before the recording did.

Return type:

pandas.DataFrame

Raises:

ValueError – If fps is not given and the project has no config.yml with an fps entry.

keypoint_moseq.analysis.compute_stats_df(moseq_df, min_frequency=0.005, groupby=['group', 'name'])[source]

Summary statistics for syllable frequencies and kinematic values.

Everything is computed from moseq_df, which already holds each frame’s syllable, kinematics and group, so the statistics always describe the same recordings and groups as the dataframe they were computed from.

Parameters:
  • moseq_df (pandas.DataFrame) – the dataframe that contains kinematic data for each frame (see keypoint_moseq.analysis.compute_moseq_df())

  • min_frequency (float, optional) – syllables whose frequency across all recordings is at or below this threshold are left out, by default 0.005

  • groupby (list, optional) – columns that identify the rows of stats_df, by default [‘group’, ‘name’]. Statistics are meant to be per recording, so keep ‘name’ in the list. Frequencies are always computed per recording: without ‘name’, stats_df still has a row for each recording and syllable, with that recording’s frequency, the duration and kinematic statistics pooled over its group, and no ‘name’ column. run_kruskal and the significance markers in plot_syll_stats_with_sem need ‘name’.

Returns:

stats_df – the summary statistics dataframe for syllable frequencies and kinematic values. duration is the mean length in seconds of the syllable’s instances, leaving out each recording’s first and last instance, which the start and end of the recording cut short. It is NaN when those are the syllable’s only instances. heading_mean and heading_std are the circular mean and standard deviation of the heading, and heading_min and heading_max are its smallest and largest values in (-pi, pi]. Each recording has a row for every syllable that passes min_frequency. Where the recording never used the syllable, frequency is 0, and with ‘name’ in groupby, duration and the kinematic columns are NaN.

Return type:

pandas.DataFrame

Raises:

ValueError – If any recording in moseq_df has more than one group (syllable frequencies are computed per recording, so each recording must belong to a single group), or if moseq_df has no “fps” column or more than one frame rate.

keypoint_moseq.analysis.label_syllables(project_dir, model_name, moseq_df)[source]

Label syllables in the syllable grid movie.

Parameters:
  • project_dir (str) – the path to the project directory

  • model_name (str) – the name of the model directory

  • moseq_df (pandas.DataFrame) – the dataframe from compute_moseq_df

keypoint_moseq.analysis.get_tie_correction(x, N_m)[source]

Assign tied rank values to the average of the ranks they would have received if they had not been tied for Kruskal-Wallis helper function.

Parameters:
  • x (pd.Series) – syllable usages for a single recording.

  • N_m (int) – Number of total recordings.

Returns:

corrected_rank – average of the inputted tied ranks.

Return type:

float

keypoint_moseq.analysis.run_manual_KW_test(df_usage, merged_usages_all, num_groups, n_per_group, cum_group_idx, n_perm=10000, seed=42)[source]

Run a manual Kruskal-Wallis test compare the results agree with the scipy.stats.kruskal function.

Parameters:
  • df_usage (pandas.DataFrame) – DataFrame with syllable usages. shape = (N_m, n_syllables)

  • merged_usages_all (np.array) – numpy array format of the df_usage DataFrame.

  • num_groups (int) – Number of unique groups

  • n_per_group (list) – list of value counts for recordings per group. len == num_groups.

  • cum_group_idx (list) – list of indices for different groups. len == num_groups + 1.

  • n_perm (int, optional) – Number of permuted samples to generate, by default 10000

  • seed (int, optional) – Random seed used to initialize the pseudo-random number generator, by default 42

Returns:

  • h_all (np.array) – Array of H-stats computed for given n_syllables; shape = (n_perms, N_s)

  • real_ranks (np.array) – Array of syllable ranks, shape = (N_m, n_syllables)

  • X_ties (np.array) – 1-D list of tied ranks, where if value > 0, then rank is tied. len(X_ties) = n_syllables

keypoint_moseq.analysis.dunns_z_test_permute_within_group_pairs(df_usage, vc, real_ranks, X_ties, N_m, group_names, rnd, n_perm)[source]

Run Dunn’s z-test statistic on combinations of all group pairs, handling pre- computed tied ranks.

Parameters:
  • df_usage (pandas.DataFrame) – DataFrame containing only pre-computed syllable stats.

  • vc (pd.Series) – value counts of recordings in each group.

  • real_ranks (np.array) – Array of syllable ranks.

  • X_ties (np.array) – 1-D list of tied ranks, where if value > 0, then rank is tied

  • N_m (int) – Number of recordings.

  • group_names (pd.Index) – Index list of unique group names.

  • rnd (np.random.RandomState) – Pseudo-random number generator.

  • n_perm (int) – Number of permuted samples to generate.

Returns:

  • null_zs_within_group (dict) – dict of group pair keys paired with vector of Dunn’s z-test statistics of the null hypothesis.

  • real_zs_within_group (dict) – dict of group pair keys paired with vector of Dunn’s z-test statistics

keypoint_moseq.analysis.compute_pvalues_for_group_pairs(real_zs_within_group, null_zs, df_k_real, group_names, n_perm=10000, thresh=0.05, mc_method='fdr_bh')[source]

Adjust the p-values from Dunn’s z-test statistics and computes the resulting significant syllables with the adjusted p-values.

Parameters:
  • real_zs_within_group (dict) – dict of group pair keys paired with vector of Dunn’s z-test statistics

  • null_zs (dict) – dict of group pair keys paired with vector of Dunn’s z-test statistics of the null hypothesis.

  • df_k_real (pandas.DataFrame) – DataFrame of KW test results.

  • group_names (pd.Index) – Index list of unique group names.

  • n_perm (int, optional) – Number of permuted samples to generate, by default 10000

  • thresh (float, optional) – Alpha threshold to consider syllable significant, by default 0.05

  • mc_method (str, optional) – Multiple Corrections method to use, by default “fdr_bh”

Returns:

  • df_pval_corrected (pandas.DataFrame) – DataFrame containing Dunn’s test results with corrected p-values.

  • significant_syllables (list) – List of corrected KW significant syllables (syllables with p-values < thresh).

keypoint_moseq.analysis.run_kruskal(stats_df, statistic='frequency', n_perm=10000, seed=42, thresh=0.05, mc_method='fdr_bh')[source]

Run Kruskal-Wallis test on syllable usage data.

A recording without a row for a syllable has a frequency of 0. Other missing values are left out: each syllable is tested on the recordings that have a value for statistic, and a syllable is not tested when a group has no recordings with a value, or when every value is the same. A warning gives the number of syllables where a group has fewer than 3 recordings with a value.

Parameters:
  • stats_df (pandas.DataFrame) – DataFrame containing syllable usage data.

  • statistic (str, optional) – Statistic to use for KW test, by default ‘frequency’

  • n_perm (int, optional) – Number of permutations to run, by default 10000

  • seed (int, optional) – Random seed, by default 42

  • thresh (float, optional) – Alpha threshold to consider syllable significant, by default 0.05

  • mc_method (str, optional) – Multiple Corrections method to use, by default “fdr_bh”

Returns:

  • df_k_real (pandas.DataFrame) – DataFrame containing KW test results, indexed by syllable. A syllable that wasn’t tested has NaN statistic, pvalue and p_adj, and is_sig False.

  • dunn_results_df (pandas.DataFrame) – Dunn’s z statistic for each syllable and pair of groups, in the columns (“syllable”, “”), group1, group2 and value. value is NaN for a syllable that wasn’t tested.

  • significant_syllables (dict) – Maps each pair of groups to the syllables whose corrected KW p-value is at most thresh and whose corrected Dunn p-value is below thresh.

keypoint_moseq.analysis.sort_syllables_by_stat_difference(stats_df, ctrl_group, exp_group, stat='frequency')[source]

Sort syllables by the difference in the stat between the control and experimental group.

Parameters:
  • stats_df (pandas.DataFrame) – the complete dataframe that contains kinematic data for each frame

  • ctrl_group (str) – the name of the control group

  • exp_group (str) – the name of the experimental group

  • stat (str, optional) – the statistic to use for finding the syllable differences between two groups, by default ‘frequency’

Returns:

ordering list of syllables based on the difference in the stat between the control and experimental group

Return type:

list

keypoint_moseq.analysis.sort_syllables_by_stat(stats_df, stat='frequency')[source]

Sort syllables by the stat and return the ordering and label mapping.

Parameters:
  • stats_df (pandas.DataFrame) – the stats dataframe that contains kinematic data and the syllable label for each recording and each syllable

  • stat (str, optional) – the statistic to sort on, by default ‘frequency’

Returns:

  • ordering (list) – the list of syllables sorted by the stat

  • relabel_mapping (dict) – the mapping from the syllable to the new plotting label

keypoint_moseq.analysis.save_analysis_figure(fig, plot_name, project_dir, model_name, save_dir)[source]

Save an analysis figure.

The figure is saved as both a .png and .pdf, either to save_dir if it is provided, or else to project_dir/model_name/figures.

keypoint_moseq.analysis.plot_syll_stats_with_sem(stats_df, project_dir, model_name, save_dir=None, plot_sig=True, thresh=0.05, stat='frequency', order='stat', groups=None, ctrl_group=None, exp_group=None, colors=None, join=False, figsize=(8, 4))[source]

Plot syllable statistics with 68% bootstrap confidence intervals.

Parameters:
  • stats_df (pandas.DataFrame) – the dataframe that contains kinematic data and the syllable label

  • project_dir (str) – the project directory

  • model_name (str) – the model directory name

  • save_dir (str, optional) – directory to save the figure to, by default {project_dir}/{model_name}/figures

  • plot_sig (bool, optional) – whether to plot the significant syllables, by default True

  • thresh (float, optional) – the threshold for significance, by default 0.05

  • stat (str, optional) – the statistic to plot, by default ‘frequency’

  • order (str, optional) – the ordering of the syllables, by default ‘stat’

  • groups (list, optional) – the list of groups to plot, by default None

  • ctrl_group (str, optional) – the control group, by default None

  • exp_group (str, optional) – the experimental group, by default None

  • colors (list, optional) – the list of colors to use for each group, by default None

  • join (bool, optional) – whether to join the points with a line, by default False

  • figsize (tuple, optional) – the figure size, by default (8, 4)

Returns:

  • fig (matplotlib.figure.Figure) – the figure object

  • legend (matplotlib.legend.Legend) – the legend object

keypoint_moseq.analysis.get_transitions(label_sequence)[source]

Get the syllable transitions and their locations.

Parameters:

label_sequence (np.ndarray) – the sequence of syllable labels for a recording

Returns:

  • transitions (np.ndarray) – the sequence of syllable transitions

  • locs (np.ndarray) – the locations of the syllable transitions

keypoint_moseq.analysis.n_gram_transition_matrix(labels, n=2, max_label=99)[source]

The transition matrix for n-grams.

Parameters:
  • labels (list or np.ndarray) – recording state lists

  • n (int, optional) – the number of successive states in the sequence, by default 2

  • max_label (int, optional) – the maximum number of the syllable labels to include, by default 99

Returns:

trans_mat – the transition matrices for the n-grams

Return type:

np.ndarray

keypoint_moseq.analysis.normalize_transition_matrix(init_matrix, normalize)[source]

Normalize the transition matrices.

Parameters:
  • init_matrix (numpy.ndarray) – the initial transition matrix to be normalized

  • normalize (str) – the method to normalize the transition matrix

Returns:

init_matrix – the transition matrix normalized by the method specified

Return type:

numpy.ndarray

keypoint_moseq.analysis.get_transition_matrix(labels, max_syllable=100, normalize='bigram', smoothing=0.0, combine=False, disable_output=False)[source]

Compute the transition matrix for the syllable labels.

Parameters:
  • labels (list or np.ndarray) – syllable labels per recording

  • max_syllable (int, optional) – the maximum number of syllables to include, by default 100

  • normalize (str, optional) – the method to normalize the transition matrix, by default ‘bigram’

  • smoothing (float, optional) – the smoothing value (pseudo count) to add to the transition matrix, by default 0.0

  • combine (bool, optional) – whether to combine the transition matrices for all the recordings, by default False

  • disable_output (bool, optional) – whether to disable the progress bar, by default False

Returns:

all_mats – the list of transition matrices for each recording

Return type:

list

keypoint_moseq.analysis.get_group_trans_mats(labels, label_group, group, syll_include, normalize='bigram')[source]

Get the transition matrices for each group.

Parameters:
  • labels (list or np.ndarray) – recording state lists

  • label_group (list or np.ndarray) – the group labels for each recording

  • group (list or np.ndarray) – the groups in the project

  • syll_include (array) – the syllables to include

  • normalize (str, optional) – the method to normalize the transition matrix, by default ‘bigram’

Returns:

  • trans_mats (list) – the list of transition matrices for each group

  • frequencies (list) – the list of syllable frequencies for each group

keypoint_moseq.analysis.visualize_transition_bigram(project_dir, model_name, group, trans_mats, syll_include, save_dir=None, normalize='bigram', figsize=(12, 6), show_syllable_names=True)[source]

Visualize the transition matrices for each group.

Parameters:
  • project_dir (str) – the path to the project directory

  • model_name (str) – the name of the model directory

  • group (list or np.ndarray) – the groups in the project

  • trans_mats (list) – the list of transition matrices for each group

  • syll_include (array) – the syllables included in trans_mats (from generate_transition_matrices)

  • save_dir (str, optional) – directory to save the figure to, by default {project_dir}/{model_name}/figures

  • normalize (str, optional) – the normalization used by generate_transition_matrices; only sets the colorbar label, by default ‘bigram’

  • figsize (tuple, optional) – the figure size, by default (12,6)

  • show_syllable_names (bool, optional) – whether to show just syllable indexes (False) or syllable indexes and names (True)

keypoint_moseq.analysis.generate_transition_matrices(project_dir, model_name, normalize='bigram', min_frequency=0.005)[source]

Generate a transition matrix for each group.

Parameters:
  • project_dir (str) – the path to the project directory

  • model_name (str) – the name of the model directory

  • normalize (str, optional) – the method to normalize the transition matrix (“bigram”, “rows” or “columns”), by default ‘bigram’

  • min_frequency (float, optional) – syllables whose frequency is at or below this threshold are left out, by default 0.005

Returns:

  • trans_mats (list) – the transition matrix of each group

  • usages (list) – the syllable frequencies of each group

  • groups (list) – the group names, in the same order

  • syll_include (ndarray) – the syllables included in the matrices

keypoint_moseq.analysis.plot_transition_graph_group(project_dir, model_name, groups, trans_mats, usages, syll_include, save_dir=None, layout='circular', node_scaling=2000, show_syllable_names=False)[source]

Plot the transition graph for each group.

Parameters:
  • project_dir (str) – the path to the project directory

  • model_name (str) – the name of the model directory

  • groups (list) – the list of groups to plot

  • trans_mats (list) – the list of transition matrices for each group

  • usages (list) – the list of syllable usage for each group

  • syll_include (array) – the syllables included in trans_mats (from generate_transition_matrices)

  • save_dir (str, optional) – directory to save the figure to, by default {project_dir}/{model_name}/figures

  • layout (str, optional) – the layout of the graph, by default ‘circular’

  • node_scaling (int, optional) – the scaling factor for the node size, by default 2000

  • show_syllable_names (bool, optional) – whether to show just syllable indexes (False) or syllable indexes and names (True)

keypoint_moseq.analysis.plot_transition_graph_difference(project_dir, model_name, groups, trans_mats, usages, syll_include, save_dir=None, layout='circular', node_scaling=3000, show_syllable_names=False)[source]

Plot the difference of transition graph between groups.

Each pair of groups gets its own panel, so at least two groups are needed. With fewer, the function prints a message and returns without plotting.

Parameters:
  • project_dir (str) – the path to the project directory

  • model_name (str) – the name of the model directory

  • groups (list) – the list of groups to plot

  • trans_mats (list) – the list of transition matrices for each group

  • usages (list) – the list of syllable usage for each group

  • syll_include (array) – the syllables included in trans_mats (from generate_transition_matrices)

  • save_dir (str, optional) – directory to save the figure to, by default {project_dir}/{model_name}/figures

  • layout (str, optional) – the layout of the graph, by default ‘circular’

  • node_scaling (int, optional) – the scaling factor for the node size, by default 3000

  • show_syllable_names (bool, optional) – whether to show just syllable indexes (False) or syllable indexes and names (True)