Skip to content

I/O

Loading Clumppling and compModels outputs and related input files.

Classes

ClumpplingResults dataclass

Clumppling results for one model.

Attributes:

Name Type Description
align_dir Path

Clumppling output directory.

suffix str

Suffix of the aligned Q files ("rep" or "avg").

mode_alignment DataFrame

Table from modes/mode_alignment.txt.

mode_stats DataFrame

Table from modes/mode_stats.txt.

modes List[str]

Mode names (e.g. "K5M1").

mode_K Dict[str, int]

{mode name: K}.

K_range List[int]

Sorted K values.

K_max int

Largest K.

mode_names_list List[List[str]]

Mode names grouped by K.

Q_by_mode Dict[str, ndarray]

{mode name: aligned Q matrix (n_cells, K)}.

alignment_acrossK Dict[str, Sequence[int]]

{"A-B": mapping of clusters of B to clusters of A, in original indices}.

cost_acrossK Dict[str, float]

{"A-B": alignment cost}.

all_modes_alignment Dict[str, Sequence[int]]

{mode name: column order after alignment}.

mode_coord_dict Dict[str, Tuple[int, int]]

{mode name: (row, column)} in a grid by K.

mode_sep_coord_dict Dict[Tuple[str, int], Tuple[int, int]]

{(mode name, cluster index): (row, column)}.

input_meta DataFrame | None

Table from input/input_meta.txt, if loaded.

Q_unaligned_by_mode Dict[str, ndarray] | None

{mode name: unaligned Q matrix}, if loaded.

P_unaligned_by_mode Dict[str, ndarray] | None

{mode name: unaligned P matrix (n_features, K)}, if loaded.

P_aligned_by_mode Dict[str, ndarray] | None

{mode name: aligned P matrix (n_features, K)}, if loaded.

Functions
reorder_inds(reorder_idx)

Return a copy with the cells (Q rows) reordered by reorder_idx.

CompModelsResults dataclass

compModels results for several models.

Attributes:

Name Type Description
res_dir Path

compModels output directory.

input_dir Optional[Path]

compModels input directory, with the mode_stats files.

models List[str]

Model names.

modes_by_model Dict[str, List[str]]

{model: mode names (e.g. "K21M1")}.

full_mode_names_by_model Dict[str, List[str]]

{model: full mode names (e.g. "model_K21M1")}.

full_mode_names List[str]

All full mode names.

Q_by_mode Dict[str, ndarray]

{full mode name: aligned Q matrix (n_cells, K)}.

all_modes_alignment Dict[str, Sequence[int]]

{full mode name: column order after alignment}.

alignment_across_all Optional[Dict[str, Sequence[int]]]

{"A-B": mapping of clusters of B to clusters of A}.

cost_across_all Optional[Dict[str, float]]

{"A-B": alignment cost}.

mode_stats_by_model Dict[str, DataFrame]

{model: mode_stats table}.

K_max int

Largest K over all models.

K_max_by_model Dict[str, int]

{model: largest K}.

Functions
get_Q(full_mode_name)

Aligned Q matrix of a full mode name.

get_Q_for(model, mode_short)

Aligned Q matrix of a model and mode name (e.g. "K21M1").

reorder_inds(reorder_idx)

Return a copy with the cells (Q rows) reordered by reorder_idx.

Functions

add_pairwise_alignment(res, alignment)

Return a copy with the columns of each mode reordered by a new alignment.

Parameters:

Name Type Description Default
res ClumpplingResults

Results to update.

required
alignment Dict[str, Sequence[int]]

{mode name: column order}, e.g. {"K3M1": [2, 0, 1]}.

required

Returns:

Type Description
ClumpplingResults

Results with Q_by_mode, P_aligned_by_mode and all_modes_alignment updated.

filter_bed_by_peaks(bed_path, peaks, *, ccre_id_col=3)

Keep the lines of a BED file that overlap any peak.

Parameters:

Name Type Description Default
bed_path str | Path

BED file.

required
peaks Iterable[str]

Peak strings such as "chr1:10109-10357".

