COSIE.downstream_analysis.cluster_and_visualize

cluster_and_visualize(final_embeddings, data_dict, n_clusters, mode='joint', vis_basis='spatial', cluster_key='cluster_labels', random_state=0, s=50, alpha=0.9, colormap='tab20', plot_style='original', swap_xy=False, invert_x=False, invert_y=False, save_path=None, dpi=300)[source]

Cluster cell embeddings and visualize the results for each tissue section at the spot level. Supports both joint and per-section clustering modes, and offers flexible visualization controls (axis flip, equal scaling, saving, etc.).

Parameters

final_embeddingsdict

A dictionary mapping section names (e.g., ‘s1’, ‘s2’, …) to 2D NumPy arrays of shape (n_cells, latent_dim), representing cell embeddings for each section.

data_dictdict

A dictionary where each key is a modality (e.g., ‘RNA’, ‘Protein’) and each value is a list of AnnData objects, one per tissue section. If a modality is missing in a section, use None as a placeholder.

n_clustersint

Number of clusters to assign using k-means.

modestr, optional

Clustering mode. Must be one of {‘joint’, ‘independent’}.

  • ‘joint’: Cluster all sections together.

  • ‘independent’: Cluster each section separately. Default is ‘joint’.

vis_basisstr, optional

The key in .obsm to use for visualization (e.g., ‘spatial’). Default is ‘spatial’.

cluster_keystr, optional

Column name in .obs to store cluster assignments. Default is ‘cluster_labels’.

random_stateint, optional

Random seed for k-means reproducibility. Default is 0.

sint, optional

Dot size in scatter plots. Default is 50.

alphafloat, optional

Point transparency (0 to 1). Default is 0.9.

colormapstr, optional

Matplotlib colormap name for cluster coloring. Default is ‘tab20’.

plot_stylestr, optional

Must be one of {‘equal’, ‘original’}.

  • ‘equal’: Enforce equal axis aspect ratio.

  • ‘original’: Retain raw coordinate scale. Default is ‘original’.

swap_xybool, optional

If True, swap x and y axes in the scatter plot. Default is False.

invert_xbool, optional

If True, invert the x-axis. Default is False.

invert_ybool, optional

If True, invert the y-axis. Default is False.

save_pathstr or None, optional

If provided, save the figures using this prefix. Individual files will be saved for each section. Default is None (no saving).

dpiint, optional

Resolution of saved figures in DPI (dots per inch). Default is 300.

Returns

cluster_labelsdict

A dictionary mapping section IDs to arrays of assigned cluster labels.