Skip to content

About

Batch-effect correction for proteomics and other omics matrices with missing values: ComBat and limma within the HarmonizR missing-value pipeline, in pure Python, validated against R's sva, limma and HarmonizR.

Topics

Resources

Stars

3 stars

Watchers

0 watching

Forks

Repository files navigation

HarmonizePy

Pure-Python batch-effect harmonization toolkit validated against R sva::ComBat, limma::removeBatchEffect, and HarmonizR.

Python 3.12-3.14 v0.4.0 Alpha CI Coverage GPL-3.0

Changelog Citation Issues Docs

HarmonizePy is a pure-Python batch-effect correction package for omics data. The high-level harmonize() entry point handles structural missingness automatically: features are grouped by observed batch support, corrected with ComBat or limma within compatible subsets, and reassembled without imputation. No R installation is required at runtime.

Documentation

Capabilities

ComBat (Johnson et al. 2007). All four modes:

  • Mode 1: parametric, location + scale
  • Mode 2: parametric, location only
  • Mode 3: non-parametric, location + scale
  • Mode 4: non-parametric, location only

limma (Ritchie et al. 2015). Linear-model batch correction via sum-to-zero contrasts.

HarmonizR pipeline (follows v1.10.0; the differences are listed in R Compatibility):

  • Structural missingness handled automatically: features are grouped by observed batch support, corrected in compatible subsets, and reassembled into the original matrix shape.
  • Batch sorting: reorder batches so that similar ones become neighbours before blocking. Three strategies: "sparsity" (number of features present), "jaccard" (overlap of present features), "seriation" (first principal component of the presence vectors).
  • Batch blocking: group block=N neighbouring batches when forming sub-matrices. A feature needs enough values in every batch of a block for the block to count, so blocking trades observed values for fewer, larger groups. The engines still correct each batch.
  • Unique-combination removal (unique_removal=True, default): a feature whose batch-presence pattern no other feature shares would form a group of one and keep its raw values. Its affiliation is cropped to the longest affiliation of another feature within its own (spanning at least two batches), trading the values in the dropped blocks for a group correction.

Validation against R reference workflows: the package is tested against sva::ComBat, limma::removeBatchEffect, and HarmonizR v1.10.0 reference outputs. Known edge-case differences in retention policy are documented in the R Compatibility wiki page. Runtime benchmarks across seven datasets are in Benchmarks.

Performance

The same correction as HarmonizR 1.10.0, on the same matrices, in a fraction of the time:

Wall time of HarmonizePy and HarmonizR on five matrices for limma, ComBat mode 1 and ComBat mode 3: HarmonizePy takes 21 ms to 2.0 s, HarmonizR 1.0 s to 312 s, 3.9 to 338 times longer

Dataset Features x samples HarmonizePy HarmonizR Faster Largest difference
small 1,000 x 20 0.11 s 7.6 s 67x 6e-06
murine 4,753 x 25 0.47 s 1.8 s 3.9x 3e-04
medium 5,000 x 60 2.0 s 14 s 7.0x 0.42*
dia 8,470 x 36 0.49 s 4.8 s 9.9x 5e-15
scp_small 3,000 x 1,000 0.71 s 59 s 82x 7e-06

ComBat mode 1, the default, both on one core; the largest difference is the largest relative difference between the two outputs over the cells both have, and mode 1's solver stops at a 1e-4 convergence threshold. * On medium without blocking, the two unique-removal rules take features in a different order, so some features join different groups. Benchmark results has every scenario, the scaling sweeps, and the method.

It also needs less memory. Each tool runs in a fresh process that reads both files, corrects once and exits:

Peak memory of HarmonizePy and HarmonizR on five matrices for limma, ComBat mode 1 and ComBat mode 3: HarmonizePy 116 to 208 MB, HarmonizR 170 to 848 MB, 1.4 to 5.9 times more

HarmonizePy peaks at 116 to 208 MB; HarmonizR needs 1.4 to 2.6 times that with limma and 3.8 to 5.9 times with ComBat, most of it the sva package it loads.

Installation

# Package install (if published for this release)
pip install harmonizepy

# From GitHub
pip install git+https://github.com/LangeLab/HarmonizePy.git

# Development install with uv
uv python install 3.12.13
uv sync --dev --python 3.12.13

# Optional extras
pip install harmonizepy[config]      # YAML config files for --config
pip install harmonizepy[completion]  # Shell tab-completion via argcomplete
pip install harmonizepy[io]          # Parquet input and output

See Installation for the full dependency list and optional extras detail.

Quick start

harmonize() returns a pandas.DataFrame with the input's features and column order; a feature repeated with the same name and values appears once. Features are rows (DataFrame index), samples are columns.

import pandas as pd
from harmonizepy import harmonize

# From file paths (returns a DataFrame)
result = harmonize("data.tsv", "description.csv")
# result is a pd.DataFrame, features as index, samples as columns

# From DataFrames
data_df = pd.read_csv("data.tsv", sep="\t", index_col=0)
desc_df = pd.read_csv("description.csv")
result = harmonize(data_df, desc_df, algorithm="limma", sort="sparsity", block=2)

