-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.R
More file actions
4266 lines (4019 loc) · 181 KB
/
Copy pathapp.R
File metadata and controls
4266 lines (4019 loc) · 181 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
suppressPackageStartupMessages({
suppressWarnings(library(shiny))
suppressWarnings(library(ggplot2))
suppressWarnings(library(dplyr))
suppressWarnings(library(readr))
suppressWarnings(library(emmeans))
suppressWarnings(library(broom))
suppressWarnings(library(DT))
suppressWarnings(library(colourpicker))
})
demo_file <- "dummy_cfu_example.csv"
`%||%` <- function(x, y) {
if (is.null(x) || length(x) == 0 || all(is.na(x))) y else x
}
axis_limit <- function(x) {
if (is.null(x) || length(x) == 0 || is.na(x) || !is.finite(x)) NA_real_ else as.numeric(x)
}
clean_names <- function(x) {
trimws(x)
}
MM_PER_INCH <- 25.4
# Screen pixels per figure inch for the preview. The preview canvas is sized to
# export_inches * PREVIEW_PPI and the device resolution is set to the same
# number, so a 7 pt tick label occupies the same fraction of the figure on
# screen as it will in the exported file. Fixed rather than user-adjustable
# because renderPlot() forces `res` once and never re-reads it.
PREVIEW_PPI <- 144
# Figure width/height are entered in whichever unit the user picked, but every
# export path (ggsave, officer, gifski) wants inches. Convert at the boundary so
# there is exactly one place where the unit is interpreted.
size_to_inches <- function(x, units, fallback = NA_real_) {
x <- suppressWarnings(as.numeric(x))
if (length(x) != 1 || is.na(x) || !is.finite(x) || x <= 0) return(fallback)
if (identical(units, "mm")) x / MM_PER_INCH else x
}
# Emit a live function's own source into the exported reproducible script, so
# the script and the app can never drift apart.
exported_function_source <- function(name) {
# Resolve in the environment these helpers were defined in, which is the app's
# top level whether it was sourced or run by shiny::runApp().
fn <- get(name, envir = environment(exported_function_source))
lhs <- if (make.names(name) == name) name else paste0("`", name, "`")
paste0(lhs, " <- ", paste(deparse(fn), collapse = "\n"))
}
# ---------------------------------------------------------------------------
# Fixed panel geometry
# ---------------------------------------------------------------------------
# ggplot sizes the PANEL last: it takes whatever is left after the legend, the
# titles, the axis labels and the caption have claimed their space. Two figures
# exported at the same width therefore have different-sized data areas the
# moment their legends differ -- measured on a 7 x 4.4 in figure, a long legend
# and a three-line caption shrink the panel from 5.62 x 3.62 in to 4.31 x 3.29,
# a 30% change in width with identical data. Panels that are meant to be
# compared side by side cannot be built that way.
#
# Pinning the panel cells to absolute units inverts the priority: the data area
# is fixed and the figure grows around it.
fix_panel_size <- function(p, panel_w_in, panel_h_in) {
g <- if (inherits(p, "gtable")) p else ggplot2::ggplotGrob(p)
lay <- g$layout[grepl("^panel", g$layout$name), , drop = FALSE]
if (nrow(lay) == 0) return(g)
if (is.finite(panel_w_in) && panel_w_in > 0) {
g$widths[unique(lay$l)] <- grid::unit(panel_w_in, "in")
}
if (is.finite(panel_h_in) && panel_h_in > 0) {
g$heights[unique(lay$t)] <- grid::unit(panel_h_in, "in")
}
g
}
# Measuring text-shaped grobs needs an open device, and the answer depends on
# its resolution. Do the measuring on a throwaway device matching the export so
# the number does not drift between the preview and the file.
with_measure_device <- function(expr, dpi = 300) {
f <- tempfile(fileext = ".png")
grDevices::png(f, width = 30, height = 30, units = "in", res = max(72, dpi))
on.exit({grDevices::dev.off(); unlink(f)}, add = TRUE)
force(expr)
}
# Total figure size a pinned gtable needs. A cell still measured in "null" units
# has no intrinsic size and converts to zero, which would silently understate
# the total, so those are counted and reported rather than dropped.
gtable_size_in <- function(g, dpi = 300) {
with_measure_device({
w <- sum(grid::convertWidth(g$widths, "in", valueOnly = TRUE))
h <- sum(grid::convertHeight(g$heights, "in", valueOnly = TRUE))
list(
width = w, height = h,
unresolved = sum(as.character(grid::unitType(g$widths)) == "null") +
sum(as.character(grid::unitType(g$heights)) == "null")
)
}, dpi = dpi)
}
format_figure_size <- function(width_in, height_in, dpi) {
if (!is.finite(width_in) || !is.finite(height_in)) return("Figure size is not set.")
sprintf(
"%.2f x %.2f in (%.0f x %.0f mm) at %s DPI = %d x %d px",
width_in, height_in, width_in * MM_PER_INCH, height_in * MM_PER_INCH,
if (is.finite(dpi)) format(dpi) else "?",
round(width_in * dpi), round(height_in * dpi)
)
}
guess_column <- function(cols, candidates) {
# Lowercase BEFORE stripping to [a-z0-9], or every capital letter in a header is
# deleted rather than folded ("CFU" -> "", "Sample" -> "ample").
norm <- function(x) gsub("[^a-z0-9]+", "", tolower(x))
cols_clean <- norm(cols)
candidates_clean <- norm(candidates)
candidates_clean <- candidates_clean[nzchar(candidates_clean)]
hit <- match(candidates_clean, cols_clean, nomatch = 0)
if (any(hit > 0)) return(cols[hit[hit > 0][1]])
# Fall back to a header that contains a candidate, so real bench headers like
# "inducer_concentration" or "CFU_per_mL" still find "concentration" / "cfu".
for (cand in candidates_clean) {
idx <- which(grepl(cand, cols_clean, fixed = TRUE))
if (length(idx) > 0) return(cols[idx[1]])
}
cols[1]
}
format_label <- function(x, unit = "", append_unit = TRUE) {
x_chr <- as.character(x)
x_num <- suppressWarnings(as.numeric(x_chr))
if (all(!is.na(x_num))) {
ord <- order(x_num)
unit_text <- trimws(unit %||% "")
suffix <- if (isTRUE(append_unit) && nzchar(unit_text)) paste0(" ", unit_text) else ""
labels <- paste0(x_num[ord], suffix)
list(values = x_chr[ord], labels = labels, numeric = x_num[ord])
} else {
vals <- unique(x_chr)
list(values = vals, labels = vals, numeric = seq_along(vals))
}
}
axis_step_breaks <- function(min_val, max_val, step, log_base_10 = FALSE) {
step <- suppressWarnings(as.numeric(step))
if (length(step) == 0 || is.na(step) || !is.finite(step) || step <= 0) return(NULL)
if (!is.finite(min_val) || !is.finite(max_val) || min_val >= max_val) return(NULL)
if (isTRUE(log_base_10)) {
min_val <- max(min_val, .Machine$double.eps)
start <- floor(log10(min_val) / step) * step
end <- ceiling(log10(max_val) / step) * step
return(10^seq(start, end, by = step))
}
start <- ceiling(min_val / step) * step
end <- floor(max_val / step) * step
seq(start, end, by = step)
}
scale_breaks_or_default <- function(x) {
if (is.null(x) || length(x) == 0) waiver() else x
}
plot_setting_ids <- c(
"plot_mode", "comparison", "stats_method", "p_adjust", "p_adjust_scope", "label_kind", "show_ns",
"y_mode", "chart_geom", "bar_color_mode", "error_type", "variation_display", "show_points", "y_min", "y_max",
"surv_baseline", "surv_readout", "surv_scale", "surv_match_replicates",
"plot_title", "plot_subtitle", "show_subtitle", "hide_subtitle_no_stats", "show_method_caption",
"x_label", "y_label", "treatment_unit", "append_treatment_unit", "time_unit", "append_time_unit",
"show_n_labels", "legend_title", "bar_orientation", "plot_theme", "plot_box", "show_y_ticks",
"show_minor_y_ticks", "show_y_grid", "show_minor_y_grid", "y_major_step", "y_minor_step",
"y_tick_length", "minor_y_tick_length", "axis_line_width", "box_line_width",
"axis_color", "grid_color", "bar_outline_color", "bar_outline_width", "errorbar_width",
"sample_color_1", "sample_color_2", "time_color_1", "time_color_2", "single_color", "stat_color",
"bar_width", "dodge_width", "point_size", "point_alpha", "jitter_width", "jitter_seed",
"font_size", "title_size", "subtitle_size", "stat_size", "x_angle",
"title_hjust", "subtitle_hjust", "caption_hjust", "x_title_hjust", "y_title_hjust",
"legend_position", "legend_x", "legend_y", "legend_just_x", "legend_just_y",
"size_mode", "size_units", "download_width", "download_height", "download_dpi", "animation_fps", "animation_duration",
"animation_dpi", "ppt_editable"
)
select_setting_ids <- c(
"plot_mode", "comparison", "stats_method", "p_adjust", "p_adjust_scope", "y_mode",
"error_type", "variation_display", "bar_orientation", "plot_theme", "legend_position",
"size_units", "chart_geom", "bar_color_mode",
# slider_setting_ids is a setdiff residual, so a select id missing from this
# list gets updateSliderInput called against it: no error, no effect, and the
# preset silently fails to restore.
"surv_baseline", "surv_readout", "surv_scale", "size_mode"
)
radio_setting_ids <- c("label_kind")
checkbox_setting_ids <- c(
"show_ns", "show_points", "show_subtitle", "hide_subtitle_no_stats", "show_method_caption",
"surv_match_replicates", "append_treatment_unit",
"append_time_unit", "show_n_labels", "plot_box", "show_y_ticks", "show_minor_y_ticks", "show_y_grid",
"show_minor_y_grid", "ppt_editable"
)
text_setting_ids <- c("plot_title", "plot_subtitle", "x_label", "y_label", "treatment_unit", "time_unit", "legend_title")
numeric_setting_ids <- c(
"y_min", "y_max", "y_major_step", "y_minor_step", "download_width", "download_height",
"download_dpi", "animation_dpi", "jitter_seed"
)
slider_setting_ids <- setdiff(
plot_setting_ids,
c(select_setting_ids, radio_setting_ids, checkbox_setting_ids, text_setting_ids, numeric_setting_ids)
)
collect_plot_settings <- function(input) {
out <- lapply(plot_setting_ids, function(id) input[[id]])
names(out) <- plot_setting_ids
Filter(function(x) !is.null(x) && length(x) > 0, out)
}
plot_settings_payload <- function(input) {
list(
app = "CFU Plot Studio",
preset_version = 1,
created_at = format(Sys.time(), "%Y-%m-%d %H:%M:%S %Z"),
settings = collect_plot_settings(input)
)
}
significance_label <- function(p) {
case_when(
is.na(p) ~ NA_character_,
p < 0.001 ~ "***",
p < 0.01 ~ "**",
p < 0.05 ~ "*",
TRUE ~ "ns"
)
}
# Okabe-Ito colorblind-safe qualitative palette (Wong 2011, Nat Methods 8:441).
# Order chosen so the first two entries read clearly for the common 2-group CFU case.
okabe_ito <- c(
"#0072B2", "#D55E00", "#009E73", "#CC79A7",
"#E69F00", "#56B4E9", "#F0E442", "#000000"
)
# Human-readable label for the variation/error-bar summary, for figure captions.
error_type_caption <- function(error_type, variation_display = "errorbar") {
if (identical(variation_display, "none")) return(NULL)
descr <- switch(
error_type %||% "SD",
"SD" = "error bars show mean ± SD",
"SEM" = "error bars show mean ± SEM",
"95% CI" = "error bars show mean with 95% CI",
"IQR" = "intervals show median IQR (Q1-Q3)",
"Range (min-max)" = "intervals show min-max range",
paste0("error bars: ", error_type)
)
descr
}
# Names the statistical test + multiple-comparison correction for figure captions.
stats_caption <- function(stats_method, p_adjust) {
test_txt <- switch(
stats_method %||% "welch",
"welch" = "Welch t-test on log10(CFU)",
"student" = "Student t-test on log10(CFU)",
"wilcoxon" = "Wilcoxon rank-sum test on log10(CFU)",
"emmeans" = "linear model + emmeans on log10(CFU)",
"statistical test"
)
corr_txt <- switch(
p_adjust %||% "BH",
"BH" = "Benjamini-Hochberg FDR",
"holm" = "Holm",
"bonferroni" = "Bonferroni",
"none" = "no",
p_adjust
)
paste0(test_txt, "; ", corr_txt, " correction")
}
named_palette <- function(levels_vec, seed_colors) {
levels_vec <- as.character(levels_vec)
seed_colors <- unname(seed_colors)
if (length(levels_vec) <= length(seed_colors)) {
setNames(seed_colors[seq_along(levels_vec)], levels_vec)
} else {
extra <- grDevices::hcl.colors(length(levels_vec) - length(seed_colors), palette = "Dark 3")
setNames(c(seed_colors, extra), levels_vec)
}
}
format_p <- function(p) {
ifelse(is.na(p), NA_character_, ifelse(p < 0.001, "p<0.001", paste0("p=", signif(p, 2))))
}
format_q <- function(p) {
ifelse(is.na(p), NA_character_, ifelse(p < 0.001, "q<0.001", paste0("q=", signif(p, 2))))
}
prep_cfu_data <- function(raw, mapping, treatment_unit = "", time_unit = "min", append_treatment_unit = TRUE, append_time_unit = TRUE) {
names(raw) <- clean_names(names(raw))
out <- tibble(
sample = as.character(raw[[mapping$sample]]),
concentration_raw = as.character(raw[[mapping$concentration]]),
time_raw = as.character(raw[[mapping$time]]),
replicate = as.character(raw[[mapping$replicate]]),
cfu = suppressWarnings(as.numeric(raw[[mapping$cfu]]))
) %>%
filter(!is.na(sample), !is.na(concentration_raw), !is.na(time_raw), !is.na(cfu), cfu > 0)
conc_info <- format_label(out$concentration_raw, treatment_unit, append_treatment_unit)
time_info <- format_label(out$time_raw, time_unit, append_time_unit)
out %>%
mutate(
sample = factor(sample, levels = unique(sample)),
concentration_value = suppressWarnings(as.numeric(concentration_raw)),
concentration_label = factor(
concentration_raw,
levels = conc_info$values,
labels = conc_info$labels
),
time_value = suppressWarnings(as.numeric(time_raw)),
time_min = factor(
time_raw,
levels = time_info$values,
labels = time_info$labels
),
replicate = factor(replicate),
log10_cfu = log10(cfu)
)
}
summary_cfu <- function(dat) {
dat %>%
group_by(sample, concentration_label, time_min) %>%
summarize(
n = n(),
mean_cfu = mean(cfu),
sd_cfu = sd(cfu),
sem_cfu = sd_cfu / sqrt(n),
mean_log10_cfu = mean(log10_cfu),
sd_log10_cfu = sd(log10_cfu),
sem_log10_cfu = sd_log10_cfu / sqrt(n),
geometric_mean_cfu = 10^mean_log10_cfu,
.groups = "drop"
)
}
qc_summary <- function(dat) {
dat %>%
group_by(sample, concentration_label, time_min) %>%
summarize(
replicates = n_distinct(replicate),
rows = n(),
min_cfu = min(cfu, na.rm = TRUE),
max_cfu = max(cfu, na.rm = TRUE),
mean_log10_cfu = mean(log10_cfu, na.rm = TRUE),
sd_log10_cfu = sd(log10_cfu, na.rm = TRUE),
flag = case_when(
replicates < 2 ~ "Check: fewer than 2 replicates",
rows != replicates ~ "Check: duplicate replicate labels",
TRUE ~ "OK"
),
.groups = "drop"
)
}
raw_qc_summary <- function(raw, mapping) {
tibble(
check = c("Rows in source", "Missing CFU values", "Nonpositive CFU values", "Unique samples", "Unique treatments", "Unique timepoints"),
value = c(
nrow(raw),
sum(is.na(suppressWarnings(as.numeric(raw[[mapping$cfu]])))),
sum(suppressWarnings(as.numeric(raw[[mapping$cfu]])) <= 0, na.rm = TRUE),
n_distinct(raw[[mapping$sample]]),
n_distinct(raw[[mapping$concentration]]),
n_distinct(raw[[mapping$time]])
)
)
}
model_formula <- function(dat) {
terms <- c("sample", "concentration_label", "time_min")
usable <- terms[vapply(terms, function(z) n_distinct(dat[[z]]) > 1, logical(1))]
if (length(usable) == 0) {
as.formula("log10_cfu ~ 1")
} else {
as.formula(paste("log10_cfu ~", paste(usable, collapse = " * ")))
}
}
run_anova <- function(dat) {
if (nrow(dat) < 3 || n_distinct(dat$log10_cfu) < 2) return(tibble())
fit <- lm(model_formula(dat), data = dat)
# CFU designs are routinely unbalanced by the time they reach the ANOVA: the
# cfu > 0 filter removes whole replicates from some cells. Type I sequential
# SS then makes each main effect's F depend on the order the terms happen to
# be listed in the formula. Type II tests each term after the others at its
# level, which is order-invariant, so use it whenever car is available and
# label the table with what was actually computed.
out <- NULL
ss_type <- "Type I (sequential)"
if (requireNamespace("car", quietly = TRUE)) {
out <- tryCatch(tidy(car::Anova(fit, type = 2)), error = function(e) NULL)
if (!is.null(out)) ss_type <- "Type II (car::Anova)"
}
if (is.null(out)) out <- tidy(anova(fit))
out %>%
mutate(
across(where(is.numeric), ~ signif(.x, 4)),
ss_type = ss_type
)
}
adjust_stats <- function(out, p_adjust, adjustment_scope) {
if (nrow(out) == 0 || !"p.value" %in% names(out)) return(out)
# mutate() DELETES a column assigned NULL rather than filling it, so a missing
# correction method silently removes p_adjust_method and the select() at the
# end of the caller then fails with "column doesn't exist". Normalise both
# settings to their UI defaults before they are recorded.
usable <- function(x) length(x) == 1 && !is.na(x) && nzchar(as.character(x))
p_adjust <- if (usable(p_adjust)) as.character(p_adjust) else "BH"
adjustment_scope <- if (usable(adjustment_scope)) as.character(adjustment_scope) else "global"
if (identical(adjustment_scope, "within_panel") && "panel" %in% names(out)) {
out <- out %>%
group_by(panel) %>%
mutate(q.value = p.adjust(p.value, method = p_adjust)) %>%
ungroup()
} else {
out <- out %>% mutate(q.value = p.adjust(p.value, method = p_adjust))
}
out %>%
mutate(
significance = significance_label(q.value),
label_stars = significance,
label_q = if (identical(p_adjust, "none")) format_p(p.value) else format_q(q.value),
p_adjust_method = p_adjust,
adjustment_scope = adjustment_scope
)
}
# Hedges' g: Cohen's d with the small-sample correction. CFU assays run n=3, and
# at n=3 the uncorrected d overstates the effect by roughly a third.
hedges_g <- function(a, b) {
na <- length(a); nb <- length(b)
if (na < 2 || nb < 2) return(NA_real_)
s_pooled <- sqrt(((na - 1) * var(a) + (nb - 1) * var(b)) / (na + nb - 2))
if (!is.finite(s_pooled) || s_pooled == 0) return(NA_real_)
d <- (mean(a) - mean(b)) / s_pooled
df <- na + nb - 2
d * (1 - 3 / (4 * df - 1))
}
# Paired effect size for the survival readout. d_z uses the SD of the
# within-replicate differences, which is a different denominator from the
# two-sample Hedges' g -- conflating them overstates or understates the effect
# by a large factor, so the two are reported under different column names.
paired_dz <- function(d) {
if (length(d) < 2) return(NA_real_)
s <- sd(d)
if (!is.finite(s) || s == 0) return(NA_real_)
mean(d) / s
}
empty_two_group_result <- function(a, b, note, paired = FALSE, n_matched = NA_integer_) {
# mean(numeric(0)) is NaN, so an empty group produced a NaN estimate. NaN then
# survives every downstream is.na() guard written for NA and reaches the table.
est <- mean(a, na.rm = TRUE) - mean(b, na.rm = TRUE)
if (!is.finite(est)) est <- NA_real_
tibble(
p.value = NA_real_, statistic = NA_real_, parameter = NA_real_,
estimate = est,
conf.low = NA_real_, conf.high = NA_real_,
hedges_g = NA_real_, d_z = NA_real_, stderr = NA_real_,
paired = paired, n_matched = n_matched, message = note
)
}
# Match two groups replicate by replicate. Only meaningful when the replicate
# labels mean the same thing on both sides -- same split culture, same
# experimental day. That is a claim about how the experiment was run which the
# CSV cannot settle, so the caller has to opt in.
matched_pairs <- function(dat, group_col, level_a, level_b) {
side <- function(lv) {
dat %>%
filter(.data[[group_col]] == lv,
!is.na(replicate), nzchar(trimws(as.character(replicate)))) %>%
group_by(replicate) %>%
summarize(v = mean(log10_cfu), .groups = "drop")
}
aa <- side(level_a); bb <- side(level_b)
m <- inner_join(aa, bb, by = "replicate", suffix = c("_a", "_b"), na_matches = "never")
list(
d = m$v_a - m$v_b,
n_matched = nrow(m),
n_dropped = (nrow(aa) - nrow(m)) + (nrow(bb) - nrow(m))
)
}
run_two_group_test <- function(dat, group_col, level_a, level_b, var_equal,
test_family = "t", paired = FALSE) {
a <- dat %>% filter(.data[[group_col]] == level_a) %>% pull(log10_cfu)
b <- dat %>% filter(.data[[group_col]] == level_b) %>% pull(log10_cfu)
if (isTRUE(paired)) {
mp <- matched_pairs(dat, group_col, level_a, level_b)
d <- mp$d
drop_note <- if (mp$n_dropped > 0) {
paste0(mp$n_dropped, " replicate(s) had no counterpart in the other group and were excluded. ")
} else ""
if (length(d) < 2) {
note <- if (mp$n_matched == 0) {
paste0(drop_note, "No replicate label appears in both groups, so nothing can be paired.")
} else {
paste0(drop_note, "Fewer than two matched replicates, so no paired test is defined.")
}
return(empty_two_group_result(a, b, note, paired = TRUE, n_matched = mp$n_matched) %>%
mutate(estimate = if (length(d) == 1) d[1] else NA_real_))
}
sd_d <- sd(d)
if (!is.finite(sd_d) || sd_d == 0) {
return(empty_two_group_result(a, b, paste0(
drop_note, "Every matched replicate differed by an identical amount, so the spread is zero and no t-test is defined."),
paired = TRUE, n_matched = mp$n_matched) %>% mutate(estimate = mean(d)))
}
tt <- tryCatch(t.test(d, mu = 0), error = function(e) e)
if (inherits(tt, "error")) {
return(empty_two_group_result(a, b, paste0(drop_note, conditionMessage(tt)),
paired = TRUE, n_matched = mp$n_matched))
}
return(tibble(
p.value = unname(tt$p.value),
statistic = unname(tt$statistic),
parameter = unname(tt$parameter),
estimate = mean(d),
conf.low = unname(tt$conf.int[1]), conf.high = unname(tt$conf.int[2]),
# Paired data gets the paired effect size. Reporting Hedges' g here would
# divide by the wrong spread entirely.
hedges_g = NA_real_, d_z = paired_dz(d),
stderr = unname(tt$stderr %||% (sd_d / sqrt(length(d)))),
paired = TRUE, n_matched = mp$n_matched,
message = if (nzchar(drop_note)) trimws(drop_note) else NA_character_
))
}
if (length(a) < 2 || length(b) < 2) {
return(empty_two_group_result(a, b, "Each group needs at least two replicates for a test."))
}
if (identical(test_family, "wilcoxon")) {
# exact is left at its default so R uses the EXACT distribution whenever the
# sample is small and untied -- the case a CFU assay is always in. Forcing
# the normal approximation at n=3 gives p=0.383 where the exact test gives
# p=0.4. Ties force the approximation; that is reported, not hidden.
test <- tryCatch(
suppressWarnings(wilcox.test(a, b, conf.int = TRUE)),
error = function(e) e
)
if (inherits(test, "error")) return(empty_two_group_result(a, b, conditionMessage(test)))
notes <- character(0)
if (min(length(a), length(b)) < 4) {
# With n=3 vs n=3 the smallest attainable two-sided p is 0.1, so a rank
# test on a typical CFU assay can never reach 0.05. Say so, per row.
notes <- c(notes, "Rank test: with this n the smallest attainable p may exceed 0.05.")
}
if (anyDuplicated(c(a, b)) > 0) {
notes <- c(notes, "Ties present, so the normal approximation replaced the exact test.")
}
return(tibble(
p.value = unname(test$p.value),
statistic = unname(test$statistic),
parameter = NA_real_,
paired = FALSE, n_matched = NA_integer_, d_z = NA_real_,
# The Hodges-Lehmann shift, so the point estimate matches the interval the
# same call returns. A median difference would not sit inside that CI.
estimate = unname(test$estimate %||% (median(a, na.rm = TRUE) - median(b, na.rm = TRUE))),
conf.low = unname(test$conf.int[1] %||% NA_real_),
conf.high = unname(test$conf.int[2] %||% NA_real_),
hedges_g = hedges_g(a, b),
stderr = NA_real_,
message = if (length(notes) > 0) paste(notes, collapse = " ") else NA_character_
))
}
test <- tryCatch(
t.test(a, b, var.equal = var_equal),
error = function(e) e
)
if (inherits(test, "error")) {
return(empty_two_group_result(a, b, conditionMessage(test)))
}
tibble(
p.value = unname(test$p.value),
statistic = unname(test$statistic),
parameter = unname(test$parameter),
paired = FALSE, n_matched = NA_integer_, d_z = NA_real_,
estimate = mean(a, na.rm = TRUE) - mean(b, na.rm = TRUE),
conf.low = unname(test$conf.int[1] %||% NA_real_),
conf.high = unname(test$conf.int[2] %||% NA_real_),
hedges_g = hedges_g(a, b),
stderr = unname(test$stderr %||% NA_real_),
message = NA_character_
)
}
run_groupwise_t_tests <- function(dat, comparison, p_adjust, adjustment_scope, control_concentration, ttest_type,
paired = FALSE) {
var_equal <- identical(ttest_type, "student")
test_family <- if (identical(ttest_type, "wilcoxon")) "wilcoxon" else "t"
# Pairing is a t-test concept here; matched-pair ranks would be a signed rank
# test, a different procedure, so the rank option stays unpaired.
# NOTE the distinct name: `paired` is also a column in the result, and inside
# mutate() the data mask would shadow the argument.
use_paired <- isTRUE(paired) && !identical(test_family, "wilcoxon")
if (comparison == "sample") {
if (n_distinct(dat$sample) < 2) return(tibble(message = "Sample comparison requires at least two samples."))
# ALL sample pairs, not just the first two. With 3+ samples the old code
# silently ignored every comparison beyond levels 1-2, and because the
# missing rows never entered the table, the multiplicity correction was
# computed over the wrong m as well. pair_rank marks the first pair, which
# is the one annotated on the plot.
sample_pairs <- utils::combn(levels(droplevels(dat$sample)), 2, simplify = FALSE)
strata <- dat %>% distinct(concentration_label, time_min)
out <- bind_rows(lapply(seq_len(nrow(strata)), function(i) {
sub <- dat %>% filter(concentration_label == strata$concentration_label[i], time_min == strata$time_min[i])
bind_rows(lapply(seq_along(sample_pairs), function(k) {
pair <- sample_pairs[[k]]
res <- run_two_group_test(sub, "sample", pair[1], pair[2], var_equal, test_family, use_paired)
res %>%
mutate(
comparison_family = "Sample/vector within treatment and time",
contrast = paste(pair[1], "-", pair[2]),
sample = NA_character_,
concentration_label = strata$concentration_label[i],
time_min = strata$time_min[i],
panel = paste(strata$time_min[i]),
numerator = pair[1],
denominator = pair[2],
pair_rank = k
)
}))
}))
} else if (comparison == "time") {
if (n_distinct(dat$time_min) < 2) return(tibble(message = "Timepoint comparison requires at least two timepoints."))
time_pairs <- utils::combn(levels(droplevels(dat$time_min)), 2, simplify = FALSE)
strata <- dat %>% distinct(sample, concentration_label)
out <- bind_rows(lapply(seq_len(nrow(strata)), function(i) {
sub <- dat %>% filter(sample == strata$sample[i], concentration_label == strata$concentration_label[i])
bind_rows(lapply(seq_along(time_pairs), function(k) {
pair <- time_pairs[[k]]
res <- run_two_group_test(sub, "time_min", pair[1], pair[2], var_equal, test_family, use_paired)
res %>%
mutate(
comparison_family = "Timepoints within sample/vector and treatment",
contrast = paste(pair[1], "-", pair[2]),
sample = as.character(strata$sample[i]),
concentration_label = strata$concentration_label[i],
time_min = NA_character_,
panel = paste(strata$sample[i]),
numerator = pair[1],
denominator = pair[2],
pair_rank = k
)
}))
}))
} else if (comparison == "concentration_vs_control") {
if (n_distinct(dat$concentration_label) < 2) return(tibble(message = "Treatment comparison requires at least two treatment groups."))
if (!control_concentration %in% levels(droplevels(dat$concentration_label))) {
return(tibble(message = "The selected control treatment is not present in the filtered data."))
}
strata <- dat %>% distinct(sample, time_min)
out <- bind_rows(lapply(seq_len(nrow(strata)), function(i) {
sub <- dat %>% filter(sample == strata$sample[i], time_min == strata$time_min[i])
test_levels <- setdiff(levels(droplevels(sub$concentration_label)), control_concentration)
bind_rows(lapply(test_levels, function(lvl) {
res <- run_two_group_test(sub, "concentration_label", lvl, control_concentration, var_equal, test_family, use_paired)
res %>%
mutate(
comparison_family = "Treatment versus control within sample/vector and time",
contrast = paste(lvl, "-", control_concentration),
sample = as.character(strata$sample[i]),
concentration_label = lvl,
time_min = as.character(strata$time_min[i]),
panel = paste(strata$sample[i], strata$time_min[i]),
numerator = lvl,
denominator = control_concentration,
pair_rank = 1
)
}))
}))
} else if (comparison == "concentration_all") {
if (n_distinct(dat$concentration_label) < 2) return(tibble(message = "Treatment comparison requires at least two treatment groups."))
strata <- dat %>% distinct(sample, time_min)
out <- bind_rows(lapply(seq_len(nrow(strata)), function(i) {
sub <- dat %>% filter(sample == strata$sample[i], time_min == strata$time_min[i])
levs <- levels(droplevels(sub$concentration_label))
pairs <- combn(levs, 2, simplify = FALSE)
bind_rows(lapply(seq_along(pairs), function(k) {
pair <- pairs[[k]]
res <- run_two_group_test(sub, "concentration_label", pair[1], pair[2], var_equal, test_family, use_paired)
res %>%
mutate(
comparison_family = "All treatment pairs within sample/vector and time",
contrast = paste(pair[1], "-", pair[2]),
sample = as.character(strata$sample[i]),
concentration_label = pair[1],
time_min = as.character(strata$time_min[i]),
panel = paste(strata$sample[i], strata$time_min[i]),
numerator = pair[1],
denominator = pair[2],
pair_rank = k
)
}))
}))
} else {
return(tibble())
}
adjust_stats(out, p_adjust, adjustment_scope) %>%
mutate(
test = if (identical(test_family, "wilcoxon")) "Wilcoxon rank-sum on log10(CFU)"
else if (use_paired) "Paired t-test on log10(CFU), matched by replicate"
else if (var_equal) "Student t-test on log10(CFU)"
else "Welch t-test on log10(CFU)",
estimate_log10_difference = estimate,
# The test runs on log10, so the CI transforms straight into a fold-change
# interval -- the scale the result is actually reported on.
fold_change = 10^estimate,
fold_change_low = 10^conf.low,
fold_change_high = 10^conf.high
) %>%
select(
comparison_family, test, contrast, sample, concentration_label, time_min,
estimate_log10_difference, conf.low, conf.high, fold_change, fold_change_low, fold_change_high,
hedges_g, d_z, paired, n_matched, statistic, parameter, p.value, q.value,
significance, p_adjust_method, adjustment_scope, message, everything()
)
}
run_survival_stats <- function(surv, comparison, p_adjust, adjustment_scope,
control_concentration, ttest_type, paired = FALSE) {
if (!is_survival_frame(surv)) {
return(tibble(message = "Survival statistics require a paired survival frame."))
}
if (identical(comparison, "none")) return(tibble())
if (identical(comparison, "time")) {
return(tibble(message = paste(
"The timepoint comparison is not available on a survival readout:",
"both timepoints have already been consumed to form the ratio.",
"Use 'Survival vs no change' instead."
)))
}
if (!identical(comparison, "survival_vs_zero")) {
# The survival frame carries the per-replicate log ratio in log10_cfu, so
# the existing pairwise machinery tests exactly the right quantity. Whether
# these BETWEEN-cell comparisons are themselves paired depends on whether a
# replicate label means the same thing on both sides -- the caller's claim.
out <- run_groupwise_t_tests(surv, comparison, p_adjust, adjustment_scope,
control_concentration, ttest_type, paired = paired)
if (nrow(out) > 0 && "test" %in% names(out)) {
out <- out %>% mutate(
test = sub("on log10\\(CFU\\)", "on log10 survival ratio", test),
effect_size_kind = ifelse(paired & !is.na(d_z),
"paired (d_z)", "two-sample (Hedges g)")
)
}
return(out)
}
if (nrow(surv) == 0) return(tibble())
cells <- surv %>% distinct(sample, concentration_label)
out <- bind_rows(lapply(seq_len(nrow(cells)), function(i) {
d <- surv %>%
filter(sample == cells$sample[i], concentration_label == cells$concentration_label[i]) %>%
pull(log10_cfu)
n <- length(d)
base <- tibble(
comparison_family = "Survival versus no change, within sample/vector and treatment",
contrast = "survival vs no change",
sample = as.character(cells$sample[i]),
concentration_label = cells$concentration_label[i],
time_min = NA_character_,
panel = as.character(cells$sample[i]),
numerator = "readout", denominator = "baseline",
n_pairs = n, pair_rank = 1
)
if (n < 2) {
return(base %>% mutate(
estimate = if (n == 1) d[1] else NA_real_,
conf.low = NA_real_, conf.high = NA_real_, hedges_g = NA_real_,
d_z = NA_real_, statistic = NA_real_, parameter = NA_real_, p.value = NA_real_,
stderr = NA_real_,
message = if (n == 0) "No complete pairs at this cell." else
"n = 1 pair: point estimate only, no inference."
))
}
s <- sd(d)
if (!is.finite(s) || s == 0) {
# Every replicate moved by exactly the same amount. t.test() returns a NaN
# statistic when that constant equals mu and hard-errors when it does not,
# so neither a bare call nor a tryCatch alone is sufficient.
return(base %>% mutate(
estimate = mean(d), conf.low = NA_real_, conf.high = NA_real_,
hedges_g = NA_real_, d_z = NA_real_, statistic = NA_real_,
parameter = NA_real_, p.value = NA_real_, stderr = 0,
message = "Every replicate changed by an identical amount, so the spread is zero and no t-test is defined."
))
}
tt <- tryCatch(t.test(d, mu = 0), error = function(e) e)
if (inherits(tt, "error")) {
return(base %>% mutate(
estimate = mean(d), conf.low = NA_real_, conf.high = NA_real_,
hedges_g = NA_real_, d_z = NA_real_, statistic = NA_real_,
parameter = NA_real_, p.value = NA_real_, stderr = NA_real_,
message = conditionMessage(tt)
))
}
base %>% mutate(
estimate = mean(d),
conf.low = unname(tt$conf.int[1]), conf.high = unname(tt$conf.int[2]),
hedges_g = NA_real_, d_z = paired_dz(d),
statistic = unname(tt$statistic), parameter = unname(tt$parameter),
p.value = unname(tt$p.value), stderr = unname(tt$stderr %||% (s / sqrt(n))),
message = NA_character_
)
}))
# A NaN p survives p.adjust and then makes every comparison against it NA
# rather than "ns", so it would silently draw nothing. Scrub before adjusting.
out <- out %>% mutate(p.value = ifelse(is.finite(p.value), p.value, NA_real_))
adjust_stats(out, p_adjust, adjustment_scope) %>%
mutate(
test = "One-sample t-test on log10 survival ratio (paired within replicate)",
estimate_log10_difference = estimate,
fold_change = 10^estimate,
fold_change_low = 10^conf.low,
fold_change_high = 10^conf.high,
percent_survival = 100 * 10^estimate,
effect_size_kind = "paired (d_z)"
) %>%
select(
comparison_family, test, contrast, sample, concentration_label, n_pairs,
estimate_log10_difference, conf.low, conf.high,
fold_change, fold_change_low, fold_change_high, percent_survival,
d_z, effect_size_kind, statistic, parameter, p.value, q.value,
significance, p_adjust_method, adjustment_scope, message, everything()
)
}
run_contrast <- function(dat, comparison, p_adjust, control_concentration) {
if (nrow(dat) < 3 || n_distinct(dat$log10_cfu) < 2) return(tibble())
if (comparison == "sample" && n_distinct(dat$sample) < 2) return(tibble(message = "Sample comparison requires at least two samples."))
if (comparison == "time" && n_distinct(dat$time_min) < 2) return(tibble(message = "Timepoint comparison requires at least two timepoints."))
if (comparison %in% c("concentration_vs_control", "concentration_all") && n_distinct(dat$concentration_label) < 2) {
return(tibble(message = "Treatment comparison requires at least two treatment groups."))
}
fit <- lm(model_formula(dat), data = dat)
result <- tryCatch({
if (comparison == "sample") {
by_vars <- c("concentration_label", "time_min")
by_vars <- by_vars[vapply(by_vars, function(z) n_distinct(dat[[z]]) > 1, logical(1))]
spec <- if (length(by_vars) > 0) {
as.formula(paste("~ sample |", paste(by_vars, collapse = " * ")))
} else {
~ sample
}
pairs(emmeans(fit, spec), adjust = "none")
} else if (comparison == "time") {
by_vars <- c("sample", "concentration_label")
by_vars <- by_vars[vapply(by_vars, function(z) n_distinct(dat[[z]]) > 1, logical(1))]
spec <- if (length(by_vars) > 0) {
as.formula(paste("~ time_min |", paste(by_vars, collapse = " * ")))
} else {
~ time_min
}
pairs(emmeans(fit, spec), adjust = "none")
} else if (comparison == "concentration_vs_control") {
by_vars <- c("sample", "time_min")
by_vars <- by_vars[vapply(by_vars, function(z) n_distinct(dat[[z]]) > 1, logical(1))]
spec <- if (length(by_vars) > 0) {
as.formula(paste("~ concentration_label |", paste(by_vars, collapse = " * ")))
} else {
~ concentration_label
}
emm <- emmeans(fit, spec)
emm_df <- as.data.frame(emm)
control_idx <- which(as.character(emm_df$concentration_label) == control_concentration)[1]
if (is.na(control_idx)) {
stop("The selected control treatment is not present in the data.", call. = FALSE)
}
contrast(emm, method = "trt.vs.ctrl", ref = control_idx, adjust = "none")
} else {
by_vars <- c("sample", "time_min")
by_vars <- by_vars[vapply(by_vars, function(z) n_distinct(dat[[z]]) > 1, logical(1))]
spec <- if (length(by_vars) > 0) {
as.formula(paste("~ concentration_label |", paste(by_vars, collapse = " * ")))
} else {
~ concentration_label
}
pairs(emmeans(fit, spec), adjust = "none")
}
}, error = function(e) {
tibble(message = conditionMessage(e))
})
out <- as_tibble(as.data.frame(result))
if (nrow(out) == 0) return(out)
if (!"p.value" %in% names(out)) return(out)
adjust_stats(out, p_adjust, "global") %>%
mutate(
test = "Linear model + emmeans on log10(CFU)",
estimate_log10_difference = estimate,
fold_change = 10^estimate
)
}
# ---------------------------------------------------------------------------
# Paired survival readout
# ---------------------------------------------------------------------------
# For an induction time-course the readout is survival: CFU at the readout
# timepoint relative to CFU at baseline, WITHIN THE SAME CULTURE.
#
# Why pair at all. For a cell where every replicate has both timepoints, the
# paired point estimate is algebraically IDENTICAL to the marginal one --
# mean(a_i - b_i) == mean(a_i) - mean(b_i) is an identity. Pairing buys two
# things instead:
# 1. The standard error becomes the SD of within-replicate differences rather
# than the pooled spread across replicates. On cultures whose starting
# titres differ by orders of magnitude that is the difference between
# p = 0.002 and p = 0.5 on the same estimate.
# 2. When a replicate is missing one timepoint, the marginal estimator
# subtracts a baseline mean containing a replicate the readout mean cannot
# contain, charging that replicate's titre to the treatment effect. On the
# gp75 dummy file that flips the sign of the biology at one dose.
SURVIVAL_READOUT_MARKER <- "survival_log10_ratio"
# A survival frame reuses the plotting contract column names, so nothing
# downstream can tell it apart by shape alone. This marker is how the survival
# code paths refuse to run against raw counts, and vice versa.
is_survival_frame <- function(x) {
is.data.frame(x) && "readout" %in% names(x) &&
(nrow(x) == 0 || all(as.character(x$readout) == SURVIVAL_READOUT_MARKER, na.rm = TRUE))
}
# Timepoint levels in true chronological order. format_label() already sorts
# numerically when every time parses as a number, but falls back to order of
# appearance for labels like "pre"/"post" -- so never assume levels()[1] is the
# baseline without consulting time_value.
survival_time_levels <- function(dat) {
lv <- levels(droplevels(dat$time_min))
if (length(lv) == 0 || !"time_value" %in% names(dat)) return(lv)
v <- vapply(lv, function(l) {
vals <- dat$time_value[as.character(dat$time_min) == l]
if (length(vals) == 0) NA_real_ else vals[1]
}, numeric(1))
if (all(is.finite(v))) lv[order(v)] else lv
}
survival_time_label <- function(baseline_time, readout_time) {
paste(readout_time, "vs", baseline_time)
}
# Axis text for each display scale. All three scales plot the SAME underlying
# quantity (the log10 ratio) and differ only in how the ticks are written, so
# switching scale never rescales or distorts the data.
survival_axis_label <- function(surv_scale, baseline_time, readout_time) {
ctx <- paste0(" (", readout_time, " vs ", baseline_time, ")")
switch(
surv_scale %||% "log10",
"fold" = paste0("Fold change in CFU/mL", ctx),
"percent" = paste0("Survival, % of baseline CFU/mL", ctx),
bquote(log[10] ~ "survival ratio" ~ .(ctx))
)
}
survival_scale_labeller <- function(surv_scale) {
switch(
surv_scale %||% "log10",