Using harmony in Seurat



This tutorial describes how to use harmony in Seurat v5 single-cell analysis workflows. RunHarmony() is a generic function is designed to interact with Seurat objects. This vignette will walkthrough basic workflow of Harmony with Seurat objects. Also, it will provide some basic downstream analyses demonstrating the properties of harmonized cell embeddings and a brief explanation of the exposed algorithm parameters.

## Install latest branch of harmony
## devtools::install_github('immunogenomics/harmony', force = TRUE)

Generating the dataset

For this demo, we will be aligning two groups of PBMCs Kang et al., 2017. In this experiment, PBMCs are in stimulated and control conditions. The stimulated PBMC group was treated with interferon beta.

Download Data

The full dataset used for this vignette are located under the following zenodo directory

Generate SeuratObject

## Source required data
pbmc <- CreateSeuratObject(counts = cbind(pbmc.stim, pbmc.ctrl), project = "PBMC", min.cells = 5)

## Separate conditions$stim <- c(rep("STIM", ncol(pbmc.stim)), rep("CTRL", ncol(pbmc.ctrl)))

Running Harmony

Harmony works on an existing matrix with cell embeddings and outputs its transformed version with the datasets aligned according to some user-defined experimental conditions. By default, harmony will look up the pca cell embeddings and use these to run harmony. Therefore, it assumes that the Seurat object has these embeddings already precomputed.

Calculate PCA cell embeddings

Here, using Seurat::NormalizeData(), we will be generating a union of highly variable genes using each condition (the control and stimulated cells). These features are going to be subsequently used to generate the 20 PCs with Seurat::RunPCA().

pbmc <- pbmc %>%
    NormalizeData(verbose = FALSE)

