glhmm.graphics

Basic graphics - Gaussian Linear Hidden Markov Model @author: Diego Vidaurre & Nick Yao Larsen 2025

glhmm.graphics.blue_colormap()[source]

Generate a custom blue colormap.

Returns:

A custom colormap with shades of blue.

glhmm.graphics.check_exists(filename, fallback_directory='.')[source]

Check if a file exists, optionally falling back to a secondary directory.

Parameters:
  • (str) (fallback_directory) – File path or name to check.

  • (str) – Directory to look in if the file is not found at the original path. Default is current directory.

  • optional – Directory to look in if the file is not found at the original path. Default is current directory.

Returns:

Full path to the found file.

Return type:

str

Raises:

FileNotFoundError – If the file is not found in either location.

glhmm.graphics.create_cmap_alpha(cmap_list, color_array, alpha)[source]

Modify the colors in a colormap based on an alpha threshold.

Parameters:

cmap_list (numpy.ndarray)

List of colors representing the original colormap.

color_array (numpy.ndarray)

Array of color values corresponding to each colormap entry.

alpha (float)

Alpha threshold for modifying colors.

Returns:

Modified list of colors representing the colormap with adjusted alpha values.

glhmm.graphics.custom_colormap()[source]

Generate a custom colormap consisting of segments from red to blue.

Returns:

A custom colormap with defined color segments.

glhmm.graphics.get_custom_colormap()[source]

Create a custom colormap for brain activation plotting.

Returns:

A custom colormap transitioning through turquoise, blue, gray, and red-yellow.

Return type:

matplotlib.colors.LinearSegmentedColormap

glhmm.graphics.get_distinct_colors(n_colors, cmap=None)[source]

Generate visually distinct colors using a combination of built-in categorical and perceptually uniform colormaps.

Parameters:

n_colors (int):

The number of distinct colors to generate.

cmap (str, optional):

Name of a colormap to use as the primary source of colors. If not provided, defaults to a combination of standard categorical colormaps. If the requested number of colors exceeds what is available, additional colors are sampled from other colormaps to fill the gap.

Returns:

colors (list):

A list of RGBA tuples representing distinct colors. If the number of requested colors exceeds what is available from standard categorical maps, additional colors are sampled from a continuous colormap.

glhmm.graphics.get_parcellation_centers(parcellation_file)[source]

Extracts MNI coordinates for each parcel in a 4D NIfTI parcellation.

Parameters:

parcellation_file (str):

Path to a 4D binary NIfTI file where each volume corresponds to a parcel.

Returns:

centers (np.ndarray):

Array of shape (n_parcels, 3) containing the MNI coordinates for each parcel.

glhmm.graphics.interpolate_colormap(cmap_list)[source]

Create a new colormap with the modified color_array.

Parameters:

cmap_list (numpy.ndarray):

Original color array for the colormap.

Returns:

modified_cmap (numpy.ndarray):

Modified colormap array.

glhmm.graphics.parcel_vector_to_voxel_grid(mask_file, parcellation_file, vector)[source]

Map a vector of parcel values onto a 3D voxel grid using a mask and parcellation.

Parameters:
  • (str) (parcellation_file) – Path to a NIfTI mask file.

  • (str) – Path to a NIfTI parcellation file.

  • (np.ndarray) (vector) – 1D array of values (one per parcel). Shape must match number of parcels.

Returns:

3D voxel grid with mapped values at each brain voxel.

Return type:

np.ndarray

Raises:

ValueError – If the number of parcels in the parcellation does not match the length of the vector.

glhmm.graphics.plot_FO(FO, figsize=(8, 4), fontsize_ticks=12, fontsize_labels=14, fontsize_title=16, width=0.8, xlabel='Subject', ylabel='Fractional occupancy', title='State Fractional Occupancies', cmap=None, show_legend=True, num_x_ticks=11, num_y_ticks=5, pad_y_spine=None, save_path=None, return_fig=False)[source]

Plot fractional occupancies for different states.

Parameters:

FO (numpy.ndarray):

Fractional occupancy data matrix.

figsize (tuple, optional), default=(8,4):

Figure size.

fontsize_ticks (int, optional), default=12:

Font size for tick labels.

fontsize_labels (int, optional), default=14:

Font size for axes labels.

fontsize_title (int, optional), default=16:

Font size for plot title.

width (float, optional), default=0.5:

Width of the bars.

xlabel (str, optional), default=’Subject’:

Label for the x-axis.

ylabel (str, optional), default=’Fractional occupancy’:

Label for the y-axis.

title (str, optional), default=’State Fractional Occupancies’:

Title for the plot.

cmap (str, optional):

Name of a colormap to use for state line colors (default is ‘Set3’).

show_legend (bool, optional), default=True:

Whether to show the legend.

num_x_ticks (int, optional), default=11:

Number of ticks for the x-axis.

num_y_ticks (int, optional), default=5:

Number of ticks for the y-axis.

pad_y_spine (float, optional), default=None:

Shifting the positin of the spine for the y-axis.

save_path (str, optional), default=None:

If a string is provided, it saves the figure to that specified path.

glhmm.graphics.plot_average_probability(Gamma_data, title='Average probability for each state', fontsize=16, figsize=(7, 5), vertical_lines=None, line_colors=None, highlight_boxes=False, save_path=None, return_fig=False)[source]

Plots the average probability for each state over time.

Parameters:

Gamma_data (numpy.ndarray)

Can be a 2D or 3D array representing gamma values. Shape: (num_timepoints, num_states) or (num_timepoints, num_trials, num_states)

title (str, optional), default=’Average probability for each state’:

Title for the plot.

fontsize (int, optional), default=16:

Font size for labels and title.

figsize (tuple, optional), default=(8,6):

Figure size (width, height) in inches).

vertical_lines (list of tuples, optional), default=None:

List of pairs specifying indices for vertical lines.

line_colors (list of str or bool, optional), default=None:

List of colors for each pair of vertical lines. If True, generates random colors (unless a list is provided).

highlight_boxes (bool, optional), default=False:

Whether to include highlighted boxes for each pair of vertical lines.

save_path (str, optional), default=None

If a string is provided, it saves the figure to that specified path

