rapids_singlecell.pp.harmony_integrate#

rapids_singlecell.pp.harmony_integrate(adata, batch=None, *, use=None, out=False, dtype=<class 'numpy.float32'>, flavor='harmony2', n_clusters=None, max_iter_harmony=10, max_iter_clustering=None, tol_harmony=None, tol_clustering=None, sigma=0.1, theta=2.0, tau=0, ridge_lambda=1.0, alpha=0.2, batch_prune_threshold=1e-05, correction_method=None, colsum_algo=None, block_proportion=0.05, rng=None, multi_gpu=False, verbose=False, key=None, basis=None, adjusted_basis=None)[source]#

Integrate different experiments using the Harmony algorithm [KMF+19, PYM+26].

This GPU-accelerated implementation was originally based on the harmony-pytorch package. Multiple batch variables now follow the per-covariate formulation described in the Harmony papers: each key is modeled separately instead of combining all keys into one joint category. As Harmony works by adjusting the principal components, this function should be run after performing PCA but before computing the neighbor graph.

By default, the Harmony2 algorithm is used, which includes a stabilized diversity penalty, dynamic per-cluster-per-batch ridge regularization, and automatic batch pruning. To revert to the original Harmony behavior:

rsc.pp.harmony_integrate(adata, batch, flavor="harmony1")
Parameters:
adata AnnData

The annotated data matrix.

batch AdRef | str | Sequence[AdRef | str] | None (default: None)

The annotation(s) that differentiate(s) among experiments/batches, e.g. A.obs['batch'] or [A.obs['batch'], A.obs['donor']]. Strings name .obs columns, or are resolved by anndata.acc.AdAcc.resolve() (e.g. 'obs.batch') if rapids_singlecell.settings.preset is ScanpyV2Preview. Multiple batch variables are modeled separately, with one active categorical level per variable and cell. To retain the joint-combination behavior of earlier releases, combine the desired columns into one categorical column and pass that.

use MultiAcc | str | None (default: None)

Which embedding to adjust, e.g. A.obsm['X_pca'] (or 'obsm.X_pca'). By default, the one pca() wrote under either preset’s name.

out MultiAcc | str | bool (default: False)

Where to write the adjusted embedding, e.g. A.obsm['pca_harmony']. If True, it is returned instead. If False, it is written to .obsm[k + '_harmony'] for use=A.obsm[k].

dtype type | str (default: <class 'numpy.float32'>)

The data type used for initialization and Harmony computation. Defaults to numpy.float32. Use numpy.float64 when additional precision is needed; it can be slower on GPUs with reduced double-precision throughput. "bfloat16" computes in float32 but stores the soft cluster assignments in bfloat16, which is faster and halves their memory (about a quarter less GPU memory with 50 components). It needs one batch key and the batched correction and falls back to float32 with a warning otherwise. None keeps the input’s float32 or float64.

flavor Literal['harmony2', 'harmony1'] (default: 'harmony2')

Which version of the Harmony algorithm to use. "harmony2" (default) enables the stabilized diversity penalty, dynamic per-cluster-per-batch ridge regularization, and automatic batch pruning from [PYM+26]. "harmony1" uses the original algorithm from [KMF+19].

n_clusters int | None (default: None)

Number of clusters used for soft k-means in the Harmony algorithm. If None, uses min(100, N / 30). More clusters capture finer-grained structure but increase computation time.

max_iter_harmony int (default: 10)

Maximum number of outer Harmony iterations (each consisting of a clustering step followed by a correction step).

max_iter_clustering int | None (default: None)

Maximum iterations for the clustering step within each Harmony iteration. If None, uses the value of the reference implementation for the chosen flavor: 4 for "harmony2", 200 for "harmony1".

tol_harmony float | None (default: None)

Convergence tolerance for the Harmony objective function. The algorithm stops when the relative change in objective falls below this value. If None, 1e-2 for "harmony2" and 1e-4 for "harmony1".

tol_clustering float | None (default: None)

Convergence tolerance for the clustering step within each Harmony iteration. If None, 1e-3 for "harmony2" and 1e-5 for "harmony1".

sigma float (default: 0.1)

