Skip to content

Analysis

Feature Metrics and Mode Mappings

Feature metrics, mode subsets and cluster mappings between modes.

Classes

Functions

analyze_sep_genes(df_mode, sepH, sepL, gene_set, top_n=10)

Find genes of a gene set whose sepCls matches a (sepH, sepL) split.

Prints the number of matching genes (ordered and unordered match) and returns the top ones by sepLFC.

Parameters:

Name Type Description Default
df_mode DataFrame

Feature metrics of one mode, indexed by gene name.

required
sepH

High cluster indices.

required
sepL

Low cluster indices.

required
gene_set List[str]

Gene names to rank.

required
top_n int

Number of genes to return.

10

Returns:

Type Description
DataFrame

Top matching genes, with columns sepLFC, sepCls and weighted_Psum.

compute_all_feature_metrics(results, feature_names)

Compute feature metrics for all modes.

Parameters:

Name Type Description Default
results ClumpplingResults

Results loaded with P matrices.

required
feature_names Sequence[str]

Names of the P rows.

required

Returns:

Type Description
dict

{mode name: DataFrame from compute_feature_metrics}.

compute_feature_metrics(P, Q, feature_names)

Compute weighted_Psum, sepLFC and sepCls for one mode.

Parameters:

Name Type Description Default
P ndarray

P matrix (n_features, K).

required
Q ndarray

Aligned Q matrix (n_cells, K).

required
feature_names Sequence[str]

Names of the P rows.

required

Returns:

Type Description
DataFrame

Indexed by feature name, with columns weighted_Psum, sepLFC and sepCls.

compute_profile(P)

Sort each feature's P values and compute log2 ratios between neighbors.

Zeros in P are replaced by the smallest positive value so that log2 stays finite.

Parameters:

Name Type Description Default
P ndarray

P matrix (n_features, K).

required

Returns:

Type Description
LFC_sorted

Log2 ratios between consecutive sorted values (n_features, K-1).

idx_sorted

Cluster indices sorting each row in ascending order (n_features, K).

compute_profile_unnorm(P)

Same as compute_profile, for any matrix of non-negative values (e.g. null mean-P vectors).

Adds 1e-10 before log2 instead of replacing zeros.

Parameters:

Name Type Description Default
P ndarray

Values (n_rows, K).

required

Returns:

Type Description
LFC_sorted

Log2 ratios between consecutive sorted values (n_rows, K-1).

idx_sorted

Column indices sorting each row in ascending order (n_rows, K).

compute_weighted_Psum(P, Q)

Sum P across clusters, weighted by cluster size.

Parameters:

Name Type Description Default
P ndarray

P matrix (n_features, K).

required
Q ndarray

Aligned Q matrix (n_cells, K); its column sums give the cluster sizes.

required

Returns:

Type Description
ndarray

weighted_Psum per feature.

get_mode_pair_mappings(mode_names, all_modes_alignment, alignment_acrossK)

Map clusters between every pair of modes, through intermediate modes if needed.

Parameters:

Name Type Description Default
mode_names

Mode names.

required
all_modes_alignment

{mode name: column order after alignment}.

required
alignment_acrossK

{"A-B": mapping}, where mapping[k_B] = k_A in original cluster indices.

required

Returns:

Type Description
dict

{"A-B": [(column in A, column in B), ...]}, in aligned column indices.

get_sepLFC(LFC_sorted, idx_sorted)

Compute sepLFC and sepCls from a sorted profile.

Parameters:

Name Type Description Default
LFC_sorted ndarray

Output of compute_profile.

required
idx_sorted ndarray

Output of compute_profile.

required

Returns:

Type Description
sepLFC

Largest log2 ratio per feature.

sepCls

Per feature, (low clusters, high clusters) on either side of the largest gap.

map_alt_to_ref(ref_Q, alt_Q, pair_mapping)

Map an alternative Q matrix onto the clusters of a reference Q matrix.

Parameters:

Name Type Description Default
ref_Q ndarray

Reference Q matrix (n_cells, ref_K).

required
alt_Q ndarray

Alternative Q matrix (n_cells, alt_K), with alt_K >= ref_K.

required
pair_mapping Sequence[Tuple[int, int]]

(reference column, alternative column) pairs.

required

Returns:

Type Description
alt_Q_mapped

Alternative Q matrix summed into the reference clusters (n_cells, ref_K).

diff_Q

Absolute difference between ref_Q and alt_Q_mapped.