glhmm.graphics.plot_brain_state_maps(power_map, mask_file, parcellation_file, filename=None, fig_format='png', component=0, subtract_mean=False, mean_weights=None, match_color_scale=False, plot_kwargs=None, show_plots=True, combined=False, titles=None, n_rows=1, save_figures=False, figure_filenames=None, save_folder_name='brain_maps', return_fig=False)[source]

Plots or saves power spectral brain state maps projected to surface.

Parameters:

power_map (np.ndarray):

Array of shape (n_components, n_modes, n_channels) or similar.

mask_file (str):

Path to NIfTI mask file.

parcellation_file (str):

Path to NIfTI parcellation file.

filename (str, optional):

Base filename for saving output. Supports .nii/.nii.gz/.png/.svg/.pdf.

fig_format (str, optional), default=’png’:

File format for figure export (e.g., “pdf”, “png”).

component (int, optional):

Index of the spectral component to plot.

subtract_mean (bool, optional), default=False:

Whether to subtract mean across modes.

mean_weights (np.ndarray, optional):

Weights for computing the average across modes.

match_color_scale (bool, optional), default=False:

Force consistent vmin/vmax across plots.

plot_kwargsdict, optional

Keyword arguments passed to nilearn.plotting.plot_img_on_surf. Common options include:

  • surf_mesh (str) or dict, default=’fsaverage5’

    Cortical mesh to use for plotting.

  • hemisphereslist of str, default=[‘left’, ‘right’]

    Hemispheres to show (‘left’, ‘right’, or both).

  • viewslist of str, default=[‘lateral’, ‘medial’]

    View angles for each hemisphere.

  • inflate (bool), default=False

    Whether to use an inflated surface.

  • bg_on_data (bool), default=False

    Whether to blend background surface with data overlay.

  • title (str), optional

    Title shown above each surface plot.

  • colorbar (bool), default=True

    Show colorbar alongside the figure.

  • vmin, vmaxfloat, optional

    Value range for colormap.

  • thresholdfloat, optional

    Values below this (in absolute value) are masked out.

  • symmetric_cbar (bool) or ‘auto’, default=’auto’

    Whether to center the colorbar symmetrically around zero.

  • cmap (str) or colormap, default=’cold_hot’

    Colormap used for surface data.

  • cbar_tick_format (str), default=’%i’

    Tick formatting for the colorbar.

show_plots (bool, optional):

Whether to display the plots.

combined (bool, optional):

Combine plots into a single figure (enables save_figures).

titles (list or bool, optional):

List of titles for each mode or True for auto-generated labels.

n_rows (int, optional):

Number of rows in the combined figure.

save_figures (bool, optional):

Whether to save each plot as a file.

figure_filenames (str or list, optional):

Base name or list of full paths for saving each plot.

save_folder_name (str, optional):

Name of the output folder where saved figures will be stored. Default is “brain_maps”.

glhmm.graphics.plot_condition_difference(Gamma_epoch, R_trials, title='Average Probability and Difference', condition_labels=('Condition 1', 'Condition 2'), fontsize_sup_title=16, fontsize_title=14, fontsize_labels=12, figsize=(12, 3), vertical_lines=None, line_colors=None, highlight_boxes=False, stimulus_onset=None, x_tick_min=None, x_tick_max=None, num_x_ticks=5, num_y_ticks=5, xlabel='Timepoints', ylabel='Average Probability', save_path=None, return_fig=False)[source]

Plots the average probability for each state over time for two conditions and their difference.

Parameters:

Gamma_epoch (numpy.ndarray)

3D array representing reconstructed gamma values. Shape: (num_timepoints, num_trials, num_states)

R_trials (numpy.ndarray)

1D array representing the condition for each trial. Should have the same length as the second dimension of Gamma_epoch.

title (str, optional), default=’Average Probability and Difference’:

Title for the plot.

condition_labelstuple of str, optional

Labels for the two conditions. Default is (‘Condition 1’, ‘Condition 2’).

fontsize_sup_title (int, optional), default=16:

Font size for sup_title.

fontsize_title (int, optional), default=14:

Font size for title.

fontsize_labels (int, optional), default=12:

Font size for labels.

figsize (tuple, optional), default=(9, 2):

Figure size (width, height).

vertical_lines (list of tuples, optional), default=None:

List of pairs specifying indices for vertical lines.

line_colors (list of str or bool, optional), default=None:

List of colors for each pair of vertical lines. If True, generates random colors (unless a list is provided).

highlight_boxes (bool, optional), default=False:

Whether to include highlighted boxes for each pair of vertical lines.

stimulus_onset (int, optional), default=None:

Index of the data where the stimulus onset should be positioned.

x_tick_min (float, optional), default=None:

Minimum value for the x-tick labels.

x_tick_max (float, optional), default=None:

Maximum value for the x-tick labels.

num_x_ticks (int, optional), default=5:

Number of x-ticks.

num_y_ticks (int, optional), default=5:

Number of y-ticks.

save_path (str), optional, default=None

If a string is provided, it saves the figure to that specified path

Example usage:

plot_condition_difference(Gamma_epoch, R_trials, vertical_lines=[(10, 100)], highlight_boxes=True)

glhmm.graphics.plot_connectivity_maps(connectivity_map, parcellation_file, filename=None, fig_format='png', component=None, threshold=0, match_color_scale=True, plot_kwargs=None, show_plots=True, axes=None, combined=False, save_figures=False, titles=None, n_rows=1, figure_filenames=None, save_folder_name='connectivity_maps', return_fig=False)[source]

Plot connectivity maps, such as functional or spectral connectivity, using a parcellation layout.

Parameters:

connectivity_map (numpy.ndarray):

Array of shape (n_modes, n_channels, n_channels) or (n_components, n_modes, n_channels, n_channels). Represents connectivity matrices for each mode (or component and mode).

parcellation_file (str):

Path to a parcellation file used to define node coordinates for plotting the connectome.

filename (str, optional):

If provided, the base filename for saving the figure(s). The appropriate format (e.g., .png, .svg) will be determined by fig_format.

fig_format (str, optional):

Format to save the figures, e.g., ‘png’, ‘svg’, or ‘pdf’. Default is ‘png’.

component (int, optional):

