[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M73GTXDQDD9PD07VXD9KCBD9":3,"skill-same:01M73GTXDQDD9PD07VXD9KCBD9":48},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":24,"commitSha":25,"skillDirectory":26,"forksCount":27,"repositoryHtmlUrl":28,"repositoryHomepageUrl":29,"ownerHtmlUrl":30,"ownerBlogUrl":31,"ownerDescription":32,"updatedAt":33,"install":34,"resources":47},"01M73GTXDQDD9PD07VXD9KCBD9","harmony-batch-correction",null,"Harmony batch correction for scRNA-seq and other omics. Removes batch effects from PCA embeddings while preserving biology. Run after PCA, before UMAP. Scales to millions of cells. Python (harmonypy, scanpy) and R (Seurat).","bg-szy\u002FTOP-SKILLS","bg-szy","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F106576190?v=4","01M73A4E8KPV67SFXRY8XZGNBX","ShuZhiyong","01M73A4E96MQ294MHM74TZBVQD",6,"MIT","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fawesome-skills\u002Fharmony-batch-correction\u002FSKILL.md",[],[],"2026-11-11 15:11:14",false,"---\nname: \"harmony-batch-correction\"\ndescription: \"Harmony batch correction for scRNA-seq and other omics. Removes batch effects from PCA embeddings while preserving biology. Run after PCA, before UMAP. Scales to millions of cells. Python (harmonypy, scanpy) and R (Seurat).\"\nlicense: \"MIT\"\n---\n\n# Harmony Batch Correction\n\n## Overview\n\nHarmony is a fast, scalable algorithm for batch integration in single-cell data. It takes a PCA embedding (cells × PCs) as input and returns a corrected embedding from which batch effects have been regressed out via iterative soft-clustering and per-cluster linear regression. The corrected embedding is then used to compute neighbors, UMAP, and downstream clustering — the raw count matrix is never modified. Harmony works for single-cell RNA-seq, ATAC-seq, and other omics modalities where a PCA-like embedding is available.\n\n## When to Use\n\n- Integrating scRNA-seq datasets from different samples, donors, sequencing runs, or experimental batches that should contain the same cell types\n- Removing technical variation (library preparation protocol, 10x chemistry version, sequencing depth, sequencing platform) while preserving biological differences between cell types and conditions\n- Performing fast, scalable batch correction on datasets with millions of cells where deep generative model training would be prohibitively slow\n- Correcting for multiple confounding variables simultaneously (batch, donor, sequencing platform, tissue processing protocol)\n- Preparing a corrected embedding for UMAP visualization, Leiden clustering, or label transfer without modifying the gene expression count matrix\n- Use **omics-plotting** SKILL for generic result-table figures; batch-evaluation UMAPs use scanpy `sc.pl.*`\n- Use **scVI\u002Fscvi-tools** instead when you need probabilistic batch correction with a variational autoencoder (deep learning), differential expression with uncertainty estimates, or multi-modal integration (RNA + protein)\n- Use **BBKNN** instead when you want graph-based integration that avoids constructing a corrected embedding altogether and directly builds a cross-batch nearest-neighbor graph\n- Use **Seurat Integration \u002F CCA** (R) instead when you are already in a Seurat workflow and prefer anchor-based integration methods\n\n## Prerequisites\n\n- **Python packages**: `harmonypy`, `scanpy>=1.10`, `leidenalg`, `igraph`, `anndata`, `pandas`, `matplotlib`\n- **R packages** (optional): `harmony`, `Seurat>=4.0` (for R workflow in Step 7)\n- **Data requirements**: AnnData object with raw counts, batch\u002Fsample metadata in `adata.obs`, and PCA embedding already computed (`adata.obsm[\"X_pca\"]`)\n- **Environment**: Python 3.9+; 8 GB RAM sufficient for up to ~500k cells; linear memory scaling\n\n```bash\npip install harmonypy \"scanpy[leiden]\" anndata pandas matplotlib\n```\n\n```r\n# R installation (for Step 7 \u002F Seurat integration)\ninstall.packages(\"harmony\")\n# If using Seurat:\ninstall.packages(\"Seurat\")\n```\n\n## Pre-flight Interview\n\nSettle these with the user before writing any analysis code.\n\n```yaml\ndecisions:\n  - id: D1\n    param: batchKey\n    kind: required\n    source: data\n    ask: \"Which variable separates samples that were processed apart - donor, run, chemistry, or a combination?\"\n    default: null\n\n  - id: D2\n    param: inputEmbedding\n    kind: derived\n    source: upstream\n    ask: \"Which reduced space should be corrected?\"\n    default: \"the PCA embedding computed upstream\"\n\n  - id: D3\n    param: diversityPenalty\n    kind: required\n    source: user\n    depends_on: [D1]\n    ask: \"How hard should batches be pushed together? Too hard erases real differences between samples.\"\n    default: \"2.0; raise toward 4-6 when batch sizes are very uneven\"\n\n  - id: D4\n    param: numClusters\n    kind: optional_conditional\n    source: data\n    ask: \"Does the dataset contain rare populations that need more soft clusters to survive correction?\"\n    default: \"automatic, min(100, cells\u002F30)\"\n\n  - id: D5\n    param: maxIterations\n    kind: optional_conditional\n    source: data\n    ask: \"Did the correction converge, or does it need more iterations?\"\n    default: 10\n\n  - id: D6\n    param: smallClusterProtection\n    kind: optional_conditional\n    source: user\n    ask: \"Are small populations being over-split during correction?\"\n    default: \"off\"\n\n  - id: D7\n    param: kernelBandwidth\n    kind: optional\n    source: user\n    ask: \"Should Harmony use its standard soft-clustering bandwidth, or be tuned for unusually heterogeneous batches?\"\n    default: 0.1\n```\n\nD3 is where batch correction goes wrong in the direction nobody checks.\nUnder-correction is visible - batches stay separated in the embedding.\nOver-correction is not: samples mix beautifully because a real treatment effect\nwas removed along with the batch effect. Ask what the batch variable is\nconfounded with before raising it.\n\n## Quick Start\n\nMinimal pipeline — load preprocessed data, run Harmony via scanpy, produce UMAP:\n\n```python\nimport scanpy as sc\n\n# Load preprocessed AnnData (counts normalized, HVGs selected, PCA run)\nadata = sc.read_h5ad(\"preprocessed.h5ad\")   # must have adata.obs[\"batch\"]\n\n# Run Harmony batch correction (corrects adata.obsm[\"X_pca\"] → \"X_pca_harmony\")\nsc.external.pp.harmony_integrate(adata, key=\"batch\")\n\n# Build neighborhood graph on corrected embedding, then UMAP\nsc.pp.neighbors(adata, use_rep=\"X_pca_harmony\")\nsc.tl.umap(adata)\nsc.tl.leiden(adata, resolution=0.5)\n\n# Visualize\nsc.pl.umap(adata, color=[\"batch\", \"leiden\"], ncols=2)\nprint(f\"Clusters: {adata.obs['leiden'].nunique()} | Cells: {adata.n_obs}\")\n```\n\n## Workflow\n\n### Step 1: Quality Control and Preprocessing\n\nFilter, normalize, select highly variable genes (HVGs), and run PCA. Harmony is applied to the PCA embedding produced here.\n\n```python\nimport scanpy as sc\nimport numpy as np\n\nsc.settings.set_figure_params(dpi=80, facecolor=\"white\")\n\n# Load multi-batch data — adata.obs must contain a batch column\nadata = sc.read_h5ad(\"multi_batch_counts.h5ad\")\n# Alternatively, concatenate multiple AnnData objects:\n# adata = sc.concat([adata1, adata2, adata3], label=\"batch\",\n#                   keys=[\"batch1\", \"batch2\", \"batch3\"])\n\nprint(f\"Loaded: {adata.n_obs} cells × {adata.n_vars} genes\")\nprint(f\"Batches: {adata.obs['batch'].value_counts().to_dict()}\")\n\n# QC: annotate mitochondrial genes and filter low-quality cells\nadata.var[\"mt\"] = adata.var_names.str.startswith(\"MT-\")\nsc.pp.calculate_qc_metrics(adata, qc_vars=[\"mt\"], inplace=True)\nsc.pp.filter_cells(adata, min_genes=200)\nsc.pp.filter_cells(adata, max_genes=6000)\nsc.pp.filter_genes(adata, min_cells=3)\nadata = adata[adata.obs[\"pct_counts_mt\"] \u003C 20].copy()\nprint(f\"After QC: {adata.n_obs} cells × {adata.n_vars} genes\")\n\n# Normalize and log-transform (store raw counts first)\nadata.layers[\"counts\"] = adata.X.copy()\nsc.pp.normalize_total(adata, target_sum=1e4)\nsc.pp.log1p(adata)\n\n# Select HVGs and compute PCA\nsc.pp.highly_variable_genes(adata, n_top_genes=3000, batch_key=\"batch\")\nsc.pp.pca(adata, n_comps=50, use_highly_variable=True)\nprint(f\"PCA shape: {adata.obsm['X_pca'].shape}\")  # (n_cells, 50)\n```\n\n### Step 2: Run Harmony via Scanpy Integration\n\nThe scanpy wrapper calls `harmonypy` under the hood and stores the corrected embedding in `adata.obsm[\"X_pca_harmony\"]`.\n\n```python\nimport scanpy as sc\n\n# Run Harmony — corrects adata.obsm[\"X_pca\"] in-place and stores result as \"X_pca_harmony\"\nsc.external.pp.harmony_integrate(\n    adata,\n    key=\"batch\",           # obs column with batch labels\n    basis=\"X_pca\",         # source embedding (default)\n    adjusted_basis=\"X_pca_harmony\",  # destination key (default)\n    max_iter_harmony=20,   # maximum Harmony iterations (default 10; increase for complex batches)\n    theta=2.0,             # diversity penalty per batch variable (default 2)\n    sigma=0.1,             # width of soft-clustering Gaussian kernel\n    random_state=42,\n)\n\nprint(f\"Corrected embedding: {adata.obsm['X_pca_harmony'].shape}\")\n# Expected: (n_cells, 50) — same shape as X_pca\n```\n\n### Step 3: Run Harmony via harmonypy Directly\n\nUse the lower-level `harmonypy` API when you need finer control, access to the HarmonyObject, or integration outside of scanpy.\n\n```python\nimport harmonypy\nimport pandas as pd\nimport numpy as np\n\n# Extract PCA embedding and metadata\npca_embeddings = adata.obsm[\"X_pca\"]                  # numpy array (n_cells, n_PCs)\nmeta_data = adata.obs[[\"batch\", \"donor\"]].copy()       # DataFrame with batch variables\n\n# Run Harmony\nho = harmonypy.run_harmony(\n    pca_embeddings,\n    meta_data,\n    vars_use=[\"batch\"],        # list of columns to correct for\n    theta=2.0,                 # diversity penalty strength (per variable)\n    sigma=0.1,                 # soft-clustering bandwidth\n    nclust=None,               # number of clusters; None → auto (min(100, n_cells\u002F30))\n    tau=0,                     # protection against over-clustering small clusters\n    block_size=0.05,           # fraction of cells per mini-batch\n    max_iter_harmony=20,\n    max_iter_kmeans=20,\n    epsilon_cluster=1e-5,\n    epsilon_harmony=1e-4,\n    random_state=42,\n    verbose=True,\n)\n\ncorrected = ho.Z_corr.T   # (n_cells, n_PCs) corrected embedding\nadata.obsm[\"X_pca_harmony\"] = corrected\nprint(f\"Harmony converged. Corrected embedding shape: {corrected.shape}\")\n```\n\n### Step 4: Compute Neighbors and UMAP on Harmony Embedding\n\nAlways use `use_rep=\"X_pca_harmony\"` so that downstream graph construction is based on the corrected embedding, not the original PCA.\n\n```python\nimport scanpy as sc\n\n# Build k-nearest neighbor graph using corrected embedding\nsc.pp.neighbors(\n    adata,\n    n_neighbors=15,          # number of neighbors (15-30 typical for scRNA-seq)\n    n_pcs=None,              # use all PCs in the embedding\n    use_rep=\"X_pca_harmony\", # IMPORTANT: use corrected embedding\n    random_state=42,\n)\n\n# Compute UMAP for visualization\nsc.tl.umap(adata, min_dist=0.3, spread=1.0, random_state=42)\n\nprint(f\"UMAP computed: {adata.obsm['X_umap'].shape}\")  # (n_cells, 2)\n```\n\n### Step 5: Leiden Clustering on Harmony-Corrected Graph\n\nClustering is performed on the neighbor graph built from the Harmony-corrected embedding in Step 4.\n\n```python\nimport scanpy as sc\n\n# Run Leiden community detection at multiple resolutions\nfor resolution in [0.3, 0.5, 0.8]:\n    sc.tl.leiden(adata, resolution=resolution, key_added=f\"leiden_{resolution}\")\n\n# Select final resolution\nadata.obs[\"leiden\"] = adata.obs[\"leiden_0.5\"]\n\nprint(f\"Clusters at resolution 0.5: {adata.obs['leiden'].nunique()}\")\nprint(adata.obs[\"leiden\"].value_counts().head())\n\n# Find marker genes per cluster\nsc.tl.rank_genes_groups(adata, groupby=\"leiden\", method=\"wilcoxon\", n_genes=50)\nsc.pl.rank_genes_groups_dotplot(adata, n_genes=5, groupby=\"leiden\")\n```\n\n### Step 6: Evaluate Batch Correction\n\nPlot UMAP colored by batch and by cell type \u002F cluster to visually confirm batch effects are removed while biological structure is preserved.\n\n```python\nimport scanpy as sc\nimport matplotlib.pyplot as plt\n\nfig, axes = plt.subplots(1, 3, figsize=(18, 5))\n\n# Before correction: color by batch using uncorrected PCA-based UMAP\nsc.pp.neighbors(adata, use_rep=\"X_pca\", key_added=\"uncorrected_neighbors\", random_state=42)\nsc.tl.umap(adata, neighbors_key=\"uncorrected_neighbors\", random_state=42)\nadata.obsm[\"X_umap_uncorrected\"] = adata.obsm[\"X_umap\"].copy()\n\n# Restore Harmony UMAP\nsc.pp.neighbors(adata, use_rep=\"X_pca_harmony\", random_state=42)\nsc.tl.umap(adata, random_state=42)\n\n# Panel 1: Corrected UMAP colored by batch\nsc.pl.umap(adata, color=\"batch\", title=\"Harmony: colored by batch\",\n           ax=axes[0], show=False)\n\n# Panel 2: Corrected UMAP colored by leiden cluster\nsc.pl.umap(adata, color=\"leiden\", title=\"Harmony: Leiden clusters\",\n           ax=axes[1], show=False)\n\n# Panel 3: Uncorrected UMAP colored by batch (for comparison)\nsc.pl.embedding(adata, basis=\"X_umap_uncorrected\", color=\"batch\",\n                title=\"Uncorrected PCA: batch separation\",\n                ax=axes[2], show=False)\n\nplt.tight_layout()\nplt.savefig(\"harmony_batch_evaluation.png\", dpi=150, bbox_inches=\"tight\")\nplt.show()\nprint(\"Batch evaluation figure saved to harmony_batch_evaluation.png\")\n```\n\n### Step 7: R Integration with Seurat\n\nFor users working in R, Harmony integrates directly with Seurat via `RunHarmony()`.\n\n```r\nlibrary(Seurat)\nlibrary(harmony)\n\n# Load Seurat object with batch metadata in metadata column \"batch\"\nseurat_obj \u003C- readRDS(\"multi_batch_seurat.rds\")\n\n# Ensure PCA is computed\nseurat_obj \u003C- NormalizeData(seurat_obj)\nseurat_obj \u003C- FindVariableFeatures(seurat_obj, nfeatures = 3000)\nseurat_obj \u003C- ScaleData(seurat_obj)\nseurat_obj \u003C- RunPCA(seurat_obj, npcs = 50)\n\n# Run Harmony — corrects the \"pca\" reduction and adds \"harmony\" reduction\nseurat_obj \u003C- RunHarmony(\n  seurat_obj,\n  group.by.vars = \"batch\",   # metadata column(s) to correct for\n  dims.use = 1:30,           # number of PCs to use\n  theta = 2,                 # diversity penalty\n  sigma = 0.1,               # soft-clustering bandwidth\n  max.iter.harmony = 20,\n  plot_convergence = TRUE,   # plot objective function convergence\n  verbose = TRUE\n)\n\n# Build neighbor graph and UMAP using Harmony embedding\nseurat_obj \u003C- FindNeighbors(seurat_obj, reduction = \"harmony\", dims = 1:30)\nseurat_obj \u003C- FindClusters(seurat_obj, resolution = 0.5)\nseurat_obj \u003C- RunUMAP(seurat_obj, reduction = \"harmony\", dims = 1:30)\n\n# Visualize\nDimPlot(seurat_obj, reduction = \"umap\", group.by = \"batch\")\nDimPlot(seurat_obj, reduction = \"umap\", group.by = \"seurat_clusters\")\n\ncat(sprintf(\"Clusters: %d | Cells: %d\\n\",\n            length(unique(seurat_obj$seurat_clusters)),\n            ncol(seurat_obj)))\n```\n\n## Key Parameters\n\n| Parameter | Default | Range \u002F Options | Effect |\n|-----------|---------|-----------------|--------|\n| `theta` | `2.0` | `0`–`10` | Diversity penalty per batch variable. Higher values force more mixing; set to 0 to disable penalty. Increase to `4`–`6` for very uneven batch sizes. |\n| `sigma` | `0.1` | `0.01`–`0.5` | Bandwidth of the soft-clustering Gaussian kernel. Smaller values → sharper cluster assignments; larger values → smoother. Rarely needs changing. |\n| `nclust` | `None` (auto) | `5`–`200` | Number of soft clusters used for correction. Auto-set to `min(100, n_cells\u002F30)`. Increase for datasets with many rare cell types. |\n| `max_iter_harmony` | `10` | `5`–`50` | Maximum Harmony iterations. Increase to `20`–`30` for datasets with strong or complex batch effects where convergence is slow. |\n| `tau` | `0` | `0`–`10` | Overclustering protection. Positive values penalize very small clusters; use `tau=5` when tiny populations are over-splitting. |\n| `n_neighbors` (scanpy) | `15` | `5`–`50` | Number of nearest neighbors for the post-Harmony graph. Increase for larger datasets (>100k cells) to stabilize clusters. |\n| `block_size` | `0.05` | `0.01`–`0.1` | Fraction of cells per mini-batch for the K-means step. Smaller values are faster but less stable; default is usually appropriate. |\n\n## Key Concepts\n\n### How Harmony Works\n\nHarmony correction proceeds in three repeated phases until convergence:\n\n1. **Soft K-means assignment**: Each cell is softly assigned to `K` clusters based on Euclidean distance in PC space, weighted by the batch-diversity penalty `theta`.\n2. **Per-cluster linear regression**: Within each cluster, a linear correction is estimated for each batch variable and applied to the cluster's cells.\n3. **Convergence check**: The objective function (mixture model likelihood + diversity penalty) is evaluated; iterations stop when improvement \u003C `epsilon_harmony`.\n\nThe corrected embedding lives in the same PC space as the input PCA but with batch-specific directions subtracted. The raw count matrix (`adata.X`) and all gene-level information are untouched.\n\n### PCA Before Harmony\n\nHarmony assumes the input PCA was computed with `batch_key` awareness. In scanpy, always pass `batch_key=\"batch\"` to `sc.pp.highly_variable_genes()` before PCA so that HVGs are selected independently per batch and then intersected, preventing batch-specific HVGs from dominating the embedding.\n\n### Embedding Not Counts\n\nHarmony corrects the embedding, not the count matrix. Differential expression analysis should still use the raw or normalized counts (stored in `adata.layers[\"counts\"]` or `adata.raw`), not the corrected PCs.\n\n## Common Recipes\n\n### Recipe: Multi-Variable Correction (Batch + Donor + Platform)\n\nCorrect for multiple confounding variables simultaneously by passing a list to `vars_use`. Each variable gets its own diversity penalty `theta`.\n\n```python\nimport harmonypy\nimport pandas as pd\n\n# Prepare metadata with multiple batch variables\nmeta_data = adata.obs[[\"batch\", \"donor\", \"platform\"]].copy()\n\n# Run Harmony correcting for all three variables\nho = harmonypy.run_harmony(\n    adata.obsm[\"X_pca\"],\n    meta_data,\n    vars_use=[\"batch\", \"donor\", \"platform\"],  # correct for all three\n    theta=[2.0, 1.0, 2.0],  # per-variable diversity penalty\n    # theta can also be a scalar (same for all variables)\n    max_iter_harmony=30,\n    random_state=42,\n    verbose=True,\n)\n\nadata.obsm[\"X_pca_harmony\"] = ho.Z_corr.T\nprint(f\"Multi-variable correction complete. Shape: {adata.obsm['X_pca_harmony'].shape}\")\n\n# Verify batch mixing improved for all variables\nimport scanpy as sc\nsc.pp.neighbors(adata, use_rep=\"X_pca_harmony\")\nsc.tl.umap(adata, random_state=42)\nsc.pl.umap(adata, color=[\"batch\", \"donor\", \"platform\"], ncols=3)\n```\n\n### Recipe: Diagnose Over-Correction with Marker Genes\n\nIf Harmony over-corrects (merges biologically distinct populations), canonical marker genes will lose cell-type specificity on the UMAP. Check this before downstream analysis.\n\n```python\nimport scanpy as sc\nimport matplotlib.pyplot as plt\n\n# Define known canonical marker genes for your tissue\nmarker_genes = {\n    \"T cells\": [\"CD3D\", \"CD3E\", \"TRAC\"],\n    \"B cells\": [\"MS4A1\", \"CD79A\", \"CD19\"],\n    \"NK cells\": [\"GNLY\", \"NKG7\", \"KLRD1\"],\n    \"Monocytes\": [\"LYZ\", \"CD14\", \"CST3\"],\n    \"Dendritic cells\": [\"FCER1A\", \"CLEC10A\"],\n}\n\n# Plot canonical markers on the Harmony-corrected UMAP\nall_markers = [g for genes in marker_genes.values() for g in genes\n               if g in adata.var_names]\n\nsc.pl.umap(\n    adata,\n    color=all_markers[:6],    # plot first 6 markers\n    ncols=3,\n    vmax=\"p99\",               # clip color scale at 99th percentile\n    frameon=False,\n    save=\"_marker_genes.png\",\n)\n\n# If markers look diffuse or don't separate cell types cleanly,\n# reduce theta (e.g., from 2.0 to 1.0) or reduce max_iter_harmony\nprint(\"If marker gene expression is diffuse across clusters, reduce theta.\")\nprint(\"If batch effects remain visible, increase theta or max_iter_harmony.\")\n```\n\n### Recipe: Save and Reload Harmony-Corrected AnnData\n\nSave the corrected object with all embeddings for downstream analysis without re-running Harmony.\n\n```python\nimport scanpy as sc\n\n# Save with all embeddings\nadata.write_h5ad(\"harmony_corrected.h5ad\", compression=\"gzip\")\nprint(f\"Saved to harmony_corrected.h5ad ({adata.n_obs} cells)\")\n\n# Reload and verify\nadata_loaded = sc.read_h5ad(\"harmony_corrected.h5ad\")\nprint(f\"Loaded. Keys in obsm: {list(adata_loaded.obsm.keys())}\")\n# Expected: ['X_pca', 'X_pca_harmony', 'X_umap']\n```\n\n## Expected Outputs\n\n| Output | Type | Description |\n|--------|------|-------------|\n| `adata.obsm[\"X_pca_harmony\"]` | `np.ndarray` (cells × PCs) | Harmony-corrected PCA embedding; input for neighbors\u002FUMAP\u002Fclustering |\n| `adata.obsm[\"X_umap\"]` | `np.ndarray` (cells × 2) | 2D UMAP coordinates from corrected embedding |\n| `adata.obs[\"leiden\"]` | `pd.Categorical` | Leiden cluster labels |\n| `adata.uns[\"neighbors\"]` | `dict` | KNN graph metadata (`connectivities`, `distances`) |\n| `adata.uns[\"rank_genes_groups\"]` | `dict` | Per-cluster marker gene statistics (scores, p-values, log fold changes) |\n| `harmony_batch_evaluation.png` | PNG figure | Side-by-side UMAP panels: batch labels, cluster labels, uncorrected comparison |\n\n## Troubleshooting\n\n| Problem | Cause | Solution |\n|---------|-------|----------|\n| Harmony does not converge (max iterations reached) | Strong batch effects or too few iterations | Increase `max_iter_harmony` to 30–50; check that PCA was computed with `batch_key` HVG selection |\n| Batches still separate on UMAP after correction | `theta` too low or too few PCs | Increase `theta` to 3–4; use more PCs (40–50); ensure `use_rep=\"X_pca_harmony\"` is set in `sc.pp.neighbors()` |\n| Over-correction: biologically distinct populations merge | `theta` too high or too many iterations | Reduce `theta` to 1.0; reduce `max_iter_harmony`; verify marker gene expression is cell-type-specific |\n| `KeyError: 'X_pca_harmony'` in `sc.pp.neighbors()` | Step 2 (harmony_integrate) not run yet | Run `sc.external.pp.harmony_integrate(adata, key=\"batch\")` before calling `sc.pp.neighbors()` |\n| `AttributeError` or import error for `sc.external.pp.harmony_integrate` | `harmonypy` not installed | Run `pip install harmonypy`; verify `import harmonypy` succeeds |\n| `ValueError: vars_use not in meta_data columns` | Batch column name mismatch | Check `adata.obs.columns` and confirm the column name passed to `key=` exists |\n| Memory error on large datasets (>1M cells) | Full PCA matrix loaded into memory | Use harmonypy directly with chunked PCA; consider subsampling to 200k cells for parameter tuning first |\n| Clusters appear identical before and after correction | PCA was not computed with HVGs selected per batch | Re-run `sc.pp.highly_variable_genes(adata, batch_key=\"batch\")` and `sc.pp.pca()` before Harmony |\n\n## References\n\n- [Harmony paper — Korsunsky et al., Nature Methods 2019](https:\u002F\u002Fdoi.org\u002F10.1038\u002Fs41592-019-0619-0) — original algorithm, benchmarks against MNN, Seurat, BBKNN, Scanorama\n- [harmonypy (Python) — GitHub](https:\u002F\u002Fgithub.com\u002Fslowkow\u002Fharmonypy) — Python port by Kamil Slowikowski\n- [harmony (R) — GitHub](https:\u002F\u002Fgithub.com\u002Fimmunogenomics\u002Fharmony) — original R implementation by Immunogenomics Lab\n- [Harmony documentation — Broad Institute](https:\u002F\u002Fportals.broadinstitute.org\u002Fharmony\u002F) — tutorials and parameter guidance\n- [Scanpy external API — harmony_integrate](https:\u002F\u002Fscanpy.readthedocs.io\u002Fen\u002Fstable\u002Fgenerated\u002Fscanpy.external.pp.harmony_integrate.html) — scanpy wrapper documentation\n- [Single-cell best practices — batch correction chapter](https:\u002F\u002Fwww.sc-best-practices.org\u002Fpreprocessing_visualization\u002Fbatch_correction.html) — benchmarks and when to use each method\n","# Harmony Batch Correction\n\n## Overview\n\nHarmony is a fast, scalable algorithm for batch integration in single-cell data. It takes a PCA embedding (cells × PCs) as input and returns a corrected embedding from which batch effects have been regressed out via iterative soft-clustering and per-cluster linear regression. The corrected embedding is then used to compute neighbors, UMAP, and downstream clustering — the raw count matrix is never modified. Harmony works for single-cell RNA-seq, ATAC-seq, and other omics modalities where a PCA-like embedding is available.\n\n## When to Use\n\n- Integrating scRNA-seq datasets from different samples, donors, sequencing runs, or experimental batches that should contain the same cell types\n- Removing technical variation (library preparation protocol, 10x chemistry version, sequencing depth, sequencing platform) while preserving biological differences between cell types and conditions\n- Performing fast, scalable batch correction on datasets with millions of cells where deep generative model training would be prohibitively slow\n- Correcting for multiple confounding variables simultaneously (batch, donor, sequencing platform, tissue processing protocol)\n- Preparing a corrected embedding for UMAP visualization, Leiden clustering, or label transfer without modifying the gene expression count matrix\n- Use **omics-plotting** SKILL for generic result-table figures; batch-evaluation UMAPs use scanpy `sc.pl.*`\n- Use **scVI\u002Fscvi-tools** instead when you need probabilistic batch correction with a variational autoencoder (deep learning), differential expression with uncertainty estimates, or multi-modal integration (RNA + protein)\n- Use **BBKNN** instead when you want graph-based integration that avoids constructing a corrected embedding altogether and directly builds a cross-batch nearest-neighbor graph\n- Use **Seurat Integration \u002F CCA** (R) instead when you are already in a Seurat workflow and prefer anchor-based integration methods\n\n## Prerequisites\n\n- **Python packages**: `harmonypy`, `scanpy>=1.10`, `leidenalg`, `igraph`, `anndata`, `pandas`, `matplotlib`\n- **R packages** (optional): `harmony`, `Seurat>=4.0` (for R workflow in Step 7)\n- **Data requirements**: AnnData object with raw counts, batch\u002Fsample metadata in `adata.obs`, and PCA embedding already computed (`adata.obsm[\"X_pca\"]`)\n- **Environment**: Python 3.9+; 8 GB RAM sufficient for up to ~500k cells; linear memory scaling\n\n```bash\npip install harmonypy \"scanpy[leiden]\" anndata pandas matplotlib\n```\n\n```r\n# R installation (for Step 7 \u002F Seurat integration)\ninstall.packages(\"harmony\")\n# If using Seurat:\ninstall.packages(\"Seurat\")\n```\n\n## Pre-flight Interview\n\nSettle these with the user before writing any analysis code.\n\n```yaml\ndecisions:\n  - id: D1\n    param: batchKey\n    kind: required\n    source: data\n    ask: \"Which variable separates samples that were processed apart - donor, run, chemistry, or a combination?\"\n    default: null\n\n  - id: D2\n    param: inputEmbedding\n    kind: derived\n    source: upstream\n    ask: \"Which reduced space should be corrected?\"\n    default: \"the PCA embedding computed upstream\"\n\n  - id: D3\n    param: diversityPenalty\n    kind: required\n    source: user\n    depends_on: [D1]\n    ask: \"How hard should batches be pushed together? Too hard erases real differences between samples.\"\n    default: \"2.0; raise toward 4-6 when batch sizes are very uneven\"\n\n  - id: D4\n    param: numClusters\n    kind: optional_conditional\n    source: data\n    ask: \"Does the dataset contain rare populations that need more soft clusters to survive correction?\"\n    default: \"automatic, min(100, cells\u002F30)\"\n\n  - id: D5\n    param: maxIterations\n    kind: optional_conditional\n    source: data\n    ask: \"Did the correction converge, or does it need more iterations?\"\n    default: 10\n\n  - id: D6\n    param: smallClusterProtection\n    kind: optional_conditional\n    source: user\n    ask: \"Are small populations being over-split during correction?\"\n    default: \"off\"\n\n  - id: D7\n    param: kernelBandwidth\n    kind: optional\n    source: user\n    ask: \"Should Harmony use its standard soft-clustering bandwidth, or be tuned for unusually heterogeneous batches?\"\n    default: 0.1\n```\n\nD3 is where batch correction goes wrong in the direction nobody checks.\nUnder-correction is visible - batches stay separated in the embedding.\nOver-correction is not: samples mix beautifully because a real treatment effect\nwas removed along with the batch effect. Ask what the batch variable is\nconfounded with before raising it.\n\n## Quick Start\n\nMinimal pipeline — load preprocessed data, run Harmony via scanpy, produce UMAP:\n\n```python\nimport scanpy as sc\n\n# Load preprocessed AnnData (counts normalized, HVGs selected, PCA run)\nadata = sc.read_h5ad(\"preprocessed.h5ad\")   # must have adata.obs[\"batch\"]\n\n# Run Harmony batch correction (corrects adata.obsm[\"X_pca\"] → \"X_pca_harmony\")\nsc.external.pp.harmony_integrate(adata, key=\"batch\")\n\n# Build neighborhood graph on corrected embedding, then UMAP\nsc.pp.neighbors(adata, use_rep=\"X_pca_harmony\")\nsc.tl.umap(adata)\nsc.tl.leiden(adata, resolution=0.5)\n\n# Visualize\nsc.pl.umap(adata, color=[\"batch\", \"leiden\"], ncols=2)\nprint(f\"Clusters: {adata.obs['leiden'].nunique()} | Cells: {adata.n_obs}\")\n```\n\n## Workflow\n\n### Step 1: Quality Control and Preprocessing\n\nFilter, normalize, select highly variable genes (HVGs), and run PCA. Harmony is applied to the PCA embedding produced here.\n\n```python\nimport scanpy as sc\nimport numpy as np\n\nsc.settings.set_figure_params(dpi=80, facecolor=\"white\")\n\n# Load multi-batch data — adata.obs must contain a batch column\nadata = sc.read_h5ad(\"multi_batch_counts.h5ad\")\n# Alternatively, concatenate multiple AnnData objects:\n# adata = sc.concat([adata1, adata2, adata3], label=\"batch\",\n#                   keys=[\"batch1\", \"batch2\", \"batch3\"])\n\nprint(f\"Loaded: {adata.n_obs} cells × {adata.n_vars} genes\")\nprint(f\"Batches: {adata.obs['batch'].value_counts().to_dict()}\")\n\n# QC: annotate mitochondrial genes and filter low-quality cells\nadata.var[\"mt\"] = adata.var_names.str.startswith(\"MT-\")\nsc.pp.calculate_qc_metrics(adata, qc_vars=[\"mt\"], inplace=True)\nsc.pp.filter_cells(adata, min_genes=200)\nsc.pp.filter_cells(adata, max_genes=6000)\nsc.pp.filter_genes(adata, min_cells=3)\nadata = adata[adata.obs[\"pct_counts_mt\"] \u003C 20].copy()\nprint(f\"After QC: {adata.n_obs} cells × {adata.n_vars} genes\")\n\n# Normalize and log-transform (store raw counts first)\nadata.layers[\"counts\"] = adata.X.copy()\nsc.pp.normalize_total(adata, target_sum=1e4)\nsc.pp.log1p(adata)\n\n# Select HVGs and compute PCA\nsc.pp.highly_variable_genes(adata, n_top_genes=3000, batch_key=\"batch\")\nsc.pp.pca(adata, n_comps=50, use_highly_variable=True)\nprint(f\"PCA shape: {adata.obsm['X_pca'].shape}\")  # (n_cells, 50)\n```\n\n### Step 2: Run Harmony via Scanpy Integration\n\nThe scanpy wrapper calls `harmonypy` under the hood and stores the corrected embedding in `adata.obsm[\"X_pca_harmony\"]`.\n\n```python\nimport scanpy as sc\n\n# Run Harmony — corrects adata.obsm[\"X_pca\"] in-place and stores result as \"X_pca_harmony\"\nsc.external.pp.harmony_integrate(\n    adata,\n    key=\"batch\",           # obs column with batch labels\n    basis=\"X_pca\",         # source embedding (default)\n    adjusted_basis=\"X_pca_harmony\",  # destination key (default)\n    max_iter_harmony=20,   # maximum Harmony iterations (default 10; increase for complex batches)\n    theta=2.0,             # diversity penalty per batch variable (default 2)\n    sigma=0.1,             # width of soft-clustering Gaussian kernel\n    random_state=42,\n)\n\nprint(f\"Corrected embedding: {adata.obsm['X_pca_harmony'].shape}\")\n# Expected: (n_cells, 50) — same shape as X_pca\n```\n\n### Step 3: Run Harmony via harmonypy Directly\n\nUse the lower-level `harmonypy` API when you need finer control, access to the HarmonyObject, or integration outside of scanpy.\n\n```python\nimport harmonypy\nimport pandas as pd\nimport numpy as np\n\n# Extract PCA embedding and metadata\npca_embeddings = adata.obsm[\"X_pca\"]                  # numpy array (n_cells, n_PCs)\nmeta_data = adata.obs[[\"batch\", \"donor\"]].copy()       # DataFrame with batch variables\n\n# Run Harmony\nho = harmonypy.run_harmony(\n    pca_embeddings,\n    meta_data,\n    vars_use=[\"batch\"],        # list of columns to correct for\n    theta=2.0,                 # diversity penalty strength (per variable)\n    sigma=0.1,                 # soft-clustering bandwidth\n    nclust=None,               # number of clusters; None → auto (min(100, n_cells\u002F30))\n    tau=0,                     # protection against over-clustering small clusters\n    block_size=0.05,           # fraction of cells per mini-batch\n    max_iter_harmony=20,\n    max_iter_kmeans=20,\n    epsilon_cluster=1e-5,\n    epsilon_harmony=1e-4,\n    random_state=42,\n    verbose=True,\n)\n\ncorrected = ho.Z_corr.T   # (n_cells, n_PCs) corrected embedding\nadata.obsm[\"X_pca_harmony\"] = corrected\nprint(f\"Harmony converged. Corrected embedding shape: {corrected.shape}\")\n```\n\n### Step 4: Compute Neighbors and UMAP on Harmony Embedding\n\nAlways use `use_rep=\"X_pca_harmony\"` so that downstream graph construction is based on the corrected embedding, not the original PCA.\n\n```python\nimport scanpy as sc\n\n# Build k-nearest neighbor graph using corrected embedding\nsc.pp.neighbors(\n    adata,\n    n_neighbors=15,          # number of neighbors (15-30 typical for scRNA-seq)\n    n_pcs=None,              # use all PCs in the embedding\n    use_rep=\"X_pca_harmony\", # IMPORTANT: use corrected embedding\n    random_state=42,\n)\n\n# Compute UMAP for visualization\nsc.tl.umap(adata, min_dist=0.3, spread=1.0, random_state=42)\n\nprint(f\"UMAP computed: {adata.obsm['X_umap'].shape}\")  # (n_cells, 2)\n```\n\n### Step 5: Leiden Clustering on Harmony-Corrected Graph\n\nClustering is performed on the neighbor graph built from the Harmony-corrected embedding in Step 4.\n\n```python\nimport scanpy as sc\n\n# Run Leiden community detection at multiple resolutions\nfor resolution in [0.3, 0.5, 0.8]:\n    sc.tl.leiden(adata, resolution=resolution, key_added=f\"leiden_{resolution}\")\n\n# Select final resolution\nadata.obs[\"leiden\"] = adata.obs[\"leiden_0.5\"]\n\nprint(f\"Clusters at resolution 0.5: {adata.obs['leiden'].nunique()}\")\nprint(adata.obs[\"leiden\"].value_counts().head())\n\n# Find marker genes per cluster\nsc.tl.rank_genes_groups(adata, groupby=\"leiden\", method=\"wilcoxon\", n_genes=50)\nsc.pl.rank_genes_groups_dotplot(adata, n_genes=5, groupby=\"leiden\")\n```\n\n### Step 6: Evaluate Batch Correction\n\nPlot UMAP colored by batch and by cell type \u002F cluster to visually confirm batch effects are removed while biological structure is preserved.\n\n```python\nimport scanpy as sc\nimport matplotlib.pyplot as plt\n\nfig, axes = plt.subplots(1, 3, figsize=(18, 5))\n\n# Before correction: color by batch using uncorrected PCA-based UMAP\nsc.pp.neighbors(adata, use_rep=\"X_pca\", key_added=\"uncorrected_neighbors\", random_state=42)\nsc.tl.umap(adata, neighbors_key=\"uncorrected_neighbors\", random_state=42)\nadata.obsm[\"X_umap_uncorrected\"] = adata.obsm[\"X_umap\"].copy()\n\n# Restore Harmony UMAP\nsc.pp.neighbors(adata, use_rep=\"X_pca_harmony\", random_state=42)\nsc.tl.umap(adata, random_state=42)\n\n# Panel 1: Corrected UMAP colored by batch\nsc.pl.umap(adata, color=\"batch\", title=\"Harmony: colored by batch\",\n           ax=axes[0], show=False)\n\n# Panel 2: Corrected UMAP colored by leiden cluster\nsc.pl.umap(adata, color=\"leiden\", title=\"Harmony: Leiden clusters\",\n           ax=axes[1], show=False)\n\n# Panel 3: Uncorrected UMAP colored by batch (for comparison)\nsc.pl.embedding(adata, basis=\"X_umap_uncorrected\", color=\"batch\",\n                title=\"Uncorrected PCA: batch separation\",\n                ax=axes[2], show=False)\n\nplt.tight_layout()\nplt.savefig(\"harmony_batch_evaluation.png\", dpi=150, bbox_inches=\"tight\")\nplt.show()\nprint(\"Batch evaluation figure saved to harmony_batch_evaluation.png\")\n```\n\n### Step 7: R Integration with Seurat\n\nFor users working in R, Harmony integrates directly with Seurat via `RunHarmony()`.\n\n```r\nlibrary(Seurat)\nlibrary(harmony)\n\n# Load Seurat object with batch metadata in metadata column \"batch\"\nseurat_obj \u003C- readRDS(\"multi_batch_seurat.rds\")\n\n# Ensure PCA is computed\nseurat_obj \u003C- NormalizeData(seurat_obj)\nseurat_obj \u003C- FindVariableFeatures(seurat_obj, nfeatures = 3000)\nseurat_obj \u003C- ScaleData(seurat_obj)\nseurat_obj \u003C- RunPCA(seurat_obj, npcs = 50)\n\n# Run Harmony — corrects the \"pca\" reduction and adds \"harmony\" reduction\nseurat_obj \u003C- RunHarmony(\n  seurat_obj,\n  group.by.vars = \"batch\",   # metadata column(s) to correct for\n  dims.use = 1:30,           # number of PCs to use\n  theta = 2,                 # diversity penalty\n  sigma = 0.1,               # soft-clustering bandwidth\n  max.iter.harmony = 20,\n  plot_convergence = TRUE,   # plot objective function convergence\n  verbose = TRUE\n)\n\n# Build neighbor graph and UMAP using Harmony embedding\nseurat_obj \u003C- FindNeighbors(seurat_obj, reduction = \"harmony\", dims = 1:30)\nseurat_obj \u003C- FindClusters(seurat_obj, resolution = 0.5)\nseurat_obj \u003C- RunUMAP(seurat_obj, reduction = \"harmony\", dims = 1:30)\n\n# Visualize\nDimPlot(seurat_obj, reduction = \"umap\", group.by = \"batch\")\nDimPlot(seurat_obj, reduction = \"umap\", group.by = \"seurat_clusters\")\n\ncat(sprintf(\"Clusters: %d | Cells: %d\\n\",\n            length(unique(seurat_obj$seurat_clusters)),\n            ncol(seurat_obj)))\n```\n\n## Key Parameters\n\n| Parameter | Default | Range \u002F Options | Effect |\n|-----------|---------|-----------------|--------|\n| `theta` | `2.0` | `0`–`10` | Diversity penalty per batch variable. Higher values force more mixing; set to 0 to disable penalty. Increase to `4`–`6` for very uneven batch sizes. |\n| `sigma` | `0.1` | `0.01`–`0.5` | Bandwidth of the soft-clustering Gaussian kernel. Smaller values → sharper cluster assignments; larger values → smoother. Rarely needs changing. |\n| `nclust` | `None` (auto) | `5`–`200` | Number of soft clusters used for correction. Auto-set to `min(100, n_cells\u002F30)`. Increase for datasets with many rare cell types. |\n| `max_iter_harmony` | `10` | `5`–`50` | Maximum Harmony iterations. Increase to `20`–`30` for datasets with strong or complex batch effects where convergence is slow. |\n| `tau` | `0` | `0`–`10` | Overclustering protection. Positive values penalize very small clusters; use `tau=5` when tiny populations are over-splitting. |\n| `n_neighbors` (scanpy) | `15` | `5`–`50` | Number of nearest neighbors for the post-Harmony graph. Increase for larger datasets (>100k cells) to stabilize clusters. |\n| `block_size` | `0.05` | `0.01`–`0.1` | Fraction of cells per mini-batch for the K-means step. Smaller values are faster but less stable; default is usually appropriate. |\n\n## Key Concepts\n\n### How Harmony Works\n\nHarmony correction proceeds in three repeated phases until convergence:\n\n1. **Soft K-means assignment**: Each cell is softly assigned to `K` clusters based on Euclidean distance in PC space, weighted by the batch-diversity penalty `theta`.\n2. **Per-cluster linear regression**: Within each cluster, a linear correction is estimated for each batch variable and applied to the cluster's cells.\n3. **Convergence check**: The objective function (mixture model likelihood + diversity penalty) is evaluated; iterations stop when improvement \u003C `epsilon_harmony`.\n\nThe corrected embedding lives in the same PC space as the input PCA but with batch-specific directions subtracted. The raw count matrix (`adata.X`) and all gene-level information are untouched.\n\n### PCA Before Harmony\n\nHarmony assumes the input PCA was computed with `batch_key` awareness. In scanpy, always pass `batch_key=\"batch\"` to `sc.pp.highly_variable_genes()` before PCA so that HVGs are selected independently per batch and then intersected, preventing batch-specific HVGs from dominating the embedding.\n\n### Embedding Not Counts\n\nHarmony corrects the embedding, not the count matrix. Differential expression analysis should still use the raw or normalized counts (stored in `adata.layers[\"counts\"]` or `adata.raw`), not the corrected PCs.\n\n## Common Recipes\n\n### Recipe: Multi-Variable Correction (Batch + Donor + Platform)\n\nCorrect for multiple confounding variables simultaneously by passing a list to `vars_use`. Each variable gets its own diversity penalty `theta`.\n\n```python\nimport harmonypy\nimport pandas as pd\n\n# Prepare metadata with multiple batch variables\nmeta_data = adata.obs[[\"batch\", \"donor\", \"platform\"]].copy()\n\n# Run Harmony correcting for all three variables\nho = harmonypy.run_harmony(\n    adata.obsm[\"X_pca\"],\n    meta_data,\n    vars_use=[\"batch\", \"donor\", \"platform\"],  # correct for all three\n    theta=[2.0, 1.0, 2.0],  # per-variable diversity penalty\n    # theta can also be a scalar (same for all variables)\n    max_iter_harmony=30,\n    random_state=42,\n    verbose=True,\n)\n\nadata.obsm[\"X_pca_harmony\"] = ho.Z_corr.T\nprint(f\"Multi-variable correction complete. Shape: {adata.obsm['X_pca_harmony'].shape}\")\n\n# Verify batch mixing improved for all variables\nimport scanpy as sc\nsc.pp.neighbors(adata, use_rep=\"X_pca_harmony\")\nsc.tl.umap(adata, random_state=42)\nsc.pl.umap(adata, color=[\"batch\", \"donor\", \"platform\"], ncols=3)\n```\n\n### Recipe: Diagnose Over-Correction with Marker Genes\n\nIf Harmony over-corrects (merges biologically distinct populations), canonical marker genes will lose cell-type specificity on the UMAP. Check this before downstream analysis.\n\n```python\nimport scanpy as sc\nimport matplotlib.pyplot as plt\n\n# Define known canonical marker genes for your tissue\nmarker_genes = {\n    \"T cells\": [\"CD3D\", \"CD3E\", \"TRAC\"],\n    \"B cells\": [\"MS4A1\", \"CD79A\", \"CD19\"],\n    \"NK cells\": [\"GNLY\", \"NKG7\", \"KLRD1\"],\n    \"Monocytes\": [\"LYZ\", \"CD14\", \"CST3\"],\n    \"Dendritic cells\": [\"FCER1A\", \"CLEC10A\"],\n}\n\n# Plot canonical markers on the Harmony-corrected UMAP\nall_markers = [g for genes in marker_genes.values() for g in genes\n               if g in adata.var_names]\n\nsc.pl.umap(\n    adata,\n    color=all_markers[:6],    # plot first 6 markers\n    ncols=3,\n    vmax=\"p99\",               # clip color scale at 99th percentile\n    frameon=False,\n    save=\"_marker_genes.png\",\n)\n\n# If markers look diffuse or don't separate cell types cleanly,\n# reduce theta (e.g., from 2.0 to 1.0) or reduce max_iter_harmony\nprint(\"If marker gene expression is diffuse across clusters, reduce theta.\")\nprint(\"If batch effects remain visible, increase theta or max_iter_harmony.\")\n```\n\n### Recipe: Save and Reload Harmony-Corrected AnnData\n\nSave the corrected object with all embeddings for downstream analysis without re-running Harmony.\n\n```python\nimport scanpy as sc\n\n# Save with all embeddings\nadata.write_h5ad(\"harmony_corrected.h5ad\", compression=\"gzip\")\nprint(f\"Saved to harmony_corrected.h5ad ({adata.n_obs} cells)\")\n\n# Reload and verify\nadata_loaded = sc.read_h5ad(\"harmony_corrected.h5ad\")\nprint(f\"Loaded. Keys in obsm: {list(adata_loaded.obsm.keys())}\")\n# Expected: ['X_pca', 'X_pca_harmony', 'X_umap']\n```\n\n## Expected Outputs\n\n| Output | Type | Description |\n|--------|------|-------------|\n| `adata.obsm[\"X_pca_harmony\"]` | `np.ndarray` (cells × PCs) | Harmony-corrected PCA embedding; input for neighbors\u002FUMAP\u002Fclustering |\n| `adata.obsm[\"X_umap\"]` | `np.ndarray` (cells × 2) | 2D UMAP coordinates from corrected embedding |\n| `adata.obs[\"leiden\"]` | `pd.Categorical` | Leiden cluster labels |\n| `adata.uns[\"neighbors\"]` | `dict` | KNN graph metadata (`connectivities`, `distances`) |\n| `adata.uns[\"rank_genes_groups\"]` | `dict` | Per-cluster marker gene statistics (scores, p-values, log fold changes) |\n| `harmony_batch_evaluation.png` | PNG figure | Side-by-side UMAP panels: batch labels, cluster labels, uncorrected comparison |\n\n## Troubleshooting\n\n| Problem | Cause | Solution |\n|---------|-------|----------|\n| Harmony does not converge (max iterations reached) | Strong batch effects or too few iterations | Increase `max_iter_harmony` to 30–50; check that PCA was computed with `batch_key` HVG selection |\n| Batches still separate on UMAP after correction | `theta` too low or too few PCs | Increase `theta` to 3–4; use more PCs (40–50); ensure `use_rep=\"X_pca_harmony\"` is set in `sc.pp.neighbors()` |\n| Over-correction: biologically distinct populations merge | `theta` too high or too many iterations | Reduce `theta` to 1.0; reduce `max_iter_harmony`; verify marker gene expression is cell-type-specific |\n| `KeyError: 'X_pca_harmony'` in `sc.pp.neighbors()` | Step 2 (harmony_integrate) not run yet | Run `sc.external.pp.harmony_integrate(adata, key=\"batch\")` before calling `sc.pp.neighbors()` |\n| `AttributeError` or import error for `sc.external.pp.harmony_integrate` | `harmonypy` not installed | Run `pip install harmonypy`; verify `import harmonypy` succeeds |\n| `ValueError: vars_use not in meta_data columns` | Batch column name mismatch | Check `adata.obs.columns` and confirm the column name passed to `key=` exists |\n| Memory error on large datasets (>1M cells) | Full PCA matrix loaded into memory | Use harmonypy directly with chunked PCA; consider subsampling to 200k cells for parameter tuning first |\n| Clusters appear identical before and after correction | PCA was not computed with HVGs selected per batch | Re-run `sc.pp.highly_variable_genes(adata, batch_key=\"batch\")` and `sc.pp.pca()` before Harmony |\n\n## References\n\n- [Harmony paper — Korsunsky et al., Nature Methods 2019](https:\u002F\u002Fdoi.org\u002F10.1038\u002Fs41592-019-0619-0) — original algorithm, benchmarks against MNN, Seurat, BBKNN, Scanorama\n- [harmonypy (Python) — GitHub](https:\u002F\u002Fgithub.com\u002Fslowkow\u002Fharmonypy) — Python port by Kamil Slowikowski\n- [harmony (R) — GitHub](https:\u002F\u002Fgithub.com\u002Fimmunogenomics\u002Fharmony) — original R implementation by Immunogenomics Lab\n- [Harmony documentation — Broad Institute](https:\u002F\u002Fportals.broadinstitute.org\u002Fharmony\u002F) — tutorials and parameter guidance\n- [Scanpy external API — harmony_integrate](https:\u002F\u002Fscanpy.readthedocs.io\u002Fen\u002Fstable\u002Fgenerated\u002Fscanpy.external.pp.harmony_integrate.html) — scanpy wrapper documentation\n- [Single-cell best practices — batch correction chapter](https:\u002F\u002Fwww.sc-best-practices.org\u002Fpreprocessing_visualization\u002Fbatch_correction.html) — benchmarks and when to use each method\n",{"name":5,"license":15,"description":7},"master","fd76f882a04e445e899d5cfb2732f2105ea054ee","skills\u002Fawesome-skills\u002Fharmony-batch-correction",0,"https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS","https:\u002F\u002Fbg-szy.github.io\u002FTOP-SKILLS\u002F","https:\u002F\u002Fgithub.com\u002Fbg-szy","https:\u002F\u002Fwww.ecust.edu.cn\u002F","a student of East China University of Science and Technology","2026-11-15 03:38:02",{"source":8,"skillName":5,"commands":35,"prompt":45,"zipAvailable":46},[36,39,42],{"tool":37,"command":38},"npx","npx skills add bg-szy\u002FTOP-SKILLS --skill harmony-batch-correction",{"tool":40,"command":41},"bunx","bunx skills add bg-szy\u002FTOP-SKILLS --skill harmony-batch-correction",{"tool":43,"command":44},"pnpm","pnpm dlx skills add bg-szy\u002FTOP-SKILLS --skill harmony-batch-correction","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fawesome-skills\u002Fharmony-batch-correction\u002FSKILL.md",true,[],[49,57,64,71,78,85],{"skillNo":50,"name":51,"nameZh":6,"description":52,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":53,"categories":54,"keywords":55,"publishedAt":56},"01M7DXW9N826PKXK174PVW3038","serpmaven","Scrape Google search results (SERP) to JSON with SERP Maven (serpmaven) - a real Chrome browser on a residential proxy with sticky sessions. Run it as a CLI, a Python library, a local HTTP search API (`serve`), an MCP server or a Docker image; set the proxy login, workers, pages and cost tracking. Use when the user wants Google results, rank tracking, a self-hosted SERP API, or live Google search for an AI agent.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Fserpmaven\u002FSKILL.md",[],[],"2026-11-15 14:19:17",{"skillNo":58,"name":59,"nameZh":6,"description":60,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":61,"categories":62,"keywords":63,"publishedAt":56},"01M7DXVHSTWDV65475QEQ915M7","revnu-landing-page-audit","Find out why a landing page isn't turning visitors into signups, demos or sales. Audits one page against what the ad, post or search that sends people there promised, then checks the first screen, proof, call to action, friction and mobile. Returns at most 7 prioritized fixes, plus what is fine and what could not be checked; rewrites specific lines and fixes the page in the repo when asked. Never promises a conversion lift. Works without a Revnu account. Use when the user says or asks: \"audit my landing page\", \"why isn't this page converting\", \"review my homepage\", \"my ads get clicks but no signups\", \"people bounce from the pricing page\", \"CRO review\", \"improve conversion rate\", \"is my hero section clear\", \"roast my landing page\", \"rewrite my headline\", \"what's wrong with this page\", \"landing page feedback\", \"make the signup page convert better\". Not for SEO or AI-search audits, page speed engineering on its own, or building a new page from scratch.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-landing-page-audit\u002FSKILL.md",[],[],{"skillNo":65,"name":66,"nameZh":6,"description":67,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":68,"categories":69,"keywords":70,"publishedAt":56},"01M7DXV8X2D7B3VTD4HHYYHTGR","revnu-growth-context","Write down once who buys, what they're stuck on, what it costs, what proof you have and what you've already tried, so every growth task starts from facts instead of a questionnaire. Creates or updates .agents\u002Frevnu-growth.md from the repo, the live site and the user, and imports an existing product-marketing.md. Use when the user says \"set up our marketing context\", \"who is our ideal customer\", \"write our ICP\", \"describe the product for marketing\", \"positioning doc\", \"what's our brand voice\", \"remember this about our customers\", \"log what we tried\", \"what have we learned from marketing\", \"we changed pricing, update the context\", \"update our growth notes\", \"summarize the business for the agent\", \"import my product-marketing.md\", \"start a growth doc\", or before a first marketing, SEO, outreach or launch task when no context file exists. Works without a Revnu account.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-growth-context\u002FSKILL.md",[],[],{"skillNo":72,"name":73,"nameZh":6,"description":74,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":75,"categories":76,"keywords":77,"publishedAt":56},"01M7DXV0DGJ1G0A60PAHC6J3C5","revnu-get-listed","Get onto the third-party pages AI answers and search cite when buyers ask for the best tool in your category: \"best X\" roundups, directories, review sites, GitHub awesome lists, community threads and comparison pages. Finds which ones are cited, ranks them by fit and effort, and drafts each submission, PR or pitch by the target's own rules. Use when the user says \"get us listed\", \"which directories should we submit to\", \"how do we get into best-of lists\", \"why does ChatGPT recommend competitors and not us\", \"get mentioned in AI answers\", \"submit to awesome lists\", \"get on G2\", \"where are our competitors listed\", \"pitch listicle authors\", \"find backlink opportunities\", \"launch directories\", \"get into roundups\", \"Product Hunt alternatives\", \"where should we be listed\", \"get cited by Perplexity\". Never submits, pays or posts without a yes. Works without a Revnu account.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-get-listed\u002FSKILL.md",[],[],{"skillNo":79,"name":80,"nameZh":6,"description":81,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":82,"categories":83,"keywords":84,"publishedAt":56},"01M7DXTSPMGT9D6DSS0HP9BSTA","revnu-ai-readiness-audit","Audit whether your website gives ChatGPT, Perplexity, Claude, Gemini and Google's AI Overviews something worth quoting, and fix the pages that don't. Use when the user says or asks \"is my site ready for AI search\", \"audit my site for AI answers\", \"AEO audit\", \"GEO audit\", \"why doesn't ChatGPT quote our pricing\", \"make our pages citable by AI\", \"do I need llms.txt\", \"does schema help with ChatGPT\", \"check our structured data\", \"is our content visible without JavaScript\", \"AI SEO audit\", \"optimize our homepage for AI answers\", \"LLM SEO check\", \"why does AI get our product wrong\", \"fix our site for AI Overviews\". Checks fetchability and indexability, answers in the raw HTML, entity facts, schema (including JS-injected markup), headings, dates and llms.txt, then gives at most 10 prioritised fixes and edits the repo when asked. Works without a Revnu account.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Frevnu-ai-readiness-audit\u002FSKILL.md",[],[],{"skillNo":86,"name":87,"nameZh":6,"description":88,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":89,"categories":90,"keywords":91,"publishedAt":56},"01M7DXSZHCVTRS620GC3S97JZV","proxy-troubleshooting","Diagnose residential proxy failures, with NodeMaven's gateway as the reference - 407 with correct credentials, 406, 410, 500, a connection that hangs, ERR_TUNNEL_CONNECTION_FAILED in a browser, Playwright or Puppeteer ignoring proxy credentials, a sticky session that changes IP, geo-targeting that is silently ignored, passwords with special characters, and unexpected traffic from headless Chrome. Use when a proxy connection fails, returns the wrong location, or costs more traffic than expected.","https:\u002F\u002Fgithub.com\u002Fbg-szy\u002FTOP-SKILLS\u002Fblob\u002Fmaster\u002Fskills\u002Fmarketplace\u002Fproxy-troubleshooting\u002FSKILL.md",[],[]]