-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathModular.R
3933 lines (3530 loc) · 223 KB
/
Modular.R
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
##Jeremy Koelmel jeremykoelmel@gmail.com
##Michael Kummer mk.code.na@gmail.com
##David Schiessel david@schiessel.us
##Paul Stelben paul.stelben@yale.edu
##Nick Kroeger nkroeger.cs@gmail.com
rm(list = ls()) #remove all R objects from memory, this program can be memory intensive as it is dealing with huge datasets
closeAllConnections()
#### Mandatory Parameter to Change ####
#If you want to manually input your variables...
# 1. Set ManuallyInputVariables <- TRUE (all caps)
# 2. Assign variables under the next if statement, "if (ManuallyInputVariables==TRUE)"
FLOW <- FALSE
csvInput <- TRUE
ManuallyInputVariables <- FALSE
RT_flagging <- TRUE #JPK: for PFAS analysis
ParallelComputing <- TRUE
Lipid <- FALSE
TWeen_pos <- FALSE #PJS: for PolyMatch
FilterAbovePrecursor <- 1 #how far from the precursor should fragment masses be kept (e.g. if precursor is 700, should 702 be considered?)
TargetEIC_Only <- TRUE
alignMS2_ppm <- FALSE #selection accuracy will be divided by 4, eg. 1 Da Window = +/- 0.25 difference, if FALSE, Otherwise the mass accuracy in ppm will be used to align MSMS scans to the feature table
EICcpp <- FALSE #Whether to use the C++ version of the EIC / MS1 generation code, seems to give the same results, faster but less well tested
IMfirst<-FALSE #For running Modular after Running FluoroMatch IM using PNNL processed DIA to DDA workflow or similar
#### END Mandatory Parameter to Change ####
#### END "Read Me" Section ####
#Force the directory for packages to be the one that is distributed not the local R directory
if(length(.libPaths())>1){
R_DistrDir<-.libPaths()[2]
.libPaths(R_DistrDir)
}
#Or just force .libPaths()
# .libPaths("C:/NEW_SOFTWARE/2023_24_UPDATES_FM_LM/FluoroMatch-4.4_GitHub/Flow/R-4.2.1/library/")
if (FLOW == TRUE) {
csvInput <- TRUE
ManuallyInputVariables <- FALSE
}
#Checks for updates, installs packagaes: "installr" "stringr" "sqldf" "gWidgets" "gWidgetstcltk" and "compiler"
# if(!require(stringr)) {
# install.packages("stringr"); require(installr)}
# library(installr)
if (!require("stringr", quietly = TRUE))install.packages("stringr", repos = "http://cran.us.r-project.org")
library("stringr")
if (EICcpp==TRUE) {
#These are distributed by us (thanks Jonathan)
#cannot installed online
if("Rcpp" %in% (.packages())){
detach("package:mzR", unload=TRUE)
detach("package:Rcpp", unload=TRUE)
}
library("EICim")
library("MS1im")
}
if (!require("BiocManager", quietly = TRUE))install.packages("BiocManager", repos = "http://cran.us.r-project.org")
if (ParallelComputing == TRUE) {
if("foreach" %in% rownames(installed.packages()) == FALSE) {install.packages("foreach", repos = "http://cran.us.r-project.org")}
library(foreach)
if("doParallel" %in% rownames(installed.packages()) == FALSE) {install.packages("doParallel", repos = "http://cran.us.r-project.org")}
library(doParallel)
if("parallelly" %in% rownames(installed.packages()) == FALSE) {install.packages("parallelly", repos = "http://cran.us.r-project.org")}
library("parallelly")
# tic("Main")
###NOTE not sure if any of this is necessary but was causing error
DC <- as.numeric(availableCores(constraints = "connections"))
print(paste0(freeConnections()," connections are free and will be used of ",availableConnections()," R hard limited connections; the following numbers of cores exist on your system: ",as.numeric(detectCores())))
if (is.na(DC)) {
DC <- makePSOCKcluster(4)
registerDoParallel(DC)
} else if (DC <= 4) {
DC <- makePSOCKcluster(DC)
registerDoParallel(DC)
} else {
DC <- makePSOCKcluster(DC-2)
registerDoParallel(DC)
}
# Force the directory for parallel computing to be the one that is distributed not the local R directory (doPar error)
invisible(clusterEvalQ(DC, .libPaths()[2]))
}
if("tictoc" %in% rownames(installed.packages()) == FALSE) {install.packages("tictoc", repos = "http://cran.us.r-project.org")}
library(tictoc)
tic.clear()
# tic("Main")
if("remotes" %in% rownames(installed.packages()) == FALSE) {install.packages("remotes", repos = "http://cran.us.r-project.org")}
library("remotes")
if("MassTools" %in% rownames(installed.packages()) == FALSE) {remotes::install_github("mjhelf/MassTools")}
library("MassTools")
#library(MetaboCoreUtils)
if("enviPat" %in% rownames(installed.packages()) == FALSE) {install.packages("enviPat", repos = "http://cran.us.r-project.org")}
library(enviPat, quietly=T)
if("RMassBank" %in% rownames(installed.packages()) == FALSE) {BiocManager::install("RMassBank")}
library("RMassBank")
if("MetaboCoreUtils" %in% rownames(installed.packages()) == FALSE) {BiocManager::install("MetaboCoreUtils")}
library("MetaboCoreUtils")
if("sqldf" %in% rownames(installed.packages()) == FALSE) {install.packages("sqldf", repos = "http://cran.us.r-project.org")}
library("sqldf")
if("Rdisop" %in% rownames(installed.packages()) == FALSE) {install.packages("Rdisop", repos = "http://cran.us.r-project.org")}
library("Rdisop")
if("RSQLite" %in% rownames(installed.packages()) == FALSE) {install.packages("RSQLite", repos = "http://cran.us.r-project.org")}
library("RSQLite")
if("gWidgets" %in% rownames(installed.packages()) == FALSE) {install.packages("gWidgets", repos = "http://cran.us.r-project.org")}
if("gWidgetstcltk" %in% rownames(installed.packages()) == FALSE) {install.packages("gWidgetstcltk", repos = "http://cran.us.r-project.org")}
if("agricolae" %in% rownames(installed.packages()) == FALSE) {install.packages("agricolae", repos = "http://cran.us.r-project.org")}
library("agricolae")
# if (FLOW == FALSE && csvInput == FALSE && ManuallyInputVariables == FALSE) {
require(gWidgets)
require(gWidgetstcltk)
options(guiToolkit="tcltk")
# }
#library(Rdisop)
#BiocManager::install("Rdisop")
library(RSQLite)
library(sqldf)
library(agricolae)
library(Rdisop)
options(warn=-1)#suppress warning on
errorBox <- function(message) {
window <- gwindow("Confirm")
group <- ggroup(container = window)
## A group for the message and buttons
inner.group <- ggroup(horizontal=FALSE, container = group)
glabel(message, container=inner.group, expand=TRUE, icon="error")
## A group to organize the buttons
button.group <- ggroup(container = inner.group)
## Push buttons to right
addSpring(button.group)
gbutton("ok", handler=function(h,...) dispose(window), container=button.group)
return()
}
if("data.table" %in% rownames(installed.packages()) == FALSE) {install.packages("data.table", repos = "http://cran.us.r-project.org")}
library(data.table)
if("SearchTrees" %in% rownames(installed.packages()) == FALSE) {install.packages("SearchTrees", repos = "http://cran.us.r-project.org")}
library(SearchTrees)
if("comprehenr" %in% rownames(installed.packages()) == FALSE) {install.packages("comprehenr", repos = "http://cran.us.r-project.org")}
library(comprehenr)
if("mzR" %in% rownames(installed.packages()) == FALSE) {
BiocManager::install("mzR")}
library(mzR)
if (ManuallyInputVariables==TRUE){
#Retention Time plus or minus
RT_Window <- .3 #window of .2 => +/- .1
#parts-per-million window for matching the m/z of fragments obtained in the library to those in experimentally obtained
ppm_Window <- 10 #window of 10 => +/- 5 ppm error
#Tolerance for mass-to-charge matching at ms1 level (Window)
PrecursorMassAccuracy<-0.01
#Plus minus range for the mass given after targeting parent ions portrayed in excalibur to match exact mass of Lipid in library
SelectionAccuracy<-1
#Threshold for determining that the average signal intensity for a given MS/MS ion should be used for confirmation
intensityCutOff<-1000
#Feature Table information
CommentColumn <- 1
MZColumn <- 2
RTColumn <- 3
RowStartForFeatureTableData <- 2 #Look at your Feature Table (.csv)...What row do you first see numbers?
#ddMS data? set this parameter. If not? Leave it.
#The minimum number of scans required for the result to be a confirmation
ScanCutOff<-1
#Have AIF data? set these parameters. If not? Leave them.
corrMin <-.6
minNumberOfAIFScans <- 5
# Input Directory for Feature Table and MS2 files ...must have forward slashes but nothing at the end of the directory
InputDirectory<-"C:/Users/Jeremy Koelmel/Downloads/LipidMatch_Flow_3.5/LipidMatch_Flow_3.5/LipidMatch_Modular/ExampleData"
# Input Directory for Libraries ...must have forward slashes but nothing at the end of the directory
InputLibrary<-"C:/Users/Jeremy Koelmel/Downloads/LipidMatch_Flow_3.5/LipidMatch_Flow_3.5/LipidMatch_Modular/LipidMatch_Libraries_Acetate"
## PFAS Specific parameters
# RT_flagging <- TRUE #JPK: for PFAS analysis
# Mass defect filtering
upper <- 0.12 #JPK: Upper limit for PFAS mass defect
lower <- -0.11 #JPK: Lower limit for PFAS mass defect
#the isotopes that you can add for MS1 isotope labeling and isotope ratio calculations, if you don't differentiate the mass number it will use all from "secondary_isotopes.csv"
ISOstring <- "13C3;15N;33S;34S;Cl3;18O;Br3;29Si;30Si"
#Check your parameters and see that they are all correct.
#Then press ctrl+shift+s to execute all code.
####################### END MANUALLY INPUTTING VARIABLES SECTION #######################
}else if(csvInput == TRUE){
####################### Get input from csv VARIABLES SECTION ###############################
#parametersDirectory
parametersDir <- "D:/FluoroMatch_Data/2024_07_01_SarahStow_IM_PNNLtool/2024_07_14_NIST_C_FIN/"
parametersFile <- paste(parametersDir, "PARAMETERS.csv", sep="")
parametersInput_csv <- read.csv(parametersFile, sep=",", na.strings="NA", dec=".", strip.white=TRUE,header=FALSE)
parametersInput_csv <- as.matrix(parametersInput_csv)
ErrorOutput<-0
#Retention Time plus or minus
RT_Window <- as.numeric(parametersInput_csv[2,2]) #window of .2 => +/- .1
#parts-per-million window for matching the m/z of fragments obtained in the library to those in experimentally obtained
ppm_Window <- as.numeric(parametersInput_csv[4,2]) #window of 10 => +/- 5 ppm error
#Tolerance for mass-to-charge matching at ms1 level (Window)
PrecursorMassAccuracy <- as.numeric(parametersInput_csv[3,2])
#Plus minus range for the mass given after targeting parent ions portrayed in excalibur to match exact mass of Lipid in library
SelectionAccuracy <- as.numeric(parametersInput_csv[5,2])
#Threshold for determining that the average signal intensity for a given MS/MS ion should be used for confirmation
intensityCutOff <- as.numeric(parametersInput_csv[7,2])
#Feature Table information
CommentColumn <- as.numeric(parametersInput_csv[10,2])
MZColumn <- as.numeric(parametersInput_csv[11,2])
RTColumn <- as.numeric(parametersInput_csv[12,2])
RowStartForFeatureTableData <- as.numeric(parametersInput_csv[13,2]) #Look at your Feature Table (.csv)...What row do you first see numbers?
#ddMS data? set this parameter. If not? Leave it.
#The minimum number of scans required for the result to be a confirmation
ScanCutOff<-as.numeric(parametersInput_csv[6,2])
#Have AIF data? set these parameters. If not? Leave them.
corrMin <-as.numeric(parametersInput_csv[9,2])
minNumberOfAIFScans <- as.numeric(parametersInput_csv[8,2])
# Input Directory for Feature Table and MS2 files ...must have \\ (double backslash) at the end of the directory
InputDirectory<-as.character(parametersInput_csv[14,2])
InputDirectory = substring(InputDirectory,1, nchar(InputDirectory)-1)
# Input Directory for Libraries ...must have \\ (double backslash) at the end of the directory
InputLibrary<-as.character(parametersInput_csv[15,2])
InputLibrary <- substring(InputLibrary,1, nchar(InputLibrary)-1)
GroupCSVDirectory<-as.character(parametersInput_csv[20,2])
ISOstring <- as.character(parametersInput_csv[23,2])
## PFAS Specific parameters
RT_flagging <- TRUE #JPK: for PFAS analysis
# Mass defect filtering
upper <- 0.12 #JPK: Upper limit for PFAS mass defect
lower <- -0.11 #JPK: Lower limit for PFAS mass defect
}else{
####################### Pop-up boxes input VARIABLES SECTION ###############################
# check if R version is equal to, or between, version 2.0.3 and 3.3.3, otherwise present pop-up box warning
# Comment out for now
# if(!((as.numeric(paste(version$major,version$minor,sep=""))>=20.3) && (as.numeric(paste(version$major,version$minor,sep=""))<=33.3))) {
# errorBox(message=paste("ERROR: R version must be equal to, or between, 2.0.3 and 3.3.3. Please download 3.3.3. You are using version: ", paste(version$major,version$minor,sep=".")))
# stop(paste("R version must be equal to, or between, 2.0.3 and 3.3.3. Please download 3.3.3. You are using version: ", paste(version$major,version$minor,sep=".")))
# }
ISOstring <- "13C3;15N;33S;34S;Cl3;18O;Br3;29Si;30Si"
## Input Directory that holds each folder of .ms2 files & feature table (contains features, peak heights/areas, etc.) (.csv file)
InputDirectory<-tk_choose.dir(caption="Input Directory of MS2 + Feature Tables")
if(is.na(InputDirectory)){
stop()
}
foldersToRun <- list.dirs(path=InputDirectory, full.names=FALSE, recursive=FALSE)
ErrorOutput<-0
for (i in seq_len(length(foldersToRun))){
if(foldersToRun[i] == "Output"){
ErrorOutput<-1
errorBox(message=paste("ERROR: Remove your 'Output' folder\nfrom the current Input Directory:\n", InputDirectory))
stop("Warning: Remove your 'Output' folder from the current Input Directory: ", InputDirectory)
}
}
## Input Directory for Libraries
InputLibrary<-tk_choose.dir(caption="Input Directory of libraries (came with LipidMatch)")
if(is.na(InputLibrary)){
stop()
}
GroupCSVDirectory <- tk_choose.files(caption="If there are no groupings select CANCEL, Otherwise: \nInput file containing groupings \none column file with characters unique to each grouping\neach row as a seperate group",multi=FALSE)
GetInputAndErrorHandle <- function(typeOfVariable, message, title){
isValidInput <- FALSE
inputVariable <- ginput(message=message, title=title,icon="question")
while(!isValidInput){
##Retention Time plus or minus
if(inputVariable == "d" || inputVariable == "D"){
if(typeOfVariable=="RT"){ inputVariable <- 0.3
}else if(typeOfVariable=="ppm"){ inputVariable <- 10
}else if(typeOfVariable=="precMassAccuracy"){ inputVariable <- 0.01
}else if(typeOfVariable=="selectionAccuracy"){ inputVariable <- 1
}else if(typeOfVariable=="maxInt"){ inputVariable <- 1000
}else if(typeOfVariable=="scanCutOff"){ inputVariable <- 1
}else if(typeOfVariable=="FeatRT"){inputVariable<-0.1
}else if(typeOfVariable=="FeatMZ"){inputVariable<-0.006
}else if(typeOfVariable=="corrMin"){inputVariable<-0.6
}else if(typeOfVariable=="minAIFScans"){inputVariable<-5
}else if(typeOfVariable=="upper"){inputVariable<-.12
}else if(typeOfVariable=="lower"){inputVariable<-(-0.11)
}
isValidInput <- TRUE
}else if(suppressWarnings(!is.na(as.numeric(inputVariable)))){
inputVariable <- as.numeric(inputVariable)
isValidInput <- TRUE
}else{
inputVariable <- ginput(message=paste("Error! Invalid Input.\n\n",message), title=title, icon="error")
}
}
return(inputVariable)
}
RT_Window <- GetInputAndErrorHandle("RT", message="Retention Time Window\n(Window of .3 => +/- .15)\nOr type \"d\" for default: .3", title="RT_Window")
ppm_Window <- GetInputAndErrorHandle("ppm", message="Parts-per-million window for matching experimental and in-silico fragments m/z \n(Window of 10 => +/- 5)\nOr type \"d\" for default value: 10", title="ppm_Window")
PrecursorMassAccuracy <- GetInputAndErrorHandle("precMassAccuracy", message="Mass accuracy window for matching experimental and in-silico precursors m.z\nfor full scan (precursor) mass matching \n(Window of .01 Da => +/- .005 Da)\nOr type \"d\" for default: .01", title="PrecMassAccuracyWindow")
SelectionAccuracy <- GetInputAndErrorHandle("selectionAccuracy", message="MS/MS Isolation Window (Da) \n(For determining MS/MS scans for each feature)\nOr type \"d\" for default: 1", title="SelectionAccuracy")
intensityCutOff <- GetInputAndErrorHandle("maxInt", message="Threshold for determining what the minimum signal intensity cut off for a\ngiven MS/MS ion should be (used for confirmations)\nOr type \"d\" for default: 1000", title="intensityCutOff")
CommentColumn <- GetInputAndErrorHandle("CommentCol", message= "Feature Table Info: Comment Column/Row ID \n(look at feature table .csv, first column is 1)\nNote that the column should be the same in negative and positive feature tables \nNo default value.",title="CommentColumn")
MZColumn <- GetInputAndErrorHandle("MZCol", message= "Feature Table Info: Mass-to-Charge Column \n(look at feature table .csv, first column is 1)\nNote that the column should be the same in negative and positive feature tables \nNo default value.", title="MZColumn")
RTColumn <- GetInputAndErrorHandle("RTCol", message= "Feature Table Info: Retention Time Column \n(look at feature table .csv, first column is 1)\nNote that the column should be the same in negative and positive feature tables \nNo default value.", title="RTColumn")
RowStartForFeatureTableData <- GetInputAndErrorHandle("RowStart", message= "Feature Table Info: What row does your numeric data start? \n(First row of .csv starts counting at 1)\nNote that the row should be the same in negative and positive feature tables \nNo default value.", title="RowStartForFeatureTableData")
upper <- GetInputAndErrorHandle("upper", message= "what is the upper limit for mass defect filtering (scoring, wont remove)? \nOr type \"d\" for default: 0.12 \n(0.12 is the upper 95 percentile of EPA Masterlist mass defects)", title="upper")
lower <- GetInputAndErrorHandle("lower", message= "what is the lower limit for mass defect filtering (scoring, wont remove)? \nOr type \"d\" for default: -0.11 \n(-0.11 is the lowest 5 percentile of EPA Masterlist mass defects)", title="lower")
RT_flagging <- TRUE #JPK: will simpy be default, changeable in code for now
hasAIF <- FALSE
hasdd <- FALSE
foldersToRun <- list.dirs(path=InputDirectory, full.names=FALSE, recursive=FALSE)
if(length(foldersToRun)==0){
lengthFoldersToRun <- 1 #if there are no subfolders, that means you have the faeture table and ms2s in that current directory, therefore, run analysis on those files.
}else{
lengthFoldersToRun <- length(foldersToRun)#run analysis on all subfolders
}
#checks for output folder, we don't want to overwrite your files
for (i in seq_len(lengthFoldersToRun)){
numOfAIFFiles <- vector()
if(length(foldersToRun)==0){#we're in current (and only) folder that contains feature table and ms2
fpath <- InputDirectory
}else if(foldersToRun[i] == "Output"){
fpath <- InputDirectory
print(paste("Warning: Remove your 'Output' folder from the current Input Directory:", InputDirectory))
}else{
fpath <- file.path(InputDirectory, foldersToRun[i])
}
#separate ddMS and AIF
numOfddFiles <- length(list.files(path=fpath, pattern="[dD][dD][Mm][Ss]", ignore.case=FALSE))
numOfAIFFiles <- length(list.files(path=fpath, pattern="[aA][iI][fF]", ignore.case=FALSE))
if(numOfAIFFiles > 0){ #if # of AIF .ms2 or .ms1 > 0, ask for variable input
hasAIF <- TRUE
}else{
print(paste("Warning: Couldn't find .ms1 or .ms2 files. Make sure you have 'aif' in your .ms1 or .ms2 file name (for data independent analysis)."))
}
if(numOfddFiles > 0){
hasdd <- TRUE
}else{
print(paste("Warning: Couldn't find data dependent .ms2 files. Make sure you have 'dd' in your .ms2 file name (for data dependent analysis)."))
}
}
if(hasAIF){
corrMin <- GetInputAndErrorHandle("corrMin", message= "Minimum adjusted R2 value for AIF confirmation\n(Used in correlating fragment ms1 and ms2 intensities).\nOr type \"d\" for default: 0.6", title="corrMin")
minNumberOfAIFScans <- GetInputAndErrorHandle("minAIFScans", message= "Minimum number of scans for confirming fragments (AIF)\nOr type \"d\" for default: 5", title="minNumberOfAIFScans")
}
if(hasdd){#then has ddMS
ScanCutOff <- GetInputAndErrorHandle("scanCutOff", message="Minimum number of scans required for the result to be a confirmation (ddMS)\nOr type \"d\" for default: 1", title="ScanCutOff")
}
} ####################### END AUTO INPUTTING VARIABLES SECTION ####################
#Error handling for manual input section... specifically the Input Directory. Checks for Output folder, and stops.
if(ManuallyInputVariables==TRUE || csvInput == TRUE){
#checks for output folder, we don't want to overwrite your files
foldersToRun <- list.dirs(path=InputDirectory, full.names=FALSE, recursive=FALSE)
if(length(foldersToRun)==0){
lengthFoldersToRun <- 1 #if there are no subfolders, that means you have the faeture table and ms2s in that current directory, therefore, run analysis on those files.
}else{
lengthFoldersToRun <- length(foldersToRun)#run analysis on all subfolders
}
for (i in seq_len(length(foldersToRun))){
if(foldersToRun[i] == "Output"){
errorBox(message=paste("Warning: Remove your 'Output' folder\nfrom the current Input Directory:\n", InputDirectory))
stop("Warning: Remove your 'Output' folder from the current Input Directory: ", InputDirectory)
}
if(length(foldersToRun)==0){#we're in current (and only) folder that contains feature table and ms2
fpath <- InputDirectory
}else if(foldersToRun[i] == "Output"){
fpath <- InputDirectory
print(paste("Warning: Remove your 'Output' folder from the current Input Directory:", InputDirectory))
}else{
fpath <- file.path(InputDirectory, foldersToRun[i])
}
numOfAIFFiles <- length(list.files(path=fpath, pattern="[AIFaif][AIFaif][AIFaif]", ignore.case=FALSE))
if(numOfAIFFiles %% 2 == 1){ #if # of AIF .ms2 or .ms1 are odd, STOP!
stop("Warning: You should have a one-to-one relationship between AIF.ms1 and AIF.ms2 files...We found ", numOfAIFFiles," AIF .ms1 and/or .ms2 files. You should have an even number of AIF files.",sep="")
}#else, do nothing.
}
}
#### END VARIABLE DECLARATIONS SECTION ####
#### CODE - DO NOT TOUCH ####
#Library Information
# NAME AND DIRECTORY for exact mass library
ImportLibPOS<-file.path(InputLibrary, "Precursor_Library_POS.csv")
ImportLibNEG<-file.path(InputLibrary, "Precursor_Library_NEG.csv")
# if (Lipid == TRUE || FLOW == TRUE) {
# LibCriteria<- file.path(InputLibrary, "PFAS_ID_CRITERIA.csv")
# } else {
# LibCriteria<- file.path(InputLibrary, "PFAS_ID_CRITERIA.csv")
# }
##Bernard Brooks 12/15/2022 9:05 AM - Error I found##
# if (FLOW == TRUE || Lipid == TRUE) {
# LibCriteria<- file.path(InputLibrary, "LIPID_ID_CRITERIA.csv")
# } else {
LibCriteria<- file.path(InputLibrary, "PFAS_ID_CRITERIA.csv")
# }
LibColInfo<-1 #Look at your Library. What column are your IDs? (Columns to retrieve ID information and align with data)
ParentMZcol_in<-2 #Look at your Library. What column are your precursor masses in? (Columns to retrieve ID information and align with data)
ddMS2_Code<-"1"
AIF_Code<-"2"
Class_Code<-"3"
ExactMass_Code<-"4"
NoID_Code<-"5"
#PrecursorMassAccuracy<-PrecursorMassAccuracy/2
PPM_CONST <- (10^6 + ppm_Window/2) / 10^6
################### FUNCTIONS ###################
RunAIF <- function(ms1_df, ms2_df, FeatureList, LibraryLipid_self, ParentMZcol, OutputDirectory, ExtraFileNameInfo, ConfirmORcol, ConfirmANDcol, OutputInfo){
tStart<-Sys.time()
ColCorrOR <- ConfirmORcol
ColCorrAND <- ConfirmANDcol
if(!dir.exists(file.path(OutputDirectory,"Confirmed_Compounds"))){
dir.create(file.path(OutputDirectory,"Confirmed_Compounds"))
}
if(!dir.exists(file.path(OutputDirectory,"Additional_Files"))){
dir.create(file.path(OutputDirectory,"Additional_Files"))
}
LibraryLipid<-read.csv(LibraryLipid_self, sep=",", na.strings="NA", dec=".", strip.white=TRUE,header=FALSE)
libraryLipidMZColumn <- ParentMZcol
FeatureListMZColumn <- 1
## Create a Library of Lipids and fragments for those masses in Feature List
FeatureListHeader <- FeatureList[1,]
LibraryLipidHeader <- LibraryLipid[1,]
NewLibraryLipidHeader <- cbind(LibraryLipidHeader, FeatureListHeader)
sqlMerged <- sqldf(paste("select * from LibraryLipid lib inner join FeatureList iList on lib.", colnames(LibraryLipid)[libraryLipidMZColumn], "-", PrecursorMassAccuracy, "<= iList.", colnames(FeatureList)[FeatureListMZColumn], " and iList.", colnames(FeatureList)[FeatureListMZColumn], " <= lib.", colnames(LibraryLipid)[libraryLipidMZColumn], "+", PrecursorMassAccuracy, sep = ""))
# sqlMerged <- sqldf(paste("select * from LibraryLipid lib inner join FeatureList iList on iList.", colnames(FeatureList)[FeatureListMZColumn], " >= lib.", colnames(LibraryLipid)[libraryLipidMZColumn], " -.005 and iList.", colnames(FeatureList)[FeatureListMZColumn], " <= lib.", colnames(LibraryLipid)[libraryLipidMZColumn], "+ .005", sep = ""))
NewLibraryLipid <- as.matrix(sqlMerged)
# if sqlMerged is not empty the names of the columns need to be adjusted, maybe better to always adjust them
colnames(NewLibraryLipid) <- colnames(NewLibraryLipidHeader)
NewLibraryLipid <- rbind(NewLibraryLipidHeader,NewLibraryLipid)
NewLibraryLipid <- NewLibraryLipid[,-(ncol(LibraryLipid)+1)] #removes mz from Feature list
#Removes 1 rt col and creates RT_min and RT_max cols based on RT_Window
RT_Col <- as.numeric(NewLibraryLipid[2:nrow(NewLibraryLipid),ncol(NewLibraryLipid)-1])
NewLibraryLipid <- NewLibraryLipid[,-(ncol(NewLibraryLipid)-1)]
RT_Window_Vector <- rep(RT_Window/2, each=nrow(NewLibraryLipid)-1)
#Issue found 10/30 Removed Levels function
RT_min <- RT_Col - as.numeric(RT_Window_Vector)
RT_max <- RT_Col + as.numeric(RT_Window_Vector)
RT_min <- c("RT_min",RT_min)
RT_max <- c("RT_max",RT_max)
Comment <- NewLibraryLipid[,ncol(NewLibraryLipid)]
NewLibraryLipid <- cbind(NewLibraryLipid[,1:(ncol(NewLibraryLipid)-1)], RT_min, RT_max, Comment)
colnames(NewLibraryLipid) <- as.character(as.matrix(NewLibraryLipid[1,]))
NewLibraryLipid <- NewLibraryLipid[-1,]
NewLibraryLipid <- NewLibraryLipid[!is.na(NewLibraryLipid[,1]),!is.na(NewLibraryLipid[1,])]
startRTCol <- ncol(NewLibraryLipid)-2
endRTCol <- startRTCol + 1
LibParentHits_df <- NewLibraryLipid #name change
nrowLibParentHits <- nrow(LibParentHits_df)
ncolLibParentHits <- ncol(LibParentHits_df)
NoMatches_dir<-file.path(OutputDirectory,"Additional_Files", paste0(ExtraFileNameInfo,"_NoIDs.csv"))
if(nrowLibParentHits == 0){#No hits between Feature List and Library
write.table("No Matches Found between Library and Feature List", NoMatches_dir, col.names=FALSE, row.names=FALSE, quote=FALSE)
}else{#If there was at least one match between Feature List and the Library
#Output dataframes. Used to build the All Confirmed
ConfirmedFragments_df <- data.frame(matrix(0, ncol = ncolLibParentHits, nrow = nrowLibParentHits))
RTMaxIntensity_df <- data.frame(matrix(0, ncol = ncolLibParentHits, nrow = nrowLibParentHits))
MaxIntensity_df <- data.frame(matrix(0, ncol = ncolLibParentHits, nrow = nrowLibParentHits))
NumOfScans_df <- data.frame(matrix(0, ncol = ncolLibParentHits, nrow = nrowLibParentHits))
AverageMZ_df <- data.frame(matrix(0, ncol = ncolLibParentHits, nrow = nrowLibParentHits))
outputHeader <- colnames(LibParentHits_df) #get header from LibParentHits_df
colnames(ConfirmedFragments_df) <- outputHeader
colnames(RTMaxIntensity_df) <- outputHeader
colnames(MaxIntensity_df) <- outputHeader
colnames(NumOfScans_df) <- outputHeader
colnames(AverageMZ_df) <- outputHeader
outputLibData <- LibParentHits_df[,c(1,startRTCol:ncolLibParentHits)] #gets data from LibParentHits_df
ConfirmedFragments_df[,c(1,startRTCol:ncolLibParentHits)] <- outputLibData
RTMaxIntensity_df[,c(1,startRTCol:ncolLibParentHits)] <- outputLibData
MaxIntensity_df[,c(1,startRTCol:ncolLibParentHits)] <- outputLibData
NumOfScans_df[,c(1,startRTCol:ncolLibParentHits)] <- outputLibData
AverageMZ_df[,c(1,startRTCol:ncolLibParentHits)] <- outputLibData
########################################################################################
# loop through lib parent hits M+H column, see #
# 1) if the precursor(from ms2) falls within this targetAcccuracy mz window #
# 2) if so... does this ms2 RT fall within the start and end RT from LibParentHits?#
# 3) if mz frag from ms2 falls within ppm of LibParentHits #
# Then fragment is confirmed. #
# #
# ms2_df[[1, 3]][1, 1] #
# ^matrix ^[row, column] from matrix #
########################################################################################
AIFms2SubsettedRTList <- list()
for(p in seq_len(nrowLibParentHits)){
RTConditional <- as.numeric(as.character(LibParentHits_df[p,startRTCol])) <= as.numeric(ms2_df[,2]) & as.numeric(ms2_df[,2]) <= as.numeric(as.character(LibParentHits_df[p,endRTCol]))
AIFms2SubsettedRTList[[p]] <- subset(ms2_df, RTConditional)
}
AIFms1SubsettedRTList <- list()
for(p in seq_len(nrowLibParentHits)){
RTConditional <- as.numeric(as.character(LibParentHits_df[p,startRTCol])) <= as.numeric(ms1_df[,2]) & as.numeric(ms1_df[,2]) <= as.numeric(as.character(LibParentHits_df[p,endRTCol]))
AIFms1SubsettedRTList[[p]] <- subset(ms1_df, RTConditional)
}
############################################################################
#Building All_Confirmed data frame for output (ddMS and/or AIF) #
# Creates a list of dataframes for each section of the All_Confirmed.csv. #
# Why? To organize our data. #
# Each list's element corresponds to a row from LibParentHits #
# Each list's element holds a fragment found in the scans #
############################################################################
#building ALL_Confirmed for AIF
for(c in ParentMZcol:((startRTCol - ParentMZcol)+1)){ #loop all fragment columns
subsettedFragList <- list() #has nrow(LibParentHits_df) elements
for(p in 1:nrowLibParentHits){ #loop through all AIFms2SubsettedRTList elements
# if(nrow(AIFms2SubsettedRTList[[p]]) != 0){ #don't loop if the list is empty! (for loops run once when the size is 0... :(...)
subsettedFrag_df <- data.frame(scans=numeric(), rt=numeric(), frags=numeric(), intensity=numeric())
scans <- vector()
rt <- vector()
frags <- vector()
intensity <- vector()
nrow_AIFms2SubsettedRTList <- nrow(AIFms2SubsettedRTList[[p]])
for(d in seq_len(nrow_AIFms2SubsettedRTList)){ #loop through each element in the list
subsettedFrag <- vector(length=0)
#Take the theoretical LibParentHits fragment m/z and look within a ppm window through the scan's ms2 fragments
fragConditional <- as.numeric(as.character(LibParentHits_df[p, c])) - abs(as.numeric(as.character(LibParentHits_df[p, c])) - as.numeric(as.character(LibParentHits_df[p, c]))*PPM_CONST) <= as.numeric(AIFms2SubsettedRTList[[p]][,3][[d]][,1]) & as.numeric(AIFms2SubsettedRTList[[p]][,3][[d]][,1]) <= as.numeric(as.character(LibParentHits_df[p, c])) + abs(as.numeric(as.character(LibParentHits_df[p, c])) - as.numeric(as.character(LibParentHits_df[p, c]))*PPM_CONST)
subsettedFrag <- subset(AIFms2SubsettedRTList[[p]][,3][[d]], fragConditional)
nrow_subsettedFrag <- nrow(subsettedFrag)
if(nrow_subsettedFrag>1){#more than one matching frag
for(s in 1:nrow_subsettedFrag){
scans <- append(scans, as.numeric(AIFms2SubsettedRTList[[p]][d,1])) #gets scan number
rt <- append(rt, as.numeric(AIFms2SubsettedRTList[[p]][d,2])) #get rt
}
}else if(nrow_subsettedFrag==1){#only 1 mataching frag
scans <- append(scans, as.numeric(AIFms2SubsettedRTList[[p]][d,1])) #gets scan number
rt <- append(rt, as.numeric(AIFms2SubsettedRTList[[p]][d,2])) #get rt
}#else, length is 0. no fragments found. do nothing.
frags <- append(frags, as.numeric(subsettedFrag[,1])) #gets fragment from ms2
intensity <- append(intensity, as.numeric(subsettedFrag[,2])) #gets intensity associated with that fragment
}
subsettedFrag_df <- data.frame(scans, rt, frags, intensity)
subsettedFragList[[p]] <- subsettedFrag_df
#Stores information into respective dataframes for output as All_Confirmed
if(nrow(subsettedFragList[[p]])>0){#loop over list elements that have values
#Max Intensity
maxIntensity <- max(subsettedFragList[[p]][,4])
MaxIntensity_df[p, c] <- maxIntensity
#Number of Scans
numScans <- nrow(subsettedFragList[[p]])
NumOfScans_df[p, c] <- numScans
#Confirming fragments
if(sum(subsettedFragList[[p]][,4] > intensityCutOff) > 0 & (numScans >= minNumberOfAIFScans)){ #at least one fragment's intensity is above user inputed threshold and number of scans is greater than or equal to user inputed, ScansCutOff
ConfirmedFragments_df[p, c] <- 1 #1 for yes, 0 for no. (ConfirmedFragments_df was initialized with all 0s)
}
#RT at max intensity
maxIntIndex <- which.max(subsettedFragList[[p]][,4])
RTMaxInt <- subsettedFragList[[p]][maxIntIndex,2]
RTMaxIntensity_df[p, c] <- RTMaxInt
#Average m/z for confirmed fragment
avgMZ <- mean(subsettedFragList[[p]][,3])
AverageMZ_df[p, c] <- avgMZ
}
}
}
#Creates df for output "AllConfirmed"
AllConfirmed_df <- data.frame(matrix("", ncol = ncolLibParentHits*5, nrow = nrowLibParentHits))
blankColumn <- rep("", nrowLibParentHits)
AllConfirmed_df <- cbind(blankColumn, ConfirmedFragments_df, blankColumn, RTMaxIntensity_df, blankColumn, NumOfScans_df, blankColumn, MaxIntensity_df, blankColumn, AverageMZ_df, blankColumn, LibParentHits_df)
colnames(AllConfirmed_df)[1] <- paste("Confirmed fragments if intensity is above", intensityCutOff,"and number of scans is greater than or equal to", minNumberOfAIFScans)
colnames(AllConfirmed_df)[ncolLibParentHits+2] <- "RT at Max Intensity"
colnames(AllConfirmed_df)[ncolLibParentHits*2+3] <- "Number of Scans"
colnames(AllConfirmed_df)[ncolLibParentHits*3+4] <- "Max Intensity"
colnames(AllConfirmed_df)[ncolLibParentHits*4+5] <- "Average m/z"
colnames(AllConfirmed_df)[ncolLibParentHits*5+6] <- "Theoretical, Library Parent Hits"
#DON'T WRITE THIS OUT. WE want to write out the final confirmed with Adj R2 and Slope
# ConfirmedAll_dir<-paste(OutputDirectory,"Additional_Files//", ExtraFileNameInfo,"_All_confirmed.csv",sep="")
# write.table(AllConfirmed_df, ConfirmedAll_dir, sep=",", col.names=TRUE, row.names=FALSE, quote=TRUE, na="NA")
## Code to reduce the dataset to lipids containing necessary fragments
## Start with both true, if no inputs then all rows are retained
AllConfirmed_matrix<-as.matrix(AllConfirmed_df)
OR_BinTruth<-1
AND_BinTruth<-1
## For any given confirmed fragment/precursor
## add an extra row to avoid error in an apply function encase of a one row matrix
DataCombined<-rbind(AllConfirmed_matrix,((1:ncol(AllConfirmed_matrix))*0))
if ((length(ConfirmORcol)>0)&&(is.matrix(DataCombined[1:nrow(DataCombined),ConfirmORcol+1]))) {
## Sum all the elements from the binary confirmation table, if any fragment is 1 (above threshold & minimum # of scans) the element is TRUE
OR_BinTruth<-as.numeric(c((apply(apply(DataCombined[1:nrow(DataCombined),ConfirmORcol+1],2,as.numeric),1,sum)>0)))
}
if ((length(ConfirmANDcol)>0)&&(is.matrix(DataCombined[1:nrow(DataCombined),ConfirmANDcol+1]))) {
## Sum all the elements from the binary confirmation table, if ALL fragments are 1 (above threshold & minimum # of scans) the element is TRUE
AND_BinTruth<-as.numeric(c((apply(apply(DataCombined[1:nrow(DataCombined),ConfirmANDcol+1],2,as.numeric),1,sum)>(length(ConfirmANDcol)-1))))
}
if ((length(ConfirmANDcol)>0)&&(is.vector(DataCombined[1:nrow(DataCombined),ConfirmANDcol+1]))) {
AND_BinTruth<-as.numeric(c(DataCombined[1:nrow(DataCombined),ConfirmANDcol+1]))
}
## Reduce the data set to those values which are TRUE for both the OR and AND fragments calculated in the two IF statements above
DataCombinedConfirmed<-DataCombined[(OR_BinTruth+AND_BinTruth)>1,,drop=FALSE]
NoMatches_dir<-file.path(OutputDirectory,"Additional_Files", paste0(ExtraFileNameInfo,"_NoIDs.csv"))
if(nrow(DataCombinedConfirmed)==0){
write.table("No Confirmed Compounds Found",NoMatches_dir, col.names=FALSE, row.names=FALSE, quote=FALSE)
}else{
# ConfirmedReduced_dir <- paste(OutputDirectory,"Confirmed_Lipids//",ExtraFileNameInfo,"_reduced_confirmed.csv",sep="")
# write.table(DataCombinedConfirmed, ConfirmedReduced_dir, sep=",",col.names=TRUE, row.names=FALSE, quote=TRUE, na="NA")
rowsToKeep <- as.numeric(row.names(DataCombinedConfirmed))-1 #used to reduce AIFms1SubsettedList and AIFms2SubsettedList
AIFms1SubsettedRTList <- AIFms1SubsettedRTList[rowsToKeep]
AIFms2SubsettedRTList <- AIFms2SubsettedRTList[rowsToKeep]
DataCombinedConfirmed_df <- as.data.frame(DataCombinedConfirmed)#reduced confirmed df
nrowReduced <- nrow(DataCombinedConfirmed_df)
ncolReduced <- ncol(DataCombinedConfirmed_df)
#gets the original theoretical library that was reduced
LibInfoFromDataComb_df<- DataCombinedConfirmed_df[,(ncolReduced-ncolLibParentHits+1):ncolReduced]
colsToCorr <- c(ColCorrAND, ColCorrOR)
numColsForAIF <- 4 + length(colsToCorr) #4 because ID, RTmin, RTmax, Comment
nameOfMiddleColsForAIF <- vector()
for(c in colsToCorr){#get "precursor vs fragment" header for output
nameOfMiddleColsForAIF <- append(nameOfMiddleColsForAIF, paste(colnames(LibParentHits_df[ParentMZcol]), " vs ", colnames(LibParentHits_df[c]), sep=""))
}
AIFHeader <- c(colnames(LibParentHits_df[1]), nameOfMiddleColsForAIF, colnames(LibParentHits_df[startRTCol:ncolLibParentHits])) #get header from LibParentHits_df
AdjR2_df <- data.frame(matrix(0, ncol = numColsForAIF, nrow = nrowReduced))
Slope_df <- data.frame(matrix(0, ncol = numColsForAIF, nrow = nrowReduced))
colnames(AdjR2_df) <- AIFHeader
colnames(Slope_df) <- AIFHeader
outputLibData <- LibInfoFromDataComb_df[,c(1,startRTCol:ncolLibParentHits)] #gets data from DataCombinedConfirmed_df
AdjR2_df[,c(1,(numColsForAIF-2):numColsForAIF)] <- outputLibData
Slope_df[,c(1,(numColsForAIF-2):numColsForAIF)] <- outputLibData
#correlate precursor from ms1 against predefined columns to correlate against from ms2
for(c in colsToCorr){ #loop fragment columns to correlate against ms1
for(p in seq_len(nrowReduced)){#loop all rows of reduced confirmed data frame
fragCorr_df<-NULL
ms1ScanNum <- vector()
ms2ScanNum <- vector()
ms1Intensity <- vector()
ms2Intensity <- vector()
length_AIFms1SubsettedRTList <- length(AIFms1SubsettedRTList[[p]][,1])
for(d in seq_len(length_AIFms1SubsettedRTList)){#store ms1 scan number and PRECURSOR intensity
subsettedFrag <- vector(length=0)
#Take the theoretical LibParentHits fragment m/z and look within a ppm window through the scan's ms2 fragments
AIFms1fragConditional <- (as.numeric(as.character(LibInfoFromDataComb_df[p, ParentMZcol])) - abs(as.numeric(as.character(LibInfoFromDataComb_df[p, ParentMZcol])) - as.numeric(as.character(LibInfoFromDataComb_df[p, ParentMZcol]))*PPM_CONST) <= as.numeric(AIFms1SubsettedRTList[[p]][,3][[d]][,1])) & (as.numeric(AIFms1SubsettedRTList[[p]][,3][[d]][,1]) <= as.numeric(as.character(LibInfoFromDataComb_df[p, ParentMZcol])) + abs(as.numeric(as.character(LibInfoFromDataComb_df[p, ParentMZcol])) - as.numeric(as.character(LibInfoFromDataComb_df[p, ParentMZcol]))*PPM_CONST))
subsettedFrag <- subset(AIFms1SubsettedRTList[[p]][,3][[d]], AIFms1fragConditional)
#error handling if you find 2 fragments masses within a ppm window. Then what?
if(nrow(subsettedFrag)>1){
LibMass<-as.numeric(as.character(LibInfoFromDataComb_df[p, c]))
fragMass<-as.numeric(subsettedFrag[,1])
closestMass<-which(abs(LibMass-fragMass)==min(abs(LibMass-fragMass)))
subsettedFrag<-subsettedFrag[closestMass,]
subsettedFrag<-matrix(subsettedFrag,1,2)
if(length(closestMass)>1){#edge case: if the two fragment masses are equidistant from the lib mass... then avg their intensities
#average the intensities (and masses, but I don't use the mass later, so it doesn't matter)
subsettedFrag<-matrix(c(mean(as.numeric(subsettedFrag[,1])),mean(as.numeric(subsettedFrag[,2]))), 1, 2)
}
}
# print("------------MS1-----------------")
# print(paste("d: ", d, "subsettedFrag:", subsettedFrag))
if(nrow(subsettedFrag)==0){
ms1Intensity <- append(ms1Intensity, 0)
}else{# if there's 1 fragment
ms1Intensity <- append(ms1Intensity, subsettedFrag[,2])
}
ms1ScanNum <- append(ms1ScanNum, as.numeric(AIFms1SubsettedRTList[[p]][d,1])) #gets scan number
}
length_AIFms2SubsettedRTList <- length(AIFms2SubsettedRTList[[p]][,1])
for(d in seq_len(length_AIFms2SubsettedRTList)){#store ms2 intensity
subsettedFrag <- vector(length=0)
#Take the theoretical LibParentHits fragment m/z and look within a ppm window through the scan's ms2 fragments
AIFms2fragConditional <- as.numeric(as.character(LibInfoFromDataComb_df[p, c])) - abs(as.numeric(as.character(LibInfoFromDataComb_df[p, c])) - as.numeric(as.character(LibInfoFromDataComb_df[p, c]))*PPM_CONST) <= as.numeric(AIFms2SubsettedRTList[[p]][,3][[d]][,1]) & as.numeric(AIFms2SubsettedRTList[[p]][,3][[d]][,1]) <= as.numeric(as.character(LibInfoFromDataComb_df[p, c])) + abs(as.numeric(as.character(LibInfoFromDataComb_df[p, c])) - as.numeric(as.character(LibInfoFromDataComb_df[p, c]))*PPM_CONST)
subsettedFrag <- subset(AIFms2SubsettedRTList[[p]][,3][[d]], AIFms2fragConditional)
if(nrow(subsettedFrag)>1){
LibMass<-as.numeric(as.character(LibInfoFromDataComb_df[p, c]))
fragMass<-as.numeric(subsettedFrag[,1])
closestMass<-which(abs(LibMass-fragMass)==min(abs(LibMass-fragMass)))
subsettedFrag<-subsettedFrag[closestMass,]
subsettedFrag<-matrix(subsettedFrag,1,2)
if(length(closestMass)>1){#edge case: if the two fragment masses are equidistant from the lib mass... then avg their intensities
#average the intensities (and masses, but I don't use the mass later, so it doesn't matter)
subsettedFrag<-matrix(c(mean(as.numeric(subsettedFrag[,1])),mean(as.numeric(subsettedFrag[,2]))), 1, 2)
}
}
# print("------------MS2-----------------")
# print(paste("d: ", d, "subsettedFrag:", subsettedFrag))
if(nrow(subsettedFrag)==0){
ms2Intensity <- append(ms2Intensity, 0)
}else{
ms2Intensity <- append(ms2Intensity, subsettedFrag[,2])
}
ms2ScanNum <- append(ms2ScanNum, as.numeric(AIFms2SubsettedRTList[[p]][d,1])) #gets scan number
}
ms1ScanNum<-as.numeric(ms1ScanNum)
ms2ScanNum<-as.numeric(ms2ScanNum)
ms1Intensity <- as.numeric(ms1Intensity)
ms2Intensity <- as.numeric(ms2Intensity)
ms1IntensityAveraged<-vector()
ms1ScanNumAveraged <- vector()
#average each ms1's intensity that are next to eachother so we can correlate it against ms2
length_ms1Intensity <- length(ms1Intensity)
for(a in seq_len(length_ms1Intensity-1)){#-1 so I don't go out of bounds
temp <- ms1Intensity[a+1]#next intensity
averaged <- mean(c(ms1Intensity[a], temp))
ms1IntensityAveraged <- append(ms1IntensityAveraged, averaged)
}
length_ms1ScanNum <- length(ms1ScanNum)
for(b in seq_len(length_ms1ScanNum-1)){#-1 so I don't go out of bounds
temp <- ms1ScanNum[b+1]#next intensity
averaged <- mean(c(ms1ScanNum[b], temp))
ms1ScanNumAveraged <- append(ms1ScanNumAveraged, averaged)
}
intensityCol1 <- ms1IntensityAveraged[ms1ScanNumAveraged %in% ms2ScanNum]
intensityCol2 <- ms2Intensity[ms2ScanNum %in% ms1ScanNumAveraged]
#test for mininum number of couples (found fragments in both ms1 and ms2)
intensitiesMultiplied <- intensityCol1*intensityCol2
numOfCouples <- length(subset(intensitiesMultiplied, intensitiesMultiplied != 0))
columnToFill <- match(c, colsToCorr) + 1 # +1 because the ID column in AdjR2_df is column 1.
#are there min number of user specified couples (Definition: Couples (noun) := fragment found in both ms1 and ms2 at the same scan time)
if(numOfCouples < minNumberOfAIFScans){#bad, you get no adj R2
# AdjR2_df[p,columnToFill] <- paste("Not enough ms1 averaged scans & ms2 scans for a linear model. We found: ", numOfCouples, " ms1 and ms2 scan couples. You specified: ", minNumberOfAIFScans, " number of coupled scans.",sep="")
# Slope_df[p,columnToFill] <- paste("Not enough ms1 averaged scans & ms2 scans for a linear model. We found: ", numOfCouples, " ms1 and ms2 scan couples. You specified: ", minNumberOfAIFScans, " number of coupled scans.",sep="")
AdjR2_df[p,columnToFill] <- NA
Slope_df[p,columnToFill] <- NA
}else{
fragCorr_df <- data.frame(ms1ScanNumAveraged, intensityCol1, intensityCol2)
intensityFit<-lm(fragCorr_df[,3]~fragCorr_df[,2])
intensitySummary <- summary(intensityFit)
intensityAdjR2 <- intensitySummary$adj.r.squared
intensitySlope <- intensityFit$coefficients[2]
# if(intensityAdjR2 > corrMin){
AdjR2_df[p,columnToFill] <- round(intensityAdjR2, 3)
Slope_df[p,columnToFill] <- round(intensitySlope, 5)
# }else{
# AdjR2_df[p,columnToFill] <- NA
# Slope_df[p,columnToFill] <- NA
# }
# print(fragCorr_df)
##We don't use this. But I'll keep it here. intensityCorr <- cor(fragCorr_df[,2],fragCorr_df[,3],use="complete.obs")##
}
}#end row loop
}#end column loop
# write the table out.
#remove theoretical library from end of DataCombinedConfirmed_df
DataCombinedConfirmed_df <- DataCombinedConfirmed_df[,-((ncolReduced-ncolLibParentHits):ncolReduced)] #CAREFUL NICK! THIS MESSES WITH THE HEADER!...but I kinda like the .1 .2 .3. .4
blankColumn <- rep("", nrowReduced)
DataCombinedConfirmed_df <- cbind(DataCombinedConfirmed_df, blankColumn, AdjR2_df, blankColumn, Slope_df, blankColumn, LibInfoFromDataComb_df)
colnames(DataCombinedConfirmed_df)[ncolLibParentHits*5+6] <- paste("Adjusted R2, Precursor Intensity vs Fragment Intensity (AIF). AdjR2 > ", corrMin, sep="")
colnames(DataCombinedConfirmed_df)[ncolLibParentHits*5+6 + numColsForAIF + 1] <- "Slope, Precursor Intensity vs Fragment Intensity (AIF)"
colnames(DataCombinedConfirmed_df)[ncolLibParentHits*5+6 + numColsForAIF*2 + 2] <- "Theoretical, Library Parent Hits"
ConfirmedReduced_dir <- file.path(OutputDirectory,"Additional_Files", paste0(ExtraFileNameInfo,"_AdjR2Info.csv"))
write.table(DataCombinedConfirmed_df, ConfirmedReduced_dir, sep=",",col.names=TRUE, row.names=FALSE, quote=TRUE, na="NA")
#Reduce matches based on ConfirmAndCol
if(length(ConfirmANDcol) > 0){
columnToFill<-vector()
# AdjR2_df[] <- lapply(AdjR2_df, as.numeric)
for(i in ConfirmANDcol){
columnToFill <- append(columnToFill, match(i, ConfirmANDcol) + 1)
}
#get R2 rows with text in them, and remove them.
if(!is.numeric(AdjR2_df[,columnToFill])){#if the adjR2 column is already numeric, (don't change to as.numeric...this gives an error)
AdjR2_df[,columnToFill] <- lapply(AdjR2_df[,columnToFill], as.numeric)
}
if(!is.numeric(Slope_df[,columnToFill])){#if the adjR2 column is already numeric, (don't change to as.numeric...this gives an error)
Slope_df[,columnToFill] <- lapply(Slope_df[,columnToFill], as.numeric)
}
#We want AdjR2 to be > corrMin and slopes to be positive!
#set non positive slopes to NA
Slope_df[,columnToFill] <- replace(Slope_df[,columnToFill],Slope_df[,columnToFill]<=0,NA)
#remove negative slopes
AdjR2_df <- AdjR2_df[apply(cbind(AdjR2_df[,columnToFill],Slope_df[,columnToFill]), 1, function(x) all(!is.na(x))),]
AdjR2_df <- AdjR2_df[apply(AdjR2_df[,columnToFill, drop=F], 1, function(x) all(x > corrMin)),]
rowsToKeep <- as.numeric(row.names(AdjR2_df)) #used to reduce final output table based on the reduced AdjR2_df rows from above ConfirmAND and ConfirmOR columns
Slope_df <- Slope_df[rowsToKeep,]
# AdjR2_df <- AdjR2_df[apply(AdjR2_df[columnToFill], 1, function(x) all(x > corrMin & !is.na(x))),]
# AdjR2_df <- AdjR2_df[apply(AdjR2_df[c(2,3)], 1, function(x) all((x > corrMin) & is.numeric(x))),]
}
#difference here is in the apply function.... "all" vs "any"
if(length(ConfirmORcol) > 0){
columnToFill<-vector()
# AdjR2_df[] <- lapply(AdjR2_df, as.numeric)
length_ConfirmANDcol <- length(ConfirmANDcol)
for(i in ConfirmORcol){
columnToFill <- append(columnToFill, match(i, ConfirmORcol) + 1 + length_ConfirmANDcol)
}
if(nrow(AdjR2_df[,columnToFill]) !=0){#The AND could've removed all rows, so now we have nothing to work with.
if(!is.numeric(AdjR2_df[,columnToFill])){#if the adjR2 column is already numeric, (don't change to as.numeric...this gives an error)
AdjR2_df[,columnToFill] <- lapply(AdjR2_df[,columnToFill], as.numeric)
}
if(!is.numeric(Slope_df[,columnToFill])){#if the adjR2 column is already numeric, (don't change to as.numeric...this gives an error)
Slope_df[,columnToFill] <- lapply(Slope_df[,columnToFill], as.numeric)
}
#We want AdjR2 to be > corrMin and slopes to be positive!
#set non positive slopes to NA
Slope_df[,columnToFill] <- replace(Slope_df[,columnToFill],Slope_df[,columnToFill]<=0,NA)
#remove negative slopes
AdjR2_df <- AdjR2_df[apply(cbind(AdjR2_df[,columnToFill],Slope_df[,columnToFill]), 1, function(x) all(!is.na(x))),]
AdjR2_df <- AdjR2_df[apply(AdjR2_df[,columnToFill, drop=F], 1, function(x) any(x > corrMin)),]
}
}
rowsToKeep <- as.numeric(row.names(AdjR2_df)) #used to reduce final output table based on the reduced AdjR2_df rows from above ConfirmAND and ConfirmOR columns
DataCombinedConfirmed_df <- DataCombinedConfirmed_df[rowsToKeep,]
ConfirmedReduced_dir <- file.path(OutputDirectory,"Confirmed_Compounds", paste0(ExtraFileNameInfo,"_IDed.csv"))
if(nrow(DataCombinedConfirmed_df)>0){#don't output if there's nothing in the reduced file
write.table(DataCombinedConfirmed_df, ConfirmedReduced_dir, sep=",",col.names=TRUE, row.names=FALSE, quote=TRUE, na="NA")
}
}#end else (if there are matches after reduction step)
tEnd<-Sys.time()
# Capture parameters used for this run and save them
RunInfo<-matrix("",24,2)
RunInfo[,1]<-c("Parameters Used","","Run Time","Computation Started:","Computation Ended:","Elapsed Time (largest time unit)","","Files","MS2 file name and Directory:","MS1 file name and Directory","Feature Table name and directory:","Library name and directory:","","MS/MS confirmation criteria","Library columns for confirmation (AND)","Library columns for confirmation (OR)","m/z ppm window:","RT window (min):","minimum scans:","minimum intensity:", "","AIF confirmation criteria","Minimum adjusted R2 value","Minimum scans:")
RunInfo[,2]<-c("Values","","",as.character(tStart),as.character(tEnd),tEnd-tStart,"","",OutputInfo[1],OutputInfo[4],OutputInfo[3],LibraryLipid_self,"","",paste(ConfirmANDcol,collapse=","),paste(ConfirmORcol,collapse=","),ppm_Window,RT_Window,minNumberOfAIFScans,intensityCutOff,"","",corrMin,minNumberOfAIFScans)
Info_dir<-file.path(OutputDirectory,"Additional_Files", paste0(ExtraFileNameInfo,"_Parameters.csv"))
write.table(RunInfo, Info_dir, sep=",",col.names=FALSE, row.names=FALSE, quote=TRUE, na="NA")
}
}#end RunAIF
# ms2_df <- MS2_df_list[[c]]
# FeatureList <- FeatureList_in
# LibraryLipid_self <- file.path(InputLibrary, LibraryCriteria[i,1])
# ParentMZcol <- ParentMZcol_in
# OutputDirectory <- OutputDirectoryddMSNeg_in
# ExtraFileNameInfo <- paste(ExtraSample,"_",gsub('.{4}$', '', LibraryCriteria[i,1]), sep="")
# ms2FileName <- ddMS2NEG_in[c]
# NegPos <- "Neg"
#Function for MS/MS ID
RunTargeted <- function(ms2_df, FeatureList, LibraryLipid_self, ParentMZcol, OutputDirectory, ExtraFileNameInfo, ConfirmORcol, ConfirmANDcol, OutputInfo, ms2FileName, NegPos){
# message("RunTar")
if(!dir.exists(file.path(OutputDirectory,"Confirmed_Compounds"))){
dir.create(file.path(OutputDirectory,"Confirmed_Compounds"))
}
if(!dir.exists(file.path(OutputDirectory,"Additional_Files"))){
dir.create(file.path(OutputDirectory,"Additional_Files"))
}
#store starting time
tStart<-Sys.time()
LibraryLipid<-read.csv(LibraryLipid_self, sep=",", na.strings="NA", dec=".", strip.white=TRUE,header=FALSE)
libraryLipidMZColumn <- ParentMZcol
FeatureListMZColumn <- 1
## Create a Library of Lipids and fragments for those masses in Feature List
FeatureListHeader <- FeatureList[1,]
LibraryLipidHeader <- LibraryLipid[1,]
NewLibraryLipidHeader <- cbind(LibraryLipidHeader, FeatureListHeader)
sqlMerged <- sqldf(paste("select * from LibraryLipid lib inner join FeatureList iList on lib.", colnames(LibraryLipid)[libraryLipidMZColumn], "-", PrecursorMassAccuracy, "<= iList.", colnames(FeatureList)[FeatureListMZColumn], " and iList.", colnames(FeatureList)[FeatureListMZColumn], " <= lib.", colnames(LibraryLipid)[libraryLipidMZColumn], "+", PrecursorMassAccuracy, sep = ""))
# sqlMerged <- sqldf(paste("select * from LibraryLipid lib inner join FeatureList iList on iList.", colnames(FeatureList)[FeatureListMZColumn], " >= lib.", colnames(LibraryLipid)[libraryLipidMZColumn], " -.005 and iList.", colnames(FeatureList)[FeatureListMZColumn], " <= lib.", colnames(LibraryLipid)[libraryLipidMZColumn], "+ .005", sep = ""))
NewLibraryLipid <- as.matrix(sqlMerged)
# if sqlMerged is not empty the names of the columns need to be adjusted, maybe better to always adjust them
colnames(NewLibraryLipid) <- colnames(NewLibraryLipidHeader)
NewLibraryLipid <- rbind(NewLibraryLipidHeader,NewLibraryLipid)
NewLibraryLipid <- NewLibraryLipid[,-(ncol(LibraryLipid)+1)] #removes mz from Feature list
#Removes 1 rt col and creates RT_min and RT_max cols based on RT_Window
RT_Col <- as.numeric(NewLibraryLipid[2:nrow(NewLibraryLipid),ncol(NewLibraryLipid)-1])
NewLibraryLipid <- NewLibraryLipid[,-(ncol(NewLibraryLipid)-1)]
RT_Window_Vector <- rep(RT_Window/2, each=nrow(NewLibraryLipid)-1)
#Issue found 10/30 Removed Levels function
RT_min <- RT_Col - as.numeric(RT_Window_Vector)
RT_max <- RT_Col + as.numeric(RT_Window_Vector)
RT_min <- c("RT_min",RT_min)
RT_max <- c("RT_max",RT_max)
Comment <- NewLibraryLipid[,ncol(NewLibraryLipid)]
NewLibraryLipid <- cbind(NewLibraryLipid[,1:(ncol(NewLibraryLipid)-1)], RT_min, RT_max, Comment)
colnames(NewLibraryLipid) <- as.character(as.matrix(NewLibraryLipid[1,]))
NewLibraryLipid <- NewLibraryLipid[-1,]
NewLibraryLipid <- NewLibraryLipid[!is.na(NewLibraryLipid[,1]),!is.na(NewLibraryLipid[1,])]
startRTCol <- ncol(NewLibraryLipid)-2
endRTCol <- startRTCol + 1
LibParentHits_df <- NewLibraryLipid #name change
nrowLibParentHits <- nrow(LibParentHits_df)
ncolLibParentHits <- ncol(LibParentHits_df)
NoMatches_dir<-file.path(OutputDirectory,"Additional_Files", paste0(ExtraFileNameInfo,"_NoIDs.csv"))
if(nrowLibParentHits == 0){#No hits between Feature List and Library
write.table("No Matches Found between Library and Feature List", NoMatches_dir, col.names=FALSE, row.names=FALSE, quote=FALSE)
}else{#If there was at least one match between Feature List and the Library
#Output dataframes. Used to build the All Confirmed
ConfirmedFragments_df <- data.frame(matrix(0, ncol = ncolLibParentHits, nrow = nrowLibParentHits))
RTMaxIntensity_df <- data.frame(matrix(0, ncol = ncolLibParentHits, nrow = nrowLibParentHits))
MaxIntensity_df <- data.frame(matrix(0, ncol = ncolLibParentHits, nrow = nrowLibParentHits))
NumOfScans_df <- data.frame(matrix(0, ncol = ncolLibParentHits, nrow = nrowLibParentHits))
AverageMZ_df <- data.frame(matrix(0, ncol = ncolLibParentHits, nrow = nrowLibParentHits))
colnames(ConfirmedFragments_df) <- colnames(LibParentHits_df) #get header from LibParentHits_df
colnames(RTMaxIntensity_df) <- colnames(LibParentHits_df) #get header from LibParentHits_df
colnames(MaxIntensity_df) <- colnames(LibParentHits_df) #get header from LibParentHits_df
colnames(NumOfScans_df) <- colnames(LibParentHits_df) #get header from LibParentHits_df
colnames(AverageMZ_df) <- colnames(LibParentHits_df) #get header from LibParentHits_df
ConfirmedFragments_df[,c(1,startRTCol:ncolLibParentHits)] <- LibParentHits_df[,c(1,startRTCol:ncolLibParentHits)] #gets data from LibParentHits_df
RTMaxIntensity_df[,c(1,startRTCol:ncolLibParentHits)] <- LibParentHits_df[,c(1,startRTCol:ncolLibParentHits)] #gets data from LibParentHits_df
MaxIntensity_df[,c(1,startRTCol:ncolLibParentHits)] <- LibParentHits_df[,c(1,startRTCol:ncolLibParentHits)] #gets data from LibParentHits_df
NumOfScans_df[,c(1,startRTCol:ncolLibParentHits)] <- LibParentHits_df[,c(1,startRTCol:ncolLibParentHits)] #gets data from LibParentHits_df
AverageMZ_df[,c(1,startRTCol:ncolLibParentHits)] <- LibParentHits_df[,c(1,startRTCol:ncolLibParentHits)] #gets data from LibParentHits_df
########################################################################################
# loop through lib parent hits M+H column, see #
# 1) if the precursor(from ms2) falls within this targetAcccuracy mz window #
# 2) if so... does this ms2 RT fall within the start and end RT from LibParentHits?#
# 3) if mz frag from ms2 falls within ppm of LibParentHits #
# Then fragment is confirmed. #
# #
# ms2_df[[1, 3]][1, 1] #
# ^matrix ^[row, column] from matrix #