# A fixed mitochondrial cutoff can delete a cell type # https://pseudocount.com/posts/fixed-mitochondrial-cutoff/ # # The R code of the post, in the order the page runs it. Run it top to bottom in a fresh # R session. Commented-out blocks are shown on the page but not run there. The package # versions behind the numbers on the page are listed at the end of the post. ## ---- setup ---- suppressPackageStartupMessages({ library(scuttle) # attaches SingleCellExperiment as well library(ggplot2) }) stopifnot(packageVersion("scuttle") >= "1.12.0", packageVersion("SingleCellExperiment") >= "1.24.0", packageVersion("ggplot2") >= "3.4.0") fmt_pct <- function(x, d = 0) sprintf(paste0("%.", d, "f%%"), 100 * x) fmt_int <- function(x) formatC(round(x), format = "d", big.mark = ",") fmt_num <- function(x, d = 1) sprintf(paste0("%.", d, "f"), x) fmt_mt <- function(x, d = 1) sprintf(paste0("%.", d, "f%%"), x) # x already in percent fmt_prng <- function(v, d = 1) paste(fmt_pct(min(v), d), "to", fmt_pct(max(v), d)) fmt_mrng <- function(v, d = 1) paste(fmt_mt(min(v), d), "to", fmt_mt(max(v), d)) violet <- "#5a3fc0"; magenta <- "#d14fa6"; grey <- "#8a8799" theme_set(theme_minimal(base_size = 12) + theme(panel.grid.minor = element_blank(), plot.background = element_rect(fill = "white", colour = "white"), strip.text = element_text(face = "bold"))) ## ---- run-first: the page runs simulate, filters, replicate, scenario-majority, scenario-sample, scenario-cluster here ---- ## ---- simulate ---- types <- c("T cell", "macrophage", "hepatocyte") share <- c(0.55, 0.25, 0.20) # expected share of each type among healthy cells mito0 <- c(0.03, 0.05, 0.15) # healthy median mitochondrial fraction lib0 <- c(4000, 5000, 6000) # healthy median UMIs per cell names(share) <- names(mito0) <- names(lib0) <- types logit <- function(p) log(p / (1 - p)) expit <- function(x) 1 / (1 + exp(-x)) sim_qc <- function(n_samples = 4, n_cells = 1500, p_dam = rep(0.10, n_samples), shares = share, sd_sample = 0.25, sd_cell = 0.35, sd_lib = 0.45, dam_mito = 2.5, sd_dam_mito = 0.6, dam_lib = -1.4, sd_dam_lib = 0.4) { do.call(rbind, lapply(seq_len(n_samples), function(s) { type <- sample(types, n_cells, replace = TRUE, prob = shares) damaged <- runif(n_cells) < p_dam[s] shift <- rnorm(1, 0, sd_sample) # sample-level baseline shift lib <- round(lib0[type] * exp(rnorm(n_cells, 0, sd_lib) + damaged * rnorm(n_cells, dam_lib, sd_dam_lib))) eta <- logit(mito0[type]) + shift + rnorm(n_cells, 0, sd_cell) + damaged * rnorm(n_cells, dam_mito, sd_dam_mito) # damage raises the log-odds mt <- rbinom(n_cells, lib, expit(eta)) # mitochondrial UMIs data.frame(sample = paste0("S", s), type = factor(type, types), damaged = damaged, sum = lib, mito = 100 * mt / lib) # mito in percent, like percent.mt })) } set.seed(1) d1 <- sim_qc() pars <- formals(sim_qc) n_samples <- length(unique(d1$sample)); n_cells <- nrow(d1) p_dam <- eval(pars$p_dam, list(n_samples = n_samples))[1] dam_lib_fold <- exp(eval(pars$dam_lib)) med_mt <- tapply(d1$mito[!d1$damaged], d1$type[!d1$damaged], median) med_mt_dam <- tapply(d1$mito[d1$damaged], d1$type[d1$damaged], median) ## ---- filters ---- # TRUE = cell is removed filters <- function(d, cluster = d$type) { mt_hi <- function(batch = NULL) as.logical(isOutlier(d$mito, nmads = 3, type = "higher", log = FALSE, batch = batch)) lib_lo <- function(nmads) as.logical(isOutlier(d$sum, nmads = nmads, type = "lower", log = TRUE, batch = d$sample)) list("Fixed 5%" = d$mito > 5, "Fixed 10%" = d$mito > 10, "Fixed 20%" = d$mito > 20, "3 MADs, all cells" = mt_hi(), "3 MADs, per sample" = mt_hi(d$sample), "3 MADs, per cell type" = mt_hi(cluster), "3 MADs, per sample x type" = mt_hi(paste(d$sample, cluster)), "High mito AND low library" = mt_hi(d$sample) & lib_lo(3), "Same, library at 2 MADs" = mt_hi(d$sample) & lib_lo(2)) } score <- function(d) { f <- filters(d) true_share <- prop.table(table(d$type[!d$damaged])) do.call(rbind, lapply(names(f), function(nm) { drop <- f[[nm]] data.frame(filter = nm, type = types, healthy_kept = as.numeric(tapply(!drop[!d$damaged], d$type[!d$damaged], mean)), damaged_removed = as.numeric(tapply(drop[d$damaged], d$type[d$damaged], mean)), share_true = as.numeric(true_share), share_est = as.numeric(prop.table(table(d$type[!drop])))) })) } ## ---- replicate ---- set.seed(2) n_rep <- 100 res <- do.call(rbind, lapply(seq_len(n_rep), function(i) score(sim_qc()))) agg <- aggregate(cbind(healthy_kept, damaged_removed, share_true, share_est) ~ filter + type, data = res, FUN = mean) agg$filter <- factor(agg$filter, names(filters(d1))) agg$type <- factor(agg$type, types) pick <- function(f, t, col) agg[agg$filter == f & agg$type == t, col] ## ---- scenario-majority ---- set.seed(5) shares_major <- c("T cell" = 0.2, macrophage = 0.2, hepatocyte = 0.6) # hepatocyte-like majority n_rep_major <- 50 res_m <- sapply(seq_len(n_rep_major), function(i) { d <- sim_qc(shares = shares_major) f <- filters(d)[c("3 MADs, all cells", "3 MADs, per cell type")] sapply(f, function(x) tapply(x[d$damaged], d$type[d$damaged], mean)[c("T cell", "macrophage")]) }) dam_major <- matrix(rowMeans(res_m), 2, dimnames = list(c("T cell", "macrophage"), c("all", "type"))) ## ---- scenario-sample ---- set.seed(3) n_rep2 <- 50 bad <- c(0.10, 0.10, 0.10, 0.50) # sample S4: half of its cells damaged res_s <- sapply(seq_len(n_rep2), function(i) { d <- sim_qc(p_dam = bad) f <- filters(d)[c("3 MADs, per sample", "3 MADs, per cell type", "3 MADs, per sample x type")] s4 <- d$sample == "S4" thr <- attr(isOutlier(d$mito, type = "higher", batch = d$sample), "thresholds")["higher", ] c(sapply(f, function(x) mean(x[s4 & d$damaged])), sapply(f, function(x) mean(!x[s4 & !d$damaged])), thr_good = max(thr[c("S1", "S2", "S3")]), thr_bad = unname(thr["S4"])) }) dam_s4 <- rowMeans(res_s)[1:3]; kept_s4 <- rowMeans(res_s)[4:6] thr_good <- mean(res_s["thr_good", ]); thr_bad <- mean(res_s["thr_bad", ]) names(dam_s4) <- names(kept_s4) <- c("sample", "type", "sample_type") ## ---- scenario-cluster ---- set.seed(4) split_share <- c(all = 1, half = 0.5) # share of damaged cells that leave their type's cluster res_c <- sapply(seq_len(n_rep2), function(i) { d <- sim_qc() sapply(split_share, function(q) { moved <- d$damaged & runif(nrow(d)) < q cl <- ifelse(moved, "damaged", as.character(d$type)) x <- as.logical(isOutlier(d$mito, type = "higher", batch = cl)) mean(x[d$damaged]) }) }) dam_cl <- rowMeans(res_c) # damaged cells removed, per scenario cl1 <- factor(ifelse(d1$damaged, "damaged", as.character(d1$type)), c(types, "damaged")) cluster_table <- data.frame( cluster = levels(cl1), cells = as.numeric(table(cl1)), median_mito = as.numeric(tapply(d1$mito, cl1, median)), median_umis = as.numeric(tapply(d1$sum, cl1, median))) # the analysis chunks shown below run here first, so the opening can quote their results ## ---- key-numbers ---- hep <- "hepatocyte"; tc <- "T cell"; mac <- "macrophage" kept_hep <- setNames(sapply(levels(agg$filter), pick, t = hep, col = "healthy_kept"), levels(agg$filter)) kept_mac_5 <- pick("Fixed 5%", mac, "healthy_kept") share_hep_true <- pick("Fixed 5%", hep, "share_true") share_hep_5 <- pick("Fixed 5%", hep, "share_est") share_tc_true <- pick("Fixed 5%", tc, "share_true") share_tc_5 <- pick("Fixed 5%", tc, "share_est") dam_tc_20 <- pick("Fixed 20%", tc, "damaged_removed") dam_min <- tapply(agg$damaged_removed, agg$filter, min) dam_max <- tapply(agg$damaged_removed, agg$filter, max) kept_min <- tapply(agg$healthy_kept, agg$filter, min) share_err <- tapply(abs(agg$share_est - agg$share_true), agg$filter, max) thr_global <- unname(attr(isOutlier(d1$mito, type = "higher"), "thresholds")["higher"]) thr_sample <- attr(isOutlier(d1$mito, type = "higher", batch = d1$sample), "thresholds")["higher", ] thr_type <- attr(isOutlier(d1$mito, type = "higher", batch = d1$type), "thresholds")["higher", ] cells_per_sample <- n_cells / n_samples n_cells_total <- n_rep * n_cells mad_const <- eval(formals(mad)$constant) osorio_failed <- "13"; osorio_tissues <- "44" # quoted from the abstract of Osorio and Cai 2021 and_rules <- c("High mito AND low library", "Same, library at 2 MADs") stopifnot(kept_min[and_rules] > 0.999) # 'almost no healthy cell removed' stopifnot(thr_bad > 3 * thr_good, abs(kept_mac_5 - 0.5) < 0.1) # 'several times', 'about half' ## ---- simulate: shown here on the page, run above ---- ## ---- fig-distribution ---- ggplot(d1, aes(mito, fill = ifelse(damaged, "damaged", "healthy"))) + geom_histogram(bins = 60, position = "identity", alpha = 0.85) + geom_vline(xintercept = c(5, 10, 20), linetype = "dashed", colour = "grey30") + facet_wrap(~ type, ncol = 1, scales = "free_y") + scale_x_sqrt(breaks = c(1, 5, 10, 20, 40, 80)) + scale_y_sqrt(breaks = c(0, 10, 50, 200, 500)) + scale_fill_manual(values = c(healthy = grey, damaged = magenta), name = NULL) + labs(x = "mitochondrial UMIs (% of the cell's UMIs)", y = "cells") + theme(legend.position = "top") ## ---- filters: shown here on the page, run above ---- ## ---- replicate: shown here on the page, run above ---- ## ---- fig-filters ---- long <- rbind( data.frame(agg[, c("filter", "type")], panel = "healthy cells kept", value = agg$healthy_kept), data.frame(agg[, c("filter", "type")], panel = "damaged cells removed", value = agg$damaged_removed)) long$panel <- factor(long$panel, c("healthy cells kept", "damaged cells removed")) nf <- nlevels(agg$filter) long$y <- (nf + 1 - as.integer(long$filter)) + c(0.2, 0, -0.2)[as.integer(long$type)] ggplot(long, aes(100 * value, y, colour = type)) + geom_point(size = 2.6) + facet_wrap(~ panel) + scale_y_continuous(breaks = nf:1, labels = levels(agg$filter)) + scale_colour_manual(values = setNames(c(violet, grey, magenta), types), name = NULL) + labs(x = "% of cells", y = NULL) + theme(legend.position = "top", panel.grid.major.y = element_blank()) ## ---- tbl-shares ---- tab <- reshape(agg[, c("filter", "type", "share_est")], idvar = "filter", timevar = "type", direction = "wide") tab <- tab[order(tab$filter), c("filter", paste0("share_est.", types))] names(tab) <- c("filter", types) truth <- tapply(agg$share_true, agg$type, mean)[types] tab <- rbind(data.frame(filter = "Truth (healthy cells only)", t(truth), check.names = FALSE), tab) tab[, types] <- lapply(tab[, types], function(v) sprintf("%.1f", 100 * v)) knitr::kable(tab, row.names = FALSE, align = "lrrr", col.names = c("Rule", paste0(types, " (%)"))) ## ---- fig-scatter ---- thr_df <- data.frame(type = factor(types, types), thr = thr_type[types]) ggplot(d1, aes(sum, mito, colour = ifelse(damaged, "damaged", "healthy"))) + geom_point(size = 0.5, alpha = 0.5) + geom_hline(data = thr_df, aes(yintercept = thr), colour = violet, linewidth = 0.8) + facet_wrap(~ type) + scale_x_log10() + scale_y_log10() + scale_colour_manual(values = c(healthy = grey, damaged = magenta), name = NULL) + labs(x = "UMIs per cell", y = "mitochondrial UMIs (%)") + guides(colour = guide_legend(override.aes = list(size = 2, alpha = 1))) + theme(legend.position = "top") ## ---- scenario-majority: shown here on the page, run above ---- ## ---- scenario-sample: shown here on the page, run above ---- ## ---- scenario-cluster: shown here on the page, run above ---- ## ---- tbl-clusters ---- ct <- cluster_table ct$median_mito <- sprintf("%.1f", ct$median_mito) ct$median_umis <- fmt_int(ct$median_umis) ct$cells <- fmt_int(ct$cells) knitr::kable(ct, row.names = FALSE, align = "lrrr", col.names = c("Cluster", "Cells", "Median mito (%)", "Median UMIs")) ## ---- practice ---- # In your data (human gene names; mouse uses "^mt-"): # qc <- perCellQCMetrics(sce, subsets = list(Mito = grepl("^MT-", rownames(sce)))) # mito <- qc$subsets_Mito_percent; umis <- qc$sum # with cluster labels from a first, lenient pass. Here the simulated d1 stands in. mito <- d1$mito; umis <- d1$sum; cluster <- d1$type; sample_id <- d1$sample high_mt <- isOutlier(mito, nmads = 3, type = "higher", batch = cluster) round(attr(high_mt, "thresholds")["higher", ], 1) # one threshold per cluster # per-sample thresholds as a check: one far above the others marks a damaged sample round(attr(isOutlier(mito, type = "higher", batch = sample_id), "thresholds")["higher", ], 1) # per-cluster medians: high mito AND few UMIs marks a damaged cluster round(sapply(list(mito = mito, umis = umis), function(v) tapply(v, cluster, median)), 1) table(cluster, removed = as.logical(high_mt)) # what is being removed, per cluster ## ---- api-checks ---- f <- formals(isOutlier) c(nmads = f$nmads, log = f$log, type_default = eval(f$type)[1]) formals(mad)$constant # the scaling isOutlier() gets from mad() set.seed(5) qc_mock <- perCellQCMetrics(mockSCE(), subsets = list(Mito = 1:10)) grep("Mito", colnames(qc_mock), value = TRUE) colnames(perCellQCFilters(qc_mock)) # no mito filter colnames(perCellQCFilters(qc_mock, sub.fields = "subsets_Mito_percent")) colnames(perCellQCFilters(qc_mock, sub.fields = TRUE)) # every *_percent column