Inspect guide and gene effects
A gene rank compresses several guide measurements into one result. This lesson returns to normalized guide counts for the first six genes in the primary RRA enrichment ranking. The selection rule is fixed in the code, so the plot does not replace a discordant guide with a more favorable example.
Keep guide coverage visible
Section titled “Keep guide coverage visible”The complete library has unequal coverage for a small number of genes, and the comparator count filter removes more guides. A four-guide gene and a one-guide gene do not provide the same evidence about consistency. Both examples report the full retained coverage distribution before plotting the selected genes.
The plotted guide effect is log2 of the drug culture mean plus one divided by the DMSO culture mean plus one, after the preserved control normalization. This descriptive effect has an explicit pseudocount. It is not the RRA score, the MLE beta, or a measure of absolute growth.
The examples also list each selected gene’s native RRA rank. A rank does not supply a discovery threshold; the complete-family correction in the MAGeCK lesson supplies that decision.
library(ggplot2)library(jsonlite)dir.create("outputs", showWarnings = FALSE)counts <- read.delim("/fixtures/main_counts.tsv", check.names = FALSE)factors <- read.delim("/fixtures/rra_primary_normalization.tsv")rra <- read.delim(gzfile("/fixtures/rra_primary_genes.tsv.gz"), check.names = FALSE)selected_genes <- head(rra$id[order(rra[["pos|rank"]])], 6)values <- as.matrix(counts[, factors$sample])normalized <- sweep(values, 2, factors$count_multiplier, "*")keep <- counts$Gene %in% selected_genessummary <- data.frame( gene = counts$Gene[keep], sgRNA = counts$sgRNA[keep], dmso_mean = rowMeans(normalized[keep, 1:2]), drug_mean = rowMeans(normalized[keep, 3:4]))summary$log2_ratio <- log2((summary$drug_mean + 1) / (summary$dmso_mean + 1))summary$rra_rank <- rra[["pos|rank"]][match(summary$gene, rra$id)]summary$guide_index <- ave(seq_len(nrow(summary)), summary$gene, FUN = seq_along)coverage <- table(counts$Gene[counts$Gene != "Control"])coverage_table <- as.data.frame(table(as.integer(coverage)))names(coverage_table) <- c("retained_guides", "genes")coverage_table$retained_guides <- as.integer( as.character(coverage_table$retained_guides))write.table(summary, "outputs/summary_r.tsv", sep = "\t", quote = FALSE, row.names = FALSE)write.table(coverage_table, "outputs/coverage_r.tsv", sep = "\t", quote = FALSE, row.names = FALSE)metrics <- list(genes = length(coverage), targeting_guides = sum(coverage), single_guide_genes = sum(coverage == 1), selected_guides = nrow(summary), selected_mean_effect = mean(summary$log2_ratio))write_json(metrics, "outputs/metrics_r.json", auto_unbox = TRUE, digits = 16)print(coverage_table, row.names = FALSE)cat("Selected genes follow the first six primary RRA enrichment ranks.\n")print(unique(summary[, c("gene", "rra_rank")]), row.names = FALSE)figure <- ggplot(summary, aes(guide_index, log2_ratio)) + geom_hline(yintercept = 0, color = "gray") + geom_point(color = "#176B87", size = 2.5) + facet_wrap(~gene, ncol = 3) + theme_bw(base_size = 12) + scale_x_continuous(breaks = 1:4) + labs(x = "Retained guide index", y = "Descriptive log2 drug/DMSO")ggsave("outputs/guide_effects_r.png", figure, width = 8, height = 5, dpi = 160) retained_guides genes 1 28 2 138 3 1141 4 17804Selected genes follow the first six primary RRA enrichment ranks. gene rra_rank CCDC101 1 MED12 6 NF2 5 SUPT20H 3 TADA2B 4 TAF6L 2
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")factors = pd.read_csv("/fixtures/rra_primary_normalization.tsv", sep="\t")rra = pd.read_csv("/fixtures/rra_primary_genes.tsv.gz", sep="\t")selected_genes = rra.sort_values("pos|rank")["id"].head(6).tolist()values = counts[factors["sample"]].to_numpy()normalized = values * factors["count_multiplier"].to_numpy()keep = counts["Gene"].isin(selected_genes)summary = pd.DataFrame({ "gene": counts.loc[keep, "Gene"].to_numpy(), "sgRNA": counts.loc[keep, "sgRNA"].to_numpy(), "dmso_mean": normalized[keep, :2].mean(1), "drug_mean": normalized[keep, 2:].mean(1),})summary["log2_ratio"] = np.log2((summary["drug_mean"] + 1) / (summary["dmso_mean"] + 1))summary["rra_rank"] = summary["gene"].map(rra.set_index("id")["pos|rank"])summary["guide_index"] = summary.groupby("gene").cumcount() + 1coverage = counts.loc[counts["Gene"].ne("Control"), "Gene"].value_counts()coverage_table = coverage.value_counts().sort_index().rename_axis( "retained_guides").reset_index(name="genes")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)reference = pd.read_csv(output / "coverage_r.tsv", sep="\t")pd.testing.assert_frame_equal(coverage_table, reference, check_dtype=False, check_exact=True)summary.to_csv(output / "summary_python.tsv", sep="\t", index=False)coverage_table.to_csv(output / "coverage_python.tsv", sep="\t", index=False)metrics = {"genes": len(coverage), "targeting_guides": int(coverage.sum()), "single_guide_genes": int(coverage.eq(1).sum()), "selected_guides": len(summary), "selected_mean_effect": float(summary["log2_ratio"].mean())}(output / "metrics_python.json").write_text(json.dumps(metrics))print(coverage_table.to_string(index=False))print("Selected genes follow the first six primary RRA enrichment ranks.")print(summary[["gene", "rra_rank"]].drop_duplicates().to_string(index=False))fig, axes = plt.subplots(2, 3, figsize=(8, 5), sharex=True, sharey=True)for ax, gene in zip(axes.flat, sorted(selected_genes)): selected = summary.loc[summary["gene"].eq(gene)] ax.axhline(0, color="gray", linewidth=0.7) ax.scatter(selected["guide_index"], selected["log2_ratio"], color="#176B87") ax.set(title=gene, xticks=range(1, 5))fig.supxlabel("Retained guide index")fig.supylabel("Descriptive log2 drug/DMSO")fig.tight_layout()fig.savefig(output / "guide_effects_python.png", dpi=160)plt.close(fig) retained_guides genes 1 28 2 138 3 1141 4 17804Selected genes follow the first six primary RRA enrichment ranks. gene rra_rankCCDC101 1 MED12 6 NF2 5SUPT20H 3 TADA2B 4 TAF6L 2
The plot describes within-gene agreement after the declared count filter. A candidate still needs independent perturbation and phenotype validation. The sensitivity lesson asks whether analysis choices or collection time change the result set.
Further reading
Section titled “Further reading”The MAGeCK output specification distinguishes gene ranks, effect estimates, p-values, and false discovery rates. Use those field definitions when you compare the guide log ratios with the native RRA ranking. Goh and colleagues’ study supplies the experimental context for the source screen.