# Immunofluorescence intensity, knockdown vs control: corrected total cell fluorescence (CTCF) per cell, analysed with
# cells, images or experiments as n, and without background subtraction. R 4.3.3, base R.
d <- read.csv("cells.csv")                           # one row per cell: experiment, condition, image, cell, area_px, int_den, bg_mean (per image)
f2 <- function(p) formatC(signif(p, 2), format = "g")
fmt <- function(x) formatC(x, format = "f", digits = 0, big.mark = ",")
d$ctcf <- d$int_den - d$area_px * d$bg_mean          # CTCF = integrated density - area x mean background
d$log_ctcf <- log(d$ctcf); d$log_raw <- log(d$int_den)
cat(sprintf("Cells: %d, CTCF median %s, smallest %s; background is %.0f%% of the raw integrated density\n", nrow(d), fmt(median(d$ctcf)), fmt(min(d$ctcf)), 100 * sum(d$area_px * d$bg_mean) / sum(d$int_den)))
img <- aggregate(cbind(log_ctcf, log_raw) ~ experiment + condition + image, data = d, FUN = mean)
kd <- d$condition == "knockdown"; ct <- d$condition == "control"; t <- t.test(d$log_ctcf[kd], d$log_ctcf[ct])
cat(sprintf("A. Cells as n (%d vs %d), Welch t-test on log CTCF: knockdown / control %.2f, p = %s\n", sum(kd), sum(ct), exp(mean(d$log_ctcf[kd]) - mean(d$log_ctcf[ct])), f2(t$p.value)))
ik <- img$condition == "knockdown"; ic <- img$condition == "control"; t <- t.test(img$log_ctcf[ik], img$log_ctcf[ic])
cat(sprintf("B. Images as n (%d vs %d), Welch t-test on mean log CTCF: knockdown / control %.2f, p = %s\n", sum(ik), sum(ic), exp(mean(img$log_ctcf[ik]) - mean(img$log_ctcf[ic])), f2(t$p.value)))
for (v in c("log_ctcf", "log_raw")) {
  e <- tapply(img[[v]], list(img$experiment, img$condition), mean); r <- e[, "knockdown"] - e[, "control"]; t <- t.test(r)
  lab <- if (v == "log_ctcf") "C. Experiments as n, CTCF" else "D. Experiments as n, raw integrated density (no background subtraction)"
  cat(sprintf("%s, log ratio per experiment (n = %d): knockdown / control %.2f (95%% CI %.2f to %.2f), p = %s\n", lab, length(r), exp(mean(r)), exp(t$conf.int[1]), exp(t$conf.int[2]), f2(t$p.value)))
}