# What happened to each feature: corrected, or kept raw and why
result, report = harmonize(data_df, desc_df, return_report=True)
report["status"].value_counts()

# Low-level API (ndarray in, ndarray out)
from harmonizepy import combat, remove_batch_effect

corrected = combat(data_matrix, batch_labels, par_prior=True, mean_only=False)
corrected = remove_batch_effect(data_matrix, batch_labels)

The low-level engines handle missing observations per feature and preserve NaN positions in the returned array.

Input format

  • data: features x samples matrix of log-transformed values, usually log2; HarmonizePy does not transform them, and warns with InputScaleWarning when the values look untransformed. For TSV/CSV files, the first column must contain feature names (read as the DataFrame index). When passing a DataFrame directly, feature names must be in DataFrame.index and sample names in DataFrame.columns.
  • description: CSV/DataFrame with at least three columns: ID (sample names matching data columns), sample (not read), and batch (whole-number batch label). Without the names ID and batch, the first column holds the sample names and the third the batch labels.

Parameter reference

Parameter Type Default Description
algorithm "ComBat" or "limma" "ComBat" Batch correction algorithm
combat_mode 1, 2, 3, 4 1 ComBat variant (ignored for limma)
sort "sparsity", "jaccard", "seriation", or None None Batch sorting strategy before blocking
block int >= 2 or None None Group N consecutive batches into one sub-matrix block
unique_removal bool True Crop singletons to another feature's pattern
return_report bool False Also return the per-feature correction report

Full signature with all parameters is in the API Reference.

Choosing algorithm and strategy

Start with the default (ComBat, mode 1). The non-parametric modes (3 and 4) assume no distribution for the batch effects, at a cost that grows with the square of a group's size. Blocking (block=N) forms fewer, larger groups, at the cost of the values a feature has in only part of a block; sorting decides which batches share a block and has no effect without it. No measurement in this repository yet recommends one setting over another. See Algorithms and Pipeline for full guidance.

CLI usage

# Basic
harmonizepy data.tsv batch.csv -o corrected.tsv

# Algorithm, sort, and block
harmonizepy data.tsv batch.csv --algorithm limma -o corrected.tsv
harmonizepy data.tsv batch.csv --combat-mode 3 --sort sparsity --block 2 -o corrected.tsv

# Validate inputs without running correction
harmonizepy data.tsv batch.csv --dry-run

# Also write what happened to each feature
harmonizepy data.tsv batch.csv -o corrected.tsv --report report.tsv

# Config file (TOML or JSON; YAML needs the [config] extra)
harmonizepy data.tsv batch.csv --config run.toml

When -o is omitted, the output is written next to the input file as <data_stem>_corrected with the extension of --output-format (.tsv by default). See CLI Reference for all flags, output formats, and config file syntax.

Running tests

uv run pytest               # full test suite
uv run pytest tests/ -v     # verbose

The suite covers R concordance, edge cases, failure modes, numerical stability, CLI integration, and the benchmark harness. R fixture outputs are committed to the repository, so the full concordance suite runs on a plain checkout without a live R environment. Regenerating fixtures from source requires R with sva, limma, HarmonizR, and seriation managed via renv.

Project layout

src/harmonizepy/    # Package source: pipeline, engines, CLI, I/O
tests/              # Unit, integration, R concordance, and CLI tests
benchmarks/         # Benchmark CLI, dataset catalog, results

License

HarmonizePy is licensed under GPL-3.0.

References

Manuscripts

  • Johnson WE, Li C, Rabinovic A. "Adjusting batch effects in microarray expression data using empirical Bayes methods." Biostatistics 8(1):118-127, 2007.
  • Ritchie ME et al. "limma powers differential expression analyses for RNA-sequencing and microarray studies." Nucleic Acids Research 43(7):e47, 2015.
  • Voß H et al. "HarmonizR enables data harmonization across independent proteomic datasets with appropriate handling of missing values." Nature Communications 13:3523, 2022. https://doi.org/10.1038/s41467-022-31007-x
  • Schlumbohm S, Neumann JE, Neumann P. "HarmonizR: blocking and singular feature data adjustment improve runtime efficiency and data preservation." BMC Bioinformatics, 2025. https://doi.org/10.1186/s12859-025-06073-9

Code and packages

The ComBat algorithm was introduced by Johnson, Li & Rabinovic (2007). limma::removeBatchEffect is part of the limma package, described by Ritchie et al. (2015). The HarmonizR pipeline (structural-missingness handling, batch sorting, blocking, unique-combination removal) was developed by Voß et al. (2022) and Schlumbohm, Neumann & Neumann (2025). HarmonizePy is not a line-by-line port of the R sources: the engines are reimplemented in NumPy from the published methods and the behaviour of the R packages, and validated against R reference output.

About

Batch-effect correction for proteomics and other omics matrices with missing values: ComBat and limma within the HarmonizR missing-value pipeline, in pure Python, validated against R's sva, limma and HarmonizR.

Topics

Resources

Stars

3 stars

Watchers

0 watching

Forks

Releases

Packages

Contributors

Languages