select_top_features(df_by_mode, top_quantile=0.1)

Select the top features by weighted_Psum in each mode.

Parameters:

Name Type Description Default
df_by_mode Mapping[str, DataFrame]

{mode name: feature metrics DataFrame}.

required
top_quantile float

Fraction of features to keep in each mode.

0.1

Returns:

Type Description
selected_by_mode

{mode name: selected features}, with columns suffixed by "_{mode name}".

df_selected_all

Inner join of all selections.

overlap

Features selected in every mode.

subset_results(results, modes_subset)

Restrict a ClumpplingResults to a subset of modes.

Parameters:

Name Type Description Default
results ClumpplingResults

Full results.

required
modes_subset Sequence[str]

Mode names to keep.

required

Returns:

Type Description
ClumpplingResults

New results with only the selected modes.

Membership Comparison

Membership differences between modes, summaries by annotation group, and FSTruct statistics.

Classes

Functions

bootstrap_fstruct_by_group(Q, annotation_labels, *, n_boot=1000, annot_col='annot', sort_groups=False, random_state=None, verbose=False)

Bootstrap FSTruct per annotation group, resampling cells within each group.

Parameters:

Name Type Description Default
Q ndarray

Q matrix (n_cells, K).

required
annotation_labels Sequence[str]

Annotation label per cell.

required
n_boot int

Number of bootstrap samples per group.

1000
annot_col str

Name of the annotation column in the output.

'annot'
sort_groups bool

Sort the groups; otherwise keep their order of appearance.

False
random_state Optional[int]

Random seed.

None
verbose bool

Print progress.

False

Returns:

Type Description
DataFrame

Columns annot_col, boot, Fst, FstMax and ratio; one row per group and bootstrap sample.

bootstrap_fstruct_by_model_group(comp_res, annotation_labels, *, n_boot=1000, selected_modes=None, annot_col='annot', sort_groups=False, verbose=False)

Bootstrap FSTruct per annotation group for several modes.

Parameters:

Name Type Description Default
comp_res CompModelsResults

compModels results.

required
annotation_labels Sequence[str]

Annotation label per cell.

required
n_boot int

Number of bootstrap samples per group.

1000
selected_modes Sequence[str]

Full mode names; None uses all.

None
annot_col str

Name of the annotation column in the output.

'annot'
sort_groups bool

Sort the groups; otherwise keep their order of appearance.

False
verbose bool

Print shapes.

False

Returns:

Type Description
dict

{full mode name: output of bootstrap_fstruct_by_group}.

build_diff_df(mode_group_diff, *, fill_value=0.0, sort_index=True)

Table of differences per mode (rows) and annotation group (columns).

Parameters:

Name Type Description Default
mode_group_diff Dict[str, Dict[str, float]]

{mode name: {group: difference}}.

required
fill_value float

Value for missing entries.

0.0
sort_index bool

Sort the rows by mode name.

True

Returns:

Type Description
DataFrame

compute_all_mode_diffs(comp_results, ref_mode, pair_mappings, annotation_labels=None, aggregation='sum')

Compute the membership difference of every mode from a reference mode.

Parameters:

Name Type Description Default
comp_results CompModelsResults

compModels results.

required
ref_mode str

Full mode name of the reference mode.

required
pair_mappings Mapping[str, Sequence[Tuple[int, int]]]

Output of get_mode_pair_mappings.

required
annotation_labels Optional[Sequence[Any]]

Annotation label per cell; None skips the group differences.

None
aggregation str

How to combine clusters per cell (see compute_per_cell_diff).

'sum'

Returns:

Type Description
modes_total_diff

{full mode name: overall difference}.

modes_group_diff

{full mode name: {group: difference}}.

compute_avg_memberships(models, res_models, selected_modes, annotation_labels, *, annot_col='annot', cluster_prefix='cluster_', sort_groups=False, verbose=False)

Mean cluster membership per annotation group, for one mode of each model.

Parameters:

Name Type Description Default
models Sequence[str]

Model names.

required
res_models Mapping[str, Any]

{model: results with Q_by_mode}.

required
selected_modes Mapping[str, str]

{model: mode name}.

required
annotation_labels Sequence[str]

Annotation label per cell.

required
annot_col str

Name of the annotation column in the output.

'annot'
cluster_prefix str

Prefix of the cluster columns in the output.

'cluster_'
sort_groups bool

Sort the groups; otherwise keep their order of appearance.

False
verbose bool