required
ccre_id_col int

Column (0-based) with the cCRE ID.

3

Returns:

Type Description
filtered_rows

Kept lines, split into fields.

kept_ids

cCRE IDs of the kept lines.

Keep the lines of a gene-link file whose cCRE ID is in kept_ids.

Parameters:

Name Type Description Default
gene_links_path str | Path

Gene-link file.

required
kept_ids Set[str]

cCRE IDs to keep.

required
ccre_id_col int

Column (0-based) with the cCRE ID.

0
keep_header bool

Return the first line as a header.

True

Returns:

Type Description
header

Header fields, or None.

filtered_rows

Kept lines, split into fields.

group_modes_by_K(mode_names)

Group mode names by K, e.g. ["K3M1", "K3M2", "K4M1"] -> [["K3M1", "K3M2"], ["K4M1"]].

infer_K_range(mode_names)

Sorted K values of mode names, e.g. ["K3M1", "K3M2", "K4M1"] -> [3, 4].

load_aligned_Qs(align_dir, modes, suffix='rep', *, delimiter=' ')

Load the aligned Q matrix of each mode from modes_aligned/{mode}_{suffix}.Q.

Parameters:

Name Type Description Default
align_dir PathLike

Clumppling output directory.

required
modes Sequence[str]

Mode names.

required
suffix str

"rep" or "avg".

'rep'
delimiter str

Column delimiter.

' '

Returns:

Type Description
dict

{mode name: Q matrix (n_cells, K)}.

load_alignment_across_K(align_file)

Load cluster mappings and costs between modes.

Parameters:

Name Type Description Default
align_file str | PathLike

Alignment file written by Clumppling or compModels.

required

Returns:

Type Description
alignment_acrossK

{"A-B": mapping of clusters of B to clusters of A}.

cost_acrossK

{"A-B": alignment cost}.

load_all_modes_alignment(align_dir, suffix='rep', *, filename=None)

Load the column order of each mode after alignment.

Parameters:

Name Type Description Default
align_dir PathLike

Clumppling output directory.

required
suffix str

"rep" or "avg".

'rep'
filename str | None

File name; None uses all_modes_alignment_{suffix}.txt.

None

Returns:

Type Description
dict

{mode name: column order}.

load_clumppling_replicate_Ps(clumppling_dir, cls_dir, p_ext='P', strict_P=True)

Load the P matrices of all runs of each mode, in the aligned column order.

Columns are aligned as in load_clumppling_replicate_Qs.

Parameters:

Name Type Description Default
clumppling_dir

Clumppling output directory.

required
cls_dir

Directory with the clustering files.

required
p_ext

Extension of the P files ("P", or "meanP" for fastStructure).

'P'
strict_P

Raise an error if any P file is missing. Otherwise skip those runs with a warning, so runs and modes may differ from load_clumppling_replicate_Qs (match runs by name). An error is always raised if all P files are missing.

True

Returns:

Type Description
P_reps_by_mode

{mode name: array (n_runs, n_features, K)}.

rep_names_by_mode

{mode name: run names, in the order of the first axis}.

modes

Mode names sorted by K and mode index.

load_clumppling_replicate_Qs(clumppling_dir, input_order=False)

Load the Q matrices of all runs of each mode, in the aligned column order.

Each run's columns are first matched to its mode's representative (modes/mode_alignment.txt), then put in the aligned order (modes_aligned/all_modes_alignment_rep.txt).

Parameters:

Name Type Description Default
clumppling_dir

Clumppling output directory.

required
input_order

Return rows in input order (see undo_clumppling_regroup); otherwise rows follow Clumppling's order, as in Q_by_mode.

False

Returns:

Type Description
Q_reps_by_mode

{mode name: array (n_runs, n_cells, K)}.

rep_names_by_mode

{mode name: run names, in the order of the first axis}.

modes

Mode names sorted by K and mode index.

load_clumppling_results(align_dir, *, suffix='rep', round_Q=False, cls_dir=None, load_unaligned=False, load_P=True, strict_P=False, p_ext=None)