If connectivity_map is 4D, this selects which component to plot. If None, all components are plotted.

threshold (float, optional):

Minimum absolute value for showing a connection. Values below this threshold are not shown. Default is 0 (no thresholding).

match_color_scale (bool, optional):

Whether to use the same color scale across all plots. Default is True.

plot_kwargs (dict, optional):

Additional keyword arguments passed to the plotting function (e.g., edge_cmap, node_size).

show_plots (bool, optional):

Whether to display the figures on screen. Default is True.

axes (matplotlib.axes.Axes or array-like, optional):

Axes to use for plotting, if already created externally. If None, new axes will be generated.

combined (bool, optional):

If True, all maps are shown in a single figure. Otherwise, one figure per map is created.

save_figures (bool, optional):

Whether to save the plotted figures. Default is False.

titles (list of str, optional):

Titles to use for each connectivity map. If None, titles will be generated automatically.

n_rows (int, optional):

Number of rows to use when arranging subplots (if combined=True). Default is 1.

figure_filenames (list of str, optional):

List of custom filenames for each individual figure (only used if combined=False and save_figures=True).

save_folder_name (str, optional):

Name of the output folder where saved figures will be stored. Default is “connectivity_maps”.

glhmm.graphics.plot_data_grid(data_list, titles=None, figsize_per_plot=(4, 3), main_title='Data', xlabel='Time (s)', ylabel='Signal', fontsize_labels=12, fontsize_title=18, line_width=1.8, grid=False, title_fontsize=14, tick_fontsize=10, standardize_yaxis=False, y_buffer=0.05, num_y_ticks=None, title_spacing=10, save_path=None, return_fig=False)[source]

Create a grid of subplots to visualize multiple datasets with a clean layout.

Parameters:

data_list (list of numpy.ndarray):

List of data arrays to be plotted, each representing one subplot.

titles (str, list of str, or None), default=None:

Title for each plot. If None, default titles “Plot 1”, “Plot 2”, … will be used. If a single string is provided, it will be numbered for each plot.

figsize_per_plot (tuple, optional), default=(4, 3):

Size of each subplot in the grid.

main_title (str, optional), default=”Data Visualization”:

Main title for the entire grid of subplots.

xlabel (str, optional), default=”Time (s)”:

Label for the x-axis of each subplot.

ylabel (str, optional), default=”Signal”:

Label for the y-axis of each subplot.

fontsize_labels (int, optional), default=12:

Font size for the x and y-axis labels.

fontsize_title (int, optional), default=18:

Font size for the main title.

line_width (float, optional), default=1.8:

Line width for the data plots.

grid (bool, optional), default=False:

Whether to include a grid in each subplot.

title_fontsize (int, optional), default=14:

Font size for subplot titles.

tick_fontsize (int, optional), default=10:

Font size for axis tick labels.

standardize_yaxis (bool, optional), default=False:

If True, sets the same y-axis limits for all plots based on the global min and max values.

y_buffer (float, optional), default=0.05:

Buffer added to the min and max y-axis values when standardizing, as a percentage.

num_y_ticks (int, optional), default=None:

Number of y-ticks for the y-axis. If None, matplotlib default is used.

title_spacing (int, optional), default=10:

Spacing (padding) between subplot titles and the plots.

save_path (str, optional), default=None:

If provided, saves the figure to the specified path.

glhmm.graphics.plot_initial_state_probabilities(init_stateP, cmap='coolwarm', figsize=(2, 4), title_text='Initial State Probabilities', fontsize_labels=12, fontsize_title=14, tick_size=10, num_ticks=None, save_path=None, return_fig=False)[source]

Plot the initial state probabilities of a Hidden Markov Model as a vertical heatmap.

Parameters:
  • init_probs (np.ndarray) – 1D array of shape (n_states,) representing the initial state probabilities.

  • cmap (str, default="coolwarm") – Colormap used for the heatmap.

  • figsize (tuple of float, default=(2.5, 4)) – Size of the full figure in inches (width, height).

  • title_text (str, default="Initial State Probabilities") – Title displayed above the plot.

  • fontsize_labels (int, default=12) – Font size for axis labels and colorbar label.

  • fontsize_title (int, default=14) – Font size for the plot title.

  • tick_size (int, default=10) – Font size for tick labels.

  • num_ticks (int or None, default=None) – Number of ticks to show on the y-axis and colorbar. If None, automatically adjusts based on the number of states.

  • save_path (str or None, default=None) – If provided, saves the figure to this file path.

  • return_fig (bool, default=False) – If True, returns the figure object instead of displaying it.

glhmm.graphics.plot_model_selection(results, n_total_timepoints, save_path=None, similarity_threshold=0.8, figsize=(20, 6), fontsize_title=16, fontsize_labels=14, fontsize_ticks=12, return_fig=False)[source]

Plot HMM model selection: stability (Gamma similarity), free energy elbow, and EM convergence curves.

Displays three panels to support principled selection of the number of hidden states (K):

  1. Gamma similarity violin - distribution of pairwise similarity scores across repetitions per K. A high mean (red line) combined with a narrow spread indicates a stable, well-identified solution. The grey dashed line marks the minimum-stability threshold.

  2. Free energy elbow - normalised minimum free energy vs K. Lower values indicate a better model fit; look for the elbow where gains flatten off.

  3. Convergence curves - free energy across EM cycles for the best repetition per K. Curves should plateau smoothly; a still-descending curve means cyc needs to increase.

Parameters:

results (dict):

Returned by utils.run_stability_training() or utils.load_stability_results(). Format: {K: {'FE': [list of arrays], 'similarity_scores': [list of floats]}}.

n_total_timepoints (int):

Total number of timepoints in the training data (Y.shape[0]). Used to normalise free energy values across K values.

save_path (str, optional), default=None:

If provided, saves the figure to that path.

similarity_threshold (float, optional), default=0.8:

Horizontal dashed threshold line drawn on the stability panel.

figsize (tuple, optional), default=(20, 6):

Figure size.

fontsize_title (int, optional), default=16:

Font size for panel titles.

fontsize_labels (int, optional), default=14:

Font size for axis labels.

fontsize_ticks (int, optional), default=12:

Font size for tick labels.

