-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.R
More file actions
1422 lines (1275 loc) · 61.7 KB
/
server.R
File metadata and controls
1422 lines (1275 loc) · 61.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
# Advanced plotting libraries
# devtools::install_github('hadley/ggplot2') # Use development version if needed
library(ggplot2) # Grammar of graphics for static plots
library(plotly) # Interactive web-based data visualization
library(dplyr) # Data manipulation and transformation
# Visualization and UI enhancement packages
library(RColorBrewer) # Color palettes for data visualization
library(shinyBS) # Bootstrap components for Shiny (tooltips, modals, etc.)
library(data.table) # High-performance data manipulation and reading
############################################################################
# EXTERNAL HELPER FUNCTIONS
############################################################################
# Load custom R functions for data processing and format handling
# These functions are stored in separate files for modularity and reusability
# Filter data to keep only the highest intensity features for each mass/RT pair
source("files/Rfiles/Keep_highest_signal.R", local = TRUE)
# Custom function to efficiently combine multiple data frames
source("files/Rfiles/custom_rbindlist.R", local = TRUE)
# Parse and process TopPIC software output files
source("files/Rfiles/Parse_TopPIC_input.R", local = TRUE)
# Standardize column names across different deconvolution software formats
source("files/Rfiles/rename_input_coulumns.R", local = TRUE)
# Check input files with adapted error messages
source("files/Rfiles/check_input_tables.R", local = TRUE)
############################################################################
# SERVER LOGIC
############################################################################
# Define the server-side logic that handles user inputs, processes data,
# and generates reactive outputs for the user interface
server <- function(input, output, clientData, session) {
#--------------------------------------------------------------------------
# SECTION 1: DYNAMIC UI MODIFICATIONS
#--------------------------------------------------------------------------
#--------------------------------------------------------------------------
# 1.1: Update zoom instructions based on plot type
#--------------------------------------------------------------------------
# Provide different zoom instructions for static vs interactive plots
output$ZoomParam <- renderUI({
if (input$DataPoints) {
# Instructions for interactive plotly plots
HTML("<h5>Zoom in: select the ranges of interest.<br/>Zoom out: Click on the unzoom button.</h5>")
} else {
# Instructions for static ggplot2 plots
HTML("<h5>Zoom in: select the ranges of interest and double click.<br/>Zoom out: double click.</h5>")
}
})
#--------------------------------------------------------------------------
# 1.2: Dynamic color scale updates based on number of files
#--------------------------------------------------------------------------
# Automatically switch between continuous and qualitative color palettes
# based on whether single or multiple files are loaded
observe({
if (!is.null(linput())) {
x <- linput() # Get number of input files
if (x > 1) {
# Multiple files: use qualitative color schemes for file comparison
updateSelectInput(session, "colourscale",
"Colour scale:",
c("Paired" = "Paired", # Qualitative palettes for distinguishing files
"Set1" = "Set1",
"Set2" = "Set2",
"Set3" = "Set3",
"Set4" = "Dark2",
"Set5" = "Accent"
))
} else {
# Single file: use continuous color schemes for intensity visualization
updateSelectInput(session, "colourscale",
"Colour scale:",
c("Spectral" = "Spectral", # Continuous palettes for intensity
"Red/yellow/blue" = "RdYlBu",
"Red/yellow/green" = "RdYlGn",
"yellow to red" = "YlOrRd"
))
}
}
})
# Store the selected color value in a reactive variable
colval <- reactiveVal()
observe({
x <- input$colourscale
colval(x)
})
#--------------------------------------------------------------------------
# 1.3: Dynamic protein ID selection for MS/MS mode
#--------------------------------------------------------------------------
# Populate protein selection dropdown based on loaded identification data
observe({
# For Proteome Discoverer data: extract protein descriptions from PSM file
if (!is.null(filedataMS2())) {
if (length(filedataMS2()$PSMfile$Master.Protein.Descriptions[!is.na(filedataMS2()$PSMfile$Master.Protein.Descriptions)]) > 0) {
updateSelectInput(session, "SelectProt",
"Select the ID to highlight:",
sort(unique(filedataMS2()$PSMfile$Master.Protein.Descriptions[!is.na(filedataMS2()$PSMfile$Master.Protein.Descriptions)]))
)
}
}
# For MSPathFinder data: extract protein descriptions
if (!is.null(filedataMS2PF())) {
if (length(filedataMS2PF()$Protein.Descriptions[!is.na(filedataMS2PF()$Protein.Descriptions)]) > 0) {
updateSelectInput(session, "SelectProt",
"Select the ID to highlight:",
sort(unique(filedataMS2PF()$Protein.Descriptions[!is.na(filedataMS2PF()$Protein.Descriptions)]))
)
}
}
# For TopPIC data: extract protein descriptions
if (!is.null(filedataMS2TP())) {
if (length(filedataMS2TP()$Protein.Descriptions[!is.na(filedataMS2TP()$Protein.Descriptions)]) > 0) {
updateSelectInput(session, "SelectProt",
"Select the ID to highlight:",
sort(unique(filedataMS2TP()$Protein.Descriptions[!is.na(filedataMS2TP()$Protein.Descriptions)]))
)
}
}
})
#--------------------------------------------------------------------------
# 1.4: Track number of selected proteins for plot layout
#--------------------------------------------------------------------------
# Count selected proteins to adjust plot dimensions for export
nProtSelection <- reactiveVal(0)
observeEvent(c(plotInput1, input$SelectProt), {
nProtSelection(length(input$SelectProt))
})
#--------------------------------------------------------------------------
# SECTION 2: FILE INPUT HANDLING
#--------------------------------------------------------------------------
#--------------------------------------------------------------------------
# 2.1: MS file input processing
#--------------------------------------------------------------------------
# Reactive variable to store MS file inputs
InputFileMS <- reactiveVal(NULL)
# Handle MS file uploads in MS mode
observeEvent(input$fileMS, {
ranges$x <- NULL # Reset zoom ranges when new file uploaded
ranges$y <- NULL
if (input$MSModeCheck == "MS" & !is.null(input$fileMS) & input$TestModeCheck == FALSE & input$MS2TestModeCheck == FALSE) {
InputFileMS(input$fileMS)
} else {
InputFileMS(NULL)
}
})
# Handle MS file uploads in MS/MS mode (background MS data)
observeEvent(input$fileMS2, {
if (input$MSModeCheck == "MS2" & !is.null(input$fileMS2)) {
InputFileMS(input$fileMS2)
} else {
InputFileMS(NULL)
}
})
#--------------------------------------------------------------------------
# 2.2: MS/MS file input processing for different software platforms
#--------------------------------------------------------------------------
# Proteome Discoverer files (MSMSSpectrumInfo + PSM files)
InputFilesMS2 <- reactiveVal(NULL)
observeEvent(c(input$MS2file, input$PSMfile), {
if (input$MSModeCheck == "MS2" & !is.null(input$MS2file) & !is.null(input$PSMfile)) {
InputFilesMS2(list("MS2file" = input$MS2file, "PSMfile" = input$PSMfile))
} else {
InputFilesMS2(NULL)
}
})
# MSPathFinder files
InputFilesMS2PF <- reactiveVal(NULL)
observeEvent(input$MS2filePF, {
if (input$MSModeCheck == "MS2" & !is.null(input$MS2filePF)) {
InputFilesMS2PF(input$MS2filePF)
} else {
InputFilesMS2PF(NULL)
}
})
# TopPIC files (MS/MS + identification files)
InputFilesMS2TP <- reactiveVal(NULL)
observeEvent(c(input$MS2fileTP, input$IDfileTP), {
if (input$MSModeCheck == "MS2" & !is.null(input$MS2fileTP) & !is.null(input$IDfileTP)) {
InputFilesMS2TP(list("MS2file" = input$MS2fileTP, "IDfile" = input$IDfileTP))
} else {
InputFilesMS2TP(NULL)
}
})
#--------------------------------------------------------------------------
# SECTION 3: TEST MODE AND FILE TYPE DETECTION
#--------------------------------------------------------------------------
#--------------------------------------------------------------------------
# 3.1: Test mode variables and file type tracking
#--------------------------------------------------------------------------
# Track number of input files
linput <- reactiveVal()
# Test mode states: 0=no test, 1=single file, 2=multiple files, 3=MS2 test
testfileinput <- reactiveVal(0)
# Count files by deconvolution software type
filetype <- reactiveValues(
RoWinPro = 0, # RoWinPro, Bruker, TopPIC files (point-based data)
BioPharma = 0, # BioPharma Finder files (peak range data)
ProMex = 0 # ProMex files (peak range data)
)
#--------------------------------------------------------------------------
# 3.2: Test mode file loading
#--------------------------------------------------------------------------
# Load single test file
observeEvent(input$TestFile1, {
ranges$x <- NULL # Reset zoom
ranges$y <- NULL
linput(1)
testfileinput(1)
filetype$RoWinPro <- 1
filetype$BioPharma <- 0
filetype$ProMex <- 0
colval("Spectral") # Use spectral color scheme for single file
InputFileMS(NULL)
InputFilesMS2(NULL)
InputFilesMS2PF(NULL)
})
# Load multiple test files for comparison
observeEvent(input$TestFile2, {
ranges$x <- NULL # Reset zoom
ranges$y <- NULL
linput(4)
testfileinput(2)
filetype$RoWinPro <- 4
filetype$BioPharma <- 0
filetype$ProMex <- 0
colval("Paired") # Use qualitative color scheme for multiple files
InputFileMS(NULL)
InputFilesMS2(NULL)
InputFilesMS2PF(NULL)
})
# Enable MS/MS test mode
observeEvent(input$MS2TestModeCheck, {
ranges$x <- NULL # Reset zoom
ranges$y <- NULL
if (input$MS2TestModeCheck == TRUE) {
linput(1)
testfileinput(3)
filetype$RoWinPro <- 1
filetype$BioPharma <- 0
filetype$ProMex <- 0
colval("Spectral")
}
InputFileMS(NULL)
InputFilesMS2(NULL)
InputFilesMS2PF(NULL)
})
#--------------------------------------------------------------------------
# 3.3: Automatic file type detection and counting
#--------------------------------------------------------------------------
# Detect file formats when MS files are uploaded
observeEvent(c(input$fileMS, input$fileMS2), {
InputFileMS <- InputFileMS()
testfileinput(0) # Exit test mode
if (!is.null(InputFileMS)) {
# Initialize detection arrays
l <- list() # BioPharma format detection
l2 <- list() # Bruker format detection
l3 <- list() # ProMex format detection
l4 <- list() # TopPIC format detection
# Check each uploaded file for format markers
for(i in 1:nrow(InputFileMS)){
# BioPharma detection: check for specific column headers
l[[i]] <- is_biopharama_MS_input(input = InputFileMS[i, 'datapath'])
# Bruker detection: check for specific header pattern
l2[[i]] <- is_Bruker_MS_input(input = InputFileMS[i, 'datapath'])
# ProMex detection: check file extension
l3[[i]] <- is_ProMex_MS_input(input = InputFileMS$name[i])
# TopPIC detection: check file extension
l4[[i]] <- is_TopFD_input(input = InputFileMS$name[i])
}
# Convert to logical vectors
l <- unlist(l)
l2 <- unlist(l2)
l3 <- unlist(l3)
l4 <- unlist(l4)
# Count files by type
filetype$RoWinPro <- sum(l==F & l3==F) # RoWinPro + Bruker + TopPIC files
filetype$BioPharma <- sum(l==T & l2==F & l3==F) # BioPharma files only
filetype$ProMex <- sum(l==F & l2==F & l3==T) # ProMex files only
# Determine appropriate number of files for color scaling
linput(max(as.numeric(c(filetype$RoWinPro, filetype$BioPharma, filetype$ProMex))))
# Handle mixed file types
if (linput() == 1 & length(c(filetype$RoWinPro, filetype$BioPharma, filetype$ProMex)[c(filetype$RoWinPro, filetype$BioPharma, filetype$ProMex)!=0])>1) {
linput(sum(as.numeric((c(filetype$RoWinPro, filetype$BioPharma, filetype$ProMex)))))
}
# Set appropriate color scheme based on file count
if (linput() > 1) {
colval("Paired") # Multiple files: qualitative colors
} else {
colval("Spectral") # Single file: continuous colors
}
} else {
# Reset file type counts when no files are loaded
filetype$RoWinPro <- 0
filetype$BioPharma <- 0
filetype$ProMex <- 0
}
})
#--------------------------------------------------------------------------
# SECTION 4: STATE MANAGEMENT AND RESET FUNCTIONS
#--------------------------------------------------------------------------
#--------------------------------------------------------------------------
# 4.1: Reset plot when switching modes or test settings
#--------------------------------------------------------------------------
# Reset when exiting test mode in MS mode
observeEvent(input$TestModeCheck, {
InputFileMS(NULL)
testfileinput(0)
ranges$x <- NULL # Clear zoom settings
ranges$y <- NULL
filetype$RoWinPro <- 0
filetype$BioPharma <- 0
filetype$ProMex <- 0
})
# Reset when exiting test mode in MS/MS mode
observeEvent(input$MS2TestModeCheck, {
if (input$MS2TestModeCheck==FALSE) {
InputFileMS(NULL)
InputFilesMS2(NULL)
InputFilesMS2PF(NULL)
testfileinput(0)
# Clear protein selection dropdown
updateSelectInput(session, "SelectProt",
"Select the ID to highlight:",
c(""))
# Reset to default software selection
updateRadioButtons(session, "PDPFModeCheck",
selected = 'PD')
ranges$x <- NULL # Clear zoom settings
ranges$y <- NULL
}
})
# Reset when switching between MS and MS/MS modes
observeEvent(input$MSModeCheck, {
InputFileMS(NULL)
testfileinput(0)
ranges$x <- NULL # Clear zoom settings
ranges$y <- NULL
})
# Reset when switching between different MS/MS software types
# Reset when switching between different MS/MS software types
observeEvent(input$PDPFModeCheck, {
InputFilesMS2(NULL)
InputFilesMS2PF(NULL)
testfileinput(0)
ranges$x <- NULL # Clear zoom settings
ranges$y <- NULL
# Clear protein selection dropdown
updateSelectInput(session, "SelectProt",
"Select the ID to highlight:",
c(""))
})
# Reset zoom when uploading new files
observeEvent(c(input$fileMS, input$fileMS2), {
ranges$x <- NULL
ranges$y <- NULL
})
#--------------------------------------------------------------------------
# SECTION 5: FILE TYPE VALIDATION AND FORMAT DETECTION
#--------------------------------------------------------------------------
#--------------------------------------------------------------------------
# 5.1: Comprehensive file format validation
#--------------------------------------------------------------------------
# Reactive function to validate and classify input file formats
ftype <- reactive({
if (is.null(InputFileMS()) & testfileinput() == 0) {
return(NULL)
} else {
InputFileMS <- InputFileMS()
l <- list()
# Check each uploaded file
for(i in 1:nrow(InputFileMS)){
# Initial format detection
val <- is_biopharama_MS_input(input = InputFileMS[i, 'datapath'])
val2 <- is_Bruker_MS_input(input = InputFileMS[i, 'datapath']) # Bruker format
val3 <- is_ProMex_MS_input(input = InputFileMS$name[i]) # ProMex format
val4 <- is_TopFD_input(InputFileMS$name[i]) # TopPIC format
# Classify file type based on detection results
val <- ifelse(val, "BioPharma", "RoWinPro")
val[val2] <- "Bruker"
val[val3] <- "ProMex"
val[val4] <- "TopPic"
#=======================================================================
# Format-specific validation checks
#=======================================================================
# # BioPharma format validation
# if (val == "BioPharma") {
#
# }
# RoWinPro format validation (should have exactly 4 columns)
if (val == "RoWinPro") {
RoWinPro_MS_check(input = InputFileMS[i, 'datapath'])
}
# Bruker format validation
if (val == "Bruker") {
Bruker_MS_check(input = InputFileMS[i, 'datapath'])
}
# ProMex format validation
if (val == "ProMex") {
ProMex_MS_check(input = InputFileMS[i, 'datapath'])
}
# TopPIC format validation
if (val == "TopPic") {
TopFD_MS_check(input = InputFileMS[i, 'datapath'])
}
l[[i]] <- val
}
vec <- unlist(l)
# print(vec)
return(vec)
}
})
#--------------------------------------------------------------------------
# SECTION 6: DATA LOADING AND PROCESSING FUNCTIONS
#--------------------------------------------------------------------------
#--------------------------------------------------------------------------
# 6.1: Main MS data loading function
#--------------------------------------------------------------------------
# Load and process MS data files based on format type and test mode
filedata0 <- reactive({
if (testfileinput() == 0) {
# Regular file upload mode (not test mode)
validate(
need((input$TestModeCheck==FALSE & input$MSModeCheck == "MS") | (input$MS2TestModeCheck == FALSE & input$MSModeCheck == "MS2"),
"You are in test mode. Click on a button to select a single test file or multiple test files.\nUncheck to exit and upload your own data."
)
)
if (is.null(InputFileMS())) {
# User has not uploaded a file yet
return(NULL)
} else {
# Validation: prevent mixing different file types with multiple files
validate(
need(!(max(table(ftype())) > 1 & length(unique(ftype())) > 1),
"With multiple files, all files need to be from the same deconvolution software."
)
)
InputFileMS <- InputFileMS()
lfiles <- list()
# Process each uploaded file according to its detected format
for(i in 1:nrow(InputFileMS)){
if (ftype()[i] == "BioPharma") {
# BioPharma Finder format: read tab-delimited with headers
lfiles[[i]] <- read.table(InputFileMS[i, 'datapath'], sep = "\t", header = T)
# Standardize mass column name (could be Monoisotopic.Mass or Average.Mass)
names(lfiles[[i]])[names(lfiles[[i]])=="Monoisotopic.Mass"|names(lfiles[[i]])=="Average.Mass"] <- "Mass"
# Map to standard column format: RT, Mass, Intensity, Start Time, Stop Time
lfiles[[i]] <- lfiles[[i]][,c("Apex.RT", "Mass", "Sum.Intensity", "Start.Time..min.", "Stop.Time..min.")]
} else if (ftype()[i] == "RoWinPro") {
# RoWinPro format: simple tab-delimited without headers
lfiles[[i]] <- read.table(InputFileMS[i, 'datapath'], sep = "\t", header = F)
# Add placeholder columns for consistency with BioPharma format
lfiles[[i]] <- cbind(lfiles[[i]][,1:3], " Temp1" = rep(NA, nrow(lfiles[[i]])), "Temp2" = rep(NA, nrow(lfiles[[i]])))
} else if (ftype()[i] == "Bruker") {
# Bruker DataAnalysis format: comma-separated, skip header lines
lfiles[[i]] <- read.table(InputFileMS[i, 'datapath'], sep = ",", header = F, skip = 2)
lfiles[[i]] <- cbind(lfiles[[i]][,2:4], " Temp1" = rep(NA, nrow(lfiles[[i]])), "Temp2" = rep(NA, nrow(lfiles[[i]]))) # add one more column to allow row binding later on
} else if (ftype()[i] == "ProMex") { # ProMex output
lfiles[[i]] <- read.table(InputFileMS[i, 'datapath'], sep = "\t", header = T)
lfiles[[i]] <- cbind("RT" = (lfiles[[i]]$MinElutionTime + ((lfiles[[i]]$MaxElutionTime - lfiles[[i]]$MinElutionTime)/2)), lfiles[[i]][,c("MonoMass", "ApexIntensity", "MinElutionTime", "MaxElutionTime")]) # Map the columns as in RoWinPro format, but with start and stop instead of all the points of the peak. I add a first column with the middle of the peak for zooming (plotly_select needs points, not ranges).
} else if (ftype()[i] == "TopPic") { # TopPic output
lfiles[[i]] <- TopPicMS1Parsing(InputFileMS[i,'datapath'])
}
}
names(lfiles) <- InputFileMS()$name
return(lfiles)
}
} else if (testfileinput() == 1) { # single file test
infile <- list.files("files/Unique/", pattern = ".csv", full.names = T)
lfiles <- list()
for(i in 1){
lfiles[[i]] <- read.table(infile[i], sep = "\t", header = F)
}
names(lfiles) <- c("test data")
return(lfiles)
testfileinput(0)
} else if (testfileinput() == 2) { # Multiple file tests
infile <- list.files("files/Multiple/", pattern = ".csv", full.names = T)
lfiles <- list()
for(i in 1:length(infile)){
lfiles[[i]] <- read.table(infile[i], sep = "\t", header = F)
lfiles[[i]] <- cbind(lfiles[[i]][,1:3], " Temp1" = rep(NA, nrow(lfiles[[i]])), "Temp2" = rep(NA, nrow(lfiles[[i]]))) # add one more column to allow row binding later on
}
names(lfiles) <- c("test data 1", "test data 2", "test data 3", "test data 4")
return(lfiles)
testfileinput(0)
} else if (testfileinput() == 3) { # Test file mode MS2
infile <- list.files("files/MS2/", pattern = ".csv", full.names = T)
lfiles <- list()
for(i in 1){
lfiles[[i]] <- read.table(infile[i], sep = "\t", header = F)
}
names(lfiles) <- c("test data")
return(lfiles)
}
})
#--------------------------------------------------------------------------
# 6.2: MS/MS data loading for Proteome Discoverer
#--------------------------------------------------------------------------
# Load and process Proteome Discoverer MS/MS identification data
filedataMS2 <- reactive({
if (is.null(InputFilesMS2()) & testfileinput() != 3) {
return(NULL) # No MS/MS files uploaded
} else {
if (testfileinput() == 3) {
# Test mode: load sample MS/MS files
infileMS2 <- list.files("files/MS2/", pattern = "MSMS", full.names = T)[[1]]
infilePSM <- list.files("files/MS2/", pattern = "SMs.txt", full.names = T)[[1]]
PSM <- read.table(infilePSM, sep = "\t", header = T, comment.char = "#")
MS2 <- read.table(infileMS2, sep = "\t", header = T)
} else {
# User uploaded files: read PSM and MS/MS spectrum files
PSM <- read.table(InputFilesMS2()$PSMfile$datapath, sep = "\t", header = T)
MS2 <- read.table(InputFilesMS2()$MS2file$datapath, sep = "\t", header = T, comment.char = "#")
# Validate file formats for Proteome Discoverer compatibility
PD_MS2_check(PSM_tab = PSM, MSMS_tab = MS2)
PSM <- RenamePDPrSM(PSM)
MS2 <- RenamePDMSMS(MS2)
}
}
return(list("MS2file" = MS2, "PSMfile" = PSM))
})
#--------------------------------------------------------------------------
# 6.3: MS/MS data loading for MSPathFinder
#--------------------------------------------------------------------------
# Load and process MSPathFinder identification data
filedataMS2PF <- reactive({
if (is.null(input$MS2filePF) | is.null(input$fileMS2)) {
return(NULL)
} else if (input$MSModeCheck == "MS2" & input$PDPFModeCheck == "PF") {
# Validate that both MS and MS/MS files are uploaded
validate(
need(!is.null(InputFileMS()),
"You need to upload the MS2 with the associated MS file to plot MS2 results from MSPathFinder.")
)
# File format validation
MSPathFinder_MS2_check(inputMSMS = InputFilesMS2PF(), inputMS = InputFileMS())
# Load MSPathFinder results
MS2PF <- read.table(InputFilesMS2PF()$datapath, sep = "\t", header = F, skip = 1)
# Standardize column names
names(MS2PF)[8] <- "Protein.Descriptions"
names(MS2PF)[15] <- "FeatureID"
# Merge with MS data and process
MS <- read.table(InputFileMS()$datapath, sep = "\t", header = T)
MS2PF <- merge(MS, MS2PF, by = "FeatureID", all = T)
MS2PF <- MS2PF[!is.na(MS2PF[,3]),] # Remove entries without identification
# Calculate retention time and standardize column names
MS2PF <- cbind("RT" = (MS2PF$MinElutionTime + ((MS2PF$MaxElutionTime - MS2PF$MinElutionTime)/2)),
MS2PF[,c("MonoMass", "ApexIntensity", "MinElutionTime", "MaxElutionTime", "Protein.Descriptions")])
names(MS2PF)[2] <- "Mass"
names(MS2PF)[3] <- "intensity"
names(MS2PF)[4] <- "PeakStart"
names(MS2PF)[5] <- "PeakStop"
return(MS2PF)
}
})
#--------------------------------------------------------------------------
# 6.4: MS/MS data loading for TopPIC
#--------------------------------------------------------------------------
# Load and process TopPIC identification data
filedataMS2TP <- reactive({
if (is.null(InputFilesMS2TP())) {
return(NULL)
} else if (input$MSModeCheck == "MS2" & input$PDPFModeCheck == "TP") {
# Validate TopPIC file formats
TopFD_MS2_check(input = InputFilesMS2TP())
# Parse TopPIC files using custom functions
IDTP <- TopPicIDParsing(InputFilesMS2TP()$IDfile$datapath)
MS2TP <- TopPicMS2Parsing(InputFilesMS2TP()$MS2file$datapath)
# Standardize column names and merge data
names(IDTP)[names(IDTP) == "Spectrum ID"] <- "Scan"
dat <- merge(MS2TP, IDTP, by = "Scan", all = T)
names(dat)[names(dat)=="Protein accession"] <- "Protein.Descriptions"
dat$Mass <- as.numeric(dat$Mass)
dat$Identification <- ifelse(!is.na(as.character(dat$Protein.Descriptions)), "IDed", "Not IDed")
return(dat)
}
})
#--------------------------------------------------------------------------
# SECTION 7: DATA PROCESSING AND PREPARATION FOR PLOTTING
#--------------------------------------------------------------------------
#--------------------------------------------------------------------------
# 7.1: Final data processing and formatting for visualization
#--------------------------------------------------------------------------
# Process loaded data for plotting, including intensity filtering and column standardization
filedata <- function() {
# Validate intensity threshold parameter
validate(
need(input$IntensityThresh <= 100, "Threshold value too high")
)
if (is.null(filedata0())) {
return(NULL)
} else {
lfiles <- filedata0()
lfiles <- ThresholdCleaning(lfiles, input$IntensityThresh)
if (filetype$BioPharma == 0 & filetype$ProMex == 0) {
# Only RoWinPro/Bruker/TopPIC files: rename columns and combine
l <- list()
for (i in seq_along(lfiles)) {
l[[i]] <- RenameBioPharma(lfiles[[i]])
}
names(l) <- names(lfiles)
lfiles <- l
return(RBindList(lfiles))
} else if (filetype$RoWinPro == 0) {
# Only BioPharma or ProMex files: standardize and combine
lfiles <- lapply(lfiles, function(x) {
RenameBioPharma(x)
})
return(RBindList(lfiles))
} else {
# Mixed file types: standardize but keep separate
lfiles <- lapply(lfiles, function(x) {
RenameBioPharma(x) # ProMex files will have an empty RT column
})
return(lfiles)
}
}
}
# ====================
# PLOT RANGE MANAGEMENT
# ====================
# Reactive values to store the current plot ranges for zooming functionality
ranges <- reactiveValues(x = NULL, y = NULL)
# Observer for the "De-Zoom" button - restores previous zoom level
observeEvent(input$DeZoom, {
ranges$x <- oldranges$x
ranges$y <- oldranges$y
})
# Observer for the "Total De-Zoom" button - resets to full data range
observeEvent(input$TotalDeZoom, {
# Scenario 1: Only MS data loaded (no MS/MS identification data)
if (is.null(filedataMS2())) {
if (class(filedata()) != "list") { # Single data table
# For ProMex and BioPharma formats, use column 5 for RT, column 2 for mass
if (filetype$ProMex > 0 | filetype$BioPharma > 0) {
ranges$x <- c(0, range(filedata()[,5])[2]) # RT range starting from 0
ranges$y <- range(filedata()[,2]) # Mass range
} else { # For other formats, use column 1 for RT
ranges$x <- c(0, range(filedata()[,1])[2]) # RT range starting from 0
ranges$y <- range(filedata()[,2]) # Mass range
}
} else { # Multiple data tables (mixed file types)
# Extract retention time values from all possible sources
x1 <- sapply(filedata(), function(z) {
z$RT
})
x2 <- sapply(filedata(), function(z) {
z$PeakStart
})
x3 <- sapply(filedata(), function(z) {
z$PeakStop
})
# Combine all time values and remove NAs
x <- c(unlist(x1), unlist(x2), unlist(x3))
x <- x[!is.na(x)]
# Extract mass values
y <- sapply(filedata(), function(z) {
z$Mass
})
ranges$x <- c(0, range(x)[2]) # Combined RT range
ranges$y <- range(y) # Combined mass range
}
} else if (is.null(filedata())) { # Scenario 2: Only MS/MS data loaded (no MS trace)
if (input$PDPFModeCheck == "PD") { # Proteome Discoverer format
ranges$x <- c(0, range(filedataMS2()$MS2file$RT.in.min)[2])
ranges$y <- range(filedataMS2()$MS2file$Precursor.MHplus.in.Da)
} else { # TopPIC format
ranges$x <- c(0, range(filedataMS2TP()$MS2file$RT)[2])
ranges$y <- range(filedataMS2TP()$MS2file$Mass)
}
} else { # Scenario 3: Both MS and MS/MS data loaded (overlay mode)
# Calculate combined ranges from both data sources
if (filetype$ProMex > 0 | filetype$BioPharma > 0) {
# Combine RT and mass ranges from both MS and MS/MS data
ranges$x <- c(0, range(c(filedataMS2()$MS2file$RT.in.min, filedata()[,5]))[2])
ranges$y <- range(c(filedataMS2()$MS2file$Precursor.MHplus.in.Da, filedata()[,2]))
} else if (input$PDPFModeCheck == "PD") { # Proteome Discoverer overlay
ranges$x <- c(0, range(c(filedataMS2()$MS2file$RT.in.min, filedata()[,1]))[2])
ranges$y <- range(c(filedataMS2()$MS2file$Precursor.MHplus.in.Da, filedata()[,2]))
} else if (input$PDPFModeCheck == "TP") { # TopPIC overlay
ranges$x <- c(0, range(c(filedataMS2TP()$MS2file$RT, filedata()[,1]))[2])
ranges$y <- range(c(filedataMS2()$MS2file$Mass, filedata()[,2]))
}
}
})
# Reactive values to store previous zoom ranges for "De-Zoom" functionality
oldranges <- reactiveValues(x = NULL, y = NULL)
# Observer for interactive plot selection events (brush/lasso selection for zooming)
observeEvent(event_data("plotly_selected"), {
# Store current ranges before updating (for De-Zoom functionality)
oldranges$x <- ranges$x
oldranges$y <- ranges$y
# Only process selection if DataPoints mode is enabled
if (input$DataPoints) {
newdata <- event_data("plotly_selected")
# Process valid selection data
if (!is.null(newdata) & class(newdata)=="data.frame") {
# Case 1: Single table with ProMex/BioPharma format
if (class(filedata()) != "list" & (filetype$ProMex > 0 | filetype$BioPharma > 0)) {
# For ProMex/BioPharma: use peak start/stop boundaries for X range
ranges$x <- c(min(filedata()[filedata()[,5] >= min(newdata$x),4]),
max(filedata()[filedata()[,4] <= max(newdata$x),5]))
ranges$y <- range(newdata$y)
# Case 2: Multiple file types (mixed ProMex/BioPharma with others)
} else if (class(filedata()) == "list") {
tab <- filedata()
# Extract ProMex/BioPharma data
if (sum(ftype()=="ProMex" | ftype()=="BioPharma") > 1) {
tab2 <- RBindList(tab[ftype()=="ProMex" | ftype()=="BioPharma"])
} else {
tab2 <- tab[ftype()=="ProMex" | ftype()=="BioPharma"][[1]]
}
# Extract other format data
if (sum(!(ftype()=="ProMex" | ftype()=="BioPharma")) > 1) {
tab <- RBindList(tab[!(ftype()=="ProMex" | ftype()=="BioPharma")])
} else {
tab <- tab[!(ftype()=="ProMex" | ftype()=="BioPharma")][[1]]
}
# Calculate combined X range from both data types
minx <- min(tab2[tab2[,5] >= min(newdata$x),4])
minx <- min(minx, min(tab$RT))
maxx <- max(tab2[tab2[,4] <= max(newdata$x),5])
maxx <- max(maxx, max(tab$RT))
ranges$x <- c(minx, maxx)
ranges$y <- range(newdata$y)
# Case 3: Standard single table format
} else {
ranges$x <- range(newdata$x)
ranges$y <- range(newdata$y)
}
} else {
newdata <- NULL
}
}
})
# ====================
# DYNAMIC RANGE SELECTION
# ====================
# Function to determine appropriate plot ranges based on current zoom state and data
defineranges <- function() {
# Use current zoom ranges if they exist
if (!is.null(ranges$x) & !is.null(ranges$y)) {
rangesx <- ranges$x
rangesy <- ranges$y
# Scenario 1: Only MS data loaded (no MS/MS identification data)
} else if (is.null(filedataMS2())) {
if (class(filedata()) != "list") { # Single data table
rangesx <- range(filedata()[,1]) # RT range
rangesy <- range(filedata()[,2]) # Mass range
} else { # Multiple data tables (mixed file types)
# Extract retention time values from all possible sources
x1 <- sapply(filedata(), function(z) {
as.numeric(z$RT)
})
x2 <- sapply(filedata(), function(z) {
as.numeric(z$PeakStart)
})
x3 <- sapply(filedata(), function(z) {
as.numeric(z$PeakStop)
})
# Combine all time values and remove NAs
x <- c(unlist(x1), unlist(x2), unlist(x3))
x <- x[!is.na(x)]
# Extract mass values
y <- sapply(filedata(), function(z) {
as.numeric(z$Mass)
})
rangesx <- range(x) # Combined RT range
rangesy <- range(y) # Combined mass range
}
# Scenario 2: Only MS/MS data loaded (no MS trace) OR MS trace disabled
} else if (is.null(filedata()) | input$MSTrace == FALSE) {
rangesx <- range(filedataMS2()$MS2file$RT.in.min)
rangesy <- range(filedataMS2()$MS2file$Precursor.MHplus.in.Da)
# Scenario 3: Both MS and MS/MS data loaded (overlay mode)
} else {
if (filetype$ProMex > 0 | filetype$BioPharma > 0) {
# Combine RT and mass ranges from both MS and MS/MS data
rangesx <- range(c(filedataMS2()$MS2file$RT.in.min, filedata()[,5]))
rangesy <- range(c(filedataMS2()$MS2file$Precursor.MHplus.in.Da, filedata()[,2]))
} else if (input$PDPFModeCheck == "PD") { # Proteome Discoverer overlay
ranges$x <- range(c(filedataMS2()$MS2file$RT.in.min, filedata()$RT))
ranges$y <- range(c(filedataMS2()$MS2file$Precursor.MHplus.in.Da, filedata()$Mass))
} else if (input$PDPFModeCheck == "TP") { # TopPIC overlay
ranges$x <- range(c(filedataMS2TP()$RT, filedata()[,1]))[2]
ranges$y <- range(c(filedataMS2TP()$Mass, filedata()[,2]))
}
}
return(list(rangesx, rangesy))
}
# ====================
# SIGNAL SUMMARIZATION
# ====================
## Calculate sum of signal in the plotting window
summarized_signal <- reactiveVal(NULL)
observeEvent(input$CalcSum, {
# Get current plot ranges
rangesx <- defineranges()[[1]]
rangesy <- defineranges()[[2]]
# Make table
int_tab <- filedata()
indexes <- int_tab$Mass <= rangesy[2] & int_tab$Mass >= rangesy[1] &
int_tab$RT <= rangesx[2] & int_tab$RT >= rangesx[1]
input_summarization <- data.frame(
Sum_intensities = sum(int_tab$intensity[indexes], na.rm = T),
Prop_sum_intensities = sum(int_tab$intensity[indexes], na.rm = T) / sum(int_tab$intensity, na.rm = T),
Point_count = length(int_tab$intensity[indexes][!is.na(int_tab$intensity[indexes])]),
Mass_min = rangesy[1],
Mass_max = rangesy[2],
RT_min = rangesx[1],
RT_max = rangesx[2],
Percentage_signal_threshold = input$IntensityThresh
)
summarized_signal(t(input_summarization))
})
output$SumSignal <- renderTable({ # return table with sum of signal
if (!is.null(summarized_signal())) {
summarized_signal()
} else {
return(invisible())
}
}, rownames = T, colnames = F)
observeEvent(input$CalcSumReset, { # empty table when press reset
summarized_signal(NULL)
})
## To mask button when bars are plotted instead of points:
output$show_calcsum <- reactive({
if (linput() == 1) {
if (!is.null(ftype())) {
!(ftype() %in% c("BioPharma", "ProMex"))
} else {
TRUE
}
} else {
FALSE
}
})
outputOptions(output, "show_calcsum", suspendWhenHidden = FALSE)
# ====================
# PLOT GENERATION
# ====================
# Main plotting function - generates the 2D mass spectrometry visualization
plotInput1 <- function(){
# Validate user inputs for point size and intensity threshold
validate(
need(input$pch <= 10 & input$pch >= 0.1, "Please define a size of points between 0.1 and 10.")
)
validate(
need(input$IntensityThresh <= 100 & input$IntensityThresh >= 0.1, "Please define a threshold between 0.1 and 100. This value corresponds to the proportion of the points in the data set that you want to upload (highest intensities).")
)
# Return NULL if no data is loaded
if (is.null(filedata()) & is.null(filedataMS2()) & is.null(filedataMS2PF()) & is.null(filedataMS2TP())) {
return(NULL)
} else {
# Generate plot if data is available
if (!is.null(linput())) {
# Get current plot ranges
rangesx <- defineranges()[[1]]
rangesy <- defineranges()[[2]]
# Plot generation for RoWinPro/Bruker/TopPIC formats only
if (filetype$BioPharma == 0 & filetype$ProMex == 0) {
gtab <- filedata()
# Multi-file comparison mode
if (linput() >= 2) {
g <- ggplot() +
geom_point(data = gtab, aes(x = RT, y = Mass, col = File, text = paste(RT, "min\n", Mass, "Da\nSignal:", intensity, "\n", File)), alpha = 0.7, size = input$pch) +
geom_text(parse = TRUE) +
coord_cartesian(xlim = rangesx, ylim = rangesy, expand = TRUE) +
theme_bw() +
scale_colour_brewer(palette = colval()) +
ylab("Molecular Weight (Da)") +
xlab("Retention time (min)")
# Single file mode with intensity coloring
} else {
g <- ggplot() +
geom_point(data = gtab, aes(x = RT, y = Mass, col = log10(intensity), text = paste(RT, "min\n", Mass, "Da\nSignal:", intensity)), alpha = 0.7, size = input$pch) +
coord_cartesian(xlim = rangesx, ylim = rangesy, expand = TRUE) +
theme_bw() +
scale_colour_distiller(palette = colval()) +
ylab("Molecular Weight (Da)") +
xlab("Retention time (min)")
}
} else if (filetype$RoWinPro == 0) { # Only type BioPharma/Promex