Print the mode and shape of each model.

False

Returns:

Type Description
dict

{model: DataFrame with annot_col and one column per cluster ({cluster_prefix}0, {cluster_prefix}1, ...)}.

compute_fstruct(Q, *, check_row_sums=True, atol=1e-08)

Compute FSTruct (Fst / FstMax) of a Q matrix.

Parameters:

Name Type Description Default
Q ndarray

Q matrix (n_cells, K) with rows summing to 1.

required
check_row_sums bool

Check that rows sum to 1.

True
atol float

Tolerance of the row-sum check.

1e-08

Returns:

Type Description
dict

Fst, FstMax and ratio (Fst / FstMax, or 0 if FstMax is 0).

compute_fstruct_by_group(Q, annotation_labels, *, annot_col='annot', sort_groups=False, verbose=False)

Compute FSTruct per annotation group.

Parameters:

Name Type Description Default
Q ndarray

Q matrix (n_cells, K).

required
annotation_labels Sequence[str]

Annotation label per cell.

required
annot_col str

Name of the annotation column in the output.

'annot'
sort_groups bool

Sort the groups; otherwise keep their order of appearance.

False
verbose bool

Print shapes.

False

Returns:

Type Description
DataFrame

Columns annot_col, Fst, FstMax and ratio.

compute_fstruct_by_model_group(comp_res, annotation_labels, *, selected_modes=None, annot_col='annot', sort_groups=False, verbose=False)

Compute FSTruct per annotation group for several modes.

Parameters:

Name Type Description Default
comp_res CompModelsResults

compModels results.

required
annotation_labels Sequence[str]

Annotation label per cell.

required
selected_modes Sequence[str]

Full mode names; None uses all.

None
annot_col str

Name of the annotation column in the output.

'annot'
sort_groups bool

Sort the groups; otherwise keep their order of appearance.

False
verbose bool

Print shapes.

False

Returns:

Type Description
dict

{full mode name: output of compute_fstruct_by_group}.

compute_group_diff(per_cell_diff, group_indices)

Mean per-cell difference in each annotation group, as {group: difference}.

compute_group_sizes(annotation_labels)

Number of cells per annotation group, as a sorted Series.

compute_membership_diff(diff_Q)

Overall membership difference: diff_Q summed over clusters, averaged over cells.

compute_mode_diffs(mode_Q, ref_Q, mode_name, ref_mode, pair_mappings, annotation_labels=None, aggregation='sum')

Compute the membership difference of one mode from a reference mode.

Parameters:

Name Type Description Default
mode_Q ndarray

Q matrix of the mode (n_cells, K).

required
ref_Q ndarray

Q matrix of the reference mode (n_cells, ref_K).

required
mode_name str

Name of the mode.

required
ref_mode str

Name of the reference mode.

required
pair_mappings Mapping[str, Sequence[Tuple[int, int]]]

Output of get_mode_pair_mappings.

required
annotation_labels Optional[Sequence[Any]]

Annotation label per cell; None skips the group differences.

None
aggregation str

How to combine clusters per cell (see compute_per_cell_diff).

'sum'

Returns:

Type Description
tuple

Overall difference, difference per cell, and difference per annotation group (or None).

compute_per_cell_diff(diff_Q, *, aggregation='sum')

Membership difference per cell.

Parameters:

Name Type Description Default
diff_Q ndarray

Absolute membership differences (n_cells, K).

required
aggregation str

How to combine clusters: "sum" (halved, so in [0, 1]), "max" or "mean".

'sum'

Returns:

Type Description
ndarray

Difference per cell (n_cells,).

get_diff_matrices(comp_res, pair_mappings, ref_mode, models=None, *, strict_pair_mapping=True)

Compute membership differences of every mode from a reference mode.

The mode with the smaller K is mapped onto the other with map_alt_to_ref.

Parameters:

Name Type Description Default
comp_res

compModels results.

required
pair_mappings Dict[str, Sequence[Tuple[int, int]]]

Output of get_mode_pair_mappings.

required
ref_mode str

Full mode name of the reference mode.

required
models Optional[Sequence[str]]

Models to include; None uses all.

None
strict_pair_mapping bool

Raise an error if a pair mapping is missing; otherwise use zero differences.

True

Returns:

Type Description
dict

{model: {mode name: diff_Q (n_cells, min(ref_K, K))}}; zeros for the reference mode.

get_group_indices(annotation_labels)

Cell indices of each annotation group, as {group: indices}.