return_fig (bool, optional), default=False:

If True, returns the figure object instead of calling plt.show().

Returns:

avg_similarity (dict):

Mean Gamma similarity score per K value, {K: float}.

min_fe (dict):

Normalised minimum free energy per K value, {K: float}.

fig (matplotlib.figure.Figure):

Only returned when return_fig=True.

glhmm.graphics.plot_nnm_spectral_components(nnmf_components, freqs, x_lim=None, highlight_freq=True, title='Spectral Components from NNMF Decomposition', cmap=None, bands=None, band_colors=None, figsize=(10, 5), fontsize_labels=13, fontsize_title=16, band_legend_anchor=(1.28, 1), save_path=None, return_fig=False)[source]

Plot the spectral components obtained from NNM decomposition with optional frequency band highlighting.

Parameters:

nnmf_components (numpy.ndarray):

Array of shape (n_components, n_freqs) representing the decomposed spectral components for each component.

freqs (numpy.ndarray):

1D array representing the frequency axis, should match the second dimension of nnmf_components.

x_lim (int, optional):

The upper limit of the frequency axis (x-axis). If None, it will default to the maximum value in freqs.

highlight_freq (bool, optional):

Whether to highlight canonical or custom frequency bands, default is True.

title (str, optional):

Title of the plot. Default is “Spectral Components from NNMF Decomposition”.

cmap (str, optional):

Name of a colormap to use for state line colors (default is ‘Set3’).

bands (dict, optional):

Dictionary defining frequency bands. Keys are band names and values are (start, end) tuples in Hz. If None, default bands will be used.

band_colors (dict, optional):

Dictionary mapping band names to color names. Keys must match those in bands.

figsize (tuple, optional):

Tuple defining figure size in inches, default is (10, 5).

band_legend_anchor (tuple or None, optional):

Tuple for bbox_to_anchor to control frequency band legend placement. Default is (1.28, 1). If set to None, legend is placed at ‘lower right’.

save_path (str), optional, default=None

If a string is provided, it saves the figure to that specified path

glhmm.graphics.plot_p_value_matrix(pval, alpha=0.05, normalize_vals=True, figsize=(9, 5), title_text='Heatmap (p-values)', fontsize_labels=12, fontsize_title=14, annot=False, cmap_type='default', cmap_reverse=True, xlabel='', ylabel='', xticklabels=None, yticklabels=None, x_tick_min=None, x_tick_max=None, num_x_ticks=None, num_y_ticks=None, tick_positions=[0.001, 0.01, 0.05, 0.1, 0.3, 1], none_diagonal=False, num_colors=256, xlabel_rotation=0, save_path=None, return_fig=False)[source]

Plot a heatmap of p-values.

Parameters:

pval (numpy.ndarray)

The p-values data to be plotted.

normalize_vals(bool, optional), default=False:

If True, the data range will be normalized from 0 to 1.

figsize tuple, optional, default=(12,7):

Figure size in inches (width, height).

steps (int, optional), default=11:

Number of steps for x and y-axis ticks.

title_text (str, optional), default= “Heatmap (p-values)”

Title text for the heatmap.

fontsize_labels (int, optional), default=12:

Font size for the x and y-axis labels.

fontsize_title (int, optional), default=14

fontsize of title

annot (bool, optional), default=False:

If True, annotate each cell with the numeric value.

cmap (str, optional), default= “default”:

Colormap to use. Default is a custom colormap based on ‘coolwarm’.

xlabel (str, optional), default=””

X-axis label. If not provided, default labels based on the method will be used.

ylabel (str, optional), default=””

Y-axis label. If not provided, default labels based on the method will be used.

xticklabels (List[str], optional), default=None:

If not provided, labels will be numbers equal to shape of pval.shape[1]. Else you can define your own labels, e.g., xticklabels=[‘sex’, ‘age’].

x_tick_min (float, optional), default=None:

Minimum value for the x-tick labels.

x_tick_max (float, optional), default=None:

Maximum value for the x-tick labels.

num_x_ticks (int, optional), default=5:

Number of x-ticks.

tick_positions (list, optional), default=[0, 0.001, 0.01, 0.05, 0.1, 0.3, 1]

Positions of ticks on the colorbar.

none_diagonal (bool, optional), default=False:

If you want to turn the diagonal into NaN numbers.

num_colors (numpy.ndarray), default=259:

Define the number of different shades of color.

xlabel_rotation (numpy-mdarray), default=0

The degree of rotation for the labels in the x-axis

save_path (str, optional), default=None

If a string is provided, it saves the figure to that specified path

glhmm.graphics.plot_p_values_bar(pval, xticklabels=None, figsize=(9, 4), num_colors=256, xlabel='', ylabel='P-values (Log Scale)', title_text='Bar Plot', fontsize_labels=12, fontsize_title=14, tick_positions=[0.001, 0.01, 0.05, 0.1, 0.3, 1], top_adjustment=0.8, alpha=0.05, pad_title=25, xlabel_rotation=45, pval_text_height_same=False, save_path=None, return_fig=False)[source]

Visualize a bar plot with LogNorm and a colorbar.

Parameters:

pval (numpy.ndarray):

Array of p-values to be plotted.

xticklabels (str or list, optional), default=None:

Either a list of category labels, or a single string. - If a list: Must match the length of pval. - If a string: Auto-generates labels like “<string> 1”, “<string> 2”, …, “<string> N” where N = len(pval). - If None or invalid: Default labels will be used (“Var 1”, “Var 2”, …, “Var N”).

figsize (tuple, optional), default=(9, 4):

Figure size in inches (width, height).

num_colors (int, optional), default=256:

Number of colors in the colormap.

xlabel (str, optional), default=””:

X-axis label.

ylabel (str, optional), default=”P-values (Log Scale)”:

Y-axis label.

title_text (str, optional), default=”Bar Plot”:

Title for the plot.

fontsize_labels (int, optional), default=12:

Font size for the x and y-axis labels.

fontsize_title (int, optional), default=14

fontsize of title

tick_positions (list, optional), default=[0, 0.001, 0.01, 0.05, 0.1, 0.3, 1]

Positions of ticks on the colorbar.

top_adjustment (float, optional), default=0.9:

Adjustment for extra space between title and plot.

