Skip to main content
v2026.11,986 entries · CC-BY 4.0

harmonypy: Run Harmony Batch Correction in Python

How to install harmonypy, run Harmony batch correction on PCA embeddings, read Z_corr and fix common errors, using the project’s own documentation.

Written and maintained by CASRAI Editorial Board

Published

On this page

harmonypy is a Python package that runs the Harmony algorithm to remove batch effects from the principal-component embedding of single-cell data, so that cells group by cell type rather than by donor, plate or experiment. You pass it a cells-by-PCs matrix, a table of cell metadata and the name of the batch column, and it returns a corrected embedding of the same shape. Version 2.1.0 (the latest on PyPI when checked on 2026-11-18) needs Python 3.9 or later.

What harmonypy is used for in research

Single-cell experiments are rarely run as one clean batch. Samples come from different donors, are processed on different days or are sequenced on different lanes, and those technical or biological differences can pull cells apart in a PCA or UMAP plot even when the cells are the same type. The Harmony paper (Korsunsky et al., Nature Methods 16, 1289-1296, 2019) describes the method as projecting cells into a shared embedding in which cells group by cell type rather than dataset-specific conditions. The authors report that it can account for multiple experimental and biological factors at once and makes integration of around a million cells feasible on a personal computer.

harmonypy is the Python implementation. Its README describes it as a package with a multithreaded C++ backend that follows the R harmony2 package step by step, so analyses started in Python and in R use the same algorithm. It works on the low-dimensional embedding, not on the raw count matrix: the correction is applied to the PCs, and the result is used for neighbour graphs, UMAP and clustering. Pipelines that start from the counts and need adjusted expression values for every gene use a different family of methods; our guide to ComBat batch correction covers one such method. If you are new to the upstream wet-lab and count-matrix steps, see the single-cell RNA sequencing workflow guide.

How to install or access harmonypy

The package is distributed on PyPI, and the source is on GitHub under slowkow/harmonypy. Both are the official locations named in the project README.

  1. Check that you have Python 3.9 or later (the requires-python setting in the project’s pyproject.toml and the PyPI page).
  2. Install from PyPI: pip install harmonypy. The README states that pre-built wheels are provided for Linux and macOS. The only runtime dependency declared in pyproject.toml is NumPy; pandas is used in the project’s tests and examples.
  3. Check the install with import harmonypy as hm and hm.__version__.

To build from source (for example on a platform without a wheel), the README says you need a C++17 compiler and the Python development headers (python3-dev on Debian and Ubuntu, python3-devel on Fedora). harmonypy does not use BLAS or LAPACK. CMake is installed during the build if it is missing, and the Armadillo headers are downloaded, which needs network access, if Armadillo is not already installed. Then run pip install . from the repository folder. The package is licensed GPL-3.0-or-later according to the project’s pyproject.toml, which matters if you plan to redistribute software that bundles it.

How to run Harmony step by step

The steps below follow the README’s Scanpy example. They assume you already have an AnnData file with a column in adata.obs that names the batch (here batch).

  1. Load and preprocess the data, then compute PCA: adata = sc.read_h5ad("my_data.h5ad") followed by sc.pp.pca(adata).
  2. Take the embedding from the AnnData object: pcs = adata.obsm['X_pca']. Its shape is cells by PCs.
  3. Run Harmony on the embedding, naming the metadata column to correct: harmony_out = hm.run_harmony(pcs, adata.obs, "batch"). The second argument is the metadata table with one row per cell, and the third is the column name (a string) or a list of column names.
  4. Store the corrected embedding: adata.obsm['X_pca_harmony'] = harmony_out.Z_corr.
  5. Use the corrected embedding downstream: sc.pp.neighbors(adata, use_rep='X_pca_harmony'), then sc.tl.umap(adata) and sc.tl.leiden(adata).

Without Scanpy, the README’s quick start reads a PC table and a metadata table with pandas (pd.read_csv), calls hm.run_harmony(pcs, meta, "donor") and writes pd.DataFrame(harmony_out.Z_corr, columns=pcs.columns) to a file. The same README example uses the bundled PBMC files data/pbmc_3500_pcs.tsv.gz and data/pbmc_3500_meta.tsv.gz, which is a convenient first test because the repository includes them.