Width of the soft-clustering kernel. Controls the entropy of cluster assignments: smaller values produce harder assignments (cells assigned to fewer clusters), while larger values produce softer assignments (cells spread across more clusters).

theta float | int | list[float] | ndarray | ndarray (default: 2.0)

Diversity penalty weight per batch variable. Controls how strongly Harmony encourages each cluster to contain a balanced representation of all batches. Higher values (e.g. 4) produce more aggressive mixing; lower values (e.g. 0.5) allow more batch-specific clusters. Set to 0 to disable the diversity penalty for a batch variable. A scalar is applied to every key. A sequence may contain one value per key, expanded over that key’s categorical levels, or one value per categorical level across all keys.

tau int (default: 0)

Discounting factor on theta. When tau > 0, the diversity penalty is down-weighted for batches with fewer cells, preventing over-correction of small batches. By default (0), there is no discounting.

ridge_lambda float (default: 1.0)

Ridge regression regularization for the correction step. Larger values produce more conservative (smaller) corrections, preventing over-fitting. Must be finite and greater than zero. Only used with flavor="harmony1".

alpha float (default: 0.2)

Scaling factor for the dynamic per-cluster-per-batch ridge regularization. The effective regularization for each cluster-batch pair is alpha * E_kb where E_kb is the expected number of cells. Larger values produce more conservative corrections. Only used with flavor="harmony2".

batch_prune_threshold float | None (default: 1e-05)

Fraction threshold below which a batch-cluster pair is pruned (correction suppressed). When the fraction of a batch’s cells assigned to a cluster (O_kb / N_b) falls below this threshold, that batch-cluster pair receives no correction, preventing spurious adjustments. Only used with flavor="harmony2". Set to None to disable pruning.

correction_method Literal['fast', 'batched'] | None (default: None)

Method for the correction step. Both solve the ridge regressions in closed form. "batched" corrects from exact right-hand sides, as many clusters per pass as fit in 1 GiB of workspace (clusters x batches x components), and normalizes in the same pass. "fast" corrects one cluster at a time with the least workspace (float right-hand sides, a separate normalization pass, one GPU with multi_gpu). With one key, None automatically selects "batched" unless one cluster’s workspace would exceed 1 GiB, in which case "fast" is used. Multiple keys always use the exact general-design solve because the arrowhead optimization applies only to one batch variable; clusters are processed in workspace-bounded chunks when needed. For multiple keys, use None or "batched"; passing "fast" emits a warning and uses the exact solve.

colsum_algo Literal['columns', 'atomics', 'gemm', 'benchmark'] | None (default: None)

No effect: column sums come from the fused clustering kernels. Kept for compatibility.

block_proportion float (default: 0.05)

Proportion of cells updated per clustering sub-iteration. Smaller values produce more stochastic updates. Larger values are faster but may converge to different solutions. The blocks are drawn once per call and visited in a rotating order (the reference implementations redraw random blocks every iteration). Cells join them in runs of up to 8 cells of the same batch, in random order within the batch, so a batch of fewer than 8 / block_proportion cells is spread over fewer blocks.

rng int | integer | Sequence[int] | SeedSequence | Generator | BitGenerator | None (default: None)

Random seed or Generator for reproducibility. The superseded random_state argument is still accepted. Sequential calls with identical inputs, parameters, and integer seed are bitwise reproducible on the same hardware and software stack in float32 and float64. Initialization uses k-means++ and fixed-order Lloyd reductions. Results may differ across GPU architectures or CUDA versions; concurrent CUDA streams are outside this guarantee.

multi_gpu bool | list[int] | str | None (default: False)

GPUs to split the cells across: True for all visible GPUs, a list or comma-separated string of device ids, or False/None for the current GPU. The result is bitwise identical to a run on one GPU of the same model. The fast correction runs on one GPU; it is also chosen for correction_method=None when one cluster’s batched correction would need more than 1 GiB of workspace.

verbose bool (default: False)

Whether to print the number of iterations until convergence.

Return type:

ndarray | None

Returns:

The adjusted embedding if out=True, else None. It contains the principal components adjusted by Harmony, such that different experiments are integrated.