alpha (float, optional), default=0.05:

Alpha value is the threshold we set for the p-values when doing visualization.

pad_title (int, optional), default=20:

Padding for the plot title.

save_path (str), optional, default=None

If a string is provided, it saves the figure to that specified path

pval_text_height_same (bool), default=False

Whether the p-values of each bar should be plotted at the same height or adjusted to the height of each individual bar

glhmm.graphics.plot_p_values_over_time(pval, figsize=(8, 3), xlabel='Timepoints', ylabel='P-values (Log Scale)', title_text='P-values over time', fontsize_labels=12, fontsize_title=14, stimulus_onset=None, x_tick_min=None, x_tick_max=None, num_x_ticks=5, tick_positions=[0.001, 0.01, 0.05, 0.1, 0.3, 1], num_colors=259, alpha=0.05, plot_style='line', linewidth=2.5, scatter_on=True, save_path=None, return_fig=False)[source]

Plot a scatter plot of p-values over time with a log-scale y-axis and a colorbar.

Parameters:

pval (numpy.ndarray):

The p-values data to be plotted.

figsize (tuple), optional, default=(8, 4):

Figure size in inches (width, height).

total_time_secondsfloat, optional, default=None

Total time duration in seconds. If provided, time points will be scaled accordingly.

xlabel (str, optional), default=”Timepoints”:

Label for the x-axis.

ylabel (str, optional), default=”P-values (Log Scale)”:

Label for the y-axis.

title_text (str, optional), default=”P-values over time”:

Title for the plot.

fontsize_labels (int, optional), default=12:

Font size for the x and y-axis labels.

fontsize_title (int, optional), default=14

fontsize of title

stimulus_onset (int, optional), default=None:

Index of the data where the stimulus onset should be positioned.

x_tick_min (float, optional), default=None

Minimum value for x-axis ticks.

x_tick_max (float, optional), default=None

Maximum value for x-axis ticks.

num_x_ticks (int, optional), default=5

Number of x-axis ticks.

tick_positions (list, optional), default=[0, 0.001, 0.01, 0.05, 0.1, 0.3, 1]:

Specific values to mark on the y-axis.

num_colors (int, optional), default=259:

Resolution for the color bar.

alpha (float, optional), default=0.05:

Alpha value is the threshold we set for the p-values when doing visualization.

plot_style (str, optional), default=”line”:

Style of plot.

linewidth (float, optional), default=2.5:

Width of the lines in the plot.

save_path (str), optional, default=None

If a string is provided, it saves the figure to that specified path

glhmm.graphics.plot_permutation_distribution(base_statistics_perms, title_text='Permutation Distribution', xlabel='Test Statistic Values', ylabel='Density', save_path=None, return_fig=False)[source]

Plot the histogram of the permutation with the observed statistic marked.

Parameters:

base_statistics_perms (numpy.ndarray)

An array containing the permutation values.

title_text (str, optional), default=”Permutation Distribution”:

Title text of the plot.

xlabel (str, optional), default=”Test Statistic Values”

Text of the xlabel.

ylabel (str, optional), default=”Density”

Text of the ylabel.

save_path (str, optional), default=None

If a string is provided, it saves the figure to that specified path

glhmm.graphics.plot_scatter_with_labels(p_values, alpha=0.05, title_text='', xlabel=None, ylabel=None, xlim_start=0.9, ylim_start=0, save_path=None, return_fig=False)[source]

Create a scatter plot to visualize p-values with labels indicating significant points.

Parameters:

p_values (numpy.ndarray)

An array of p-values. Can be a 1D array or a 2D array with shape (1, 5).

alpha (float, optional), default=0.05:

Threshold for significance.

title_text (str, optional), default=””:

The title text for the plot.

xlabel (str, optional), default=None:

The label for the x-axis.

ylabel (str, optional), default=None:

The label for the y-axis.

xlim_start (float, optional), default=-5

Start position of x-axis limits.

ylim_start (float, optional), default=-0.1

Start position of y-axis limits.

save_path (str, optional), default=None

If a string is provided, it saves the figure to that specified path

Notes:

Points with p-values less than alpha are considered significant and marked with red text.

glhmm.graphics.plot_state_coherence(coh, freqs, significant_states=None, x_lim=None, cmap=None, highlight_freq=False, bands=None, band_colors=None, title='State Coherence between Two Channels', figsize=(10, 5), fontsize_labels=13, fontsize_title=16, band_legend_anchor=(1.28, 1), label_line=None, save_path=None, return_fig=False)[source]

Plot the coherence between two channels for each state, with optional highlighting of frequency bands and significant states.

Parameters:

coh (numpy.ndarray):

Array of shape (n_freqs, num_states) representing the coherence between two selected channels for each state.

freqs (numpy.ndarray):

1D array representing the frequency axis, should match the first dimension of coh.

significant_states (set, optional):

Set of 1-based indices indicating which states are considered significant. Significant states are highlighted with a solid line and an asterisk.

x_lim (int, optional):

The upper limit of the frequency axis (x-axis). If None, it will default to the maximum value in freqs.

cmap (str, optional):

Name of a colormap to use for state line colors (default is ‘Set3’).

highlight_freq (bool, optional):

Whether to highlight canonical or custom frequency bands. Default is False.

bands (dict, optional):

Dictionary defining frequency bands. Keys are band names and values are (start, end) tuples in Hz. If None, default bands will be used.

band_colors (dict, optional):

Dictionary mapping band names to color names. Keys must match those in bands.

title (str, optional):

Title of the plot. Default is “State Coherence between Two Channels”.

figsize (tuple, optional):

Tuple defining figure size in inches. Default is (10, 5).

fontsize_labels (int):

Font size for x and y axis labels. Default is 13.

fontsize_title (int):

Font size for the plot title. Default is 16.

band_legend_anchor (tuple or None, optional):

Tuple for bbox_to_anchor to control frequency band legend placement. Default is (1.28, 1). If set to None, legend is placed at ‘upper right’.

label_line (str or list, optional):

Custom labels for each line. Can be a string (prefix) or a list of names. If not provided, states are labeled as “State 1”, “State 2”, etc.

save_path (str, optional, default=None):

If a string is provided, the figure will be saved to the specified path.

glhmm.graphics.plot_state_covariances(state_FC, cmap='coolwarm', fontsize_title=12, fontsize_labels=10, tick_size=8, figsize_per_plot=(2.5, 2.8), wspace=None, hspace=None, same_scale=False, num_cols=3, num_ticks=6, save_path=None, return_fig=False)[source]

Plot state-specific covariance matrices (e.g., functional connectivity) in a grid layout.

Parameters:
  • state_FC (np.ndarray) – 3D array of shape (n_channels, n_channels, n_states).

  • cmap (str, default='coolwarm') – Colormap for plotting.

  • fontsize_title (int) – Font size of subplot titles.

  • fontsize_labels (int) – Font size of axis labels.

  • tick_size (int) – Font size for tick labels.

  • figsize_per_plot (tuple) – Size per subplot (width, height).

  • wspace (float or None) – Spacing between subplots.

  • hspace (float or None) – Spacing between subplots.

  • same_scale (bool) – If True, uses the same color scale for all subplots.

  • num_ticks (int) – Number of tick marks on each axis (shared between x and y).

  • save_path (str or None) – If set, saves the plot to this path.

glhmm.graphics.plot_state_lifetimes(LT, figsize=(8, 4), fontsize_ticks=12, fontsize_labels=14, fontsize_title=16, width=0.18, group_gap=None, xlabel='Subject', ylabel='Lifetime', title='State Lifetimes', cmap=None, show_legend=True, num_x_ticks=11, num_y_ticks=5, pad_y_spine=None, save_path=None, return_fig=False)[source]

Plot state lifetimes for different states.

Parameters:

LT (numpy.ndarray):

State lifetime (dwell time) data matrix.

figsize (tuple, optional), default=(8, 4):

Figure size.

fontsize_ticks (int, optional), default=12:

Font size for tick labels.

fontsize_labels (int, optional), default=14:

Font size for axeses labels.

fontsize_title (int, optional), default=16:

Font size for plot title.

width (float, optional), default=0.18:

Width of the bars.

group_gapfloat or None

Gap between groups of bars (sessions). If None, defaults to width * 0.5.

xlabel (str, optional), default=’Subject’:

Label for the x-axesis.

ylabel (str, optional), default=’Lifetime’:

Label for the y-axesis.

title (str, optional), default=’State Lifetimes’:

Title for the plot.

cmap (str, optional):

Name of a colormap to use for state line colors (default is ‘Set3’).

show_legend (bool, optional), default=True:

Whether to show the legend.

num_x_ticks (int, optional), default=11:

Number of ticks for the x-axis.

num_y_ticks (int, optional), default=5:

Number of ticks for the y-axis.

pad_y_spine (float, optional), default=None:

Shifting the positin of the spine for the y-axis.

save_path (str, optional), default=None

If a string is provided, it saves the figure to that specified path

glhmm.graphics.plot_state_means_activations(state_means, cmap_type='coolwarm', cmap_reverse=False, figsize=(3, 5), title_text='State Mean Activations', xlabel='State', ylabel='Brain region', fontsize_labels=12, fontsize_title=14, tick_size=10, annot=False, xticklabels=None, yticklabels=None, xlabel_rotation=None, num_x_ticks=None, num_y_ticks=None, save_path=None, return_fig=False)[source]

Plot a heatmap of state mean activations with optional tick formatting and custom labels.

Parameters:
  • state_means (np.ndarray) – Array of shape (n_states, n_features) or (n_features, n_states). Each column represents the mean activation per state across features (e.g., brain regions).

  • cmap_type (str, default='coolwarm') – Name of the matplotlib colormap to use.

  • cmap_reverse (bool, default=False) – If True, reverses the selected colormap.

  • figsize (tuple of float, default=(3, 5)) – Size of the figure in inches (width, height).

  • title_text (str, default="State Mean Activations") – Title to display above the heatmap.

  • xlabel (str, default="State") – Label for the x-axis.

  • ylabel (str, default="Brain region") – Label for the y-axis.

  • fontsize_labels (int, default=12) – Font size for axis labels and colorbar label.

  • fontsize_title (int, default=14) – Font size for the plot title.

  • tick_size (int, default=10) – Font size for tick labels.

  • annot (bool, default=False) – If True, annotate each cell in the heatmap with its value.

  • xticklabels (list, str, or None, default=None) – List of custom x-tick labels, or string prefix to auto-generate labels (e.g., “State”). If None, numeric labels are used.

  • yticklabels (list, str, or None, default=None) – List of custom y-tick labels, or string prefix to auto-generate labels. If None, numeric labels are used.

  • xlabel_rotation (int or None, default=None) – Rotation angle for x-axis labels. Automatically set to 45 if number of states > 10.

  • num_x_ticks (int or None, default=None) – Number of ticks to show on the x-axis. Automatically chosen if None.

  • num_y_ticks (int or None, default=None) – Number of ticks to show on the y-axis. Automatically chosen if None.

  • save_path (str or None, default=None) – If provided, saves the figure to this path.

  • return_fig (bool, default=False) – If True, returns the figure object instead of displaying the plot.

Returns:

fig – Returns the figure if return_fig=True, otherwise shows the plot directly.

Return type:

matplotlib.figure.Figure or None

glhmm.graphics.plot_state_prob_and_covariance(init_stateP, TP, state_means, state_FC, TP_with_self_trans=False, cmap='coolwarm', figsize=(9, 7), num_ticks=5, save_path=None, title_size=None, label_size=None, tick_size=None, return_fig=False)[source]

Plot HMM parameters: initial state probabilities, transition matrix, state means, and state covariance matrices.

Parameters:
  • init_stateP (np.ndarray) – Array of shape (n_states,) representing the initial state probabilities.

  • TP (np.ndarray) – Transition probability matrix of shape (n_states, n_states).

  • state_means (np.ndarray) – Array of shape (n_states, n_features) representing the mean activity per state.

  • state_FC (np.ndarray) – Array of shape (n_features, n_features, n_states) representing state-specific covariance matrices.

  • cmap (str or matplotlib colormap, default='coolwarm') – Colormap used for all plots.

  • figsize (tuple of float, default=(9, 7)) – Size of the full figure in inches (width, height).

  • num_ticks (int, default=5) – Number of ticks to show on colorbars and axes.

  • save_path (str or None, default=None) – If provided, the figure will be saved to this path.

  • title_size (int or None, optional) – Font size for subplot titles. If None, automatically scaled based on figure size.

  • label_size (int or None, optional) – Font size for axis labels (currently reserved for future extension).

  • tick_size (int or None, optional) – Font size for tick labels. If None, automatically scaled based on figure size.

glhmm.graphics.plot_state_psd(psd, freqs, significant_states=None, x_lim=None, cmap=None, highlight_freq=False, bands=None, band_colors=None, title='Power Spectral Density (PSD) per State', log_scale_y=False, log_scale_x=False, figsize=(10, 5), fontsize_labels=13, fontsize_title=16, band_legend_anchor=(1.28, 1), label_line=None, save_path=None, return_fig=False)[source]

Plot the power spectral density (PSD) for each state, with optional highlighting of frequency bands and significant states.

Parameters:

psd (numpy.ndarray):

Array of shape (n_freqs, num_states) representing the PSD of each state.

freqs (numpy.ndarray):

1D array representing the frequency axis, should match the second dimension of psd.

significant_states (set, optional):

Set of 1-based indices indicating which states are considered significant. Significant states are highlighted with a solid line and an asterisk.

x_lim (int, optional):

The upper limit of the frequency axis (x-axis). If None, it will default to the maximum value in freqs.

cmap (str, optional):

Name of a colormap to use for state line colors (default is ‘Set3’).

highlight_freq (bool, optional):

Whether to highlight canonical or custom frequency bands. Default is True.

bands (dict, optional):

Dictionary defining frequency bands. Keys are band names and values are (start, end) tuples in Hz. If None, default bands will be used.

band_colors (dict, optional):

Dictionary mapping band names to color names. Keys must match those in bands.

title (str, optional):

Title of the plot. Default is “Power Spectral Density (PSD) per State”.

log_scale_y (bool, optional):

Whether to apply a logarithmic scale to the y-axis (power). Default is True.

log_scale_x (bool, optional):

Whether to apply a logarithmic scale to the x-axis (frequency). Default is False.

figsize (tuple, optional):

Tuple defining figure size in inches. Default is (10, 5).

fontsize_labels (int):

Font size for x and y axis labels. Default is 13.

fontsize_title (int):

Font size for the plot title. Default is 16.

band_legend_anchor (tuple or None, optional):

Tuple for bbox_to_anchor to control frequency band legend placement. Default is (1.28, 1). If set to None, legend is placed at ‘upper right’.

label_line (str or list, optional):

Custom labels for each line. Can be a string (prefix) or a list of names. If not provided, states are labeled as “State 1”, “State 2”, etc.

save_path (str, optional, default=None):

If a string is provided, the figure will be saved to the specified path.

glhmm.graphics.plot_switching_rates(SR, figsize=(8, 4), fontsize_ticks=12, fontsize_labels=14, fontsize_title=16, width=0.18, group_gap=None, xlabel='Subject', ylabel='Switching Rate', title='State Switching Rates', cmap=None, show_legend=True, num_x_ticks=11, num_y_ticks=5, pad_y_spine=None, save_path=None, return_fig=False)[source]

Plot grouped bar charts of switching rates for different states across sessions.

Parameters:
  • SR (np.ndarray) – Array of shape (n_sessions, n_states) containing switching rates.

  • figsize (tuple of float, default=(8, 4)) – Size of the figure in inches (width, height).

  • fontsize_ticks (int, default=12) – Font size for axis tick labels.

  • fontsize_labels (int, default=14) – Font size for x-axis and y-axis labels.

  • fontsize_title (int, default=16) – Font size for the title.

  • width (float, default=0.18) – Width of each individual bar representing a state.

  • group_gap (float or None, default=None) – Horizontal spacing between each group (session). If None, uses width * 0.5.

  • xlabel (str, default='Subject') – Label for the x-axis.

  • ylabel (str, default='Switching Rate') – Label for the y-axis.

  • title (str, default='State Switching Rates') – Title of the plot.

  • cmap (str or None, default=None) – Name of a matplotlib colormap. If None, a default discrete colormap is used.

  • show_legend (bool, default=True) – Whether to display the legend for states.

  • num_x_ticks (int, default=11) – Number of ticks to show on the x-axis (session axis).

  • num_y_ticks (int, default=5) – Number of ticks to show on the y-axis.

  • pad_y_spine (float or None, default=None) – Padding to shift the left spine outward. If None, it’s computed from the figure width.

  • save_path (str or None, default=None) – If provided, saves the figure to this file path.

glhmm.graphics.plot_transition_matrix(TP, with_self_transitions=False, normalize=True, cmap='coolwarm', figsize=(4, 4), fontsize_title=14, fontsize_labels=12, tick_size=10, title_text=None, num_ticks=None, save_path=None, return_fig=False)[source]

Plot a single transition probability matrix (with or without self-transitions).

Parameters:
  • TP (np.ndarray) – Transition matrix of shape (n_states, n_states).

  • with_self_transitions (bool, default=True) – If False, self-transitions will be removed and rows re-normalized.

  • normalize (bool, default=True) – Whether to normalize the rows after removing self-transitions.

  • cmap (str, default='coolwarm') – Colormap to use for the heatmap.

  • figsize (tuple, default=(4, 4)) – Size of the figure.

  • fontsize_title (int, default=14) – Font size of the title.

  • fontsize_labels (int, default=12) – Font size for x and y axis labels.

  • tick_size (int, default=10) – Font size for axis tick labels.

  • title_text (str or None) – Custom title. If None, a default is used based on with_self_transitions.

  • num_ticks (int or None) – Number of tick labels to show on each axis.

  • save_path (str or None) – If set, saves the figure to this path.

  • return_fig (bool, default=False) – If True, returns the matplotlib figure object.

glhmm.graphics.plot_vpath(viterbi_path, signal=None, idx_data=None, figsize=(7, 4), fontsize_labels=13, fontsize_title=16, yticks=None, time_conversion_rate=None, xlabel='Timepoints', ylabel='', title='Viterbi Path', cmap=None, signal_label='Signal', show_legend=True, vertical_linewidth=1.5, save_path=None, return_fig=False)[source]