Correcting for more than one variable

According to the function’s docstring, vars_use accepts a single column name or a list, so donor and processing date can be corrected together: hm.run_harmony(pcs, adata.obs, ["donor", "date"]). Per the docstring, theta can then be one number for all batches, one per variable in the order of vars_use, or one per batch level. Version 2.1.0’s changelog notes that the C++ backend was reworked so that correcting for several covariates no longer requires inverting a matrix with one row per level, which is what keeps runs with hundreds of levels fast.

Parameters and their defaults

The data table below lists the main run_harmony parameters with their defaults and meaning, compiled from the README parameter table and the function signature and docstring in harmony.py. Beyond the table, three practical points come from the documentation. First, theta is the diversity penalty: larger values push harder towards mixing batches, and the default is 2. Second, sigma is the kernel bandwidth for soft clustering (default 0.1). Third, nclust defaults to min(N/30, 100), where N is the number of cells, so very small datasets get fewer clusters. The random_state argument defaults to 0, and verbose defaults to True, which prints progress messages.

How to read the output

run_harmony returns a Harmony object. Its main attribute is Z_corr, the corrected embedding as an N by d matrix (cells by PCs), which has the same shape as the PCs you supplied. Z_orig holds the original embedding in the same layout. The object also exposes R (the soft cluster assignment matrix, N by K), Y (the cluster centroids, d by K), K (the number of clusters), objective_harmony and objective_kmeans (objective values) and kmeans_rounds (the k-means rounds per Harmony iteration).

Three consequences follow for how to use the result:

  • Z_corr is an embedding, not a count matrix. Use it for graph construction, UMAP and clustering (see Leiden clustering for single-cell data and UMAP-learn), not as corrected expression values for differential expression.
  • Keep the uncorrected PCs next to the corrected ones, as the README example does by storing the result under a new key (X_pca_harmony) rather than overwriting X_pca.
  • Check integration quantitatively, not only by eye. harmonypy includes compute_lisi(X, metadata, label_colnames, perplexity=30), which computes the Local Inverse Simpson Index for each cell. According to its docstring, with a three-category variable a LISI near 3 means a cell is surrounded by neighbours from all three categories, and a LISI near 1 means its neighbours come from one category. Compute it on the corrected embedding for the batch column, where you want high values, and for a cell-type label, where you want values near 1 if the labels are reliable.

A caution that follows from the method rather than from any single document: a strong correction can also merge groups that differ for real biological reasons if the batch variable is correlated with the biology (for instance, if every sample of one condition was processed in a single batch). Design the experiment so that each batch contains more than one condition, and report the batch variable and the theta value you used.

Run time and memory

The README reports timings against version 2.0.2 on an Apple M1 Ultra (20 cores), at default settings. They illustrate why upgrading is worthwhile for large atlases.

Dataset (README benchmark) Version 2.0.2 Current version
Small: 3.5k cells, 3 donors 0.20 s 0.06 s
Medium: 69k cells, 11 batches 4.92 s 0.24 s
Large: 858k cells, 120 batches 68.34 s 1.92 s
Large, by batch and sample (870 levels) 160.15 s 3.05 s

On a single thread (ncores=1) the large dataset takes 18.0 s, which the README gives as 3.8 times faster than 2.0.2. On Tahoe-100M (95.6 million cells, 1,344 samples, 50 PCs) the README reports 4.9 minutes on a 64-core server against 4.5 hours for 2.0.2, a peak memory of 214 GB instead of 294 GB (per the changelog), and notes that 2.0.2 ran three Harmony iterations to this version’s one. These are benchmark figures from the maintainers on their hardware; timings on your machine will differ.

Troubleshooting harmonypy

A ValueError about the shape of data_mat

In the source, run_harmony takes the number of cells N from the metadata, then checks the matrix: if its second dimension equals N it is treated as PCs by cells, and if its first dimension equals N it is transposed. If neither dimension matches, it raises a ValueError saying that one dimension of data_mat must match the number of cells. The usual cause is a metadata table that was filtered or subset differently from the embedding. Make sure both come from the same AnnData object, in the same cell order.

