-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathPreProcessing.R
More file actions
executable file
·1562 lines (1315 loc) · 84.7 KB
/
PreProcessing.R
File metadata and controls
executable file
·1562 lines (1315 loc) · 84.7 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
#################### UI ##################
preProcessingUI <- function(id, prefix="") {
ns <- NS(id)
tagList(
useShinyjs(), # Include shinyjs to enable/disable UI elements
fluidRow(
hidden(column(width = 6, id = ns("pr_c1"),
h4("Add or delete data columns"),
fluidRow(column(10, pickerInput(ns("remove_reps"), "Pick the samples you want to remove",
choices = NULL, multiple = T,
options = list(
`live-search` = TRUE,
`actions-box` = FALSE,
`max-options` = -2, # Prevent selecting more than n-2 columns
`max-options-text` = "Cannot select more than n-2 columns"
))),
column(2, actionBttn(ns("h_balancing"),
icon = icon("info-circle"),
style = "pill",
color = "royal", size = "xs")
)),
fluidRow(column(6,
p(htmlOutput(ns("res_num_reps")), style = "text-color:#AA2222")
),
column(6,
checkboxInput(ns("add_na_columns"), "Fill with empty columns")
)
),
h5("Summary:"),
htmlOutput(ns("ptable_summary"), style = "border:solid;border-width:1px;padding:10px;")
)),
hidden(column(width = 3, id = ns("pr_c2"),
h4("Data manipulation and adjustment"),
fluidRow(column(10, checkboxInput(ns("logtrafo"), "Is the data already log-transformed?", value = F)),
column(2, actionBttn(ns("h_logtrafo"),
icon = icon("info-circle"),
style = "pill",
color = "royal", size = "xs")
)),
fluidRow(column(10, numericInput(ns("max_na"), label = "Maximum number of missing values per feature",
min = 0, max = 0, step = 1, value = 100)),
column(2, actionBttn(ns("h_max_na"),
icon = icon("info-circle"),
style = "pill",
color = "royal", size = "xs")
)),
fluidRow(column(10, selectInput(ns("normalization"), label = "Normalization method",
choices = c(None = "none", Median = "colMedians", "Mean" = "colMeans", "Cyclic LOESS (LIMMA)" = "cyclicloess"),
selected = "none")),
column(2, actionBttn(ns("h_normalization"),
icon = icon("info-circle"),
style = "pill",
color = "royal", size = "xs")
)),
fluidRow(column(10, selectInput(ns("summarize"), label = "Summarize to id features",
choices = c(None = "none", "By sum" = "colSums",
"By mean" = "colMeans", "By median" = "colMedians",
"Robust median (medpolish)" = "medianPolish"
))),
column(2, actionBttn(ns("h_summarize"),
icon = icon("info-circle"),
style = "pill",
color = "royal", size = "xs")
)),
fluidRow(column(10,
selectInput(ns("batch_correction_method"), "Correction method",
choices = c("None", "limma", "Combat"), selected = "none") # New input for batch correction method
),
column(2, actionBttn(ns("h_batch_effect"),
icon = icon("info-circle"),
style = "pill",
color = "royal", size = "xs")
)),
style = 'border-left: 1px solid; margin-bottom: 20px;' # Add bottom margin to separate from next section
)),
hidden(column(3, id = ns("pr_c3"),
h4("Proceed to interaction with apps"),
actionButton(ns("proceed_to_apps"), "Proceed"),
textOutput(ns("txt_proceed_apps")),
fluidRow(
column(10,
style = "text-align: left;",
checkboxInput(ns("map2uniprot"), "Map identifiers to UniProt accession numbers?", value = FALSE),
),
column(2, actionBttn(ns("h_mapping"),
icon = icon("info-circle"),
style = "pill",
color = "royal", size = "xs")
)
),
selectInput(ns("idtype"),
"Select identifier type to map to UniProt",
choices = c("Generic gene names (will be mapped to human)" = "Gene_Name",
"Ensembl gene ids" = "Ensembl",
"GeneIDs (Entrez IDs)" = "GeneID"),
selected = "GeneID"),
style = 'border-left: 1px solid; margin-bottom: 20px;')
)),
hr(style="border:solid;border-width:1px;"),
hidden(fluidRow(id = ns("pr_plots"),
fluidRow(
column(4, fluidRow(
column(10,
style = "text-align: left;",
radioButtons(ns("show_pca_labels"),
"How to show labels",
choices = c("Add labels" = TRUE,
"No labels" = FALSE),
selected = TRUE)),
column(2, actionBttn(ns("h_pcaplot"),
icon = icon("info-circle"),
style = "pill",
color = "royal", size = "xs")
)
)
),
column(4, fluidRow(
column(10,
style = "text-align: left;",
checkboxInput(ns("scale_corrplot"),
"Adjust color gradient to available/calculated correlation values",
),
),
column(2, actionBttn(ns("h_corrplot"),
icon = icon("info-circle"),
style = "pill",
color = "royal", size = "xs")
))
),
column(4, fluidRow(
column(10,
style = "text-align: left;",
radioButtons(ns("show_missing_rows"),
"Configure plot for missing values",
choices = c("Distribution of missing values over features" = TRUE,
"Missing values per sample" = FALSE),
selected = TRUE)),
column(2, actionBttn(ns("h_missingplot"),
icon = icon("info-circle"),
style = "pill",
color = "royal", size = "xs")
))
)
),
fluidRow(column(4,
girafeOutput(ns("pca_plot"), height = "500px")
),
column(4,
plotOutput(ns("corrplot"), height = "500px")
),
column(4,
plotOutput(ns("missingplot"), height = "500px")
), style = 'margin-bottom: 20px;'
),
fluidRow(column(4,
downloadBttn(ns("download_pca"), label = "Download figure (pdf)")),
column(4,
downloadBttn(ns("download_corrplot"), label = "Download figure (pdf)")),
column(4,
downloadBttn(ns("download_missingplot"), label = "Download figure (pdf)")),
)
)
)
)
}
#################### Server ##################
preProcessingServer <- function(id, parent, expDesign, log_operations, SM) {
moduleServer(
id,
function(input, output, session) {
process_table <- reactiveVal(NULL)
processed_table <- reactiveVal(NULL)
other_cols <- reactiveVal(NULL)
pexp_design <- reactiveVal(NULL)
exp_design <- reactiveVal(NULL)
next_tab <- reactiveVal(NULL)
removed_cols <- reactiveVal(NULL)
# Reactive values to store group, batch and replicate information
group_info <- reactiveVal(NULL)
batch_info <- reactiveVal(NULL)
replicate_info <- reactiveVal(NULL)
# Reactive values to added columns
added_columns <- reactiveVal(c())
# Register ALL of them under this module's namespace
ns_id <- session$ns("preProcessing")
SM$register_vals(ns_id, list(
# processed_table = processed_table,
other_cols = other_cols,
pexp_design = pexp_design,
exp_design = exp_design,
process_table = process_table,
# next_tab = next_tab,
removed_cols = removed_cols,
group_info = group_info,
batch_info = batch_info,
replicate_info = replicate_info,
added_columns = added_columns
))
SM$set_input_reassert(session$ns("remove_reps"))
SM$set_input_reassert(session$ns("batch_correction_method"))
SM$set_input_reassert(session$ns("max_na"))
init_data <- function() {
if(!is.null(process_table())) {
# Initialize processed_table with 'id' and 'quant' columns from process_table
initial_data <- process_table()
id_column <- initial_data[, grep("id", sapply(initial_data, class)), drop = FALSE]
# Substitute NA values in id column
id_column[is.na(id_column)] <- "No_ID_Given"
id_column[id_column == ""] <- "No_ID_Given"
quant_columns <- initial_data[, grep("quant", sapply(initial_data, class)), drop = FALSE]
processed_table(cbind(id_column, quant_columns)) # Initialize processed_table
# Keep all other columns separate, only to merge when summarizing
# This is why we need to reload them
other_cols(initial_data[, !(colnames(initial_data) %in% c(colnames(id_column), colnames(quant_columns))), drop = FALSE])
}
}
##########################################################################
##########################################################################
observeEvent(expDesign$next_tab(), {
if (!is.null(expDesign$next_tab())) {
print("init preprocessing")
process_table(expDesign$process_table())
pexp_design(expDesign$pexp_design())
exp_design(expDesign$pexp_design())
init_data()
shinyjs::show("pr_c1")
shinyjs::show("pr_c2")
shinyjs::show("pr_c3")
shinyjs::show("pr_plots")
id_column <- processed_table()[, 1]
quant_columns <- processed_table()[, -1]
# Substitute NA values in id column
id_column[is.na(id_column)] <- "No_ID_Given"
id_column[id_column == ""] <- "No_ID_Given"
# Check if there are duplicate IDs and hide/show the summarize input accordingly
#print(id_column)
if (sum(duplicated(id_column)) > 0) {
shinyjs::show("summarize") # Show the 'Summarize to id features' selector if duplicates are present
} else {
shinyjs::disable("summarize") # Hide the 'Summarize to id features' selector if no duplicates
#shinyjs::disable("h_summarize")
}
# Update pickerInput with new column names and set max-options dynamically
total_columns <- ncol(expDesign$pexp_design())
if (!SM$restoring())
updatePickerInput(session, "remove_reps",
choices = colnames(exp_design()),
options = list(
`max-options` = total_columns - 2, # Set max-options dynamically
`max-options-text` = "Cannot select more than n-2 columns"
))
# Initialize group, batch and replicate information
group_info(pexp_design()[1,]) # Assuming Group info is in the first row
replicate_info(pexp_design()[2,]) # Adjust index based on data structure
batch_info(pexp_design()[3,]) # Adjust index based on data structure
# Check for different batches and batch sample number >= 2
if (length(unique(batch_info())) > 1 && min(table(batch_info()) >= 2)) {
shinyjs::enable("batch_correction_method")
updateSelectInput(session, "batch_correction_method")
} else {
shinyjs::disable("batch_correction_method")
}
# Determine if the data has been log-transformed
if (isTRUE(SM$restoring())) return() # don't clobber restored inputs
tlog <- log_operations()
if (max(quant_columns, na.rm = T) / min(quant_columns, na.rm = T) < 100 || min(quant_columns, na.rm = T) < 0) {
updateCheckboxInput(session, "logtrafo", value = TRUE)
tlog[["preprocess_take_log2"]] <- FALSE
} else {
tlog[["preprocess_take_log2"]] <- TRUE
}
updateNumericInput(session, "max_na",
min = 0, max = ncol(quant_columns),
value = ncol(quant_columns)
)
log_operations(tlog)
}
})
# choices for remove_reps come from exp_design()
observeEvent(exp_design(), {
print("Update remove_reps list")
cn <- colnames(exp_design()); req(length(cn) > 0)
sel_remove <- isolate(input$remove_reps)
sel_remove <- intersect(sel_remove %||% character(0), cn)
updatePickerInput(session, "remove_reps",
choices = cn,
selected = sel_remove,
options = list(
`max-options` = ncol(exp_design()) - 2,
`max-options-text` = "Cannot select more than n-2 columns"
)
)
updateNumericInput(session, "max_na",
min = 0, max = ncol(exp_design())
)
})
# enable/disable batch control button
observe({
if (length(unique(batch_info())) > 1 && min(table(batch_info()) >= 2)) {
shinyjs::enable("batch_correction_method")
} else {
shinyjs::disable("batch_correction_method")
}
})
observeEvent(input$remove_reps, {
req(processed_table())
removed_cols(input$remove_reps)
}, ignoreNULL = FALSE)
##########################################################################
##########################################################################
# Add or delete data columns
remove_cols <- function(tdata, remove_reps, texpdesign) {
print("Removing columns...")
withProgress(message = "Processing...", value = 0, min = 0, max = 1, {
cnames <- colnames(texpdesign)
# Removing selected columns
rem <- -which(names(tdata) %in% remove_reps)
if (length(rem) > 0) {
incProgress(0.1, detail = "Removing replicates")
tdata <- tdata[, rem]
rem2 <- -which(cnames %in% remove_reps)
pexp_design(texpdesign[, rem2])
cnames <- cnames[rem2]
tlog <- log_operations()
tlog[["preprocess_removed_replicates"]] <- remove_reps
log_operations(tlog)
} else {
pexp_design(texpdesign)
}
# Update processed_table to keep only 'id' and 'quant' columns
id_column <- tdata[, grep("id", sapply(tdata, class)), drop = FALSE]
quant_columns <- tdata[, grep("quant", sapply(tdata, class)), drop = FALSE]
processed_table(cbind(id_column, quant_columns))
})
}
##########################################################################
##########################################################################
## Check for balanced exp. design
check_balance <- function(texpdesign) {
print("check for balancing")
# Calculate the number of replicates per experimental condition
ed_stats <- as.vector(table(texpdesign[1, ]))
# Check if all experimental conditions have the same number of replicates
if (length(unique(ed_stats)) > 1) {
# If the design is unbalanced, disable the Proceed button
disable("proceed_to_apps")
enable("add_na_columns") # Enable fill with empty columns when unbalanced
tout <- paste(
"This unbalanced design has between ",
min(ed_stats),
" and maximally", max(ed_stats),
"replicates for each experimental condition (sample type). <br/><b>Please click checkbox to make data balanced.</b>"
)
tout2 <- paste("Unbalanced design!")
} else {
# If the design is balanced, enable the Proceed button
enable("proceed_to_apps")
#disable("add_na_columns") # Disable fill with empty columns when balanced
tout <- paste("Experimental design is balanced.")
tout2 <- NULL
}
output$res_num_reps <- renderText(tout)
output$txt_proceed_apps <- renderText(tout2)
}
##########################################################################
##########################################################################
# "Fill with empty columns" button
add_na_columns <- function(tdata, expdesign) {
print("Adding NA columns...")
reps <- table(expdesign[1, ])
max_reps <- max(reps)
tedes <- expdesign
added_columns <- c() # Track added columns for the summary
# Add the new columns
for (cond in unique(tedes[1, ])) {
tt <- tedes[, tedes[1, ] == cond, drop = F]
if (!is.na(reps[as.character(cond)])) {
for (i in seq_len(max_reps - reps[as.character(cond)])) {
# Create a new column that matches the number of rows in tedes
new_col <- c(cond, max(tt[2, ]) + i, 1)
# Name the new column as new_oldname_numbering
oldname <- colnames(tt)[1] # Assuming the first column is the old name
new_col_name <- paste0("new_", oldname, "_", i) # Add numbering for each new column
# Add the new column to tedes
tedes <- cbind(tedes, new_col)
# Rename the new column in tedes
colnames(tedes)[ncol(tedes)] <- new_col_name
# Add an NA column to tdata (the actual data)
tdata[new_col_name] <- NA
tdata[, new_col_name] <- as.numeric(tdata[, new_col_name])
class(tdata[, new_col_name]) <- "quant"
# Track the added column name for the summary
added_columns <- c(added_columns, new_col_name)
}
}
}
# Store the added columns in the reactive value
added_columns(added_columns)
# log
tlog <- log_operations()
tlog[["added_columns"]] <- added_columns
log_operations(tlog)
# Reorder columns according to experimental design
tedes <- tedes[, order(tedes[1, ], tedes[2, ])]
pexp_design(tedes)
# Update the processed tables
id_column <- tdata[, grep("id", sapply(tdata, class)), drop = FALSE]
quant_columns <- tdata[, grep("quant", sapply(tdata, class)), drop = FALSE]
quant_columns <- quant_columns[, colnames(pexp_design())]
# Update the processed table
#print(head(quant_columns))
processed_table(cbind(id_column, quant_columns)) # Make sure new columns are added here
}
##########################################################################
##########################################################################
# Remove any previously added na columns
remove_na_columns <- function(tdata, expdesign) {
print("Removing NA columns...")
added_cols <- added_columns()
if (length(added_cols) > 0) {
# Remove the added NA columns from tdata
tdata <- tdata[, !(colnames(tdata) %in% added_cols)]
# Remove the added NA columns from expdesign
tedes <- expdesign[, !(colnames(expdesign) %in% added_cols)]
pexp_design(tedes)
# Clear the added_columns reactive value
added_columns(c())
# Update the processed table
id_column <- tdata[, grep("id", sapply(tdata, class)), drop = FALSE]
quant_columns <- tdata[, grep("quant", sapply(tdata, class)), drop = FALSE]
processed_table(cbind(id_column, quant_columns))
}
}
##########################################################################
##########################################################################
# Apply maximum number of missing values per feature
filter_nas <- function(tdata, max_na) {
print("Filtering NAs...")
if (!is.null(max_na)) {
to_delete <- rowSums(is.na(tdata[, -1])) <= max_na
tdata <- tdata[to_delete, , drop=F]
oc <- other_cols()
if (!is.null(oc)) {
oc <- oc[to_delete, ,drop=F]
}
other_cols(oc)
tlog <- log_operations()
tlog[["max_na"]] <- max_na
log_operations(tlog)
}
processed_table(tdata)
}
##########################################################################
##########################################################################
# Log transformation
log_transformation <- function(tdata, logtrafo) {
print("Log transformation...")
if (!logtrafo) {
ttt <- as.matrix(tdata[, -1, drop=F])
ttt <- log2(ttt)
ttt[!is.finite(ttt)] <- NA
tdata[, -1] <- ttt
}
processed_table(tdata)
}
##########################################################################
##########################################################################
# Normalization
normalize_data <- function(tdata, method) {
print("Normalizing data...")
# Apply normalization method
if (method != "none") {
if (method == "colMedians") {
tdata[, -1] <- t(t(tdata[, -1]) - colMedians(as.matrix(tdata[, -1]), na.rm = TRUE))
} else if (method == "colMeans") {
tdata[, -1] <- t(t(tdata[, -1]) - colMeans(as.matrix(tdata[, -1]), na.rm = TRUE))
} else if (method == "cyclicloess") {
tdata[, -1] <- limma::normalizeBetweenArrays(as.matrix(tdata[, -1]), method = "cyclicloess")
}
tlog <- log_operations()
tlog[["normalization"]] <- method
log_operations(tlog)
processed_table(tdata)
}
}
##########################################################################
##########################################################################
# Summarization
summarize_data <- function(tdata, method) {
if (sum(duplicated(tdata[,1])) > 0) {
print("Summarizing data...")
# update other_cols by merging values using bars
o_cols <- other_cols()
if (!is.null(o_cols)) {
to_rbind <- by(o_cols, tdata[, 1], function(x) {
apply(x, 2, function(y) paste(as.character(y), collapse="|"))
})
o_cols <- do.call(rbind, as.list(to_rbind))
}
# Apply summarization method
if (method != "none") {
if (method == "colSums") {
tdata <- aggregate(. ~ tdata[, 1], data = tdata[, -1], FUN = sum, na.rm = TRUE)
} else if (method == "colMeans") {
tdata <- aggregate(. ~ tdata[, 1], data = tdata[, -1], FUN = mean, na.rm = TRUE)
} else if (method == "colMedians") {
tdata <- aggregate(. ~ tdata[, 1], data = tdata[, -1], FUN = median, na.rm = TRUE)
} else if (method == "medianPolish") {
tdata <- MsCoreUtils::aggregate_by_vector(as.matrix(tdata[, -1]), tdata[, 1], FUN = medianPolish, na.rm = TRUE)
tdata <- data.frame(ids=rownames(tdata), tdata)
}
tlog <- log_operations()
tlog[["summarization"]] <- method
log_operations(tlog)
enable("proceed_to_apps")
}
if (!is.null(o_cols))
other_cols(o_cols[as.character(tdata[, 1]), ])
# Update processed table after adjustments
processed_table(tdata)
}
}
##########################################################################
##########################################################################
# Batch Effect Detection
check_batch_effect <- function(tdata, expdesign) {
print("Checking for batch effects...")
# Ensure that there is enough data
if (is.null(tdata) || ncol(tdata) < 2 || nrow(tdata) < 10) {
return()
}
# Store total number of features before processing
total_features <- nrow(tdata)
# Prepare the data
texp_design <- expdesign
# Select only quantitative columns and remove columns with all NAs
tdata <- tdata[, -1, drop = FALSE]
# Filter NA: we go full in to avoid strange effect from potential
# imputation in the method
tdata <- tdata[, colSums(!is.na(tdata)) > 0, drop=F]
tdata <- tdata[complete.cases(tdata), , drop=F]
texp_design <- texp_design[, colnames(tdata), drop = FALSE]
# # Store number of features after removing NAs
# features_without_na <- nrow(tdata[complete.cases(tdata), ])
# # Filter out rows with missing values
# tdata <- tdata[complete.cases(tdata), ]
# Get batch labels
batch_labels <- batch_info()
# Ensure batch_labels has at least two levels
if (length(unique(batch_labels)) < 2) {
return()
}
# Align `batch_labels` to match the data columns
batch_labels <- batch_labels[match(colnames(tdata), colnames(texp_design))]
# Filter rows for having at least one value per batch
for (b in unique(batch_labels)) {
tdata <- tdata[rowSums(tdata[, batch_labels == b, drop=F]) > 0, , drop=F]
}
# Create a samples data frame required for BEclear
sample_ids <- colnames(tdata) # Assuming column names of tdata are the sample IDs
samples <- data.frame(sample_id = sample_ids, batch_id = batch_labels)
# Use BEclear to calculate batch effects
# batch_effect_results <- tryCatch({
batch_effect_results <- BEclear::calcBatchEffects(
data = tdata,
samples = samples,
adjusted = TRUE,
method = "fdr"
)
if (is.null(batch_effect_results)) return() # Exit if error occurred
# Extract median differences and p-values from the results
mdifs <- batch_effect_results$med
pvals <- batch_effect_results$pval
summary <- calcSummary(medians = mdifs, pvalues = pvals, pvaluesTreshold = 0.01, mediansTreshold = 0.5)
return(list(summary=summary, outdata=tdata))
}
#########################################################################
#################### Batch Effect Correction ###########################
batch_correction <- function(tdata, expdesign, batch_labels, method) {
req(!SM$restoring())
print("Correcting batch effects...")
withProgress(message = 'Running batch correction', value = 0, {
# Align `batch_labels` to match the data columns
batch_labels <- batch_info()
batch_labels <- batch_labels[names(batch_labels) %in% colnames(tdata)]
id_col <- NULL
# Determine the number of features with significant batch effects (p < 0.01)
if (method == "None") {
return(NULL)
}
# Filter rows for having at least one value per batch
rownames(tdata) <- paste("r", 1:nrow(tdata))
red_for_correction <- tdata
# Reduced data to batch_labeled set
red_for_correction <- cbind(red_for_correction[, 1], red_for_correction[, names(batch_labels)])
for (b in unique(batch_labels)) {
red_for_correction <- red_for_correction[rowSums(!is.na(red_for_correction[, names(batch_labels[batch_labels == b]), drop=F])) > 1, , drop=F]
}
if (nrow(red_for_correction) < 10) {
sendSweetAlert(session,
title = "Batch Effect Correction Error",
text = "Not enough data after filtering for missing values to run batch effect correction.",
type = "error")
return(NULL)
}
id_col <- tdata[, 1]
if (method == "limma") {
# Use limma to calculate and correct batch effects
batch_effect_corrected <- tryCatch({
removeBatchEffect(red_for_correction[, -1], batch = as.factor(batch_labels))
}, error = function(e) {
sendSweetAlert(session,
title = "Batch Effect Correction Error",
text = paste("An error occurred during batch effect correction with limma:", e$message),
type = "error")
return(NULL)
})
} else if (method == "Combat") {
# Use Combat to correct batch effects
batch_effect_corrected <- tryCatch({
sva::ComBat(dat = red_for_correction[, -1], batch = as.factor(batch_labels), mod = NULL, par.prior = TRUE, prior.plots = FALSE)
}, error = function(e) {
sendSweetAlert(session,
title = "Batch Effect Correction Error",
text = paste("An error occurred during batch effect correction with Combat:", e$message),
type = "error")
return(NULL)
})
} else {
sendSweetAlert(session,
title = "Batch Effect Correction Error",
text = "Unknown batch correction method selected.",
type = "error")
return()
}
if (is.null(batch_effect_corrected)) return() # Exit if error occurred
tlog <- log_operations()
tlog[["batch_correction"]] <- method
log_operations(tlog)
# Increment progress to 90%
incProgress(0.9, detail = "Updating processed table with corrected data")
# # Get the ID column (which is non-numeric column in processed_table)
# origdata <- processed_table()
# # Get data after batch correction
# origdata[, colnames(batch_effect_corrected)] <- batch_effect_corrected
# write data back
tdata[rownames(batch_effect_corrected), names(batch_labels)] <- batch_effect_corrected
processed_table(tdata)
# Increment progress to 100%
incProgress(1, detail = "Batch correction completed")
})
}
## Delay reaction to selecting rows in data table
triggerUpdate <- debounce(reactive(list( input$normalization,
input$summarize,
input$max_na,
input$add_na_columns,
removed_cols(),
input$logtrafo,
expDesign$next_tab(),
input$batch_correction_method)
),1000)
##########################################################################
##########################################################################
# Wrapper for data manipulation and adjustment
# Separate observer for normalization to avoid multiple reactivity loops
observe({
triggerUpdate()
isolate({
init_data()
tdata <- processed_table()
if (is.null(tdata)) return() # Exit if tdata is NULL
remove_cols(tdata, removed_cols(), exp_design())
if (input$add_na_columns) {
add_na_columns(processed_table(), pexp_design())
} else {
remove_na_columns(processed_table(), pexp_design())
}
check_balance(pexp_design())
filter_nas(processed_table(), input$max_na)
log_transformation(processed_table(), input$logtrafo)
normalize_data(processed_table(), input$normalization)
summarize_data(processed_table(), input$summarize)
# set classes of processed_table to id and quant
id_column <- processed_table()[,1, drop = FALSE]
class(id_column[,1]) <- "id"
quant_columns <- processed_table()[, -1]
for (i in 1:ncol(quant_columns)) {
class(quant_columns[,i]) <- "quant"
}
processed_table(cbind(id_column, quant_columns))
batch_correction(processed_table(), pexp_design(), batch_info(), input$batch_correction_method)
#print(colnames(processed_table()))
#print(pexp_design())
})
})
##########################################################################
##########################################################################
# "Summary:"
output$ptable_summary <- renderText({
print("Generating summary...")
# Get the processed table, which reflects any changes made in data treatment
tdata <- processed_table()
isolate({
# Ensure processed_table is available and valid
if (is.null(tdata) || ncol(tdata) < 2 || nrow(tdata) < 10) {
shiny::validate(
need(FALSE, "Data matrix too small for generating summary")
)
return()
}
# Identify "id" and "quant" columns
id_column <- tdata[,1]
quant_columns <- tdata[, -1, drop = FALSE]
# Ensure there is still enough data after filtering quantitative columns
if (ncol(quant_columns) < 2 || nrow(quant_columns) < 10) {
shiny::validate(
need(FALSE, "Not enough quantitative columns or rows for summary generation")
)
return()
}
added_columns <- added_columns() # Store the result in a variable
# check for batch effect
tout <- check_batch_effect(processed_table(), pexp_design())
summary <- tout$summary
# Determine the number of features with significant batch effects (p < 0.01)
significant_batches <- ifelse(is.null(summary), 0, nrow(summary))
# Prepare the summary text
paste(
"<p><b>Before Filling:</b>
<br/><b>Size:</b> The current data table contains ",
ncol(quant_columns), " samples and ", nrow(quant_columns), " features.
<br/><b>Missingness: </b>The proportion of missing values is ",
round(sum(is.na(quant_columns)) / length(as.matrix(quant_columns)), 3),
", with the number of missing values ranging from ", min(colSums(is.na(quant_columns))),
" to ", max(colSums(is.na(quant_columns))), " per sample.
<br/><b>Range:</b> The dynamic range (on log-scale) is from ",
round(min(quant_columns, na.rm = TRUE), 2), " to ", round(max(quant_columns, na.rm = TRUE), 2),
".<br/><b>Summarization:</b> The ID column contains ",
ifelse(sum(duplicated(id_column)) > 0, "non-unique IDs, and thus needs summarization.", "unique IDs, so summarization is not required."),
"<br/><br/><b>Batch Effect:</b> ", ifelse(
length(unique(batch_info())) > 1,
ifelse(min(table(batch_info())) >= 2,
ifelse(
significant_batches > 0,
paste("There are currently", significant_batches, " features potentially affected by batch effects (p < 0.01)."),
"No significant batch effects detected."),
"There need to be at least 2 samples in each batch for running batch effect correction."),
"Only one batch detected, no batch effect correction needed."),
"<br/>Used batch effect correction method: ", input$batch_correction_method, ".",
"<br/><br/><b>After Filling:</b>",
ifelse(length(added_columns()) == 0, " No columns added", paste(" New empty columns added: ", paste(added_columns(), collapse = ", "))), "</p>"
)
})
})
##########################################################################
##########################################################################
## detect id type
observeEvent(input$map2uniprot, {
ids <- unique(processed_table()[, 1])
regex_uniprot <- "^[A-NR-Z][0-9]{5}(-[0-9]+)?$|^[OPQ][0-9][A-Z0-9]{3}[0-9](-[0-9]+)?$"
detect_key_type <- function(ids) {
if (all(grepl("^ENSG[0-9]+", ids))) {
return("Ensembl")
} else if (all(grepl("^[0-9]+$", ids))) {
return("GeneID")
} else if (all(grepl(regex_uniprot, ids))) {
# Simple UniProtKB pattern (e.g., P12345, Q8NBP7)
return("UniProtKB")
} else {
return("Gene_Name")
}
}
keytype <- detect_key_type(ids)
message("Detected key type: ", keytype)
if (isTRUE(SM$restoring())) return() # don't clobber restored inputs
updatePickerInput(session, "idtype",
selected = keytype,
choices = c("Ensembl", "GeneID", "UniProtKB", "Gene_Name"))
})
##########################################################################
##########################################################################
## Send further to next tab
observeEvent(input$proceed_to_apps, {
# Ensure the processed_table is up to date
tdata <- processed_table() # Fetch the current processed_table data
if (!is.null(tdata)) {
processed_table(tdata) # Reassign the same data to ensure it is up-to-date
print("processed_table has been updated before proceeding.")
}
# add Uniprot IDs
map_gene_to_main_uniprot <- function(ids) {
keytype <- input$idtype
# Create UniProt.ws object with species restriction
# try connecting and return NULL if it fails
up <- NULL
tryCatch({
up <- UniProt.ws()
}, error = function(e) {
warning("Failed to connect to UniProt.ws: ", conditionMessage(e))
showModal(modalDialog(
title = "Warning",
"Failed to connect to UniProt.ws. Please check your internet connection or try again later.",
size = "s",
easyClose = T
))
return(NULL)
})
available_keytypes <- keytypes(up)
if (!(keytype %in% available_keytypes)) {
message("Detected key type", keytype, "is not available in UniProt.ws.\nAvailable key types include:\n",
paste(available_keytypes, collapse = ", "))
showModal(modalDialog(
title = "Warning",
paste("Detected key type", keytype, "is not available in UniProt.ws. Please check your input."),
size = "s",
easyClose = T
))
return(NULL)
}
# Exit early if input is UniProt accessions
if (keytype == "UniProtKB") {
message("Input appears to be UniProtKB accessions. No mapping performed.")
showModal(modalDialog(
title = "Warning",
"Input appears to be UniProtKB accessions. No mapping performed.",
size = "s",
easyClose = T
))
return(NULL)
}
# Columns we want (filter down later)
cols <- c("accession")
cols <- intersect(cols, columns(up))
# Fetch mappings
# Helper function to perform chunked select() calls
chunked_uniprot_select <- function(up, ids, keytype, cols, chunk_size = 1000) {
# Split IDs into chunks
id_chunks <- split(ids, ceiling(seq_along(ids) / chunk_size))
# For collecting results