API Reference
Core Functions
Preprocessing
- cccrise.import_data.prepare_dataset(X: anndata.AnnData, condition_name: str, geneThreshold: float, normalize: bool = False)[source]
Preprocess single-cell RNA-seq data for cccRISE analysis.
This function performs essential preprocessing steps including cell and gene filtering, normalization, log transformation, and creation of condition indices required for cccRISE decomposition.
- Parameters:
X (anndata.AnnData) – AnnData object containing raw count data in sparse matrix format.
condition_name (str) – Name of the column in X.obs that specifies experimental conditions for each cell.
geneThreshold (float) – Minimum mean expression threshold for gene filtering. Genes with mean expression below this value are removed.
normalize (bool, optional) – If True, performs normalization and log transformation. If False, keeps raw counts.
- Returns:
Preprocessed AnnData object with filtered cells/genes, added condition_unique_idxs column, and gene means in X.var[“means”].
- Return type:
anndata.AnnData
- cccrise.import_data.import_ligand_receptor_pairs(filename: str | Path = 'cccrise/data/Human-2020-Jin-LR-pairs.parquet', update_interaction_names: bool = True)[source]
Import ligand-receptor pairs from a compressed parquet file with caching.
Loads a curated database of ligand-receptor pairs from CellChat. The function uses LRU caching to avoid repeated file reads. For protein complexes, subunits are separated by & (e.g., CD74&CD44).
- Parameters:
- Returns:
DataFrame with ligand and receptor columns containing gene names.
- Return type:
pd.DataFrame
- cccrise.import_data.add_cond_idxs(X: anndata.AnnData, condition_key: str)[source]
Add unique 0-indexed condition identifiers to an AnnData object.
Creates a new column condition_unique_idxs in X.obs that maps condition labels to 0-based integer indices. This is required for proper data partitioning in the PARAFAC2 decomposition.
- Parameters:
X (anndata.AnnData) – AnnData object to add condition indices to.
condition_key (str) – Column name in X.obs containing condition identifiers.
- Returns:
AnnData object with added condition_unique_idxs column in X.obs.
- Return type:
anndata.AnnData
Factor Storage & Reconstruction (xarray / NetCDF)
- cccrise.factors.factors_to_xarray(cpd_factors: list[np.ndarray], cpd_weights: np.ndarray, filtered_lr_pairs: pd.DataFrame | list[str] | np.ndarray, condition_names: list[str] | np.ndarray, gene_names: list[str] | np.ndarray | None = None, pf2_factors: list[np.ndarray] | None = None, pf2_weights: np.ndarray | None = None, r2x_cp: float | None = None, r2x_pf2: float | None = None, attrs: dict | None = None)[source]
Convert PARAFAC2 and CP decomposition factor matrices into a compact, coordinate-annotated xarray Dataset.
- Parameters:
cpd_factors – List of 4 CP factor matrices: [A (condition), B (sender), C (receiver), D (LR)].
cpd_weights – Component scaling weights for CP decomposition.
filtered_lr_pairs – Ligand-receptor pair symbols matching dimension 3.
condition_names – Labels for conditions / samples matching dimension 0.
gene_names – List of gene identifiers matching single-cell features.
pf2_factors – Optional list of PARAFAC2 factor matrices [A_pf2, B_pf2, C_pf2].
pf2_weights – Optional PARAFAC2 component weights.
r2x_cp – Variance explained by CP decomposition.
r2x_pf2 – Variance explained by PARAFAC2 decomposition.
attrs – Additional metadata dictionary.
- Returns:
Annotated xarray Dataset holding the factor matrices and coordinates.
- Return type:
xr.Dataset
- cccrise.factors.save_factors_netcdf(ds: xr.Dataset, filepath: str | Path)[source]
Save an xarray Dataset of factors to a compact NetCDF file (a few MB).
- cccrise.factors.save_ccc_rise_fit(path: str | Path, adata: anndata.AnnData, cp_fit: dict, condition_column: str, attrs: dict | None = None)[source]
Write a CCC-RISE fit (a RISE-fit AnnData and a
fit_ccc_cp/run_ccc_rise_workflowresult) as the factors fileload_factors_to_anndatareads. Per-cell projections are not stored (compute_cell_projectionsrecomputes them); the file fingerprints the fit’s cells and gene centering, and stores the PaCMAP embedding (float16) when present.
- cccrise.factors.compute_cell_projections(factors_ds: xr.Dataset, adata: anndata.AnnData)[source]
Recompute the per-cell RISE projections of
adata(the fit’s own data, checked against the file’s fingerprints) under a stored RISE fit, without densifyingadata.X.
- cccrise.factors.add_fit_fingerprint(ds: xr.Dataset, adata: anndata.AnnData)[source]
Record in a factors Dataset the data its RISE fit was made on (a hash of the cell IDs and the per-gene centering), which
compute_cell_projectionsrequires and checks.
- cccrise.factors.load_factors_netcdf(filepath: str | Path)[source]
Load an xarray Dataset of factors from a NetCDF file.
- cccrise.factors.load_factors_to_anndata(factors_ds: xr.Dataset | str | Path, adata: anndata.AnnData | None = None, condition_column: str | None = None, do_embedding: bool = False, random_state: int | None = 42)[source]
Populate or construct an AnnData object with decomposition factors from an xarray Dataset.
If
adatais provided, computes single-cell factor projections (obsm["projections"]), sender loadings (obsm["sc_B"]), receiver loadings (obsm["rc_C"]), and optional 2D PaCMAP embeddings. Ifadatais None, creates a lightweight factor container AnnData in milliseconds without loading scRNA-seq matrices.- Parameters:
factors_ds – Factor dataset or path to NetCDF file.
adata – Optional single-cell AnnData to project onto.
condition_column – Condition column name in adata.obs.
do_embedding – If True, computes 2D PaCMAP on cell projections.
random_state – Random seed for reproducibility.
- Returns:
AnnData object populated with factors and projections.
- Return type:
anndata.AnnData
Factorization
- cccrise.ccc_rise.run_ccc_rise_workflow(adata: anndata.AnnData, rise_rank: int, lr_pairs: pd.DataFrame, cp_rank: int = None, condition_column: str = 'sample', random_state: int = None, complex_sep: str = '&', communication_score: str = 'expression_product', hill_k: float = 0.5, backend: str = None, compress: bool = False, cp_device: str = None, cp_dtype: str = 'float32', doEmbedding: bool = False, keep_tensor: bool = False, *, rise_n_iter_max: int, cp_n_iter_max: int, rise_tol: float, cp_tol: float)[source]
Execute the complete cccRISE workflow: RISE decomposition, interaction tensor, CPD factorization, and result storage.
This is the main function for performing cccRISE analysis. It executes both the RISE (PARAFAC2) decomposition of expression data and the CPD decomposition of the resulting interaction tensor. The function decomposes cell-cell communication into four interpretable factor matrices representing conditions, sender cells, receiver cells, and ligand-receptor pairs.
- Parameters:
adata (anndata.AnnData) – AnnData object with preprocessed scRNA-seq data.
rise_rank (int) – Number of PARAFAC2 components to extract from expression data. Typically chosen based on FMS and R²X analysis.
lr_pairs (pd.DataFrame) – DataFrame of ligand-receptor pairs with ‘ligand’ and ‘receptor’ columns.
cp_rank (int, optional) – Number of CPD components for factorizing the interaction tensor. If None, defaults to rise_rank.
condition_column (str, optional) – Column name in adata.obs containing condition identifiers.
random_state (int, optional) – Random seed for the RISE fit, the CPD fit and PaCMAP.
complex_sep (str, optional) – Separator for protein complexes in L-R pairs.
communication_score (str, optional) – Scoring strategy for communication (see
calculate_interaction_tensor).hill_k (float, optional) – Half-maximal constant when using Hill kinetics scoring.
backend (str, optional) – RISE backend (‘cpu’, ‘cupy’, ‘mlx’, or None to auto-detect).
compress (bool, optional) – Fit RISE in a compressed gene/cell subspace (see
fit_rise). The replicate runners compress; the core runner does not. CPD is never compressed.cp_device (str, optional) – Device the CPD fit runs on (‘gpu’, ‘cpu’, or None for the GPU when there is one).
cp_dtype (str, optional) – Precision of the CPD fit (‘float32’ or ‘float64’).
doEmbedding (bool, optional) – If True, computes PaCMAP embeddings for visualization and stores in adata.obsm[“PaCMAP”].
keep_tensor (bool, optional) – If True, the interaction tensor is returned.
rise_n_iter_max (int) – Maximum iterations for the RISE fit.
cp_n_iter_max (int) – Maximum iterations for the CP fit.
rise_tol (float) – Convergence tolerance for the RISE fit.
cp_tol (float) – Convergence tolerance for the CP fit.
- Returns:
Dict with keys ‘adata’, ‘tensor’ (None unless keep_tensor), ‘filtered_lr_pairs’, ‘cp_weights’, ‘cp_factors’, ‘r2x_rise’, ‘r2x_cp’ and ‘diagnostics’ (CPD component collinearity).
- Return type:
- cccrise.ccc_rise.calculate_interaction_tensor(adata: anndata.AnnData, lr_pairs: pd.DataFrame, complex_sep: str | None = '&', communication_score: str = 'expression_product', hill_k: float = 0.5)[source]
Calculate the interaction tensor from an AnnData object that has already been processed with RISE.
This function computes cell-cell communication scores for all ligand-receptor pairs across sender-receiver latent cell state pairs using the pre-computed RISE projections in adata.obsm[“projections”]. The resulting tensor has dimensions (n_conditions × rise_rank × rise_rank × n_lr_pairs).
- Parameters:
adata (anndata.AnnData) – AnnData object containing expression data and RISE projections in
obsm["projections"].lr_pairs (pd.DataFrame) – DataFrame of ligand-receptor pairs with ‘ligand’ and ‘receptor’ columns.
complex_sep (str, optional) – Symbol that separates protein subunits in multimeric complexes (default: “&”).
communication_score (str, optional) – Scoring strategy for communication (‘expression_product’, ‘expression_mean’, ‘expression_gmean’, or ‘expression_hill’).
hill_k (float, optional) – Half-maximal constant when using Hill kinetics scoring (default: 0.5).
- Returns:
Tuple containing the interaction tensor with dimensions (n_conditions × rise_rank × rise_rank × n_lr_pairs) and the filtered ligand-receptor pairs DataFrame.
- Return type:
tuple[np.ndarray, pd.DataFrame]
Analysis Functions
- cccrise.utils.expression_product_matrix(X1: anndata.AnnData, X2: anndata.AnnData, ligand: str, receptor: str)[source]
Calculate the expression product matrix for a specific ligand-receptor pair between cell populations.
For each cell in X1 (senders) and each cell in X2 (receivers), this computes the product of ligand expression (in sender) and receptor expression (in receiver). This represents the potential for that specific L-R interaction between each sender-receiver cell pair.
- Parameters:
- Returns:
DataFrame with sender cells as rows and receiver cells as columns, values are expression products.
- Return type:
pd.DataFrame
- cccrise.utils.binned_expression_product_matrix(X1: anndata.AnnData, X2: anndata.AnnData, ligand: str, receptor: str, n_bins: int = 10)[source]
Compute the expression product matrix for a ligand-receptor pair, binned into an n_bins x n_bins matrix of block means.
Equivalent to binning
expression_product_matrix(X1, X2, ligand, receptor)into an n_bins x n_bins matrix of block means, but computed without ever materializing the full len(X1) x len(X2) outer product: since block entries are a product of independent per-cell terms, the mean of a block is just the product of the row- and column-block means of the two expression vectors.- Parameters:
X1 (anndata.AnnData) – AnnData object containing sender cells.
X2 (anndata.AnnData) – AnnData object containing receiver cells.
ligand (str) – Ligand gene name (must be present in X1.var_names).
receptor (str) – Receptor gene name (must be present in X2.var_names).
n_bins (int) – Number of bins per axis.
- Returns:
n_bins x n_bins DataFrame with averaged expression products.
- Return type:
pd.DataFrame
Association Testing
One-way ANOVA tests of each CPD component’s condition loadings against sample metadata (for example, ALAD status or 6-month outcome).
- cccrise.anova.run_saved_factors_anova(factors: str | Path | xr.Dataset | anndata.AnnData, adata: anndata.AnnData | None = None, sample_to_group: pd.Series | None = None, group_column: str | None = None, condition_column: str | None = None, control_label: str | None = None, other_label: str | None = None, levels: Sequence[str] | None = None, mapping: Mapping[str, str] | None = None, alpha: float = 0.05, correction: str | None = 'fdr_bh', association_name: str | None = None, read_depth_correct: bool = True)[source]
Run a one-way ANOVA of every CPD component on a saved factors dataset (e.g.
bal_alad_factors.nc).- Parameters:
factors – Path to a saved NetCDF factor dataset, an xarray Dataset, or an AnnData holding the factors in
uns.adata – AnnData with the condition and group annotations in
obs.sample_to_group – Pre-extracted condition-to-group mapping, used instead of
group_column.group_column – Phenotype group column in
adata.obs.condition_column – Sample/condition column in
adata.obs.control_label – With
other_label, collapsesgroup_columninto two levels.levels – Subset of group levels to retain.
mapping – Dictionary mapping original group levels to new categories.
alpha – Significance threshold for the
Significantcolumn.correction – Multiple testing correction across components (‘fdr_bh’, ‘bonferroni’, ‘holm’ or None).
association_name – Name to record in an
Associationcolumn.read_depth_correct – Test the read-depth-corrected condition loadings; this needs the single-cell data in
adata. False testsuns["A"]as is.
- Returns:
One row per component with
F,P,PAdj,EtaSquared,GroupMeanDiffandSignificant.- Return type:
pd.DataFrame
- cccrise.anova.run_multiple_factors_anova(factors: str | Path | xr.Dataset | anndata.AnnData, associations: Sequence[dict[str, Any] | str], adata: anndata.AnnData | None = None, condition_column: str | None = None, alpha: float = 0.05, correction: str | None = 'fdr_bh', global_correction: bool = False, read_depth_correct: bool = True)[source]
Run several
run_saved_factors_anovatests on one factors dataset. Each association is a dictionary (keys such asname,group_column,levels,mapping,control_label,other_label) or the name of anadata.obscolumn to test across all its levels. Withglobal_correction, the correction is applied across all associations and components together. Returns one combined DataFrame with anAssociationcolumn.
- cccrise.anova.prepare_anova_inputs(adata: anndata.AnnData, factors: list[np.ndarray], condition_column: str, group_column: str, control_label: str | None = None, other_label: str | None = None, levels: Sequence[str] | None = None, mapping: Mapping[str, str] | None = None)[source]
Attach one CPD fit’s factors [A, B, C, D] to a copy of
adata(withuns["A"]read-depth corrected) and derive the group label of each condition. Returns the AnnData copy and the group labels aligned to the rows ofuns["A"].
- cccrise.anova.prepare_group_labels(sample_to_group: pd.Series, levels: Sequence[str] | None = None, mapping: Mapping[str, str] | None = None, control_label: str | None = None, other_label: str | None = None, condition_order: Sequence[str] | None = None)[source]
Filter, recode, or collapse a condition-to-group mapping:
levelskeeps a subset (the other conditions become NaN),mappingrenames levels, andcontrol_labelwithother_labelcollapses the groups into two. Returns the labels aligned tocondition_order.
- cccrise.anova.anova_component_associations(X: anndata.AnnData, sample_to_group: pd.Series, alpha: float = 0.05, control_label: str | None = None, correction: str | None = None, min_group_size: int = 2)[source]
One-way ANOVA of each CPD component’s condition loading (
X.uns["A"]) against the group label of each condition. A component’s test is NaN when any group has fewer thanmin_group_sizeconditions. Returns one row per component (1-indexed) withComponent,F,P,PAdj,EtaSquared,GroupMeanDiff,Significant,NGroupsandGroupSizes.
- cccrise.anova.adjust_pvalues(p_values: Sequence[float] | np.ndarray, method: str | None = 'fdr_bh')[source]
Adjust p-values for multiple testing across components: Benjamini-Hochberg (‘fdr_bh’), Benjamini-Yekutieli (‘fdr_by’), Bonferroni (‘bonferroni’), Holm (‘holm’), or None for the raw values. NaNs for non-finite inputs are preserved.
Pseudobulk Baseline
- cccrise.tensor.run_pseudobulk_workflow(adata: anndata.AnnData, cp_rank: int = 8, lr_pairs: pd.DataFrame | None = None, condition_column: str = 'sample', groupby: str = 'celltype', type: str = 'mean', n_iter_max: int = 1000, tol: float = 1e-11, random_state: int | None = None, complex_sep: str | None = '&')[source]
Aggregate single cells into pseudobulk matrices per (condition,
groupby), compute the four-dimensional communication tensor, fit a CP decomposition, and store the factors, weights and LR pairs inadata.uns.- Parameters:
cp_rank – Rank of the CP decomposition.
lr_pairs – Ligand-receptor pairs; loaded automatically if None.
groupby – Column in
adata.obsdefining the cell types.type – Aggregation method, ‘mean’ or ‘sum’.
- Returns:
The updated AnnData object and the R²X.
- Return type:
Utilities
- cccrise.factors.clean_memory()[source]
Garbage collect and release CuPy device and pinned host memory pools.
cccrise.ALAD_FACTORS_PATH is the path of the canonical ALAD factors file (cccrise/data/factors/bal_alad_factors.nc).
Command-Line Runners
Each runner is installed as a console script and run with uv run <script>. Runners that take --dataset use the datasets registered in cccrise.runners.datasets.DATASETS (alad and ibd) and write their results, with a provenance file, under cccrise/data/.
Script |
Module |
Purpose |
|---|---|---|
|
|
The end-to-end cccRISE pipeline; saves the dataset’s canonical factors file. |
|
|
RISE (PARAFAC2) rank selection by bi-cross-validation. |
|
|
CPD rank selection on the interaction tensor. |
|
|
cccRISE refit at a lower RISE rank, for the label-sensitivity panels. |
|
|
Per-component stability under patient jackknifing and seed refitting. |
|
|
Cell-permutation significance testing of communication. |
|
|
NicheNet-style downstream-target validation of CPD components. |
|
|
CPD factors for all four communication scores, sharing one RISE fit. |
|
|
Per-sample and per-cell-type summaries of the cohort a fit was made on. |
|
|
Tables behind the ALAD and IBD program analyses, from the finalized fit. |
|
|
Rank selection and fits of the annotation-pooled comparator methods. |
|
|
How cccRISE’s components compare with the comparators’. |
|
|
NicheNet tests on cccRISE and every comparator’s ligand-receptor columns. |
|
|
NICHES on a dataset’s production fit, compared with cccRISE’s populations. |
|
|
Scriabin reproducibility analyses. |
|
|
Build the manuscript figures. |
|
|
Build the source data files for the figures. |