get_mode_sizes(comp_res, *, size_col='Size', fill_missing=np.nan, sort_index=True)

Mode sizes (number of runs) indexed by full mode name.

Parameters:

Name Type Description Default
comp_res

compModels results.

required
size_col str

Column of the mode_stats tables with the sizes.

'Size'
fill_missing float

Value for modes without a size.

nan
sort_index bool

Sort by full mode name.

True

Returns:

Type Description
Series

get_pairwise_diff(mode_list_1, mode_list_2, pair_mappings, comp_results)

Compute diff_Q for every pair of modes from two lists.

The mode with the smaller K is mapped onto the other.

Parameters:

Name Type Description Default
mode_list_1

First mode names.

required
mode_list_2

Second mode names.

required
pair_mappings

Output of get_mode_pair_mappings.

required
comp_results

Results with Q_by_mode.

required

Returns:

Type Description
dict

{(mode 1, mode 2): diff_Q}.

get_pairwise_membership_diff(diff_Q_dict)

Overall membership difference of each diff_Q, as {(mode 1, mode 2): difference}.

Gene Set Enrichment

Gene set enrichment tests on P matrices.

Functions

compute_gene_lfc(P_gs, gene_set, sepL, sepH, kind='extreme')

Compute each gene's LFC between the high and low clusters.

Parameters:

Name Type Description Default
P_gs ndarray

Gene set rows of the P matrix (n_gs, K).

required
gene_set List[str]

Gene names of the P_gs rows.

required
sepL List[int]

Low cluster indices.

required
sepH List[int]

High cluster indices.

required
kind

"extreme" (min over sepH vs. max over sepL) or "mean" (group means).

'extreme'

Returns:

Type Description
DataFrame

Columns gene and LFC, sorted by LFC (descending).

compute_pairwise_lfc(x)

Compute log2 fold changes between all pairs of clusters.

Parameters:

Name Type Description Default
x ndarray

Value per cluster (K,), e.g. gene set mean P.

required

Returns:

Type Description
ndarray

lfc[j, k] = log2(x[j]) - log2(x[k]), shape (K, K).

resolve_gene_set(symbols_or_indices, used_genes)

Keep the genes of a gene set that are in a reference gene list.

Parameters:

Name Type Description Default
symbols_or_indices list

Gene names, or indices into used_genes.

required
used_genes list

Reference gene names (the P rows).

required

Returns:

Type Description
gene_set

Gene names found in used_genes.

gene_set_indices

Their indices in used_genes.

run_gs_enrichment(results, gene_set_indices, modes, n_perm, rng_seed)

Run the P, LFC and sepLFC enrichment tests for several modes.

Parameters:

Name Type Description Default
results

Results loaded with P matrices.

required
gene_set_indices

Gene set indices in P (from resolve_gene_set).

required
modes

Mode names.

required
n_perm

Number of random gene sets.

required
rng_seed

Random seed.

required

Returns:

Type Description
dict

{mode name: {"p_res", "lfc_res", "sep_res"}}, the outputs of test_P_enrichment, test_LFC_enrichment and test_sepLFC_enrichment.

sample_null_P(P, gs_idx, n_perm, rng_seed=1)

Sample random gene sets of the same size and record their mean P.

Parameters:

Name Type Description Default
P ndarray

P matrix (n_genes, K).

required
gs_idx ndarray

Gene set indices in P.

required
n_perm int

Number of random gene sets.

required
rng_seed int

Random seed.

1

Returns:

Type Description
ndarray

Mean P of each random gene set (n_perm, K).

test_LFC_enrichment(P, gs_idx, null_mean_P)

Test the pairwise LFCs of the gene set mean P against the null.

Parameters:

Name Type Description Default
P ndarray

P matrix (n_genes, K).

required
gs_idx ndarray

Gene set indices in P.

required
null_mean_P ndarray

Output of sample_null_P.

required

Returns:

Type Description
dict

obs_lfc (K, K), null_lfc (n_perm, K, K), test (output of test_pairwise_lfc) and df (one row per pair, sorted by q-value).

test_P_enrichment(P, gs_idx, null_mean_P)

Test whether the gene set mean P is higher than the null in each cluster.

Parameters:

Name Type Description Default
P ndarray

P matrix (n_genes, K).

required
gs_idx ndarray

Gene set indices in P.

required
null_mean_P ndarray

Output of sample_null_P.

required

Returns:

Type Description
dict