Load Clumppling results.

Q rows follow Clumppling's order, which differs from the input order if Clumppling regrouped cells by --ind_labels (see undo_clumppling_regroup).

Parameters:

Name Type Description Default
align_dir PathLike

Clumppling output directory.

required
suffix str

Suffix of the aligned Q files ("rep" or "avg").

'rep'
round_Q bool

Round Q to hard memberships.

False
cls_dir PathLike | None

Directory with the clustering files; needed to load P or unaligned Q.

None
load_unaligned bool

Also load the unaligned Q matrices.

False
load_P bool

Load the P matrices.

True
strict_P bool

Raise an error if P files are missing; otherwise warn and continue without P.

False
p_ext str | None

Extension of the P files (e.g. "meanP" for fastStructure); None uses "P".

None

Returns:

Type Description
ClumpplingResults

load_compmodels_results(res_dir, input_dir=None)

Load compModels results.

Parameters:

Name Type Description Default
res_dir str | Path

compModels output directory.

required
input_dir str | Path | None

compModels input directory, with the mode_stats files; None leaves mode_stats_by_model empty.

None

Returns:

Type Description
CompModelsResults

load_gene_intervals(gtf_file, *, upstream=5000, downstream=0, feature_type='gene', source='HAVANA', gene_type_allowlist=None)

Read gene intervals from a GTF file (gzipped or not).

Returns {chromosome: sorted (start, end, gene name)}.

load_gene_set(name, gene_set_dir, *, prefix=None)

Load a gene set file (one gene name per line).

Parameters:

Name Type Description Default
name str

Gene set name, the file stem (e.g. "HALLMARK_E2F_TARGETS").

required
gene_set_dir PathLike

Directory with the gene set files ({name}.txt).

required
prefix str | None

Prefix added to name if missing (e.g. "HALLMARK_").

None

Returns:

Type Description
list of str

Gene names.

load_input_meta(align_dir)

Load input/input_meta.txt, which links the input files to modes.

load_mode_alignment(align_dir)

Load modes/mode_alignment.txt from a Clumppling output directory.

load_mode_stats(align_dir)

Load modes/mode_stats.txt from a Clumppling output directory.

load_unaligned_for_modes(cls_dir, align_dir, *, mat_type, modes=None, mode_stats=None, input_meta=None, delimiter=None, p_ext=None)

Load the unaligned P or Q matrix of each mode's representative run.

Parameters:

Name Type Description Default
cls_dir PathLike

Directory with the clustering files.

required
align_dir PathLike

Clumppling output directory.

required
mat_type Literal['P', 'Q']

"P" or "Q".

required
modes Sequence[str] | None

Mode names; None uses all modes.

None
mode_stats DataFrame | None

Mode stats table; None loads it from align_dir.

None
input_meta DataFrame | None

Input metadata table; None loads it from align_dir.

None
delimiter str | None

Column delimiter; None splits on any whitespace.

None
p_ext str | None

Extension of the P files (e.g. "meanP" for fastStructure); None uses mat_type.

None

Returns:

Type Description
dict

{mode name: matrix}.

subset_compmodels(comp_res, K_min=None, K_max=None, K_values=None)

Restrict a CompModelsResults to modes with selected K.

Parameters:

Name Type Description Default
comp_res CompModelsResults

Full results.

required
K_min Optional[int]

Range of K to keep; None leaves that end open. Ignored if K_values is given.

None
K_max Optional[int]

Range of K to keep; None leaves that end open. Ignored if K_values is given.

None
K_values Optional[Sequence[int]]

K values to keep.

None

Returns:

Type Description
CompModelsResults

undo_clumppling_regroup(Q, align_dir)

Restore the input order of Q rows that Clumppling regrouped by --ind_labels.

Parameters:

Name Type Description Default
Q

Array (..., n_cells, K) in Clumppling's row order, as in Q_by_mode.

required
align_dir

Clumppling output directory.

required

Returns:

Type Description
ndarray

Q in input row order; unchanged if input/ind_labels_indices.txt does not exist.