VariableFeatures(pbmc) <- split(row.names(,$stim) %>% lapply(function(cells_use) {
    pbmc[,cells_use] %>%
        FindVariableFeatures(selection.method = "vst", nfeatures = 2000) %>% 
}) %>% unlist %>% unique

pbmc <- pbmc %>% 
    ScaleData(verbose = FALSE) %>% 
    RunPCA(features = VariableFeatures(pbmc), npcs = 20, verbose = FALSE)

Perform an integrated analysis

To run harmony on Seurat object after it has been normalized, only one argument needs to be specified which contains the batch covariate located in the metadata. For this vignette, further parameters are specified to align the dataset but the minimum parameters are shown in the snippet below:

## run harmony with default parameters
pbmc <- pbmc %>% RunHarmony("stim")
## is equivalent to:
pbmc <- RunHarmony(pbmc, "stim")

Here, we will be running harmony with some indicative parameters and plotting the convergence plot to illustrate some of the under the hood functionality.

pbmc <- pbmc %>% 
    RunHarmony("stim", plot_convergence = TRUE, nclust = 50, max_iter = 10, early_stop = T)
#> Transposing data matrix
#> Initializing state using k-means centroids initialization
#> Harmony 1/10
#> Harmony 2/10
#> Harmony 3/10
#> Harmony 4/10
#> Harmony 5/10
#> Harmony converged after 5 iterations
By setting `plot_converge=TRUE`, harmony will generate a plot with its objective showing the flow of the integration. Each point represents the cost measured after a clustering round. Different colors represent different Harmony iterations which is controlled by `max_iter` (assuming that early_stop=FALSE). Here `max_iter=10` and up to 10 correction steps are expected. However, `early_stop=TRUE` so harmony will stop after the cost plateaus.

By setting plot_converge=TRUE, harmony will generate a plot with its objective showing the flow of the integration. Each point represents the cost measured after a clustering round. Different colors represent different Harmony iterations which is controlled by max_iter (assuming that early_stop=FALSE). Here max_iter=10 and up to 10 correction steps are expected. However, early_stop=TRUE so harmony will stop after the cost plateaus.

Harmony API parameters on Seurat objects

RunHarmony has several parameters accessible to users which are outlined below.

object (required)

The Seurat object. This vignette assumes Seurat objects are version 5. (required)

A character vector that specifies all the experimental covariates to be corrected/harmonized by the algorithm.

When using RunHarmony() with Seurat, harmony will look up the metadata fields in the Seurat Object metadata.

For example, given the pbmc[["stim"]] exists as the stim condition, setting"stim" will perform integration of these samples accordingly. If you want to integrate on another variable, it needs to be present in Seurat object’s

To correct for several covariates, specify them in a vector: = c("stim", "new_covariate").


The cell embeddings to be used for the batch alignment. This parameter assumes that a reduced dimension already exists in the reduction slot of the Seurat object. By default, the pca reduction is used.


Optional parameter which can use a name vector to select specific dimensions to be harmonized.

Algorithm parameters

Harmony Algorithm Overview
Harmony Algorithm Overview


is a positive integer. Under the hood, harmony applies k-means soft-clustering. For this task, k needs to be determined. nclust corresponds to k. The harmonization results and performance are not particularly sensitive for a reasonable range of this parameter value. If this parameter is not set, harmony will autodetermine this based on the dataset size with a maximum cap of 200. For dataset with a vast amount of different cell types and batches this pamameter may need to be determined manually.


a positive scalar that controls the soft clustering probability assignment of single-cells to different clusters. Larger values will assign a larger probability to distant clusters of cells resulting in a different correction profile. Single-cells are assigned to clusters by their euclidean distance \(d\) to some cluster center \(Y\) after cosine normalization which is defined in the range [0,4]. The clustering probability of each cell is calculated as \(e^{-\frac{d}{\sigma}}\) where \(\sigma\) is controlled by the sigma parameter. Default value of sigma is 0.1 and it generally works well since it defines probability assignment of a cell in the range \([e^{-40}, e^0]\). Larger values of sigma restrict the dynamic range of probabilities that can be assigned to cells. For example, sigma=1 will yield a probabilities in the range of \([e^{-4}, e^0]\).


theta is a positive scalar vector that determines the coefficient of harmony’s diversity penalty for each corrected experimental covariate. In challenging experimental conditions, increasing theta may result in better integration results. Theta is an expontential parameter of the diversity penalty, thus setting theta=0 disables this penalty while increasing it to greater values than 1 will perform more aggressive corrections in an expontential manner. By default, it will set theta=2 for each experimental covariate.


The number of correction steps harmony will perform before completing the data set integration. In general, more iterations than necessary increases computational runtime especially which becomes evident in bigger datasets. Setting early_stop=TRUE may reduce the actual number of correction steps which will be smaller than max_iter.


Under the hood, harmony minimizes its objective function through a series of clustering and integration tests. By setting early_stop=TRUE, when the objective function is less than 1e-4 after a correction step harmony exits before reaching the max_iter correction steps. This parameter can drastically reduce run-time in bigger datasets.


A set of internal algorithm parameters that can be overriden. For advanced users only.

Seurat specific parameters

These parameters are Seurat-specific and do not affect the flow of the algorithm.


Toggle-like parameter, by default project_dim=TRUE. When enabled, RunHarmony() calculates genomic feature loadings using Seurat’s ProjectDim() that correspond to the harmonized cell embeddings.

The new Reduced Dimension slot identifier. By default, This option allows several independent runs of harmony to be retained in the appropriate slots in the SeuratObjects. It is useful if you want to try Harmony with multiple parameters and save them as e.g. ‘harmony_theta0’, ‘harmony_theta1’, ‘harmony_theta2’.

Miscellaneous parameters

These parameters help users troubleshoot harmony.


Option that plots the convergence plot after the execution of the algorithm. By default FALSE. Setting it to TRUE will collect harmony’s objective value and plot it allowing the user to troubleshoot the flow of the algorithm and fine-tune the parameters of the dataset integration procedure.

Accessing the data

RunHarmony() returns the Seurat object which contains the harmonized cell embeddings in a slot named harmony. This entry can be accessed via pbmc@reductions$harmony. To access the values of the cell embeddings we can also use:

harmony.embeddings <- Embeddings(pbmc, reduction = "harmony")

Inspection of the modalities

After Harmony integration, we should inspect the quality of the harmonization and contrast it with the unharmonized algorithm input. Ideally, cells from different conditions will align along the Harmonized PCs. If they are not, you could increase the theta value above to force a more aggressive fit of the dataset and rerun the workflow.

p1 <- DimPlot(object = pbmc, reduction = "harmony", pt.size = .1, = "stim")
p2 <- VlnPlot(object = pbmc, features = "harmony_1", = "stim",  pt.size = .1)
Evaluate harmonization of stim parameter in the harmony generated cell embeddings

Evaluate harmonization of stim parameter in the harmony generated cell embeddings

Plot Genes correlated with the Harmonized PCs

DimHeatmap(object = pbmc, reduction = "harmony", cells = 500, dims = 1:3)

Using harmony embeddings for dimensionality reduction in Seurat

The harmonized cell embeddings generated by harmony can be used for further integrated analyses. In this workflow, the Seurat object contains the harmony reduction modality name in the method that requires it.

Perform clustering using the harmonized vectors of cells

pbmc <- pbmc %>%
    FindNeighbors(reduction = "harmony") %>%
    FindClusters(resolution = 0.5) 
#> Computing nearest neighbor graph
#> Computing SNN
#> Modularity Optimizer version 1.3.0 by Ludo Waltman and Nees Jan van Eck
#> Number of nodes: 2000
#> Number of edges: 71966
#> Running Louvain algorithm...
#> Maximum modularity in 10 random starts: 0.8720
#> Number of communities: 9
#> Elapsed time: 0 seconds

TSNE dimensionality reduction

pbmc <- pbmc %>%
    RunTSNE(reduction = "harmony")

p1 <- DimPlot(pbmc, reduction = "tsne", = "stim", pt.size = .1)
p2 <- DimPlot(pbmc, reduction = "tsne", label = TRUE, pt.size = .1)
plot_grid(p1, p2)
t-SNE Visualization of harmony embeddings

t-SNE Visualization of harmony embeddings

One important observation is to assess that the harmonized data contain biological states of the cells. Therefore by checking the following genes we can see that biological cell states are preserved after harmonization.

FeaturePlot(object = pbmc, features= c("CD3D", "SELL", "CREM", "CD8A", "GNLY", "CD79A", "FCGR3A", "CCL2", "PPBP"), 
            min.cutoff = "q9", cols = c("lightgrey", "blue"), pt.size = 0.5)
Expression of gene panel heatmap in the harmonized PBMC dataset

Expression of gene panel heatmap in the harmonized PBMC dataset


Very similarly with TSNE we can run UMAP by passing the harmony reduction in the function.

pbmc <- pbmc %>%
    RunUMAP(reduction = "harmony",  dims = 1:20)
#> Warning: The default method for RunUMAP has changed from calling Python UMAP via reticulate to the R-native UWOT using the cosine metric
#> To use Python UMAP via reticulate, set umap.method to 'umap-learn' and metric to 'correlation'
#> This message will be shown once per session
#> 18:28:57 UMAP embedding parameters a = 0.9922 b = 1.112
#> Found more than one class "dist" in cache; using the first, from namespace 'spam'
#> Also defined by 'BiocGenerics'
#> 18:28:57 Read 2000 rows and found 20 numeric columns
#> 18:28:57 Using Annoy for neighbor search, n_neighbors = 30
#> Found more than one class "dist" in cache; using the first, from namespace 'spam'
#> Also defined by 'BiocGenerics'
#> 18:28:57 Building Annoy index with metric = cosine, n_trees = 50
#> 0%   10   20   30   40   50   60   70   80   90   100%
#> [----|----|----|----|----|----|----|----|----|----|
#> **************************************************|
#> 18:28:57 Writing NN index file to temp file /tmp/Rtmpk7NMkD/file488821cf6f76d
#> 18:28:57 Searching Annoy index using 1 thread, search_k = 3000
#> 18:28:58 Annoy recall = 100%
#> 18:28:58 Commencing smooth kNN distance calibration using 1 thread with target n_neighbors = 30
#> 18:28:59 Initializing from normalized Laplacian + noise (using RSpectra)
#> 18:28:59 Commencing optimization for 500 epochs, with 83188 positive edges
#> 18:29:02 Optimization finished

p1 <- DimPlot(pbmc, reduction = "umap", = "stim", pt.size = .1)
p2 <- DimPlot(pbmc, reduction = "umap", label = TRUE,  pt.size = .1)
plot_grid(p1, p2)
UMAP Visualization of harmony embeddings

UMAP Visualization of harmony embeddings

#> R version 4.3.2 (2023-10-31)
#> Platform: x86_64-pc-linux-gnu (64-bit)
#> Running under: Arch Linux
#> Matrix products: default
#> BLAS:   /usr/lib/ 
#> LAPACK: /usr/lib/
#> locale:
#>  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
#>  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=C              
#>  [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8   
#>  [7] LC_PAPER=en_US.UTF-8       LC_NAME=C                 
#>  [9] LC_ADDRESS=C               LC_TELEPHONE=C            
#> time zone: America/New_York
#> tzcode source: system (glibc)
#> attached base packages:
#> [1] stats     graphics  grDevices utils     datasets  methods   base     
#> other attached packages:
#> [1] cowplot_1.1.1           dplyr_1.1.3             Seurat_4.9.9.9067      
#> [4] SeuratObject_4.9.9.9091 sp_1.6-0                harmony_1.2.0          
#> [7] Rcpp_1.0.11            
#> loaded via a namespace (and not attached):
#>   [1] RColorBrewer_1.1-3      jsonlite_1.8.4          magrittr_2.0.3         
#>   [4] spatstat.utils_3.0-3    farver_2.1.1            rmarkdown_2.21         
#>   [7] zlibbioc_1.46.0         vctrs_0.6.3             ROCR_1.0-11            
#>  [10] spatstat.explore_3.1-0  RCurl_1.98-1.12         htmltools_0.5.5        
#>  [13] sass_0.4.5              sctransform_0.4.0       parallelly_1.35.0      
#>  [16] KernSmooth_2.23-22      bslib_0.4.2             htmlwidgets_1.6.2      
#>  [19] ica_1.0-3               plyr_1.8.8              plotly_4.10.1          
#>  [22] zoo_1.8-12              cachem_1.0.7            igraph_1.4.2           
#>  [25] mime_0.12               lifecycle_1.0.3         pkgconfig_2.0.3        
#>  [28] Matrix_1.6-1.1          R6_2.5.1                fastmap_1.1.1          
#>  [31] GenomeInfoDbData_1.2.10 fitdistrplus_1.1-11     future_1.32.0          
#>  [34] shiny_1.7.4             digest_0.6.31           colorspace_2.1-0       
#>  [37] patchwork_1.1.2         S4Vectors_0.38.1        tensor_1.5             
#>  [40] RSpectra_0.16-1         irlba_2.3.5.1           GenomicRanges_1.52.0   
#>  [43] labeling_0.4.3          progressr_0.13.0        fansi_1.0.5            
#>  [46] spatstat.sparse_3.0-1   httr_1.4.5              polyclip_1.10-4        
#>  [49] abind_1.4-5             compiler_4.3.2          withr_2.5.1            
#>  [52] fastDummies_1.7.3       highr_0.10              MASS_7.3-60            
#>  [55] tools_4.3.2             lmtest_0.9-40           httpuv_1.6.9           
#>  [58] future.apply_1.10.0     goftest_1.2-3           glue_1.6.2             
#>  [61] nlme_3.1-163            promises_1.2.0.1        grid_4.3.2             
#>  [64] Rtsne_0.16              cluster_2.1.4           reshape2_1.4.4         
#>  [67] generics_0.1.3          gtable_0.3.4            spatstat.data_3.0-1    
#>  [70] tidyr_1.3.0             data.table_1.14.8       utf8_1.2.3             
#>  [73] XVector_0.40.0          BiocGenerics_0.46.0     BPCells_0.1.0          
#>  [76] spatstat.geom_3.2-1     RcppAnnoy_0.0.20        ggrepel_0.9.3          
#>  [79] RANN_2.6.1              pillar_1.9.0            stringr_1.5.0          
#>  [82] spam_2.9-1              RcppHNSW_0.5.0          later_1.3.0            
#>  [85] splines_4.3.2           lattice_0.21-9          survival_3.5-7         
#>  [88] deldir_1.0-6            tidyselect_1.2.0        miniUI_0.1.1.1         
#>  [91] pbapply_1.7-0           knitr_1.42              gridExtra_2.3          
#>  [94] IRanges_2.34.0          scattermore_1.2         RhpcBLASctl_0.23-42    
#>  [97] stats4_4.3.2            xfun_0.39               matrixStats_1.0.0      
#> [100] stringi_1.7.12          lazyeval_0.2.2          yaml_2.3.7             
#> [103] evaluate_0.20           codetools_0.2-19        tibble_3.2.1           
#> [106] cli_3.6.1               uwot_0.1.14             xtable_1.8-4           
#> [109] reticulate_1.28         munsell_0.5.0           jquerylib_0.1.4        
#> [112] GenomeInfoDb_1.36.0     globals_0.16.2          spatstat.random_3.1-4  
#> [115] png_0.1-8               parallel_4.3.2          ellipsis_0.3.2         
#> [118] ggplot2_3.4.3           dotCall64_1.0-2         bitops_1.0-7           
#> [121] listenv_0.9.0           viridisLite_0.4.2       scales_1.2.1           
#> [124] ggridges_0.5.4          leiden_0.4.3            purrr_1.0.2            
#> [127] rlang_1.1.1