# Scratch assay, drug vs control: migration speed per field (from the slope of width over time) and percent closure at
# 24 h, compared with wells as n and with experiments as n. R 4.3.3, base R.
d <- read.csv("wound.csv")                           # one row per field and time: experiment, condition, well, field, hours, width_um
f2 <- function(p) formatC(signif(p, 2), format = "g")
key <- interaction(d$experiment, d$condition, d$well, d$field, drop = TRUE, lex.order = TRUE)
f <- do.call(rbind, lapply(split(d, key), function(x) {
  slope <- coef(lm(width_um ~ hours, data = x[x$width_um > 20, ]))[[2]];   # linear phase only
  w0 <- x$width_um[x$hours == 0]; w24 <- x$width_um[x$hours == 24]
  data.frame(experiment = x$experiment[1], condition = x$condition[1], well = x$well[1], field = x$field[1],
             speed = -slope / 2, closure = 100 * (w0 - w24) / w0, w0 = w0) }))
cat(sprintf("Starting width across fields: mean %.0f µm, range %.0f to %.0f; correlation of 24-h percent closure with starting width r = %.2f, with migration speed r = %.2f\n",
            mean(f$w0), min(f$w0), max(f$w0), cor(f$w0, f$closure), cor(f$w0, f$speed)))
w <- aggregate(cbind(speed, closure) ~ experiment + condition + well, data = f, FUN = mean); dw <- w$condition == "drug"
t1 <- t.test(log(w$speed[dw]), log(w$speed[!dw]))
cat(sprintf("Migration speed, wells as n (%d vs %d): drug / control %.2f, p = %s\n", sum(dw), sum(!dw), exp(mean(log(w$speed[dw])) - mean(log(w$speed[!dw]))), f2(t1$p.value)))
e <- aggregate(cbind(speed, closure) ~ experiment + condition, data = w, FUN = mean)
sp <- tapply(e$speed, list(e$experiment, e$condition), mean); cl <- tapply(e$closure, list(e$experiment, e$condition), mean)
r <- log(sp[, "drug"] / sp[, "control"]); t2 <- t.test(r)
cat(sprintf("Migration speed, experiments as n (%d): drug / control %.2f (95%% CI %.2f to %.2f), p = %s; control speed %.1f µm/h per edge\n",
            length(r), exp(mean(r)), exp(t2$conf.int[1]), exp(t2$conf.int[2]), f2(t2$p.value), mean(sp[, "control"])))
dc <- cl[, "drug"] - cl[, "control"]; t3 <- t.test(dc)
cat(sprintf("24-h percent closure, experiments as n: drug - control %.1f percentage points (95%% CI %.1f to %.1f), p = %s; control closure %.1f%%\n",
            mean(dc), t3$conf.int[1], t3$conf.int[2], f2(t3$p.value), mean(cl[, "control"])))