A KeyError or wrong column name

Batch labels are read from the metadata with meta_data[var], so each name in vars_use must be an exact column name. The docstring says metadata can be a pandas DataFrame, a dictionary of arrays, or any object that supports column access and .shape[0].

A DataFrame with text columns as the embedding

If the embedding is passed as a pandas DataFrame, the code keeps only the numeric columns before running, so an ID column in the file is dropped rather than treated as a PC. If a table has numeric ID columns, remove them yourself.

Too many or too few threads in a container or job scheduler

By default (ncores=0) harmonypy uses one thread per physical core available to the process. The README says that on Linux this respects CPU affinity, as set by Slurm or taskset, but not container CPU quotas, so set ncores explicitly in a container. Results are identical for any ncores, so this affects only speed.

The install tries to compile from source

The README notes pre-built wheels for Linux and macOS. If pip builds from source, it needs a C++17 compiler, the Python headers and, for the Armadillo headers, network access during the build.

Results differ between runs

The signature sets random_state=0 by default, so a fixed seed is used unless you change it. Record the seed you used, together with the harmonypy version, in your methods section.

Free alternatives to harmonypy

harmonypy is itself free software under GPL-3.0-or-later. The table lists related options named in the project documentation or on this site, with the limits of what the sources establish.

Option What it is Basis
harmony (R package) The R implementation of the same algorithm; harmonypy follows it step by step harmonypy README
ComBat A separate batch-correction method, discussed in our guide CASRAI guide

Harmony’s authors compare it with other integration methods in the 2019 paper; read that paper before choosing between methods for a specific dataset, because performance depends on the data, the number of batches and the biological question.

Frequently asked questions

What does harmonypy do?

It corrects batch effects in a cells-by-PCs embedding using the Harmony algorithm, returning a corrected embedding of the same shape in Z_corr.

How do I cite harmonypy?

The README asks you to cite the original Harmony paper: Korsunsky I, Millard N, Fan J et al., Fast, sensitive and accurate integration of single-cell data with Harmony, Nature Methods 16, 1289-1296 (2019), doi:10.1038/s41592-019-0619-0. For Harmony 2, it points to the 2026 bioRxiv preprint by Patikas et al. (doi:10.64898/2026.03.16.711825). The software also has a Zenodo DOI, 10.5281/zenodo.4531400.

Does harmonypy change my count matrix?

No. It returns a corrected embedding in Z_corr. Your counts and your original PCs are untouched unless you overwrite them.

Which Python versions does it support?

PyPI lists Python 3.9 or later, and the project classifiers cover 3.9 to 3.14.

Sources

Data: harmonypy run_harmony parameters: defaults and meaning (version 2.1.0)

Compiled from the harmonypy README parameter table and the run_harmony function signature and docstring in harmony.py (version 2.1.0). Lists each tuning parameter, its default value and what it controls.

Period covered: 2026.

harmonypy run_harmony parameters: defaults and meaning (version 2.1.0)
ParameterDefaultWhat it controls
theta2Diversity penalty per batch variable; one number for all batches, one per variable, or one per batch level
lambNone (estimated)Ridge regression penalty; None estimates it in each cluster from alpha
sigma0.1Kernel bandwidth for soft clustering
nclustmin(N/30, 100)Number of clusters, N = number of cells
tau0Protection against overcorrection
block_size0.05Proportion of cells updated in each block
max_iter_harmony10Maximum Harmony iterations
max_iter_kmeans4Maximum k-means iterations per Harmony iteration
epsilon_harmony0.01Harmony convergence threshold
epsilon_cluster0.001K-means convergence threshold
ncores0Threads; 0 uses one per physical core available to the process
random_state0Random seed for reproducibility

Sources

Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · full access

Ask about harmonypy: Run Harmony Batch Correction in Python

Full access: large monthly usage, up to 10 source passages behind each answer, and MCP and API access for Claude Code, Codex and other CLIs. Cancel any time.

An AI assistant for research: funder rules, compliance, methods and publishing. It links the sources behind its answers and labels answers that come from a web search.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays open to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →