# Latency with a 60-s cut-off: responded = 1 if the mouse responded before the cut-off, 0 if the trial ended at 60 s (censored).
# R 4.3.3 with survival.
suppressMessages(library(survival))
d <- read.csv("latency.csv"); d$group <- factor(d$group, levels = c("control", "treated"))
for (k in levels(d$group)) { x <- d[d$group == k, ]
  cat(sprintf("%s: n = %d, reached the cut-off (censored) = %d, mean of recorded latencies = %.2f s\n", k, nrow(x), sum(x$responded == 0), mean(x$latency_s))) }
a <- d$latency_s[d$group == "control"]; b <- d$latency_s[d$group == "treated"]
cat(sprintf("Welch's t-test on recorded latencies (cut-off values treated as real): difference %.2f s, p = %.4f\n", mean(b) - mean(a), t.test(b, a)$p.value))
cat(sprintf("Mann-Whitney test (cut-off values tied at the top): p = %.4f\n", suppressWarnings(wilcox.test(b, a, exact = FALSE, correct = TRUE))$p.value))
km <- survfit(Surv(latency_s, responded) ~ group, data = d)
med <- summary(km)$table[, "median"]
cat(sprintf("Kaplan-Meier median latency: control %.1f s, treated %.1f s\n", med[1], med[2]))
lr <- survdiff(Surv(latency_s, responded) ~ group, data = d)
cat(sprintf("Log-rank test: chi-square = %.2f, p = %.4f\n", lr$chisq, pchisq(lr$chisq, 1, lower.tail = FALSE)))
aft <- survreg(Surv(latency_s, responded) ~ group, data = d, dist = "lognormal")
b1 <- coef(aft)[["grouptreated"]]; s1 <- sqrt(vcov(aft)["grouptreated", "grouptreated"])
cat(sprintf("Log-normal survival (AFT) model: treated/control latency ratio %.2f (95%% CI %.2f to %.2f), p = %.4f\n",
            exp(b1), exp(b1 - 1.96 * s1), exp(b1 + 1.96 * s1), 2 * pnorm(-abs(b1 / s1))))
