Compare MAGeCK RRA and MLE
RRA enrichment defines the primary discovery list. MLE provides a separate method comparison on the same filtered day-14 counts. The examples read fresh outputs from the execution record, verify the complete non-control gene family, and calculate their own Benjamini-Hochberg corrections.
Understand what the methods combine
Section titled “Understand what the methods combine”MAGeCK RRA first uses a negative binomial model to test guide abundance changes. It ranks guides by that evidence and combines their ranks within genes. Its alpha threshold limits which ranked guides contribute to the aggregation. A small aggregation score indicates unusually strong ranks under the selected null; it is not a fold change.
MAGeCK MLE models guide counts with a negative binomial distribution and an explicit design matrix. Guide baseline terms and a shared gene coefficient connect each guide to the drug comparison. The pinned reader adds one to counts before normalization, so its stored size factors differ from the RRA factors. Neither approach creates independent culture replication from the guides targeting one gene.
This run explicitly retains --genes-varmodeling 0. In the pinned source,
that setting uses dispersion 0.01 instead of fitting a mean-variance trend.
The run also leaves iterative efficiency updates and outlier removal disabled.
Its Wald findings depend on these assumptions, which is another reason to keep
the MLE comparison separate from the primary discoveries.
Use the intended columns and tails
Section titled “Use the intended columns and tails”The MAGeCK output specification
distinguishes scores, effect estimates, and p-values. pos|p-value is the RRA
enrichment test. drug|wald-p-value is the MLE two-sided Wald test of the drug
coefficient against zero. MLE drug|p-value contains the permutation result,
which remains a separate field.
The pinned source computes the Wald probability as twice the upper normal
tail at the absolute z-score. The examples verify that relation with a tolerance
for the z-score precision printed by MAGeCK. That tolerance differs from the
1e-8 agreement required between R and Python summaries.
RRA adjusts a native universe that includes the control aggregate before
suppressing that aggregate from its output. This tutorial instead corrects the
complete reported non-control family and preserves pos|fdr for comparison.
Native FDR values also have limited printed precision. The execution record
checks the logged universe and bounds the unreported control probability
between zero and one. It allows 1e-4 for the printed probability and FDR
precision. The declared correction uses the reported non-control p-values
directly and does not require that hidden control probability.
The primary decision is rra_enrichment_bh <= 0.05. The MLE comparison requires
mle_wald_bh <= 0.05 and a positive drug beta. It cannot add a gene to the
primary list. The RRA gene log2 fold change and the MLE beta have different
scales, so the plot compares directions and ranks without requiring equality.
library(ggplot2)library(jsonlite)dir.create("outputs", showWarnings = FALSE)rra <- read.delim(gzfile("/fixtures/rra_primary_genes.tsv.gz"), check.names = FALSE)mle <- read.delim(gzfile("/fixtures/mle_genes.tsv.gz"), check.names = FALSE)counts <- read.delim("/fixtures/main_counts.tsv", check.names = FALSE)family <- sort(unique(counts$Gene[counts$Gene != "Control"]), method = "radix")stopifnot(setequal(rra$id, family), setequal(mle$Gene, family))stopifnot(!anyDuplicated(rra$id), !anyDuplicated(mle$Gene))rra <- rra[match(family, rra$id), ]mle <- mle[match(family, mle$Gene), ]p <- rra[["pos|p-value"]]w <- mle[["drug|wald-p-value"]]stopifnot(all(is.finite(p)), all(p >= 0 & p <= 1))stopifnot(all(is.finite(w)), all(w >= 0 & w <= 1))wald_error <- max(abs(2 * pnorm(-abs(mle[["drug|z"]])) - w))stopifnot(wald_error <= 5e-5)summary <- data.frame( gene = family, rra_lfc = rra[["pos|lfc"]], mle_beta = mle[["drug|beta"]], rra_enrichment_bh = p.adjust(p, "BH"), mle_wald_bh = p.adjust(w, "BH"))summary$rra_hit <- as.integer(summary$rra_enrichment_bh <= 0.05)summary$mle_hit <- as.integer(summary$mle_wald_bh <= 0.05 & summary$mle_beta > 0)write.table(summary, "outputs/summary_r.tsv", sep = "\t", quote = FALSE, row.names = FALSE)metrics <- list(genes = nrow(summary), rra_hits = sum(summary$rra_hit), mle_hits = sum(summary$mle_hit), shared_hits = sum(summary$rra_hit * summary$mle_hit), rank_agreement = cor(summary$rra_lfc, summary$mle_beta, method = "spearman"), wald_error = wald_error)write_json(metrics, "outputs/metrics_r.json", auto_unbox = TRUE, digits = 16)cat(sprintf("Complete non-control family: %d genes\n", metrics$genes))cat(sprintf("Primary RRA discoveries: %d\n", metrics$rra_hits))cat(sprintf("Positive MLE Wald comparison findings: %d\n", metrics$mle_hits))cat(sprintf("Shared findings: %d; effect rank correlation: %.6f\n", metrics$shared_hits, metrics$rank_agreement))cat(sprintf("Printed Wald tail maximum error: %.8f\n", wald_error))figure <- ggplot(summary, aes(rra_lfc, mle_beta, color = factor(rra_hit))) + geom_point(alpha = 0.35, size = 0.7) + geom_hline(yintercept = 0, color = "gray") + geom_vline(xintercept = 0, color = "gray") + theme_bw(base_size = 12) + scale_color_manual(values = c("#87969D", "#BA4A00"), labels = c("Other", "Primary discovery")) + labs(x = "RRA gene log2 fold change", y = "MLE drug beta", color = NULL)ggsave("outputs/method_comparison_r.png", figure, width = 7, height = 5, dpi = 160)Complete non-control family: 19111 genesPrimary RRA discoveries: 28Positive MLE Wald comparison findings: 0Shared findings: 0; effect rank correlation: 0.901472Printed Wald tail maximum error: 0.00002697
import jsonfrom pathlib import Path
import matplotlib.pyplot as pltimport numpy as npimport pandas as pdfrom scipy.stats import norm, spearmanrfrom statsmodels.stats.multitest import multipletests
output = Path("outputs")output.mkdir(exist_ok=True)
rra = pd.read_csv("/fixtures/rra_primary_genes.tsv.gz", sep="\t")mle = pd.read_csv("/fixtures/mle_genes.tsv.gz", sep="\t")counts = pd.read_csv("/fixtures/main_counts.tsv", sep="\t")family = sorted(set(counts.loc[counts["Gene"].ne("Control"), "Gene"]))assert set(rra["id"]) == set(family) == set(mle["Gene"])assert rra["id"].is_unique and mle["Gene"].is_uniquerra = rra.set_index("id").loc[family]mle = mle.set_index("Gene").loc[family]p = rra["pos|p-value"].to_numpy()w = mle["drug|wald-p-value"].to_numpy()assert np.isfinite(p).all() and ((p >= 0) & (p <= 1)).all()assert np.isfinite(w).all() and ((w >= 0) & (w <= 1)).all()wald_error = float(np.max(np.abs(2 * norm.sf(np.abs(mle["drug|z"])) - w)))assert wald_error <= 5e-5summary = pd.DataFrame({ "gene": family, "rra_lfc": rra["pos|lfc"].to_numpy(), "mle_beta": mle["drug|beta"].to_numpy(), "rra_enrichment_bh": multipletests(p, method="fdr_bh")[1], "mle_wald_bh": multipletests(w, method="fdr_bh")[1],})summary["rra_hit"] = summary["rra_enrichment_bh"].le(0.05).astype(int)summary["mle_hit"] = (summary["mle_wald_bh"].le(0.05) & summary["mle_beta"].gt(0)).astype(int)reference = pd.read_csv(output / "summary_r.tsv", sep="\t")pd.testing.assert_frame_equal(summary, reference, check_dtype=False, atol=1e-8, rtol=0)summary.to_csv(output / "summary_python.tsv", sep="\t", index=False)metrics = {"genes": len(summary), "rra_hits": int(summary["rra_hit"].sum()), "mle_hits": int(summary["mle_hit"].sum()), "shared_hits": int((summary["rra_hit"] * summary["mle_hit"]).sum()), "rank_agreement": float(spearmanr(summary["rra_lfc"], summary["mle_beta"]).statistic), "wald_error": wald_error}(output / "metrics_python.json").write_text(json.dumps(metrics))print(f"Complete non-control family: {len(summary)} genes")print(f"Primary RRA discoveries: {metrics['rra_hits']}")print(f"Positive MLE Wald comparison findings: {metrics['mle_hits']}")print(f"Shared findings: {metrics['shared_hits']}; " f"effect rank correlation: {metrics['rank_agreement']:.6f}")print(f"Printed Wald tail maximum error: {wald_error:.8f}")fig, ax = plt.subplots(figsize=(7, 5))for flag, label, color in [(0, "Other", "#87969D"), (1, "Primary discovery", "#BA4A00")]: selected = summary.loc[summary["rra_hit"].eq(flag)] ax.scatter(selected["rra_lfc"], selected["mle_beta"], s=4, alpha=0.35, color=color, label=label)ax.axhline(0, color="gray", linewidth=0.7)ax.axvline(0, color="gray", linewidth=0.7)ax.set(xlabel="RRA gene log2 fold change", ylabel="MLE drug beta")ax.legend()fig.tight_layout()fig.savefig(output / "method_comparison_python.png", dpi=160)plt.close(fig)Complete non-control family: 19111 genesPrimary RRA discoveries: 28Positive MLE Wald comparison findings: 0Shared findings: 0; effect rank correlation: 0.901472Printed Wald tail maximum error: 0.00002697
The locked MLE comparison produces no positive Wald findings at its declared threshold. Its effect estimates still support a comparison of directions and ranks, but they do not validate the RRA discoveries.
A disagreement between methods is evidence to inspect, not a reason to take the union of their discovery lists. The guide effect lesson returns to the individual counts behind selected RRA ranks.
Further reading
Section titled “Further reading”The MAGeCK output specification defines the RRA and MLE columns, including the separate permutation and Wald probabilities. The MAGeCK 0.5.9.5 source archive contains the normalization and count-reader implementations. Consult the pinned files when you compare engine factors with the values retained by the execution record.