Normalize with frozen controls
Normalization changes the reference for a relative count comparison. The main analysis uses the 997 non-targeting guides that pass the day-14 DMSO count filter. Their identities remain fixed in every comparison, including the median-normalization sensitivity run.
Preserve the engine factors
Section titled “Preserve the engine factors”MAGeCK 0.5.9.5 calculates control normalization as its median normalization procedure restricted to the supplied controls. The preparation calls that same upstream function and checks its full precision factors against the actual engine log. The examples read those preserved factors rather than estimate factors from rounded report values.
The factor shown here multiplies an RRA input count. The pinned MLE reader adds one to each count before normalization, then uses the reciprocal of its own factor in the model. Its separate factors remain in the execution record. A positive guide log2 ratio means greater normalized representation in drug cultures. The descriptive ratio adds one after the culture mean; it is not a MAGeCK p-value.
The median sensitivity changes only the normalization reference. It uses the
same count rows, sample order, non-targeting list, and RRA permutation settings.
Keeping --control-sgrna matters because that argument also supplies the RRA
null distribution. Removing it would change two analysis choices at once.
library(ggplot2)library(jsonlite)dir.create("outputs", showWarnings = FALSE)counts <- read.delim("/fixtures/main_counts.tsv", check.names = FALSE)controls <- readLines("/fixtures/control_guides.txt")primary <- read.delim("/fixtures/rra_primary_normalization.tsv")median_norm <- read.delim("/fixtures/rra_median_normalization.tsv")samples <- names(counts)[-(1:2)]stopifnot(identical(primary$sample, samples))stopifnot(identical(median_norm$sample, samples))stopifnot(setequal(counts$sgRNA[counts$Gene == "Control"], controls))values <- as.matrix(counts[, samples])normalized <- sweep(values, 2, primary$count_multiplier, "*")median_values <- sweep(values, 2, median_norm$count_multiplier, "*")control_lfc <- log2((rowMeans(normalized[, 3:4]) + 1) / (rowMeans(normalized[, 1:2]) + 1))median_lfc <- log2((rowMeans(median_values[, 3:4]) + 1) / (rowMeans(median_values[, 1:2]) + 1))selected <- counts$sgRNA %in% controlssummary <- data.frame(sgRNA = counts$sgRNA[selected], control_lfc = control_lfc[selected], median_lfc = median_lfc[selected])write.table(summary, "outputs/summary_r.tsv", sep = "\t", quote = FALSE, row.names = FALSE)metrics <- list(controls = nrow(summary), control_center = median(summary$control_lfc), median_center = median(summary$median_lfc), factor_difference = max(abs(primary$count_multiplier - median_norm$count_multiplier)))write_json(metrics, "outputs/metrics_r.json", auto_unbox = TRUE, digits = 16)cat(sprintf("Frozen non-targeting guides: %d\n", nrow(summary)))cat(sprintf("Control-normalized median log2 ratio: %.6f\n", metrics$control_center))cat(sprintf("Median-normalized median log2 ratio: %.6f\n", metrics$median_center))print(data.frame(sample = samples, control = primary$count_multiplier, median = median_norm$count_multiplier), row.names = FALSE)plot_data <- data.frame( method = rep(c("Control", "Median"), each = nrow(summary)), log2_ratio = c(summary$control_lfc, summary$median_lfc))figure <- ggplot(plot_data, aes(method, log2_ratio, fill = method)) + geom_violin(alpha = 0.5) + geom_boxplot(width = 0.15, outlier.shape = NA) + geom_hline(yintercept = 0, linetype = 2) + theme_bw(base_size = 12) + guides(fill = "none") + labs(x = "Normalization reference", y = "Control guide log2 drug/DMSO")ggsave("outputs/control_distribution_r.png", figure, width = 6.6, height = 4.6, dpi = 160)Frozen non-targeting guides: 997Control-normalized median log2 ratio: 0.034103Median-normalized median log2 ratio: -0.299888 sample control median C1D14 0.6864403 0.7646623 C2D14 0.7430563 0.8120529 P1D14 1.3128881 1.1523092 P2D14 1.4942026 1.3057843
import jsonfrom pathlib import Path
import matplotlib.pyplot as pltimport numpy as npimport pandas as pd
output = Path("outputs")output.mkdir(exist_ok=True)counts = pd.read_csv("/fixtures/main_counts.tsv", sep="\t")controls = set(Path("/fixtures/control_guides.txt").read_text().splitlines())primary = pd.read_csv("/fixtures/rra_primary_normalization.tsv", sep="\t")median_norm = pd.read_csv("/fixtures/rra_median_normalization.tsv", sep="\t")samples = counts.columns[2:].tolist()assert primary["sample"].tolist() == samplesassert median_norm["sample"].tolist() == samplesassert set(counts.loc[counts["Gene"].eq("Control"), "sgRNA"]) == controlsvalues = counts[samples].to_numpy()normalized = values * primary["count_multiplier"].to_numpy()median_values = values * median_norm["count_multiplier"].to_numpy()control_lfc = np.log2((normalized[:, 2:].mean(1) + 1) / (normalized[:, :2].mean(1) + 1))median_lfc = np.log2((median_values[:, 2:].mean(1) + 1) / (median_values[:, :2].mean(1) + 1))selected = counts["sgRNA"].isin(controls)summary = pd.DataFrame({"sgRNA": counts.loc[selected, "sgRNA"], "control_lfc": control_lfc[selected], "median_lfc": median_lfc[selected]})summary = summary.reset_index(drop=True)reference = pd.read_csv(output / "summary_r.tsv", sep="\t")pd.testing.assert_frame_equal(summary, reference, atol=1e-8, rtol=0)summary.to_csv(output / "summary_python.tsv", sep="\t", index=False)metrics = {"controls": len(summary), "control_center": float(summary["control_lfc"].median()), "median_center": float(summary["median_lfc"].median()), "factor_difference": float(np.max(np.abs( primary["count_multiplier"] - median_norm["count_multiplier"] )))}(output / "metrics_python.json").write_text(json.dumps(metrics))print(f"Frozen non-targeting guides: {len(summary)}")print(f"Control-normalized median log2 ratio: {metrics['control_center']:.6f}")print(f"Median-normalized median log2 ratio: {metrics['median_center']:.6f}")print(pd.DataFrame({"sample": samples, "control": primary["count_multiplier"], "median": median_norm["count_multiplier"]}).to_string( index=False, float_format="%.6f"))fig, ax = plt.subplots(figsize=(6.6, 4.6))ax.violinplot([summary["control_lfc"], summary["median_lfc"]], showmedians=True)ax.axhline(0, linestyle="--", color="gray")ax.set_xticks([1, 2], ["Control", "Median"])ax.set(xlabel="Normalization reference", ylabel="Control guide log2 drug/DMSO")fig.tight_layout()fig.savefig(output / "control_distribution_python.png", dpi=160)plt.close(fig)Frozen non-targeting guides: 997Control-normalized median log2 ratio: 0.034103Median-normalized median log2 ratio: -0.299888sample control median C1D14 0.686440 0.764662 C2D14 0.743056 0.812053 P1D14 1.312888 1.152309 P2D14 1.494203 1.305784
The same 997 guides estimate the control factors and supply the displayed control distribution, so normalization partly imposes its near-zero center. The plot checks the transformation and cannot independently establish that the reference is appropriate. It also cannot prove that drug treatment leaves every control culture biologically unchanged. The MAGeCK lesson keeps the primary discovery family separate from its method comparison.
Further reading
Section titled “Further reading”The MAGeCK 0.5.9.5 source archive contains mageckCountNorm.py and mleinstanceio.py. The first defines the normalization factors; the second adds one to counts for the MLE reader. These files explain why the RRA and MLE factors require separate checks in this example.