gs_mean_P (gene set mean P), z (z-score) and p_emp (one-sided empirical p-value), each of shape (K,).

test_pairwise_lfc(obs, nulls, alternative='two-sided', center='mean', compute_maxT=True)

Test each pairwise LFC against its null distribution.

Each upper-triangle pair gets a z-score and an empirical p-value, adjusted with Benjamini-Hochberg and, optionally, maxT.

Parameters:

Name Type Description Default
obs ndarray

Observed LFC matrix (K, K).

required
nulls ndarray

Null LFC matrices (B, K, K).

required
alternative

"two-sided", "greater" or "less".

'two-sided'
center

Center of the null: "mean" or "median".

'mean'
compute_maxT

Also compute maxT-adjusted p-values.

True

Returns:

Type Description
dict

p_mat, q_mat, z_mat, effect_mat, tested_pairs, p_vec, q_vec, z_vec and effect_vec; with compute_maxT, also p_maxT_mat and p_maxT_vec.

test_sepLFC_enrichment(P, gs_idx, null_mean_P)

Test the gene set sepLFC against two nulls.

sepLFC is the largest log2 gap between the sorted cluster means of P. The first null uses the best sepLFC of each random gene set; the second uses each random gene set's LFC at the observed split.

Parameters:

Name Type Description Default
P ndarray

P matrix (n_genes, K).

required
gs_idx ndarray

Gene set indices in P.

required
null_mean_P ndarray

Output of sample_null_P.

required

Returns:

Type Description
dict

gs_sepLFC log2 of min over sepH / max over sepL of the gene set mean P. gs_geomean_LFC Mean over genes of log2(min over sepH / max over sepL of P). sepL, sepH Low and high cluster indices. idx_sorted_gs Clusters sorted by gene set mean P (ascending). null_sepLFC Best sepLFC of each random gene set (n_perm,). null_lfc_at_sep LFC of each random gene set at the observed split (n_perm,). p_vs_null_sep Empirical p-value against null_sepLFC. p_vs_null_fixed Empirical p-value against null_lfc_at_sep.

Genomics

Mapping between ATAC peaks and genes.

Functions

make_col_unique(df, col, na_label='NA')

Make the values of a column unique by adding suffixes (_1, _2, ...) to duplicates.

Parameters:

Name Type Description Default
df

Input DataFrame.

required
col

Column name.

required
na_label str

Label for missing values.

'NA'

Returns:

Type Description
ndarray

Unique values, in the order of df[col].

match_peaks_to_genes(peaks, gtf_file, *, upstream=5000, downstream=0, feature_type='gene', source='HAVANA', gene_type_allowlist=None, intergenic_label='intergenic', unassigned_label='unassigned')

Map each peak to the genes it overlaps.

Parameters:

Name Type Description Default
peaks Iterable[str]

Peak strings such as "chr1:819912-823500".

required
gtf_file str

GTF file.

required
upstream int

Bases added upstream of each gene.

5000
downstream int

Bases added downstream of each gene.

0
feature_type str

GTF feature type to use (e.g. "gene").

'gene'
source Optional[str]

GTF source to keep (e.g. "HAVANA"); None keeps all.

'HAVANA'
gene_type_allowlist Optional[Set[str]]

gene_type values to keep; None keeps all.

None
intergenic_label str

Label for peaks that overlap no gene.

'intergenic'
unassigned_label str

Label for peaks on chromosomes not in the GTF.

'unassigned'

Returns:

Type Description
list of str

Per peak, the gene name, ";"-joined gene names, or a label.

peaks_with_top_gene_overlap(df_informative_peaks_sorted, df_informative_genes_sorted, n_top=None, mapped_col='mapped_genes', sep=';', drop_labels=('intergenic', 'unassigned', ''))

Find top peaks whose mapped genes are among the top genes.

Parameters:

Name Type Description Default
df_informative_peaks_sorted

Peaks, sorted by importance.

required
df_informative_genes_sorted

Genes, indexed by name and sorted by importance.

required
n_top

Number of top peaks and genes to use; None uses all.

None
mapped_col

Column of the peaks DataFrame with the mapped gene names.

'mapped_genes'
sep

Separator between gene names in mapped_col.

';'
drop_labels

Gene names to ignore (e.g. "intergenic").

('intergenic', 'unassigned', '')

Returns:

Type Description
out_overlap_only

Top peaks with at least one top gene.

out

All top peaks, with columns overlap_genes and has_overlap.