[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7ECG0SKX8E4WMSWC5CDQC6Q":3,"skill-same:01M7ECG0SKX8E4WMSWC5CDQC6Q":62},{"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":30,"commitSha":31,"skillDirectory":32,"forksCount":14,"repositoryHtmlUrl":33,"repositoryHomepageUrl":33,"ownerHtmlUrl":34,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":35,"install":36,"resources":49},"01M7ECG0SKX8E4WMSWC5CDQC6Q","bio-crispr-screens-batch-correction",null,"Batch effect correction for CRISPR screens covering ComBat empirical-Bayes, RUV, SVA, control-sgRNA normalization, and the model-based alternative of including batch as a covariate in MAGeCK MLE or Chronos. Covers screen-specific batch sources (passage cohort, library lot, infection day, sequencing run, Cas9 lot, FBS lot), PCA + variance-decomposition diagnostic to decide if correction is needed, when correction harms biology by over-correcting condition into batch, limma removeBatchEffect for visualization-only correction, and relationship to multi-condition design matrices. Use when combining screens for joint analysis, when passage cohort confounds biology, when DepMap-style panels need Chronos with batch covariates, when picking ComBat vs RUV, or when correction harms biology and should be replaced with explicit covariate modeling.","Mr-Nobody-Anonymous\u002FAll-skills","Mr-Nobody-Anonymous","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F184253119?v=4","01M7AEXFJHKTYQW5R0ZCQQTWFV","anonymous","01M7C00M3GQR4QKP9GZA42GFAK",0,"MIT","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-crispr-screens-batch-correction\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: bio-crispr-screens-batch-correction\ndescription: Batch effect correction for CRISPR screens covering ComBat empirical-Bayes, RUV, SVA, control-sgRNA normalization, and the model-based alternative of including batch as a covariate in MAGeCK MLE or Chronos. Covers screen-specific batch sources (passage cohort, library lot, infection day, sequencing run, Cas9 lot, FBS lot), PCA + variance-decomposition diagnostic to decide if correction is needed, when correction harms biology by over-correcting condition into batch, limma removeBatchEffect for visualization-only correction, and relationship to multi-condition design matrices. Use when combining screens for joint analysis, when passage cohort confounds biology, when DepMap-style panels need Chronos with batch covariates, when picking ComBat vs RUV, or when correction harms biology and should be replaced with explicit covariate modeling.\ntool_type: mixed\nprimary_tool: pyComBat\nsource: \"https:\u002F\u002Fgithub.com\u002FGPTomics\u002FbioSkills\"\nsource_repository: \"GPTomics\u002FbioSkills\"\nsource_path: \"crispr-screens\u002Fbatch-correction\u002FSKILL.md\"\nlicense: \"MIT\"\nimported_at: \"2026-09-20\"\n---\n\n## Version Compatibility\n\nReference examples tested with: pyComBat 0.3.3+ (epigenelabs\u002FpyComBat), MAGeCK 0.5.9+, R\u002Flimma 3.58+, sva 3.50+, RUVSeq 1.36+, pandas 2.2+, numpy 1.26+, scikit-learn 1.4+, scipy 1.12+.\n\nBefore using code patterns, verify installed versions match. If versions differ:\n- Python: `pip show combat`; `from combat.pycombat import pycombat`\n- R: `packageVersion('sva')`; `?ComBat`; `packageVersion('RUVSeq')`; `?RUVg`\n\nIf code throws ImportError, AttributeError, or TypeError, introspect the installed package and adapt the example to match the actual API rather than retrying.\n\n## Batch Correction for CRISPR Screens\n\n**\"Correct batch effects in my CRISPR screens\"** -> Diagnose the batch source, decide whether to remove via empirical-Bayes (ComBat), explicit covariate modeling (MAGeCK MLE \u002F Chronos design matrix), control-guide-anchored normalization, or unwanted-variation decomposition (RUV, SVA), then apply only the correction that preserves biological condition signal.\n\n- Python: `pyComBat.pycombat` for empirical-Bayes correction\n- Python: explicit batch covariates in `mageck mle --design-matrix`\n- R: `sva::ComBat`, `RUVSeq::RUVg`, `limma::removeBatchEffect`\n- Python: Chronos (`crispr_chronos`) natively handles screen-batch covariates\n\n## Batch Sources in CRISPR Screens\n\n| Source | Mechanism | Detectable by |\n|--------|-----------|---------------|\n| Library lot | Different aliquots or PCR amplifications | Gini shift; plasmid-pool sequencing |\n| Cell passage cohort | Cells passaged through different periods | PCA Day-0 samples clustering by passage |\n| Infection day | Lentivirus titer drifts; FBS lot changes | PCA Day-0 samples cluster by day |\n| Cas9 enzyme lot | Cas9 expression heterogeneity | PR-AUC drift across screens |\n| Sequencing run | Lane bias, flowcell variant, machine | Per-sample read-count distribution |\n| FBS \u002F culture lot | Fetal bovine serum lot variations confound proliferation | Day-0 vs endpoint differential not present in vehicle |\n| Tissue-prep batch | In-vivo: animal cohort, surgical day, organ-prep tech | In-vivo screens (see [[in-vivo-screens]]) |\n\n**Critical:** Batch effects in CRISPR screens often correlate with biology (e.g., the drug arm was processed in batch 2 because that's when the drug arrived). This confounds correction. Always check for confounding before applying ComBat.\n\n## Batch Effect Decision Tree\n\n| Diagnostic finding | Recommended correction |\n|--------------------|------------------------|\n| PCA shows samples cluster by condition, not batch | No correction needed; biology dominates |\n| PCA PC1 separates batches, PC2 separates conditions | Apply ComBat with condition as biological_covariate |\n| Batch fully confounded with condition (e.g. all drug in batch 2, all vehicle in batch 1) | Correction will destroy biology; instead redesign next screen with cross-batch balance OR re-analyze with batch in MAGeCK MLE design matrix |\n| Day-0 (pre-perturbation) samples cluster by batch | Strong batch effect; ComBat needed |\n| Endpoint samples cluster by batch but not Day-0 | Selection-driven artifact (FBS lot etc); correct or include batch as covariate |\n| Replicates within a batch are tight; across-batch much wider | Classic batch effect; ComBat |\n| Each replicate scatters randomly across PCs | Sample-level noise; no batch correction will help |\n| Cancer-line panel with multiple batches | Use Chronos (built-in batch modeling) |\n\n## Diagnose: PCA + Variance Decomposition\n\n**Goal:** Quantify what fraction of variance is batch vs condition before correcting.\n\n**Approach:** Run PCA on log10(counts+1); fit ANOVA decomposing variance into batch and condition components; report variance explained.\n\n```python\nimport pandas as pd\nimport numpy as np\nfrom sklearn.decomposition import PCA\nfrom scipy import stats\n\ndef batch_diagnostic(counts_df, metadata_df, batch_col='batch', condition_col='condition'):\n    '''Variance decomposition: report fraction of PC1\u002FPC2 variance attributable to batch vs condition.'''\n    log_counts = np.log10(counts_df + 1).T  # samples as rows\n    pca = PCA(n_components=5)\n    pcs = pca.fit_transform(log_counts)\n    out = pd.DataFrame({\n        'PC': range(1, 6),\n        'var_explained': pca.explained_variance_ratio_,\n    })\n    pc_df = pd.DataFrame(pcs, columns=[f'PC{i+1}' for i in range(5)], index=counts_df.columns).join(metadata_df)\n    for i in range(5):\n        pc = pc_df[f'PC{i+1}']\n        f_b, p_b = stats.f_oneway(*[pc[pc_df[batch_col] == b] for b in pc_df[batch_col].unique()])\n        f_c, p_c = stats.f_oneway(*[pc[pc_df[condition_col] == c] for c in pc_df[condition_col].unique()])\n        out.loc[i, 'batch_F'] = f_b\n        out.loc[i, 'batch_p'] = p_b\n        out.loc[i, 'cond_F'] = f_c\n        out.loc[i, 'cond_p'] = p_c\n    return out\n```\n\n**Interpretation:** If PC1 has batch F-stat > condition F-stat by 10x, batch is dominating and correction is warranted. If condition dominates PC1, no correction needed.\n\n## ComBat Empirical-Bayes Correction\n\n**Goal:** Remove batch-specific location and scale shifts while preserving biological condition signal.\n\n**Approach:** Log-transform counts, fit ComBat with explicit `biological_covariate` indicating condition (so the model knows which signal to preserve), back-transform.\n\n```python\nimport numpy as np\nfrom combat.pycombat import pycombat\n\ndef combat_correct(counts_df, batch_vector, condition_vector=None):\n    '''ComBat on log-counts with optional biological covariate (condition).\n    Preserves condition signal while removing batch shifts.'''\n    data = np.log2(counts_df.values + 1)\n    if condition_vector is not None:\n        mod = pd.get_dummies(condition_vector).values.astype(float)\n        corrected = pycombat(data, list(batch_vector), mod=mod)      # data must be a DataFrame\n    else:\n        corrected = pycombat(data, list(batch_vector))               # data must be a DataFrame\n    return pd.DataFrame(np.power(2, corrected) - 1,\n                         index=counts_df.index, columns=counts_df.columns).clip(lower=0)\n```\n\n**Critical caveat:** ComBat assumes batch effects are linear shifts of mean and variance in log space. Non-linear effects (e.g., gene-specific batch sensitivity) remain. Always re-check PCA after correction to confirm batches now overlap.\n\n## RUV (Remove Unwanted Variation)\n\n**Goal:** Identify hidden batch sources via control sgRNAs whose true signal is known.\n\n**Approach:** Designate non-targeting controls as \"negative controls\" (assumed unchanged); RUV decomposes their variance into unwanted factors, then subtracts these from all data.\n\n```r\nlibrary(RUVSeq)\n# counts_df: rows = sgRNAs, columns = samples\nntc_indices \u003C- which(rownames(counts_df) %in% ntc_sgrna_names)\nseqset \u003C- newSeqExpressionSet(counts = as.matrix(counts_df))\nruv_corrected \u003C- RUVg(seqset, cIdx = ntc_indices, k = 2)  # k = 2 unwanted factors\n# Access corrected data\ncorrected_counts \u003C- normCounts(ruv_corrected)\n```\n\n**When to use:** RUV preferred over ComBat when batches are not annotated (e.g., unknown technical confounders). Worse than ComBat when batch is known and well-annotated; ComBat is more direct.\n\n## SVA (Surrogate Variable Analysis)\n\n**Goal:** Estimate unknown latent factors that may confound the screen.\n\n**Approach:** SVA computes surrogate variables that capture variance not explained by known biological factors; these can then be added to the MAGeCK MLE design matrix as covariates.\n\n```r\nlibrary(sva)\n# counts_df: rows = sgRNAs, columns = samples\nmod \u003C- model.matrix(~ condition, data = metadata)\nmod0 \u003C- model.matrix(~ 1, data = metadata)\nsv_obj \u003C- sva(as.matrix(counts_df), mod, mod0)\nn_sv \u003C- sv_obj$n.sv  # number of surrogate variables\n# Add to design matrix for MAGeCK MLE\ndesign_mat \u003C- cbind(mod, sv_obj$sv)\n```\n\n**Use case:** When the screen has clear biological signal (e.g. essentiality recovery passes) but small effect sizes are hidden by noise; SVA-discovered latent factors as covariates can recover them.\n\n## Batch as Explicit Covariate (Preferred for MAGeCK MLE \u002F Chronos)\n\n**Goal:** Model batch and biology in the same regression instead of pre-correcting.\n\n**Approach:** Add batch indicator columns to the MLE design matrix. The fitted beta for condition is the effect after accounting for batch; no pre-correction needed.\n\n```bash\n# Design matrix for a screen with 2 batches and 2 conditions\ncat > design.txt \u003C\u003CEOF\nSamples         baseline    batch2    treatment\nVeh_b1_r1       1           0         0\nVeh_b1_r2       1           0         0\nDrug_b1_r1      1           0         1\nDrug_b1_r2      1           0         1\nVeh_b2_r1       1           1         0\nVeh_b2_r2       1           1         0\nDrug_b2_r1      1           1         1\nDrug_b2_r2      1           1         1\nEOF\n\nmageck mle \\\n    --count-table counts.txt \\\n    --design-matrix design.txt \\\n    --output-prefix batch_aware_mle\n```\n\n**Why this is preferred:** ComBat shifts counts before testing; the MLE-with-covariates approach correctly propagates uncertainty from the batch term into the condition beta's standard error. ComBat-then-test pretends the corrected counts are noise-free, biasing FDR.\n\n## Control-Sgrna Anchored Normalization\n\n**Goal:** Use non-targeting controls as the per-sample reference so batch shifts cancel.\n\n**Approach:** Scale each sample so its NTC sgRNAs have a constant median. Subsequent fold changes are relative to NTCs in each sample, automatically batch-controlling.\n\n```python\ndef ntc_anchored_normalize(counts_df, ntc_sgrna_names, target_median=1000):\n    '''Scale each sample so its NTC median is target_median. Subsequent LFC is NTC-anchored.'''\n    is_ntc = counts_df.index.isin(ntc_sgrna_names)\n    ntc_medians = counts_df.loc[is_ntc].median(axis=0)\n    scale_factors = target_median \u002F ntc_medians.replace(0, np.nan)\n    return counts_df * scale_factors, scale_factors\n```\n\n**Critical:** Requires ≥500 NTCs in the library (see [[library-design]]). With fewer, the NTC median is unstable and amplifies noise rather than removing batch.\n\n## When NOT to Correct\n\n| Situation | Why correction hurts |\n|-----------|----------------------|\n| Batch is fully confounded with condition | Correction destroys biology along with batch; redesign or accept |\n| Batch effect is smaller than between-replicate noise | Correction adds noise without removing meaningful variance |\n| Replicates already correlate >0.95 within and across batches | No batch effect to correct |\n| Single-screen analysis | No \"batch\" to correct; only replicate noise |\n| Per-batch sample size \u003C3 | Cannot estimate batch shift reliably; correction is harmful |\n\n## Failure Modes\n\n### ComBat eliminates biological signal\n\n**Trigger:** Batch is correlated with condition (e.g., all drug-arm samples were processed week 2; all vehicle-arm samples week 1).\n**Mechanism:** ComBat without a `mod` covariate treats condition variance as batch variance; corrects it away.\n**Symptom:** PR-AUC against CEGv2 drops after ComBat correction.\n**Fix:** Always supply `mod` covariate matrix indicating condition; verify by comparing PR-AUC before and after.\n\n### RUV adds noise instead of removing it\n\n**Trigger:** k (number of unwanted factors) set too high.\n**Mechanism:** RUV's least-squares decomposition over-fits; \"removed\" variance includes biology.\n**Symptom:** Hits decrease and replicate Pearson drops after correction.\n**Fix:** Choose k via cross-validation; default k=1 or 2 for most screens.\n\n### Batch-aware MLE collinear design matrix\n\n**Trigger:** Adding a batch indicator that is fully collinear with another design column (e.g., all of batch 2 is also Day 21).\n**Mechanism:** MLE design matrix is singular; betas not estimable.\n**Symptom:** MAGeCK MLE errors out or produces NaN betas.\n**Fix:** Drop the collinear column; re-design experiment with cross-batch balance.\n\n### ComBat after RUV double-corrects\n\n**Trigger:** Applying multiple corrections sequentially.\n**Mechanism:** Both methods remove variance; sequential application removes biology twice.\n**Symptom:** All signal gone; counts look uniformly noisy.\n**Fix:** Pick one method based on diagnostic; never combine.\n\n### Per-batch sample size too small\n\n**Trigger:** 2 replicates per batch with 3 batches; ComBat estimates batch shift from 2 samples.\n**Mechanism:** Insufficient data to estimate batch parameters; high-variance estimates.\n**Symptom:** Correction makes some batches worse than uncorrected.\n**Fix:** Need ≥3 (preferably 4-6) samples per batch; below this, use covariate modeling instead.\n\n## Quantitative Thresholds\n\n| Threshold | Value | Source \u002F Rationale |\n|-----------|-------|--------------------|\n| PC1 batch F vs condition F | F_batch > 10x F_cond -> apply correction | Standard variance-decomposition diagnostic |\n| ComBat min samples per batch | ≥3, ideally 4-6 | Empirical Bayes prior estimation |\n| RUV `k` (unwanted factors) | k=1 default; k=2 if multiple known batch sources | Risso 2014; cross-validate |\n| NTCs needed for NTC-anchored norm | ≥500 in library | Stable median |\n| Post-correction PCA check | Batches must overlap in PC1\u002FPC2 plot | Visual sanity check |\n| Post-correction PR-AUC | Should be same or higher than pre | If lower, correction destroyed biology |\n\n## Common Errors\n\n| Error \u002F symptom | Cause | Solution |\n|-----------------|-------|----------|\n| PR-AUC drops after ComBat | Batch confounded with condition | Add `mod` covariate; or redesign |\n| MAGeCK MLE NaN beta after adding batch column | Collinear design matrix | Drop collinear column |\n| Replicates still cluster by batch after RUV | k too low | Increase k; cross-validate |\n| Replicates lose internal cohesion after correction | Over-correction | Reduce k or revert |\n| NTC-anchored norm worse than median | Too few NTCs | Use median; add NTCs to next library |\n| Sequencing-run-level batch survives ComBat | Non-linear sequencing effect | Pre-normalize with `mageck count --norm-method control` first |\n\n## References\n\n- Johnson WE et al. 2007. *Biostatistics* 8:118. Original ComBat algorithm.\n- Leek JT et al. 2012. *Bioinformatics* 28:882. SVA package.\n- Risso D et al. 2014. *Nat Biotechnol* 32:896. RUVSeq.\n- Pacini C et al. 2021. *Nat Commun* 12:1661. Integrated cross-study dependencies; cross-screen batch-effect correction.\n- Vinceti A et al. 2024. *Genome Biol* 25:192. Benchmark of methods for correcting biases in CRISPR-Cas9 screening data.\n\n## Related Skills\n\n- crispr-screens\u002Fmageck-analysis - MAGeCK MLE with explicit batch covariates\n- crispr-screens\u002Fscreen-qc - Pre-correction PCA diagnostic\n- crispr-screens\u002Fcopy-number-correction - Chronos handles batch + CN jointly\n- crispr-screens\u002Flibrary-design - NTC composition for NTC-anchored normalization\n- crispr-screens\u002Fjacks-analysis - Joint analysis across batches with shared efficacy\n- crispr-screens\u002Fhit-calling - Post-correction hit calling\n- crispr-screens\u002Fin-vivo-screens - In-vivo-specific batch sources (animal cohort, tissue prep)\n","## Version Compatibility\n\nReference examples tested with: pyComBat 0.3.3+ (epigenelabs\u002FpyComBat), MAGeCK 0.5.9+, R\u002Flimma 3.58+, sva 3.50+, RUVSeq 1.36+, pandas 2.2+, numpy 1.26+, scikit-learn 1.4+, scipy 1.12+.\n\nBefore using code patterns, verify installed versions match. If versions differ:\n- Python: `pip show combat`; `from combat.pycombat import pycombat`\n- R: `packageVersion('sva')`; `?ComBat`; `packageVersion('RUVSeq')`; `?RUVg`\n\nIf code throws ImportError, AttributeError, or TypeError, introspect the installed package and adapt the example to match the actual API rather than retrying.\n\n## Batch Correction for CRISPR Screens\n\n**\"Correct batch effects in my CRISPR screens\"** -> Diagnose the batch source, decide whether to remove via empirical-Bayes (ComBat), explicit covariate modeling (MAGeCK MLE \u002F Chronos design matrix), control-guide-anchored normalization, or unwanted-variation decomposition (RUV, SVA), then apply only the correction that preserves biological condition signal.\n\n- Python: `pyComBat.pycombat` for empirical-Bayes correction\n- Python: explicit batch covariates in `mageck mle --design-matrix`\n- R: `sva::ComBat`, `RUVSeq::RUVg`, `limma::removeBatchEffect`\n- Python: Chronos (`crispr_chronos`) natively handles screen-batch covariates\n\n## Batch Sources in CRISPR Screens\n\n| Source | Mechanism | Detectable by |\n|--------|-----------|---------------|\n| Library lot | Different aliquots or PCR amplifications | Gini shift; plasmid-pool sequencing |\n| Cell passage cohort | Cells passaged through different periods | PCA Day-0 samples clustering by passage |\n| Infection day | Lentivirus titer drifts; FBS lot changes | PCA Day-0 samples cluster by day |\n| Cas9 enzyme lot | Cas9 expression heterogeneity | PR-AUC drift across screens |\n| Sequencing run | Lane bias, flowcell variant, machine | Per-sample read-count distribution |\n| FBS \u002F culture lot | Fetal bovine serum lot variations confound proliferation | Day-0 vs endpoint differential not present in vehicle |\n| Tissue-prep batch | In-vivo: animal cohort, surgical day, organ-prep tech | In-vivo screens (see [[in-vivo-screens]]) |\n\n**Critical:** Batch effects in CRISPR screens often correlate with biology (e.g., the drug arm was processed in batch 2 because that's when the drug arrived). This confounds correction. Always check for confounding before applying ComBat.\n\n## Batch Effect Decision Tree\n\n| Diagnostic finding | Recommended correction |\n|--------------------|------------------------|\n| PCA shows samples cluster by condition, not batch | No correction needed; biology dominates |\n| PCA PC1 separates batches, PC2 separates conditions | Apply ComBat with condition as biological_covariate |\n| Batch fully confounded with condition (e.g. all drug in batch 2, all vehicle in batch 1) | Correction will destroy biology; instead redesign next screen with cross-batch balance OR re-analyze with batch in MAGeCK MLE design matrix |\n| Day-0 (pre-perturbation) samples cluster by batch | Strong batch effect; ComBat needed |\n| Endpoint samples cluster by batch but not Day-0 | Selection-driven artifact (FBS lot etc); correct or include batch as covariate |\n| Replicates within a batch are tight; across-batch much wider | Classic batch effect; ComBat |\n| Each replicate scatters randomly across PCs | Sample-level noise; no batch correction will help |\n| Cancer-line panel with multiple batches | Use Chronos (built-in batch modeling) |\n\n## Diagnose: PCA + Variance Decomposition\n\n**Goal:** Quantify what fraction of variance is batch vs condition before correcting.\n\n**Approach:** Run PCA on log10(counts+1); fit ANOVA decomposing variance into batch and condition components; report variance explained.\n\n```python\nimport pandas as pd\nimport numpy as np\nfrom sklearn.decomposition import PCA\nfrom scipy import stats\n\ndef batch_diagnostic(counts_df, metadata_df, batch_col='batch', condition_col='condition'):\n    '''Variance decomposition: report fraction of PC1\u002FPC2 variance attributable to batch vs condition.'''\n    log_counts = np.log10(counts_df + 1).T  # samples as rows\n    pca = PCA(n_components=5)\n    pcs = pca.fit_transform(log_counts)\n    out = pd.DataFrame({\n        'PC': range(1, 6),\n        'var_explained': pca.explained_variance_ratio_,\n    })\n    pc_df = pd.DataFrame(pcs, columns=[f'PC{i+1}' for i in range(5)], index=counts_df.columns).join(metadata_df)\n    for i in range(5):\n        pc = pc_df[f'PC{i+1}']\n        f_b, p_b = stats.f_oneway(*[pc[pc_df[batch_col] == b] for b in pc_df[batch_col].unique()])\n        f_c, p_c = stats.f_oneway(*[pc[pc_df[condition_col] == c] for c in pc_df[condition_col].unique()])\n        out.loc[i, 'batch_F'] = f_b\n        out.loc[i, 'batch_p'] = p_b\n        out.loc[i, 'cond_F'] = f_c\n        out.loc[i, 'cond_p'] = p_c\n    return out\n```\n\n**Interpretation:** If PC1 has batch F-stat > condition F-stat by 10x, batch is dominating and correction is warranted. If condition dominates PC1, no correction needed.\n\n## ComBat Empirical-Bayes Correction\n\n**Goal:** Remove batch-specific location and scale shifts while preserving biological condition signal.\n\n**Approach:** Log-transform counts, fit ComBat with explicit `biological_covariate` indicating condition (so the model knows which signal to preserve), back-transform.\n\n```python\nimport numpy as np\nfrom combat.pycombat import pycombat\n\ndef combat_correct(counts_df, batch_vector, condition_vector=None):\n    '''ComBat on log-counts with optional biological covariate (condition).\n    Preserves condition signal while removing batch shifts.'''\n    data = np.log2(counts_df.values + 1)\n    if condition_vector is not None:\n        mod = pd.get_dummies(condition_vector).values.astype(float)\n        corrected = pycombat(data, list(batch_vector), mod=mod)      # data must be a DataFrame\n    else:\n        corrected = pycombat(data, list(batch_vector))               # data must be a DataFrame\n    return pd.DataFrame(np.power(2, corrected) - 1,\n                         index=counts_df.index, columns=counts_df.columns).clip(lower=0)\n```\n\n**Critical caveat:** ComBat assumes batch effects are linear shifts of mean and variance in log space. Non-linear effects (e.g., gene-specific batch sensitivity) remain. Always re-check PCA after correction to confirm batches now overlap.\n\n## RUV (Remove Unwanted Variation)\n\n**Goal:** Identify hidden batch sources via control sgRNAs whose true signal is known.\n\n**Approach:** Designate non-targeting controls as \"negative controls\" (assumed unchanged); RUV decomposes their variance into unwanted factors, then subtracts these from all data.\n\n```r\nlibrary(RUVSeq)\n# counts_df: rows = sgRNAs, columns = samples\nntc_indices \u003C- which(rownames(counts_df) %in% ntc_sgrna_names)\nseqset \u003C- newSeqExpressionSet(counts = as.matrix(counts_df))\nruv_corrected \u003C- RUVg(seqset, cIdx = ntc_indices, k = 2)  # k = 2 unwanted factors\n# Access corrected data\ncorrected_counts \u003C- normCounts(ruv_corrected)\n```\n\n**When to use:** RUV preferred over ComBat when batches are not annotated (e.g., unknown technical confounders). Worse than ComBat when batch is known and well-annotated; ComBat is more direct.\n\n## SVA (Surrogate Variable Analysis)\n\n**Goal:** Estimate unknown latent factors that may confound the screen.\n\n**Approach:** SVA computes surrogate variables that capture variance not explained by known biological factors; these can then be added to the MAGeCK MLE design matrix as covariates.\n\n```r\nlibrary(sva)\n# counts_df: rows = sgRNAs, columns = samples\nmod \u003C- model.matrix(~ condition, data = metadata)\nmod0 \u003C- model.matrix(~ 1, data = metadata)\nsv_obj \u003C- sva(as.matrix(counts_df), mod, mod0)\nn_sv \u003C- sv_obj$n.sv  # number of surrogate variables\n# Add to design matrix for MAGeCK MLE\ndesign_mat \u003C- cbind(mod, sv_obj$sv)\n```\n\n**Use case:** When the screen has clear biological signal (e.g. essentiality recovery passes) but small effect sizes are hidden by noise; SVA-discovered latent factors as covariates can recover them.\n\n## Batch as Explicit Covariate (Preferred for MAGeCK MLE \u002F Chronos)\n\n**Goal:** Model batch and biology in the same regression instead of pre-correcting.\n\n**Approach:** Add batch indicator columns to the MLE design matrix. The fitted beta for condition is the effect after accounting for batch; no pre-correction needed.\n\n```bash\n# Design matrix for a screen with 2 batches and 2 conditions\ncat > design.txt \u003C\u003CEOF\nSamples         baseline    batch2    treatment\nVeh_b1_r1       1           0         0\nVeh_b1_r2       1           0         0\nDrug_b1_r1      1           0         1\nDrug_b1_r2      1           0         1\nVeh_b2_r1       1           1         0\nVeh_b2_r2       1           1         0\nDrug_b2_r1      1           1         1\nDrug_b2_r2      1           1         1\nEOF\n\nmageck mle \\\n    --count-table counts.txt \\\n    --design-matrix design.txt \\\n    --output-prefix batch_aware_mle\n```\n\n**Why this is preferred:** ComBat shifts counts before testing; the MLE-with-covariates approach correctly propagates uncertainty from the batch term into the condition beta's standard error. ComBat-then-test pretends the corrected counts are noise-free, biasing FDR.\n\n## Control-Sgrna Anchored Normalization\n\n**Goal:** Use non-targeting controls as the per-sample reference so batch shifts cancel.\n\n**Approach:** Scale each sample so its NTC sgRNAs have a constant median. Subsequent fold changes are relative to NTCs in each sample, automatically batch-controlling.\n\n```python\ndef ntc_anchored_normalize(counts_df, ntc_sgrna_names, target_median=1000):\n    '''Scale each sample so its NTC median is target_median. Subsequent LFC is NTC-anchored.'''\n    is_ntc = counts_df.index.isin(ntc_sgrna_names)\n    ntc_medians = counts_df.loc[is_ntc].median(axis=0)\n    scale_factors = target_median \u002F ntc_medians.replace(0, np.nan)\n    return counts_df * scale_factors, scale_factors\n```\n\n**Critical:** Requires ≥500 NTCs in the library (see [[library-design]]). With fewer, the NTC median is unstable and amplifies noise rather than removing batch.\n\n## When NOT to Correct\n\n| Situation | Why correction hurts |\n|-----------|----------------------|\n| Batch is fully confounded with condition | Correction destroys biology along with batch; redesign or accept |\n| Batch effect is smaller than between-replicate noise | Correction adds noise without removing meaningful variance |\n| Replicates already correlate >0.95 within and across batches | No batch effect to correct |\n| Single-screen analysis | No \"batch\" to correct; only replicate noise |\n| Per-batch sample size \u003C3 | Cannot estimate batch shift reliably; correction is harmful |\n\n## Failure Modes\n\n### ComBat eliminates biological signal\n\n**Trigger:** Batch is correlated with condition (e.g., all drug-arm samples were processed week 2; all vehicle-arm samples week 1).\n**Mechanism:** ComBat without a `mod` covariate treats condition variance as batch variance; corrects it away.\n**Symptom:** PR-AUC against CEGv2 drops after ComBat correction.\n**Fix:** Always supply `mod` covariate matrix indicating condition; verify by comparing PR-AUC before and after.\n\n### RUV adds noise instead of removing it\n\n**Trigger:** k (number of unwanted factors) set too high.\n**Mechanism:** RUV's least-squares decomposition over-fits; \"removed\" variance includes biology.\n**Symptom:** Hits decrease and replicate Pearson drops after correction.\n**Fix:** Choose k via cross-validation; default k=1 or 2 for most screens.\n\n### Batch-aware MLE collinear design matrix\n\n**Trigger:** Adding a batch indicator that is fully collinear with another design column (e.g., all of batch 2 is also Day 21).\n**Mechanism:** MLE design matrix is singular; betas not estimable.\n**Symptom:** MAGeCK MLE errors out or produces NaN betas.\n**Fix:** Drop the collinear column; re-design experiment with cross-batch balance.\n\n### ComBat after RUV double-corrects\n\n**Trigger:** Applying multiple corrections sequentially.\n**Mechanism:** Both methods remove variance; sequential application removes biology twice.\n**Symptom:** All signal gone; counts look uniformly noisy.\n**Fix:** Pick one method based on diagnostic; never combine.\n\n### Per-batch sample size too small\n\n**Trigger:** 2 replicates per batch with 3 batches; ComBat estimates batch shift from 2 samples.\n**Mechanism:** Insufficient data to estimate batch parameters; high-variance estimates.\n**Symptom:** Correction makes some batches worse than uncorrected.\n**Fix:** Need ≥3 (preferably 4-6) samples per batch; below this, use covariate modeling instead.\n\n## Quantitative Thresholds\n\n| Threshold | Value | Source \u002F Rationale |\n|-----------|-------|--------------------|\n| PC1 batch F vs condition F | F_batch > 10x F_cond -> apply correction | Standard variance-decomposition diagnostic |\n| ComBat min samples per batch | ≥3, ideally 4-6 | Empirical Bayes prior estimation |\n| RUV `k` (unwanted factors) | k=1 default; k=2 if multiple known batch sources | Risso 2014; cross-validate |\n| NTCs needed for NTC-anchored norm | ≥500 in library | Stable median |\n| Post-correction PCA check | Batches must overlap in PC1\u002FPC2 plot | Visual sanity check |\n| Post-correction PR-AUC | Should be same or higher than pre | If lower, correction destroyed biology |\n\n## Common Errors\n\n| Error \u002F symptom | Cause | Solution |\n|-----------------|-------|----------|\n| PR-AUC drops after ComBat | Batch confounded with condition | Add `mod` covariate; or redesign |\n| MAGeCK MLE NaN beta after adding batch column | Collinear design matrix | Drop collinear column |\n| Replicates still cluster by batch after RUV | k too low | Increase k; cross-validate |\n| Replicates lose internal cohesion after correction | Over-correction | Reduce k or revert |\n| NTC-anchored norm worse than median | Too few NTCs | Use median; add NTCs to next library |\n| Sequencing-run-level batch survives ComBat | Non-linear sequencing effect | Pre-normalize with `mageck count --norm-method control` first |\n\n## References\n\n- Johnson WE et al. 2007. *Biostatistics* 8:118. Original ComBat algorithm.\n- Leek JT et al. 2012. *Bioinformatics* 28:882. SVA package.\n- Risso D et al. 2014. *Nat Biotechnol* 32:896. RUVSeq.\n- Pacini C et al. 2021. *Nat Commun* 12:1661. Integrated cross-study dependencies; cross-screen batch-effect correction.\n- Vinceti A et al. 2024. *Genome Biol* 25:192. Benchmark of methods for correcting biases in CRISPR-Cas9 screening data.\n\n## Related Skills\n\n- crispr-screens\u002Fmageck-analysis - MAGeCK MLE with explicit batch covariates\n- crispr-screens\u002Fscreen-qc - Pre-correction PCA diagnostic\n- crispr-screens\u002Fcopy-number-correction - Chronos handles batch + CN jointly\n- crispr-screens\u002Flibrary-design - NTC composition for NTC-anchored normalization\n- crispr-screens\u002Fjacks-analysis - Joint analysis across batches with shared efficacy\n- crispr-screens\u002Fhit-calling - Post-correction hit calling\n- crispr-screens\u002Fin-vivo-screens - In-vivo-specific batch sources (animal cohort, tissue prep)\n",{"name":5,"source":24,"license":15,"tool_type":25,"description":7,"imported_at":26,"source_path":27,"primary_tool":28,"source_repository":29},"https:\u002F\u002Fgithub.com\u002FGPTomics\u002FbioSkills","mixed","2026-09-20","crispr-screens\u002Fbatch-correction\u002FSKILL.md","pyComBat","GPTomics\u002FbioSkills","main","2d1750717747097b602acf30bd09a7cbd4b4c6ea","awesome_skills\u002Fbiology\u002Fbio-crispr-screens-batch-correction","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous","2026-11-09 11:45:36",{"source":8,"skillName":5,"commands":37,"prompt":47,"zipAvailable":48},[38,41,44],{"tool":39,"command":40},"npx","npx skills add Mr-Nobody-Anonymous\u002FAll-skills --skill bio-crispr-screens-batch-correction",{"tool":42,"command":43},"bunx","bunx skills add Mr-Nobody-Anonymous\u002FAll-skills --skill bio-crispr-screens-batch-correction",{"tool":45,"command":46},"pnpm","pnpm dlx skills add Mr-Nobody-Anonymous\u002FAll-skills --skill bio-crispr-screens-batch-correction","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-crispr-screens-batch-correction\u002FSKILL.md",true,[50,56],{"path":51,"resourceType":52,"resourceTypeDesc":53,"sizeBytes":54,"sourceHtmlUrl":55},"examples\u002Fbatch_correct.py","SCRIPT","脚本",6799,"https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-crispr-screens-batch-correction\u002Fexamples\u002Fbatch_correct.py",{"path":57,"resourceType":58,"resourceTypeDesc":59,"sizeBytes":60,"sourceHtmlUrl":61},"usage-guide.md","REFERENCE","参考文档",7183,"https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fbiology\u002Fbio-crispr-screens-batch-correction\u002Fusage-guide.md",[63,71,78,85,92,99],{"skillNo":64,"name":65,"nameZh":6,"description":66,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":67,"categories":68,"keywords":69,"publishedAt":70},"01M7FFFZPC2025JQQHPHDX154J","dei-assessment","Assess diversity, equity, and inclusion with metrics. TRIGGERS - Use when user needs help with dei-assessment related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fdei-assessment\u002FSKILL.md",[],[],"2026-11-16 10:05:34",{"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":70},"01M7FFFWN8H4WA7A6Y398QKB6J","dei-action-plan","Create DEI action plans with goals and initiatives. TRIGGERS - Use when user needs help with dei-action-plan related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fdei-action-plan\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":70},"01M7FFFSHTM0QZRVZ2NRJTJ0PY","culture-fit-assessment","Design culture add assessment processes. TRIGGERS - Use when user needs help with culture-fit-assessment related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fculture-fit-assessment\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":70},"01M7FFFMA12RKEQA38KHJSXXPS","cowork-to-code-bridge","Use an already-installed, independently verified cowork-to-code bridge to run narrowly approved actions on the user's own macOS, Linux, or WSL2 machine through a local file queue.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fcowork-to-code-bridge\u002FSKILL.md",[],[],{"skillNo":93,"name":94,"nameZh":6,"description":95,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":96,"categories":97,"keywords":98,"publishedAt":70},"01M7FFFH1F6M8YRGW5V487GH1K","counter-offer-response","Draft counter-offer responses for retention. TRIGGERS - Use when user needs help with counter-offer-response related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fcounter-offer-response\u002FSKILL.md",[],[],{"skillNo":100,"name":101,"nameZh":6,"description":102,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":103,"categories":104,"keywords":105,"publishedAt":70},"01M7FFFDGEHV8Y7J9N40HZXW52","continuous-feedback-system","Design continuous feedback systems. TRIGGERS - Use when user needs help with continuous-feedback-system related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fcontinuous-feedback-system\u002FSKILL.md",[],[]]