Plot Viterbi path with optional signal overlay.

Parameters:

viterbi_path

The Viterbi path data matrix.

signal (numpy.ndarray), optional

Signal data to overlay on the plot. Default is None.

idx_data (numpy.ndarray), optional

Array representing time intervals. Default is None.

figsize (tuple), optional

Figure size. Default is (7, 4).

fontsize_labels (int), optional

Font size for axis labels. Default is 13.

fontsize_title (int), optional

Font size for plot title. Default is 16.

yticks (bool), optional

Whether to show y-axis ticks. Default is None.

time_conversion_rate (float), optional

Conversion rate from time steps to seconds. Default is None.

xlabel (str), optional

Label for the x-axis. Default is “Timepoints”.

ylabel (str), optional

Label for the y-axis. Default is “”.

title (str), optional

Title for the plot. Default is “Viterbi Path”.

cmap (str, optional):

Name of a colormap to use for state line colors (default is ‘Set3’).

signal_label (str, optional

Label for the signal plot. Default is “Signal”.

show_legend (bool), optional

Whether to show the legend. Default is True.

vertical_linewidth (float), optional

Line width for vertical gray lines. Default is 1.5.

save_path (str, optional), default=None

If a string is provided, it saves the figure to that specified path

glhmm.graphics.red_colormap()[source]

Generate a custom colormap consisting of red and warm colors.

Returns:

A custom colormap with red and warm color segments.

glhmm.graphics.save_figure(fig, path, fig_format, show=False)[source]

Save a matplotlib figure to disk and optionally close it.

Parameters:
  • (matplotlib.figure.Figure) (fig) – The figure to save.

  • (str) (fig_format) – Output path where the figure will be saved.

  • (str) – Format to save the figure (e.g., ‘svg’, ‘png’).

  • (bool) (show) – Whether to keep the figure open (True) or close it (False).

glhmm.graphics.show_Gamma(Gamma, line_overlay=None, tlim=None, Hz=1, palette='viridis')[source]

Displays the activity of the hidden states as a function of time.

Parameters:

Gammaarray of shape (n_samples, n_states)

The state timeseries probabilities.

line_overlayarray of shape (n_samples, 1)

A secondary related data type to overlay as a line.

tlim2x1 array or None, default=None

The time interval to be displayed. If None (default), displays the entire sequence.

Hzint, default=1

The frequency of the signal, in Hz.

palette (str), default = ‘Oranges’

The name of the color palette to use.

glhmm.graphics.show_beta(hmm, only_active_states=True, recompute_states=False, X=None, Y=None, Gamma=None, show_average=None, alpha=1.0)[source]

Displays the beta coefficients of a given HMM. The beta coefficients can be extracted directly from the HMM structure or reestimated from the data; for the latter, X, Y and Gamma need to be provided as parameters. This is useful for example if one has run the model on PCA space, but wants to show coefficients in the original space.

Parameters:

hmm: HMM object

An instance of the HMM class containing the beta coefficients to be visualized.

only_active_states(bool), optional, default=False

If True, only the beta coefficients of active states are shown.

recompute_states(bool), optional, default=False

If True, the betas will be recomputed from the data and the state time courses

X: numpy.ndarray, optional, default=None

The timeseries of set of variables 1.

Y: numpy.ndarray, optional, default=None

The timeseries of set of variables 2.

Gamma: numpy.ndarray, optional, default=None

The state time courses

show_average(bool), optional, default=None

If True, an additional row of the average beta coefficients is shown.

alpha: float, optional, default=0.1

The regularisation parameter to be applied if the betas are to be recomputed.

glhmm.graphics.show_temporal_statistic(Gamma, indices, statistic='FO', type_plot='barplot')[source]

Plots a statistic over time for a set of sessions.

Parameters:

Gammaarray of shape (n_samples, n_states)

The state timeseries probabilities.

indices: numpy.ndarray of shape (n_sessions,)

The session indices to plot.

statistic(str), default=’FO’

The statistic to compute and plot. Can be ‘FO’, ‘switching_rate’ or ‘FO_entropy’.

type_plot(str), default=’barplot’

The type of plot to generate. Can be ‘barplot’, ‘boxplot’ or ‘matrix’.

Raises:

Exception
  • Statistic is not one of ‘FO’, ‘switching_rate’ or ‘FO_entropy’.

  • type_plot is ‘boxplot’ and there are less than 10 sessions.

  • type_plot is ‘matrix’ and there is only one session.

glhmm.graphics.show_trans_prob_mat(hmm, only_active_states=False, show_diag=True, show_colorbar=True)[source]

Displays the transition probability matrix of a given HMM.

Parameters:

hmm: HMM object

An instance of the HMM class containing the transition probability matrix to be visualized.

only_active_states (bool), optional, default=False

Whether to display only active states or all states in the matrix.

show_diag (bool), optional, defatult=True

Whether to display the diagonal elements of the matrix or not.

show_colorbar (bool), optional, default=True

Whether to display the colorbar next to the matrix or not.

glhmm.graphics.update_save_flags(save_figures, combined, fig_format)[source]

Updates save_figures and fig_format based on combined flag.

Parameters:
  • save_figures (bool) – Whether to save individual figures.

  • combined (bool) – Whether to save a combined multi-panel figure.

  • fig_format (str) – Desired figure format (e.g., ‘pdf’, ‘png’).

Returns:

  • save_figures (bool) – Updated save_figures flag.

  • fig_format (str) – Updated fig_format (forces ‘png’ if combined).

glhmm.graphics.validate(array, correct_dimensionality, allow_dimensions, error_message)[source]

Validate and reshape an array to the correct dimensionality.

Parameters:
  • (np.ndarray) (array) – The array to validate.

  • correct_dimensionality (int) – The target number of dimensions.

  • allow_dimensions (list of int) – Acceptable dimensionalities that will be expanded to the target.

  • (str) (error_message) – Error message to raise if dimensionality is incorrect.

Returns:

Array reshaped to the correct number of dimensions.

Return type:

np.ndarray

Raises:

ValueError – If the input does not meet dimensionality requirements.