-
Notifications
You must be signed in to change notification settings - Fork 62
Expand file tree
/
Copy pathdifferentialabundance_report.qmd
More file actions
1633 lines (1394 loc) · 61.8 KB
/
Copy pathdifferentialabundance_report.qmd
File metadata and controls
1633 lines (1394 loc) · 61.8 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
---
title-block: none
format:
html:
css: nf-core_style.css
toc: true
toc-location: left
toc-depth: 4
toc-image: nf-core-differentialabundance_logo_light.png
theme: default
number-sections: false
df-print: paged
embed-resources: true
self-contained: true
params:
meta: NULL
input_dir: ./
artifact_dir: NULL
cpus: 1
logo: NULL
css: NULL
citations: NULL
versions_file: NULL
observations: NULL
features: NULL
raw_matrix: NULL
normalised_matrix: NULL
variance_stabilised_matrix: NULL
filtering_tests: NULL
filtering_thresholds: NULL
contrasts_file: NULL
---
```{r setup}
#| include: false
library(knitr)
library(yaml)
library(shinyngs)
library(plotly)
library(DT)
library(dplyr)
library(ggplot2)
library(ComplexHeatmap)
library(UpSetR)
library(tidyverse)
library(reactable)
library(ggbeeswarm)
knitr::opts_chunk$set(echo = TRUE)
# Short alias for the deeply-nested user-configurable params subtree.
# Most chunks below refer to `p$foo` rather than `params$meta$params$foo`.
p <- params$meta$params
```
```{r helpers}
#| include: false
# =============================================================================
# Helpers used throughout this report.
#
# Kept in this single chunk so the prose body below stays an orchestration
# outline. The body's job is to *call* these - put implementation here, not
# inline next to the markdown.
# =============================================================================
# ---- Utilities --------------------------------------------------------------
round_dataframe_columns <- function(df, columns = NULL, digits = -1) {
if (digits == -1) return(df)
df <- data.frame(df, check.names = FALSE)
if (is.null(columns)) {
columns <- colnames(df)[map_lgl(df, is.numeric)]
}
df[, columns] <- format(
data.frame(df[, columns], check.names = FALSE),
scientific = TRUE,
digits = digits
)
for (c in columns) {
df[[c]][grep("^ *NA$", df[[c]])] <- NA
df[[c]] <- as.numeric(df[[c]])
}
df
}
module_disabled <- function(name) {
mods <- p$disable_report_modules
if (is.null(mods) || identical(mods, "")) return(FALSE)
name %in% simpleSplit(mods)
}
# Treat NULL / NA / empty string as "missing". Used by name_contrast for
# the per-column "is this populated" decisions that appeared four times
# in the original implementation.
blank <- function(x) length(x) == 0L || is.na(x) || !nzchar(as.character(x))
# Pick the label column for a differential results frame: feature_name_col
# if available, else feature_id_col.
de_label_col <- function(de_df) {
if (features_provided &&
!is.null(p$features_name_col) &&
p$features_name_col %in% colnames(de_df)) {
return(p$features_name_col)
}
p$differential_feature_id_column
}
# ---- Table rendering --------------------------------------------------------
# Single replacement for the reactable + tagList + caption div pattern that
# would otherwise repeat 14+ times throughout the report.
captioned_table <- function(df,
caption = NULL,
pagination = TRUE,
page_size = NULL,
sortable = TRUE,
searchable = FALSE,
bordered = FALSE,
full_width = TRUE,
columns = NULL,
default_sorted = NULL,
...) {
args <- list(
df,
striped = TRUE,
highlight = TRUE,
pagination = pagination,
fullWidth = full_width,
sortable = sortable,
searchable = searchable,
bordered = bordered,
...
)
if (!is.null(page_size)) args$defaultPageSize <- page_size
if (!is.null(columns)) args$columns <- columns
if (!is.null(default_sorted)) args$defaultSorted <- default_sorted
rt <- do.call(reactable::reactable, args)
if (is.null(caption)) return(htmltools::tagList(rt))
htmltools::tagList(
htmltools::tags$div(
style = "overflow-x: auto; max-width: 100%;",
rt
),
htmltools::tags$div(
caption,
style = "text-align: center; margin-top: 10px; color: #5a677a;"
)
)
}
make_params_table <- function(name, pattern = NULL, remove_pattern = FALSE) {
sub <- params_table
if (!is.null(pattern)) sub <- sub[grep(pattern, sub$Parameter), ]
if (remove_pattern) sub$Parameter <- sub(pattern, "", sub$Parameter)
print(captioned_table(sub, caption = paste("Parameters used for", name)))
}
# ---- Small plot helpers ----------------------------------------------------
plot_screeplot <- function(percentVarData) {
tick_step <- max(1, ceiling(nrow(percentVarData) / 10))
tick_vals <- seq(1, nrow(percentVarData), by = tick_step)
plotly::plot_ly(
percentVarData,
x = ~PCA, y = ~var_explained,
type = "scatter", mode = "lines+markers",
line = list(dash = "dash"),
hovertemplate = "PC %{x}<br>Variance explained %{y:.2f}%<extra></extra>"
) |>
plotly::layout(
xaxis = list(title = "PC", tickmode = "array",
tickvals = tick_vals,
ticktext = paste0("PC", tick_vals)),
yaxis = list(title = "Percent variance explained")
)
}
# ---- Differential boxplots (top genes) -------------------------------------
generate_boxplots <- function(combined, label_col) {
qval_pretty <- prettifyVariablename(p$differential_qval_column)
features_id_pretty <- prettifyVariablename(p$features_id_col)
if (!is.null(p$features_name_col) &&
prettifyVariablename(p$features_name_col) %in% colnames(combined)) {
feature_label_pretty <- prettifyVariablename(p$features_name_col)
} else {
feature_label_pretty <- prettifyVariablename(label_col)
if (!feature_label_pretty %in% colnames(combined)) {
feature_label_pretty <- features_id_pretty
}
}
if (qval_pretty %in% colnames(combined)) {
ord <- order(combined[[qval_pretty]])
top_ids <- as.character(head(combined[[features_id_pretty]][ord], 10))
} else {
top_ids <- as.character(head(combined[[features_id_pretty]], 10))
}
cat("\n::: {.panel-tabset .boxplot-container}\n\n")
walk(rev(names(assay_data)), \(assay_type) {
cat(paste0("\n###### ", prettifyVariablename(assay_type), "\n\n"))
expr_mat <- assay_data[[assay_type]]
top_present <- intersect(top_ids, rownames(expr_mat))
if (length(top_present) == 0) {
cat("*No top genes found in this assay matrix.*\n\n")
return(invisible())
}
obs_sub <- observations[colnames(expr_mat), , drop = FALSE]
plot_df <- as.data.frame(expr_mat[top_present, , drop = FALSE])
plot_df[[prettifyVariablename(p$features_type)]] <- rownames(plot_df)
features_pretty <- prettifyVariablename(p$features_type)
plot_df <- pivot_longer(
plot_df,
cols = -tidyselect::all_of(features_pretty),
names_to = "Sample",
values_to = "Expression"
)
plot_df <- arrange(plot_df, .data[[features_pretty]])
cond_var <- if (length(unique(contrast_variables)) > 0) unique(contrast_variables)[1] else main_grouping_variable
plot_df$Condition <- obs_sub[plot_df$Sample, cond_var]
feature_names <- combined[[feature_label_pretty]]
names(feature_names) <- combined[[features_id_pretty]]
plot_df$FeatureName <- unname(feature_names[plot_df[[features_pretty]]])
if (qval_pretty %in% colnames(combined)) {
pvals <- combined[[qval_pretty]]
names(pvals) <- combined[[features_id_pretty]]
plot_df$pval <- unname(pvals[plot_df[[features_pretty]]])
} else {
plot_df$pval <- NA_real_
}
pvals_grouped <- plot_df |>
group_by(FeatureName) |>
summarise(pval = first(pval), .groups = "drop")
y_pos <- plot_df |>
group_by(FeatureName) |>
summarise(y = max(Expression, na.rm = TRUE) * 1.03, .groups = "drop")
pvals_grouped <- left_join(pvals_grouped, y_pos, by = "FeatureName")
p_box <- ggplot(plot_df, aes(x = Condition, y = Expression)) +
geom_boxplot(outlier.shape = NA) +
ggbeeswarm::geom_quasirandom(
width = 0.2,
aes(color = Condition, text = paste0("Sample: ", Sample, "<br>"))
) +
facet_wrap(~ FeatureName, scales = "free_y") +
scale_color_manual(values = groupColorScale) +
theme_light() +
theme(
axis.text.x = element_text(angle = 45, hjust = 1),
axis.title.x = element_text(margin = margin(t = 15)),
legend.position = "none",
strip.text = element_text(color = "black", size = 8),
strip.background = element_rect(linewidth = 0.1),
panel.spacing.y = unit(1.5, "lines"),
panel.spacing.x = unit(1.5, "lines"),
plot.margin = margin(t = 15, b = 20)
) +
geom_text(
data = pvals_grouped,
aes(x = 1.6, y = y, label = paste0("Padj = ", signif(pval, 3))),
inherit.aes = FALSE,
size = 2, color = "grey37", fontface = "italic", na.rm = TRUE
)
p_box <- plotly::ggplotly(p_box, tooltip = c("x", "y", "color", "text")) |>
plotly::layout(height = 600)
print(htmltools::tagList(p_box))
})
cat("\n:::\n\n")
}
# ---- Contrast naming -------------------------------------------------------
# Build a human-readable name for one contrast row. Two-phase: the main
# part (either "target versus reference in variable" or a formula/contrast
# fallback when there is no `variable`), plus a parenthesised
# "(col: value, ...)" suffix listing any populated non-standard columns
# (e.g. `blocking`).
name_contrast <- function(row) {
standard <- c("id", "target", "reference", "variable", "formula", "make_contrasts_str")
main <- if (blank(row$variable)) {
if (!blank(row$formula)) {
base <- paste("Formula:", row$formula)
if (!blank(row$make_contrasts_str)) paste0(base, " (", row$make_contrasts_str, ")") else base
} else if (!blank(row$make_contrasts_str)) {
paste("Contrast:", row$make_contrasts_str)
} else {
paste("Contrast:", row$id)
}
} else {
paste(row$target, "versus", row$reference, "in", row$variable)
}
optional_pairs <- setdiff(names(row), standard) |>
keep(\(col) !blank(row[[col]])) |>
map_chr(\(col) paste(col, row[[col]], sep = ": "))
optional_part <- if (length(optional_pairs)) paste0("(", paste(optional_pairs, collapse = ", "), ")") else ""
paste(main, optional_part)
}
# ---- Section: filtering summary --------------------------------------------
render_filtering_summary <- function() {
tests_path <- file.path(params$input_dir, params$filtering_tests)
thresholds_path <- file.path(params$input_dir, params$filtering_thresholds)
tests <- read_tsv(tests_path, show_col_types = FALSE)
test_results <- tests |>
select(-1) |>
mutate(across(everything(),
~ as.logical(na_if(trimws(as.character(.x)), ""))))
total_features <- nrow(test_results)
passed_all <- test_results |>
mutate(across(everything(), ~ replace_na(.x, FALSE))) |>
mutate(pass = rowSums(across(everything(), as.integer)) == ncol(test_results)) |>
pull(pass)
retained <- sum(passed_all)
removed <- total_features - retained
failures <- test_results |>
mutate(across(everything(), ~ .x %in% FALSE))
failure_count <- failures |>
mutate(n = rowSums(across(everything(), as.integer))) |>
pull(n)
thresholds <- if (file.exists(thresholds_path) && file.size(thresholds_path) > 0) {
read_tsv(thresholds_path, show_col_types = FALSE)
} else {
tibble(rule = character(), threshold = numeric())
}
rule_map <- tibble(
column = names(test_results),
rule = case_when(
names(test_results) == "abundance" ~ "minimum_abundance",
names(test_results) == "na" ~ "minimum_samples_not_na",
names(test_results) == "most_variant_vectors" ~ "most_variant_features",
.default = NA_character_
)
)
cat("The following tables summarize retention and filtering failures.\n\n")
summary_tbl <- tibble(
Metric = c("Total features", "Retained after filtering", "Removed by filtering"),
Count = c(total_features, retained, removed),
Percent = c(100, 100 * retained / total_features, 100 * removed / total_features)
)
print(captioned_table(summary_tbl, caption = "Filtering summary"))
cat("\n")
tbl <- tibble(
column = names(failures),
`Failed (any)` = colSums(failures),
`Failed (only this rule)` = colSums(failures & (failure_count == 1))
) |>
left_join(rule_map, by = "column") |>
left_join(thresholds, by = "rule") |>
mutate(
Rule = case_when(
column == "abundance" ~ "Minimum abundance threshold",
column == "na" ~ "Minimum non-NA samples",
column == "most_variant_vectors" ~ "Top most variant features",
.default = column
),
Threshold = threshold
) |>
select(Rule, Threshold, `Failed (any)`, `Failed (only this rule)`)
print(captioned_table(tbl, caption = "Filtering rule breakdown (counts may overlap)"))
}
# ---- Section: PCA panels ---------------------------------------------------
render_pca_panels <- function() {
cat("::: {.panel-tabset}")
percentVar_list <- list()
for (assay_type in rev(names(assay_data))) {
pca_data <- pca_datas[[assay_type]]
plotdata <- pca_data$coords
percentVar <- pca_data$percentVar
plotdata$name <- rownames(plotdata)
labels <- paste0(colnames(plotdata), " (", sprintf("%.1f", percentVar), "%)")
cat(paste0("\n##### ", prettifyVariablename(assay_type), "\n"))
plot_types <- if (ncol(pca_data$coords) >= 3) {
list("2" = "scatter", "3" = "scatter3d")
} else {
list("2" = "scatter")
}
for (d in names(plot_types)) {
fig <- plotly::plot_ly()
trace_indices <- list()
trace_counter <- 0L
for (iv in informative_variables) {
plotdata$colorby <- factor(
observations[[iv]],
levels = unique(observations[[iv]])
)
pcaColorScale <- makeColorScale(length(unique(plotdata$colorby)), palette = p$exploratory_palette_name)
lvls <- levels(plotdata$colorby)
start_idx <- trace_counter + 1L
for (j in seq_along(lvls)) {
idx <- which(plotdata$colorby == lvls[j])
trace_counter <- trace_counter + 1L
common <- list(
text = plotdata$name[idx],
name = lvls[j],
legendgroup = iv,
showlegend = (iv == informative_variables[1]),
visible = (iv == informative_variables[1])
)
fig <- if (d == "2") {
do.call(plotly::add_markers, c(list(fig), common, list(
x = pca_data$coords[, 1][idx],
y = pca_data$coords[, 2][idx],
hoverinfo = "text+x+y",
marker = list(size = 8, color = pcaColorScale[j])
)))
} else {
do.call(plotly::add_markers, c(list(fig), common, list(
x = pca_data$coords[, 1][idx],
y = pca_data$coords[, 2][idx],
z = pca_data$coords[, 3][idx],
type = "scatter3d",
mode = "markers",
hoverinfo = "text+x+y+z",
marker = list(size = 3, color = pcaColorScale[j])
)))
}
}
trace_indices[[iv]] <- (start_idx):trace_counter
}
total_traces <- trace_counter
updatemenus <- list(list(
type = "dropdown", active = 0,
x = 1, xanchor = "right",
y = 1.1, yanchor = "top",
buttons = map(informative_variables, \(iv) {
vis <- rep(FALSE, total_traces); vis[trace_indices[[iv]]] <- TRUE
showleg <- rep(FALSE, total_traces); showleg[trace_indices[[iv]]] <- TRUE
list(
label = prettifyVariablename(iv),
method = "update",
args = list(
list(visible = vis, showlegend = showleg),
list(title = paste("Color by", prettifyVariablename(iv)))
)
)
})
))
if (d == "2") {
fig <- fig |> plotly::layout(
updatemenus = updatemenus,
margin = list(t = 100),
xaxis = list(title = labels[1]),
yaxis = list(title = labels[2]),
title = paste("Color by", prettifyVariablename(informative_variables[1])),
legend = list(title = list(text = prettifyVariablename(informative_variables[1])))
)
} else {
fig <- fig |> plotly::layout(
updatemenus = updatemenus,
margin = list(t = 100),
scene = list(
xaxis = list(title = labels[1]),
yaxis = list(title = labels[2]),
zaxis = list(title = labels[3])
),
title = paste("Color by", prettifyVariablename(informative_variables[1]))
)
}
print(htmltools::tagList(fig))
}
if (!assay_type %in% names(percentVar_list)) {
percentVar_list[[assay_type]] <- percentVar
}
}
cat(":::")
invisible(percentVar_list)
}
render_scree_panels <- function(percentVar_list) {
cat(paste0("\n#### Scree plot\n"))
cat("::: {.panel-tabset}")
cat("\nThe following scree plot visualizes what percentage of total variation in the data can be explained by each of the principal components computed.\n")
iwalk(percentVar_list, \(percentVar, assay_type) {
percentVarData <- data.frame(var_explained = percentVar)
percentVarData$PCA <- as.numeric(rownames(percentVarData))
cat(paste0("\n##### ", prettifyVariablename(assay_type), "\n"))
print(htmltools::tagList(plot_screeplot(percentVarData)))
cat("\n")
})
cat(":::")
}
# d3heatmap chokes on a single-row matrix; duplicate to work around it.
pca_meta_heatmap_matrix <- function() {
if (nrow(pca_vs_meta) == 1) rbind(pca_vs_meta, pca_vs_meta) else pca_vs_meta
}
# The d3heatmap call is intentionally NOT wrapped in a render-* function:
# emitting it as a top-level chunk expression lets `knit_print.htmlwidget`
# dispatch with the widget's natural sizing policy. Calling it from inside
# a function and forwarding via `tagList |> print` works but applies a
# fixed-pixel sizing that squishes the heatmap vertically.
render_pca_meta_annotations <- function() {
walk(rownames(pca_vs_meta), \(variable) {
sig_comps <- pca_vs_meta[variable, ] < 0.1
sig_comps[is.na(sig_comps)] <- FALSE
if (!any(sig_comps)) return(invisible())
min_sig_comp <- min(which(sig_comps))
cat(paste0("The variable '", variable, "' shows an association with ",
colnames(pca_vs_meta)[min_sig_comp],
" (p = ", sprintf("%.2f", pca_vs_meta[variable, min_sig_comp]), "). "))
})
}
# ---- Section: clustering heatmaps -----------------------------------------
render_clustering_heatmaps <- function() {
ntop_for <- function(mat) {
if (p$exploratory_n_features == -1) nrow(mat) else p$exploratory_n_features
}
annotation_colour <- function(iv) {
if (length(unique(observations[[iv]])) > 10) return(NULL)
if (is.numeric(observations[[iv]])) {
circlize::colorRamp2(
c(min(observations[[iv]], na.rm = TRUE), max(observations[[iv]], na.rm = TRUE)),
c("blue", "red")
)
} else {
vals <- unique(na.omit(as.character(observations[[iv]])))
cscale <- makeColorScale(length(vals), palette = p$exploratory_palette_name)
cscale <- rep(cscale, length.out = length(vals))
set_names(cscale, sort(vals))
}
}
cat("::: {.panel-tabset}")
walk(rev(names(assay_data)), \(assay_type) {
cat(paste0("\n##### ", prettifyVariablename(assay_type), "\n"))
variable_genes <- selectVariableGenes(
matrix = assay_data[[assay_type]],
ntop = ntop_for(assay_data[[assay_type]])
)
ann_colors <- compact(map(set_names(informative_variables), annotation_colour))
ha <- ComplexHeatmap::HeatmapAnnotation(
df = observations[, informative_variables, drop = FALSE],
annotation_name_side = "left",
col = ann_colors
)
heat_mat <- assay_data[[assay_type]][variable_genes, ]
ph <- ComplexHeatmap::Heatmap(
heat_mat,
name = "Expression",
top_annotation = ha,
show_row_names = FALSE,
show_column_names = length(colnames(heat_mat)) < 20,
clustering_method_columns = p$exploratory_clustering_method,
cluster_rows = FALSE,
clustering_distance_columns = p$exploratory_cor_method,
column_dend_height = grid::unit(35, "mm"),
column_title = paste0(
p$observations_type, " clustering heatmap\n(",
p$exploratory_clustering_method, " clustering, ",
p$exploratory_cor_method, " correlation)"
),
column_names_gp = grid::gpar(fontsize = 8),
column_names_rot = 45,
col = circlize::colorRamp2(
c(min(heat_mat), 0, max(heat_mat)),
c("blue", "white", "red")
),
heatmap_legend_param = list(direction = "horizontal", title_position = "lefttop")
)
ComplexHeatmap::draw(ph,
heatmap_legend_side = "bottom",
annotation_legend_side = "right",
legend_grouping = "original")
cat("\n\n")
})
cat(":::")
}
# ---- Section: outlier detection -------------------------------------------
render_outlier_detection <- function() {
iv_min_group_sizes <- map_int(
informative_variables,
\(x) min(table(observations[[x]]))
)
if (!any(iv_min_group_sizes > 2)) return(invisible())
cat("\n### Outlier detection\n")
cat("::: {.panel-tabset}")
cat("\nOutlier detection based on [median absolute deviation](https://archive.ph/o3thZ) was undertaken, the outlier scoring is plotted below. For more on MAD, see [this wiki article](https://en.wikipedia.org/wiki/Median_absolute_deviation).\n")
walk(informative_variables[iv_min_group_sizes > 2], \(iv) {
cat(paste("\n####", iv, "\n"))
plotdata <- madScore(
matrix = assay_data[[p$exploratory_final_assay]],
sample_sheet = observations,
groupby = iv
)
if (is.null(plotdata)) return(NULL)
print(htmltools::tagList(plotly_scatterplot(
x = plotdata$group,
y = plotdata$mad,
color = plotdata$outlier,
hline_thresholds = c("Outlier threshold" = p$exploratory_mad_threshold),
palette = makeColorScale(2, palette = p$differential_palette_name),
legend_title = "Outlier status",
labels = rownames(plotdata),
show_labels = TRUE,
xlab = "Sample group",
ylab = "MAD score"
)))
outliers <- rownames(plotdata)[plotdata$outlier]
if (length(outliers) == 0) {
cat(paste0("No outlying samples were detected in groups defined by ", iv, ".\n"))
} else {
cat(paste0(length(outliers), " possible outliers were detected in groups defined by ", iv,
": ", paste(outliers, collapse = ", "), "\n"))
}
})
cat(":::")
}
# ---- Section: differential method description -----------------------------
render_method_description <- function() {
cat(switch(
p$differential_method,
"deseq2" = paste0(
"The `DESeq2 R` package was used for differential analysis. p-values were adjusted with the ",
p$deseq2_p_adjust_method, " method to reduce the number of false positives. ",
ucfirst(p$features_type),
"s were considered differential if, for the respective contrast, the adjusted p-value was equal to or lower than ",
p$deseq2_alpha, " and the absolute log2 fold change was equal to or higher than ",
p$deseq2_lfc_threshold, "."
),
"limma" = paste0(
"The `limma R` package",
ifelse(isTRUE(p$limma_use_voom), " with `voom` transformation", ""),
" was used for differential analysis. p-values were adjusted with the ",
p$limma_adjust_method, " method to reduce the number of false positives. ",
ucfirst(p$features_type),
"s were considered differential if, for the respective contrast, the adjusted p-value was equal to or lower than ",
p$limma_p_value, " and the absolute log2 fold change was equal to or higher than ",
p$limma_lfc, "."
),
"dream" = paste0(
"The `variancePartition` `dream` workflow",
ifelse(isTRUE(p$dream_apply_voom), " with `voom` transformation", ""),
" was used for differential analysis. p-values were adjusted with the ",
p$dream_adjust_method, " method to reduce the number of false positives. ",
ucfirst(p$features_type),
"s were considered differential if, for the respective contrast, the adjusted p-value was equal to or lower than ",
p$dream_p_value, " and the absolute log2 fold change was equal to or higher than ",
p$dream_lfc, "."
),
paste0("The `", p$differential_method, "` method was used for differential analysis.")
))
}
# ---- Section: DE count tables (Adjusted / Unadjusted tabset) --------------
render_de_count_tables <- function() {
cat("::: {.panel-tabset}")
walk(names(p_value_types), \(pvt) {
cat("\n#### ", pvt, "\n")
caption <- paste0("Differential ", p$features_type, " ", p$abundance_type,
" (target relative to reference)")
print(captioned_table(
differential_tables[[pvt]],
caption = caption,
pagination = FALSE,
sortable = FALSE,
showSortable = FALSE
))
cat("\n")
})
cat("\n:::\n\n")
}
# ---- Section: upset plots --------------------------------------------------
render_upset_plots <- function() {
if (nrow(contrasts) <= 1) return(invisible())
cat("\n### Upset plot\n\n")
cat("::: {.panel-tabset}")
walk(names(p_value_types), \(pvt) {
cat("\n#### ", pvt, "\n")
de_genes <- map(differential_results, \(de) {
label_col <- de_label_col(de)
sig <- de[
!is.na(de[[label_col]]) &
!is.na(de[[p_value_types[[pvt]]]]) &
abs(de[[p$differential_fc_column]]) > log2(p$differential_min_fold_change) &
de[[p_value_types[[pvt]]]] < p_value_thresholds[[pvt]],
]
sig[[label_col]]
}) |> set_names(names(differential_results))
# UpSet needs at least 2 contrasts to overlap, each with >= 2 features
contrasts_with_overlap <- sum(map_int(de_genes, length) >= 2)
if (contrasts_with_overlap > 1) {
suppressWarnings(suppressMessages({
p_up <- UpSetR::upset(UpSetR::fromList(de_genes))
print(p_up)
}))
}
cat("\n\n")
})
cat("\n:::\n\n")
}
# ---- Section: per-contrast detail (volcano + table + boxplots + biotype) --
render_de_volcano <- function(full_de, pvt, pval_column, p_value_threshold, contrast_row, label_col) {
de_fc <- abs(full_de[[p$differential_fc_column]]) >= abs(log2(p$differential_min_fold_change))
de_fc_label <- paste("abs(logFC) >=", log2(p$differential_min_fold_change))
de_pval <- full_de[[pval_column]] <= p_value_threshold
de_pval_label <- paste(pvt, "<=", p_value_threshold)
de_pval_fc_label <- paste(de_fc_label, "&", de_pval_label)
full_de$differential_status <- "Not significant"
full_de$differential_status[de_fc] <- de_fc_label
full_de$differential_status[de_pval] <- de_pval_label
full_de$differential_status[de_fc & de_pval] <- de_pval_fc_label
full_de$differential_status <- factor(
full_de$differential_status,
levels = c("Not significant", de_fc_label, de_pval_label, de_pval_fc_label),
ordered = TRUE
)
vline_thresholds <- list()
vline_thresholds[[paste(p$differential_fc_column, "<=", log2(p$differential_min_fold_change))]] <- -log2(p$differential_min_fold_change)
vline_thresholds[[paste(p$differential_fc_column, ">=", log2(p$differential_min_fold_change))]] <- log2(p$differential_min_fold_change)
palette_volcano <- append(c("#999999"), makeColorScale(3, p$differential_palette_name))
hover_labels <- as.character(full_de[[label_col]])
miss <- is.na(hover_labels) | hover_labels == ""
hover_labels[miss] <- as.character(full_de[[p$differential_feature_id_column]][miss])
zero_p <- sum(full_de[[pval_column]] == 0, na.rm = TRUE)
if (zero_p) {
cat(sprintf(
"<i>%d feature%s not shown because of p value = 0; please refer to the results tables.</i><br><br>",
zero_p, ifelse(zero_p > 1, "s are", " is")
))
}
max_fc <- max(abs(full_de[[p$differential_fc_column]])) * 1.1
p_volc <- do.call(plotly_scatterplot, list(
x = full_de[[p$differential_fc_column]],
y = -log10(full_de[[pval_column]]),
colorby = full_de$differential_status,
ylab = paste("-log(10)", pval_column),
xlab = paste("higher in", contrast_row$reference,
" <<", p$differential_fc_column,
">> higher in", contrast_row$target),
labels = hover_labels,
vline_thresholds = vline_thresholds,
show_labels = FALSE,
legend_title = "Differential status",
palette = palette_volcano
)) |>
plotly::layout(xaxis = list(range = list(-max_fc, max_fc))) |>
plotly::add_segments(
x = -max_fc, xend = max_fc,
y = -log10(p_value_threshold), yend = -log10(p_value_threshold),
line = list(color = "black", width = 2, dash = "dot"),
showlegend = TRUE, inherit = FALSE,
name = paste(pval_column, "=", p_value_threshold)
)
print(htmltools::tagList(p_volc))
list(de_fc = de_fc, de_pval = de_pval)
}
# Build the prettified, ordered, Direction-annotated frame used by both the
# DE table and the boxplots. Kept separate so it stays the single source of
# truth even when the de_table module is disabled.
build_de_combined <- function(full_de, mask) {
full_de |>
filter(mask) |>
select(-tidyselect::any_of("differential_status")) |>
mutate(
Direction = if_else(.data[[p$differential_fc_column]] > 0, "Up", "Down")
) |>
arrange(
.data[[p$differential_qval_column]],
.data[[p$differential_pval_column]]
) |>
relocate(Direction) |>
rename_with(prettifyVariablename)
}
render_de_table <- function(combined, contrast_description, diff_file) {
cols_to_format_pretty <- prettifyVariablename(c(
p$differential_fc_column,
p$differential_pval_column,
p$differential_qval_column
))
cols_present_pretty <- intersect(cols_to_format_pretty, colnames(combined))
no_filter_cols <- c("Pvalue", "Padj", "Log2FoldChange")
column_defs <- list()
for (col_name in colnames(combined)) {
column_defs[[col_name]] <- if (col_name %in% cols_present_pretty) {
reactable::colDef(
format = reactable::colFormat(digits = 5),
filterable = !(col_name %in% no_filter_cols),
align = "right"
)
} else if (col_name == "Direction") {
reactable::colDef(filterable = TRUE, align = "center")
} else if (col_name == "Gene id") {
reactable::colDef(filterable = TRUE, minWidth = 180)
} else {
reactable::colDef(filterable = TRUE)
}
}
caption <- paste(
"Differential genes (Up + Down) in", contrast_description,
"(check", diff_file, "for more detail)"
)
print(captioned_table(
combined,
caption = caption,
filterable = TRUE,
bordered = TRUE,
page_size = 20,
columns = column_defs,
default_sorted = set_names(
list("asc"),
prettifyVariablename(p$differential_qval_column)
),
showPageSizeOptions = TRUE,
pageSizeOptions = c(10, 20, 50, 100)
))
}
render_biotype_plot <- function(combined) {
if (!"Gene biotype" %in% colnames(combined)) {
cat("Column 'Gene biotype' does not exist. Skipping plot.\n")
return(invisible())
}
bt <- as.data.frame(table(combined[["Gene biotype"]], combined[["Direction"]]))
colnames(bt) <- c("Gene biotype", "Direction", "count")
bt <- bt[bt$count > 0, , drop = FALSE]
biotype_plot <- ggplot(
bt,
aes(x = stats::reorder(`Gene biotype`, -count), y = count, fill = Direction)
) +
geom_bar(stat = "identity", position = position_dodge()) +
labs(
title = "Differentially Expressed Genes by Gene Biotype and Direction",
x = "Gene Biotype",
y = "Number of Differentially Expressed Genes"
) +
theme_minimal() +
theme(axis.text.x = element_text(angle = 45, hjust = 1))
print(htmltools::tagList(plotly::ggplotly(biotype_plot)))
cat("\n")
}
render_de_details <- function(i) {
if (i == 1 && length(warnings_list) > 0) walk(warnings_list, cat)
cat("\n#### ", contrast_descriptions[i], "\n")
cat('::: {.panel-tabset style="width: 1000px; min-width: 1000px;"}\n\n')
full_de <- differential_results[[i]]
needed <- c(p$differential_fc_column, p$differential_qval_column, p$differential_pval_column)
present <- intersect(needed, colnames(full_de))
if (length(present)) {
full_de <- full_de[stats::complete.cases(full_de[, present, drop = FALSE]), ]
}
label_col <- de_label_col(full_de)
walk(names(p_value_types), \(pvt) {
cat("\n##### ", pvt, " p values", "\n\n")
pval_column <- p_value_types[[pvt]]
threshold <- p_value_thresholds[[pvt]]
masks <- if (!module_disabled("volcano")) {
render_de_volcano(full_de, pvt, pval_column, threshold, contrasts[i, ], label_col)
} else {
list(
de_fc = abs(full_de[[p$differential_fc_column]]) >= abs(log2(p$differential_min_fold_change)),
de_pval = full_de[[pval_column]] <= threshold
)
}
cat("\n###### Differential Genes Table\n\n")
de_fc_sig <- masks$de_fc & masks$de_pval
if (sum(de_fc_sig) == 0) {
cat("No significantly differential genes in either direction.\n\n")
return(invisible())
}
combined <- build_de_combined(full_de, de_fc_sig)
if (!module_disabled("de_table")) {
render_de_table(combined, contrast_descriptions[i], differential_files[[i]])
}
cat("\n**Box plots**\n\n")
cat("The following box plots show the distribution of expression levels for the top 10 genes ranked by significance.\n\n")
generate_boxplots(combined, label_col)
if (!module_disabled("biotype_plot")) render_biotype_plot(combined)
})
cat(":::")
}
# ---- Section: gene set analysis -------------------------------------------
render_gsea_section <- function() {
gsea_contrasts <- contrasts[
!is.na(contrasts$reference) & contrasts$reference != "" &
!is.na(contrasts$target) & contrasts$target != "",
]
if (nrow(gsea_contrasts) == 0) {
warning("No contrasts with reference and target defined. Skipping GSEA report section.")
return(invisible())
}
render_gsea_side <- function(file, role, label) {
if (!file.exists(file)) {
cat("\n*", role, " GSEA file missing: ", file, "*\n", sep = "")
return(invisible())
}
tbl <- read_metadata(file)[, c(-2, -3)]
tbl <- round_dataframe_columns(tbl, digits = p$round_digits)
print(captioned_table(tbl,
caption = paste0(role, " (", label, ")"),
searchable = TRUE, page_size = 10))
}