-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathWorkflow_R_Functions.r
2794 lines (2298 loc) · 137 KB
/
Workflow_R_Functions.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
# ---------- Preparations ----------
# Load Libraries
library(Spectra)
library(MsBackendMgf)
library(MsBackendHmdb)
library(MsCoreUtils)
library(MsBackendMsp)
library(readr)
library(dplyr)
# 3 dependencies for latest MassBank version
library(rvest)
library(stringr)
library(xml2)
options(warn=-1)
library("mzR")
#' Download the CompDb database using curl
library(curl)
#library(CompoundDb)
download_specDB_new <- function(input_dir, db = "all"){
if (dir.exists(input_dir)){
# Track Time
start_time <- Sys.time()
# only input available as of now
databases <- 'gnps, hmdb, mbank, all'
# creat a summary file, open and store timings of download and version if possible
if (!(file.exists(paste(input_dir, "/summaryFile.txt", sep = "")))){
summaryFile <- paste(input_dir, "/summaryFile.txt", sep = "")
file.create(summaryFile, recursive = TRUE)
}
else{
summaryFile <- paste(input_dir, "/summaryFile.txt", sep = "")
}
file.conn <- file(summaryFile)
open(file.conn, open = "at")
# gnps
if (db == "all" || db =="gnps"){
# Download file
system(paste("wget -P",
input_dir,
"https://gnps-external.ucsd.edu/gnpslibrary/ALL_GNPS.msp",
sep = " "))
# load the spectra into MsBackendMgf
gnpsdb <- Spectra(paste(input_dir, "/ALL_GNPS.msp", sep = ''), source = MsBackendMsp())
save(gnpsdb, file = paste(input_dir,"/gnps.rda", sep = ""))
# delete the database in its format to free up space
system(paste("rm", (paste(input_dir, "/ALL_GNPS.mgf", sep = '')), sep = " "))
writeLines(paste("GNPS saved at", Sys.time(), sep=" "),con=file.conn)
}
#mbank
if (db == "all" || db =="mbank"){
#print("MassBank WORKS")
page <- read_html("https://github.com/MassBank/MassBank-data/releases")
page %>%
html_nodes("a") %>% # find all links
html_attr("href") %>% # get the url
str_subset("MassBank_NIST.msp") -> tmp # find those that have the name MassBank_NIST.msp
#download file
system(paste("wget ",
"https://github.com", tmp[1],
sep = ""))
mbank <- Spectra(paste(input_dir, "/MassBank_NIST.msp", sep = ''), source = MsBackendMsp())
save(mbank, file = paste(input_dir,"/mbankNIST.rda", sep = ""))
# delete the database in its format to free up space
system(paste("rm", (paste(input_dir, "/MassBank_NIST.msp", sep = '')), sep = " "))
# obtain the month and year for the database release to add to summary
res <- str_match(tmp[1], "download/\\s*(.*?)\\s*/MassBank_NIST")
writeLines(paste("MassBank saved at", Sys.time(), "with release version", res[,2], sep=" "),con=file.conn)
}
#mbank
if (db == "all" || db =="hmdb"){
# extract HMDB Current version\n",
html <- read_html("https://hmdb.ca/downloads")
strings <- html%>% html_elements("a") %>% html_text2()
ls <- unique(strings)
hmdb_curr_ver <- c()
for (i in ls){
if (grepl("Current", i)){
hmdb_curr_ver<- c(i, hmdb_curr_ver)
}
}
dbname <- "CompDb.Hsapiens.HMDB.5.0.sqlite"
db_file <- file.path(tempdir(), dbname)
curl_download(
paste0("https://github.com/jorainer/MetaboAnnotationTutorials/",
"releases/download/2021-11-02/", dbname),
destfile = db_file)
#' Load a CompDb database with compound annotation from HMDB
cdb <- CompDb(db_file)
hmdb <- Spectra(cdb)
hmdb$collisionEnergy <- as.numeric(hmdb$collisionEnergy)
hmdb <- setBackend(hmdb, backend = MsBackendDataFrame())
save(hmdb, file = paste(input_dir,"/hmdb.rda", sep = ""))
writeLines(paste("HMDB saved at", Sys.time(), "with release version", hmdb_curr_ver, sep=" "),con=file.conn)
}
#wrong input error message
else if (!grepl(db, databases, fixed = TRUE)){
stop("Wrong db input. Following inputs apply: gnps, hmdb, mbank or all")
}
close(file.conn)
end_time <- Sys.time()
print(end_time - start_time)
}
else{
stop("Your input_dir is incorrect. Please provide the directory where all your input files are stored.")
}
}
##-----------------------------------------------------------------
## filter intensity
##-----------------------------------------------------------------
#' Define a filtering function and remove peaks less than 0.05 of intensity
low_int <- function(c, ...) {
c > max(c, na.rm = TRUE) * 0.05
}
# Usage:
# filterIntensity(spectra_object, intensity = low_int)
##-----------------------------------------------------------------
## normalize intensity
##-----------------------------------------------------------------
#' Define a function to *normalize* the intensities
norm_int <- function(y, ...) {
maxint <- max(y[, "intensity"], na.rm = TRUE)
y[, "intensity"] <- 100 * y[, "intensity"] / maxint
y
}
## Specifying a function for creating result directories for each input mzml
# input for the function:
# input directory
ms2_rfilename<- function(input_dir){
if (dir.exists(input_dir)){
#list_ms2_files <- intersect(list.files(input_dir, pattern = "_PRM_"), list.files(input_dir, pattern = ".mzML"))
list_ms2_files <- list.files(input_dir, pattern = ".mzML")
mzml_file <- paste(input_dir, "/", list_ms2_files, sep = "")
#store the result file names to return to this function as output
mzml_files <- c()
ResultFileNames <- c()
File_id <- c()
nx <- 0
# x is mzML files
for (i in 1:length(mzml_file)){
nx <- nx+1
# remove .mzML to extract just the names
mzml_filex <- str_replace(mzml_file[i], input_dir, ".")
name_mzmls <- str_remove(as.character(mzml_filex), ".mzML")
name_mzmlsd <- str_remove(mzml_file[i], ".mzML")
#name_mzml <- str_replace(name_mzmls, input_dir, "./")
#' for each file a subdirectory is created to store all results in that, add working directory
if (!file.exists(name_mzmlsd)){
dir.create(name_mzmlsd) ##create folder
}
ResultFileNames<- c(ResultFileNames, name_mzmls)
mzml_files <- c(mzml_files, mzml_filex)
File_id <- c(File_id, paste("file_", nx, sep = ""))
}
input_table <- cbind(mzml_files, ResultFileNames, File_id)
write.csv(input_table, paste(input_dir, "/input_table.csv", sep = ""))
return(data.frame(input_table))
}
else{
stop("Your input_dir is incorrect. Please provide the directory where all your input files are stored. : ) Good Luck")
}
}
#' All spectra in mzML files preprocessing, return two outputs, pre-processed MS2 spectra and all precursor masses
# x is one mzML file
spec_Processing <- function(input_dir, x, result_dir){
x <- paste(input_dir, str_remove(x, "."), sep = "")
result_dir <- paste(input_dir, str_remove(result_dir, "."), sep = "")
if (file.exists(x) && substring(x, nchar(x)) == "L"){
if (dir.exists(result_dir)){
# read the spectra
sps_all <- Spectra(x, backend = MsBackendMzR())
#' Change backend to a MsBackendDataFrame: load data into memory
#sps_all <- setBackend(sps_all, MsBackendDataFrame())
#' Filter Empty Spectra
sps_all <- filterEmptySpectra(sps_all)
#' Extract Precursor m/z(s) in each file
pre_mz <- unique(precursorMz(sps_all))
#' Remove any NAs
pre_mz <- na.omit(pre_mz)
if (!file.exists(paste(result_dir, "/processedSpectra.mzML", sep = ""))){
export(sps_all, backend = MsBackendMzR(), file = paste(result_dir, "/processedSpectra.mzML", sep = ""))
}
if (!file.exists(paste(result_dir, "/premz_list.txt", sep = ""))){
write.table(pre_mz, file = paste(result_dir, "/premz_list.txt", sep = ""), sep = "/t",row.names = FALSE, col.names = FALSE)
}
spsall_pmz <- list(sps_all, pre_mz)
return(spsall_pmz)
}
else{
stop("Seems like it is not the result directory of the input .mzML file which is provided as x. Please use the function ms2_rfilename to generate a result directory or create one yourself with the same name as the .mzML input file.")
}
}
else{
stop("Are you sure x is an mzML input file?")
}
}
spec2_Processing <- function(z, obj, spec = "spec_all", ppmx = 15){
if (spec == "spec_all"){
#' Subset the dataset to MS2 spectra matching the m/z
sps <- filterPrecursorMzValues(obj, mz = z + ppm(c(-z, z), 10))
} else if (spec == "gnps"){
#gnps spectra that contains precursor mass
has_mz <- containsMz(obj, mz = z, ppm = ppmx)
#' Subset the GNPS Spectra
sps <- obj[has_mz]
} else if (spec == "hmdb"){
#hmdb spectra that contains precursor mass
has_mz <- containsMz(obj, mz = z, ppm = ppmx)
#' Subset the HMDB Spectra
sps <- obj[has_mz]
} else if (spec == "mbank"){
has_mz <- containsMz(obj, mz = z, ppm = ppmx)
#' Subset the MB Spectra
sps <- obj[has_mz]
}
#wrong input error message
else if (!grepl(db, databases, fixed = TRUE)){
stop("Wrong db input. Following inputs apply: gnps, hmdb, mbank or all")
}
if (length(sps)>0){
#' Apply the function to filter the spectra
sps <- filterIntensity(sps, intensity = low_int)
#' *Apply* the function to the data
sps <- addProcessing(sps, norm_int)
# cleaning peaks that are heavier or equal to the precursor mass
pkd <- peaksData(sps)@listData
#obtain the list of peaks that are higher or equal to precursor mass
# y is peaksData from spectra
removePrecursorPeaks <- function(m){
m <- m[m[, "mz"] <= z, ]
}
# use lapply to apply the function to the list of peaksData
pkd <- lapply(pkd, removePrecursorPeaks)
#store the indices of spectra with 0 peaks
store_i <- c()
for (i in 1:length(pkd)){
if (is.null(nrow(pkd[[i]]))){
#convert the object of one peak into a matrix
mz <- pkd[[i]][[1]]
intensity <- pkd[[i]][[2]]
mat <- cbind(mz, intensity)
pkd[[i]] <- mat
}else if(nrow(pkd[[i]])==0){
#store indices with 0 peaks
store_i <- c(store_i, i)
}
}
# if 0 peaks, remove the relevant spectra from gnps or hmdb or mbank
if (!(is.null(store_i))){
pkd <- pkd[-(store_i)]
sps <- sps[-(store_i)]
peaksData(sps@backend)<- pkd
}else {
peaksData(sps@backend)<- pkd
}
return(sps)
}
else {
sps <- NULL
return(sps)
}
}
##-----------------------------------------------------------------
## Extract peaksdata in a dataframe
##-----------------------------------------------------------------
#' obtain peaksData for each spectral matching between query and database spectra
#inputs a is best match from Database, b is best match from query spectra
peakdf <- function(a, b, ppmx){
#' obtain peaklists for both query spectra and best matched spectra from MassBank
z<- peaksData(a)[[1]] #from GNPS/HMDB
y <- peaksData(b)[[1]] #from query
if (!(nrow(z)==0)){
#' Since we used 15 ppm, so to find the range, calculate the mass error range
range <- (ppmx/1000000)*y[,"mz"]
y <- cbind(y, range)
low_range <- y[,"mz"]-y[,"range"] # low range of m/z
high_range <- y[,"mz"]+y[,"range"] # high range of m/z
y <- cbind(y, low_range, high_range)
#from GNPS/HMDB/MassBank spectra
mz.z <- c()
intensity.z <- c()
#from query spectra
mz.y <- c()
intensity.y <- c()
#difference between their intensity
diff <- c()
#' for all rows of y
for (m in 1:nrow(y)){
#' for all rows of z
for(j in 1:nrow(z)){
###################################################################
## IFELSE Statement no.2 -- LOOP 1.1.1.1
#' if the m/z of MB Spectra is within the 20 ppm range, save difference between intensities
if (y[m,"low_range"] <= z[j, "mz"] && z[j, "mz"] <= y[m,"high_range"]){
#GNPS/HMDB
mz_z <- as.numeric(z[j, "mz"])
mz.z <- c(mz.z, mz_z)
intensity_z <- as.numeric(z[j, "intensity"])
intensity.z <- c(intensity.z, intensity_z)
#QUERY
mz_y <- as.numeric(y[m, "mz"])
mz.y <- c(mz.y, mz_y)
intensity_y <- as.numeric(y[m, "intensity"])
intensity.y <- c(intensity.y, intensity_y)
#Difference between intensities
difference <- as.numeric(abs(z[j, "intensity"]-y[m, "intensity"]))
diff <- c(diff, difference)
}
}
}
df_peaklists <- cbind(mz.y, intensity.y, mz.z, intensity.z, diff)
return(df_peaklists)
}
else{
df_peaklists <- NULL
return(df_peaklists)
}
#output is a dataframe with mz and intensity from db spectra and query spectra and their difference
}
##-----------------------------------------------------------------
## Plotting Mirror Spectra
##-----------------------------------------------------------------
#' Specifying a function to draw peak labels
#label_fun <- function(x) {
#ints <- unlist(intensity(x))
#mzs <- format(unlist(mz(x)), digits = 4)
#mzs[ints < 5] <- ""
#mzs
#}
spec_dereplication_file <- function(mzml_file, pre_tbl, proc_mzml, db, result_dir, file_id, input_dir, no_of_candidates = 30, ppmx, error = TRUE){
# if the database selected is HMDB or all
# if the database selected is GNPS or all
if (db == "all" || db =="gnps"){
if (file.exists(paste(input_dir,"/gnps.rda", sep = ""))){
# load the gnps spectral database
load(file = paste(input_dir,"/gnps.rda", sep = ""))
}
else if (file.exists("gnps.rda")){
# load the gnps spectral database
load("gnps.rda")
}
}
# if the database selected is HMDB or all
if (db == "all" || db =="hmdb"){
if (file.exists(paste(input_dir,"/hmdb.rda", sep = ""))){
# load the hmdb spectral database
load(file = paste(input_dir,"/hmdb.rda", sep = ""))
}
else if (file.exists("hmdb.rda")){
# load the gnps spectral database
load("hmdb.rda")
}
}
# if the database selected is HMDB or all
if (db == "all" || db == "mbank"){
if (file.exists(paste(input_dir,"/mbankNIST.rda", sep = ""))){
# load the mbank spectral database
load(file = paste(input_dir,"/mbankNIST.rda", sep = ""))
}
else if (file.exists("mbankNIST.rda")){
# load the gnps spectral database
load("mbankNIST.rda")
}
}
# read spectra object
sps_all <- Spectra(proc_mzml, source = MsBackendMzR())
# extract precursor m/z
tbl <- read.table(pre_tbl)
pre_mz <- tbl[[1]]
# common feature information
id_X <- c() # id
premz <- c() # precursor mz
rtmin <- c() # stores rtmin
rtmax <- c() # stores rtmax
rtmed <- c() # stores calculated median of rtmin and rtmax
rtmean <- c() # stores calculated mean of rtmin and rtmax
col_eng <- c() # stores collision energy
pol <- c() # stores polarity
int <- c() # store intensity
source_file <- c() # source file
nx <- 0 # numbering the ids
pre_mzs <- listenv() # list for holding pre_mz futures
# for each pre mass
for (x in pre_mz){
print(x)
# to name the file
nx <- nx+1
# filter spectra based on precusror m/z
# this is done to extract all common information for id_X
spsrt <- filterPrecursorMzRange(sps_all, x)
# id based on file id,
id_Xx <- paste(file_id, "M", as.character(round(x, digits = 0)),
"R", as.character(round(median(spsrt$rtime, na.rm = TRUE), digits = 0)),
"ID", as.character(nx), sep = '')
id_X <- c(id_X, id_Xx)
# pre_mas
pre <- x
premz <- c(premz, pre)
# rt min
rti <- min(spsrt$rtime)
rtmin <- c(rtmin, rti)
#rt max
rtx <- max(spsrt$rtime)
rtmax <- c(rtmax, rtx)
#rt median
rtmd <- median(spsrt$rtime, na.rm = TRUE)
rtmed <- c(rtmed, rtmd)
#rt mean
rtmn <- mean(spsrt$rtime, na.rm = TRUE)
rtmean <- c(rtmean, rtmn)
#collision energy
ce <- max(spsrt$collisionEnergy)
col_eng <- c(col_eng, ce)
#polarity
pl <- max(spsrt$polarity)
if (pl == 1){
px <- 'pos'
pol <- c(pol, px)
}
else {
px <- 'neg'
pol <- c(pol, px)
}
#int
ints <- max(spsrt$precursorIntensity)
int <- c(int, ints)
#mzmlfile
source_file <- c(source_file, mzml_file)
# after all the common infromation is stored,
# move to extracting matching candidates with input spectra
pre_mzs[[x]] <- future({
sps <- spec2_Processing(x, sps_all, spec = "spec_all")
####-------------------------------------------------------------
#### Dereplication with all or GNPS ----
####-------------------------------------------------------------
# define variables for result dataframe
# if the database selected is GNPS or all
f_gnps <- future(
if (db == "all" || db =="gnps"){
GNPSmax_similarity <- c() # dot product score
GNPSmzScore <- c() # similar m/z score
GNPSintScore <- c() # similar int score
GQMatchingPeaks <- c() # matching peaks between gnps candidate and input spectra
GNPSTotalPeaks <- c() # total peaks in gnps candidate
gQueryTotalPeaks<- c() # total peaks in input spectra
GNPSSMILES <- c() # smiles of gnps candidate
#GNPSspectrumID <- c() # spectrum id of gnps candidate
GNPScompound_name <- c() # compound name of gnps candidate
#GNPSmirrorSpec <- c() # path for mirror spectra between gnps candidate and input of gnps candidate
Source <- c() # GNPS as source of result
#### GNPS spec with pre_mz
gnps_with_mz <- spec2_Processing(x, gnpsdb, spec = "gnps", ppmx) # change here later
# define the directoyr name to store all GNPS results
dir_name <- paste(input_dir, str_remove(paste(result_dir, "/spectral_dereplication/GNPS/", sep = ""), "."), sep ="")
if (!file.exists(dir_name)){
dir.create(dir_name, recursive = TRUE)
}
if (length(sps) != 0 && length(gnps_with_mz) !=0){
#' Compare experimental spectra against GNPS
res <- compareSpectra(sps, gnps_with_mz, ppm = 15, FUN = MsCoreUtils::gnps, MAPFUN = joinPeaksGnps)
# first condition for GNPS
# if more input spectra and more candidates have been extracted from GNPS
if (length(sps) > 1 && length(gnps_with_mz) >1){
# given threshold of 0.85 for GNPS, extract top candidates
res_top <- which(res > res[res>0.85], arr.ind = TRUE)
# if there are some compounds from GNPS detected
if (length(res_top) > 0){
res_topdf <- data.frame(res_top)
# to store the scores to add to res_topdf
gnps_scores <- c()
# for all rows and columns in res_topdf
for (i in 1:nrow(res_topdf)){
# store the scores
gnps_scores <- c(gnps_scores, res[(res_topdf[i, "row"]), (res_topdf[i, "col"])])
}
if (length(gnps_scores)>0){
# add the score column to res_top
gnps_res <- cbind(res_top, gnps_scores)
gnps_res <- data.frame(gnps_res)
# sort in descending order
ordered_gnps_res <- gnps_res[order(-gnps_res[,"gnps_scores"]),]
df_ord_gnps_res <- data.frame(ordered_gnps_res)
if (nrow(df_ord_gnps_res)>no_of_candidates){
df_ord_gnps_res <- df_ord_gnps_res[1:no_of_candidates,]
}
#for each candidate from GNPS
for (k in 1:nrow(df_ord_gnps_res)){
# take each component from df_ord_gnps_res
idv <- df_ord_gnps_res[k,]
df_peaklists <- peakdf(gnps_with_mz[idv[[2]]], sps[idv[[1]]], ppmx)
if (!(is.null(df_peaklists))){
GNPSscore <- idv[1, "gnps_scores"]
GNPSmax_similarity <- c(GNPSmax_similarity, GNPSscore)
GNPSmz <- (nrow(df_peaklists)*2)/(nrow(peaksData(gnps_with_mz[idv[[2]]])[[1]])+nrow(peaksData(sps[idv[[1]]])[[1]]))
GNPSmzScore <- c(GNPSmzScore, GNPSmz)
GNPSint <- mean(1-(df_peaklists[,"diff"]/100))
GNPSintScore <- c(GNPSintScore, GNPSint)
GQMatPeaks <- nrow(df_peaklists)
GQMatchingPeaks <- c(GQMatchingPeaks, GQMatPeaks)
GNPSTPeaks <- nrow(peaksData(gnps_with_mz[idv[[2]]])[[1]])
GNPSTotalPeaks <- c(GNPSTotalPeaks, GNPSTPeaks)
gQTPeaks<- nrow(peaksData(sps[idv[[1]]])[[1]])
gQueryTotalPeaks <- c(gQueryTotalPeaks, gQTPeaks)
GNPS_SMILES <- gnps_with_mz[idv[[2]]]$smiles
GNPSSMILES <- c(GNPSSMILES, GNPS_SMILES)
#GNPSID <- gnps_with_mz[idv[[2]]]$SPECTRUMID
#GNPSspectrumID <- c(GNPSspectrumID, GNPSID)
GNPSname <- gnps_with_mz[idv[[2]]]$name
GNPScompound_name <- c(GNPScompound_name, GNPSname)
Src <- "GNPS"
Source <- c(Source, Src)
}# if df_peaklists isnt empty
}# for each candidate
}# gnps_score exists
}# if res_top has some good candidates
}# first condition
# if only one sepctrum from input and more candidates from GNPS
else if (length(sps) == 1 && length(gnps_with_mz) >1){
# given threshold of 0.85 for GNPS, extract top candidates
res_top <- which(res > res[res>0.85], arr.ind = TRUE)
# if there are candidates with good score
if (length(res_top) > 0){
res_topdf <- data.frame(res_top)
# top store the scores to add to res_topdf
gnps_scores <- c()
# for all rows and columns in res_topdf
for (i in 1:nrow(res_topdf)){
# store the scores
gnps_scores <- c(gnps_scores, res[(res_topdf[i, "res_topdf"])])
}
if (length(gnps_scores)>0){
# add the score column to res_top
gnps_res <- cbind(res_top, gnps_scores)
gnps_res <- data.frame(gnps_res)
# sort in descending order
ordered_gnps_res <- gnps_res[order(-gnps_res[,"gnps_scores"]),]
df_ord_gnps_res <- data.frame(ordered_gnps_res)
if (nrow(df_ord_gnps_res)>no_of_candidates){
df_ord_gnps_res <- df_ord_gnps_res[1:no_of_candidates,]
}
# for each candidate
for (k in 1:nrow(df_ord_gnps_res)){
# take each candidate
idv <- df_ord_gnps_res[k,]
df_peaklists <- peakdf(gnps_with_mz[idv[[1]]], sps, ppmx)
# if there are matchingpeaks
if (!(is.null(df_peaklists))){
GNPSscore <- idv[1, "gnps_scores"]
GNPSmax_similarity <- c(GNPSmax_similarity, GNPSscore)
GNPSmz <- (nrow(df_peaklists)*2)/(nrow(peaksData(gnps_with_mz[idv[[1]]])[[1]])+nrow(peaksData(sps)[[1]]))
GNPSmzScore <- c(GNPSmzScore, GNPSmz)
GNPSint <- mean(1-(df_peaklists[,"diff"]/100))
GNPSintScore <- c(GNPSintScore, GNPSint)
GQMatPeaks <- nrow(df_peaklists)
GQMatchingPeaks <- c(GQMatchingPeaks, GQMatPeaks)
GNPSTPeaks <- nrow(peaksData(gnps_with_mz[idv[[1]]])[[1]])
GNPSTotalPeaks <- c(GNPSTotalPeaks, GNPSTPeaks)
gQTPeaks<- nrow(peaksData(sps)[[1]])
gQueryTotalPeaks <- c(gQueryTotalPeaks, gQTPeaks)
GNPS_SMILES <- gnps_with_mz[idv[[1]]]$smiles
GNPSSMILES <- c(GNPSSMILES, GNPS_SMILES)
#GNPSID <- gnps_with_mz[idv[[1]]]$SPECTRUMID
#GNPSspectrumID <- c(GNPSspectrumID, GNPSID)
GNPSname <- gnps_with_mz[idv[[1]]]$name
GNPScompound_name <- c(GNPScompound_name, GNPSname)
Src <- "GNPS"
Source <- c(Source, Src)
}# if df_peaklists isnt empty
}# for each candidate
}# gnps_score exists
}# if res_top has some good candidates
}# second condition
# if there are more input spectra and one candidate from GNPS
else if (length(sps) > 1 && length(gnps_with_mz) == 1){
# given threshold of 0.85 for GNPS, extract top candidates
res_top <- which(res > res[res>0.85], arr.ind = TRUE)
# if there are good matching candidates
if (length(res_top) > 0){
res_topdf <- data.frame(res_top)
# top store the scores to add to res_topdf
gnps_scores <- c()
# for all rows and columns in res_topdf
# for all candidates
for (i in 1:nrow(res_topdf)){
# store the scores
gnps_scores <- c(gnps_scores, res[(res_topdf[i, "res_topdf"])])
}
if (length(gnps_scores)>0){
# add the score column to res_top
gnps_res <- cbind(res_top, gnps_scores)
gnps_res <- data.frame(gnps_res)
# sort in descending order
ordered_gnps_res <- gnps_res[order(-gnps_res[,"gnps_scores"]),]
df_ord_gnps_res <- data.frame(ordered_gnps_res)
if (nrow(df_ord_gnps_res)>no_of_candidates){
df_ord_gnps_res <- df_ord_gnps_res[1:no_of_candidates,]
}
# for each candidate match
for (k in 1:nrow(df_ord_gnps_res)){
# take each candidate
idv <- df_ord_gnps_res[k,]
df_peaklists <- peakdf(gnps_with_mz, sps[idv[[1]]], ppmx)
# if there are matching peaks
if (!(is.null(df_peaklists))){
GNPSscore <- idv[1, "gnps_scores"]
GNPSmax_similarity <- c(GNPSmax_similarity, GNPSscore)
GNPSmz <- (nrow(df_peaklists)*2)/(nrow(peaksData(gnps_with_mz)[[1]])+nrow(peaksData(sps[idv[[1]]])[[1]]))
GNPSmzScore <- c(GNPSmzScore, GNPSmz)
GNPSint <- mean(1-(df_peaklists[,"diff"]/100))
GNPSintScore <- c(GNPSintScore, GNPSint)
GQMatPeaks <- nrow(df_peaklists)
GQMatchingPeaks <- c(GQMatchingPeaks, GQMatPeaks)
GNPSTPeaks <- nrow(peaksData(gnps_with_mz)[[1]])
GNPSTotalPeaks <- c(GNPSTotalPeaks, GNPSTPeaks)
gQTPeaks<- nrow(peaksData(sps[idv[[1]]])[[1]])
gQueryTotalPeaks <- c(gQueryTotalPeaks, gQTPeaks)
GNPS_SMILES <- gnps_with_mz$smiles
GNPSSMILES <- c(GNPSSMILES, GNPS_SMILES)
#GNPSID <- gnps_with_mz$SPECTRUMID
#GNPSspectrumID <- c(GNPSspectrumID, GNPSID)
GNPSname <- gnps_with_mz$name
GNPScompound_name <- c(GNPScompound_name, GNPSname)
Src <- "GNPS"
Source <- c(Source, Src)
}# if df_peaklists isnt empty
}# for each candidate
}# gnps_score exists
}# if res_top has some good candidates
}# third condition
else if (length(sps) == 1 && length(gnps_with_mz) == 1){
if (res>= 0.85){
#take that one candidate
gnps_best_match <- gnps_with_mz
df_peaklists <- peakdf(gnps_best_match, sps, ppmx)
# if there are matching peaks
if (!(is.null(df_peaklists))){
GNPSscore <- max(res)
GNPSmax_similarity <- c(GNPSmax_similarity, GNPSscore)
GNPSmz <- (nrow(df_peaklists)*2)/(nrow(peaksData(gnps_best_match)[[1]])+nrow(peaksData(sps)[[1]]))
GNPSmzScore <- c(GNPSmzScore, GNPSmz)
GNPSint <- mean(1-(df_peaklists[,"diff"]/100))
GNPSintScore <- c(GNPSintScore, GNPSint)
GQMatPeaks <- NA
GQMatchingPeaks <- c(GQMatchingPeaks, GQMatPeaks)
GNPSTPeaks <- nrow(peaksData(gnps_best_match)[[1]])
GNPSTotalPeaks <- c(GNPSTotalPeaks, GNPSTPeaks)
gQTPeaks<- nrow(peaksData(sps)[[1]])
gQueryTotalPeaks <- c(gQueryTotalPeaks, gQTPeaks)
GNPS_SMILES <- gnps_best_match$smiles
GNPSSMILES <- c(GNPSSMILES, GNPS_SMILES)
GNPSname <- gnps_best_match$name
GNPScompound_name <- c(GNPScompound_name, GNPSname)
#GNPSID <- gnps_best_match$SPECTRUMID
#GNPSspectrumID <- c(GNPSspectrumID, GNPSID)
Src <- "GNPS"
Source <- c(Source, Src)
}# if candidate exixts
}# if res_top has some good candidates
}# fourth condition
}# if sps and gnps has some candidate
gnps_x <- data.frame(cbind(GNPSmax_similarity, GNPSmzScore,
GNPSintScore, GQMatchingPeaks,
GNPSTotalPeaks, gQueryTotalPeaks,
GNPSSMILES, GNPScompound_name, Source))
write.csv(gnps_x, file = paste(dir_name, "/gnps_results_for_", id_Xx, ".csv", sep = ""))
})# gnps ends
####-------------------------------------------------------------
#### Dereplication with all or HMDB ----
####-------------------------------------------------------------
# if the database selected is HMDB or all
f_hmdb <- future(
if (db == "all" || db =="hmdb"){
# hmdb
HMDBmax_similarity <- c()
HMDBmzScore <- c()
HMDBintScore <- c()
HQMatchingPeaks <- c()
HMDBTotalPeaks <- c()
hQueryTotalPeaks<- c()
HMDBcompoundID <- c()
Source <- c()
#### HMDB spec with pre_mz
hmdb_with_mz <- spec2_Processing(x, hmdb, spec = "hmdb", ppmx) # change here later
# directory name for HMDB results
dir_name <- paste(input_dir, str_remove(paste(result_dir, "/spectral_dereplication/HMDB/", sep = ""), "."), sep ="")
if (!file.exists(dir_name)){
dir.create(dir_name, recursive = TRUE)
}
if (length(sps) != 0 && length(hmdb_with_mz) !=0){
#' Compare experimental spectra against HMDB
res <- compareSpectra(sps, hmdb_with_mz, ppm = 15)
# if there are more input spectra and more candidates from GNPS
if (length(sps) > 1 && length(hmdb_with_mz) >1){
# given threshold of 0.70 for HMDB, extract top candidates
res_top <- which(res > res[res>0.70], arr.ind = TRUE)
if (length(res_top) > 0){
res_topdf <- data.frame(res_top)
# to store the scores to add to res_topdf
hmdb_scores <- c()
# for all rows and columns in res_topdf
for (i in 1:nrow(res_topdf)){
# store the scores
hmdb_scores <- c(hmdb_scores, res[(res_topdf[i, "row"]), (res_topdf[i, "col"])])
}
if (length(hmdb_scores)>0){
# add the score column to res_top
hmdb_res <- cbind(res_top, hmdb_scores)
hmdb_res <- data.frame(hmdb_res)
# sort in descending order
ordered_hmdb_res <- hmdb_res[order(-hmdb_res[,"hmdb_scores"]),]
df_ord_hmdb_res <- data.frame(ordered_hmdb_res)
if (nrow(df_ord_hmdb_res)>no_of_candidates){
df_ord_hmdb_res <- df_ord_hmdb_res[1:no_of_candidates,]
}
for (k in 1:nrow(df_ord_hmdb_res)){
idv <- df_ord_hmdb_res[k,]
df_peaklists <- peakdf(hmdb_with_mz[idv[[2]]], sps[idv[[1]]], ppmx)
if (!(is.null(df_peaklists))){
HMDBscore <- idv[1, "hmdb_scores"]
HMDBmax_similarity <- c(HMDBmax_similarity, HMDBscore)
HMDBmz <- (nrow(df_peaklists)*2)/(nrow(peaksData(hmdb_with_mz[idv[[2]]])[[1]])+nrow(peaksData(sps[idv[[1]]])[[1]]))
HMDBmzScore <- c(HMDBmzScore, HMDBmz)
HMDBint <- mean(1-(df_peaklists[,"diff"]/100))
HMDBintScore <- c(HMDBintScore, HMDBint)
HQMatPeaks <- nrow(df_peaklists)
HQMatchingPeaks <- c(HQMatchingPeaks, HQMatPeaks)
HMDBTPeaks <- nrow(peaksData(hmdb_with_mz[idv[[2]]])[[1]])
HMDBTotalPeaks <- c(HMDBTotalPeaks, HMDBTPeaks)
hQTPeaks<- nrow(peaksData(sps[idv[[1]]])[[1]])
hQueryTotalPeaks<- c(hQueryTotalPeaks, hQTPeaks)
HMDBID <- hmdb_with_mz[idv[[2]]]$compound_id
HMDBcompoundID <- c(HMDBcompoundID, HMDBID)
Src <- "HMDB"
Source <- c(Source, Src)
}# if df_peaklists is not empty
}# for each candidate
}# if hmdb_scores exist
}# if there are top candidadates with good scores
}#first condition ends
else if (length(sps) == 1 && length(hmdb_with_mz) >1){
# given threshold of 0.70 for HMDB, extract top candidates
res_top <- which(res > res[res>0.70], arr.ind = TRUE)
if (length(res_top) > 0){
res_topdf <- data.frame(res_top)
# top store the scores to add to res_topdf
hmdb_scores <- c()
# for all rows and columns in res_topdf
for (i in 1:nrow(res_topdf)){
# store the scores
hmdb_scores <- c(hmdb_scores, res[(res_topdf[i, "res_topdf"])])
}
if (length(hmdb_scores > 0)){
# add the score column to res_top
hmdb_res <- cbind(res_top, hmdb_scores)
hmdb_res <- data.frame(hmdb_res)
# sort in descending order
ordered_hmdb_res <- hmdb_res[order(-hmdb_res[,"hmdb_scores"]),]
df_ord_hmdb_res <- data.frame(ordered_hmdb_res)
if (nrow(df_ord_hmdb_res)>no_of_candidates){
df_ord_hmdb_res <- df_ord_hmdb_res[1:no_of_candidates,]
}
for (k in 1:nrow(df_ord_hmdb_res)){
idv <- df_ord_hmdb_res[k,]
df_peaklists <- peakdf(hmdb_with_mz[idv[[1]]], sps, ppmx)
if (!(is.null(df_peaklists))){
HMDBscore <- idv[1, "hmdb_scores"]
HMDBmax_similarity <- c(HMDBmax_similarity, HMDBscore)
HMDBmz <- (nrow(df_peaklists)*2)/(nrow(peaksData(hmdb_with_mz[idv[[1]]])[[1]])+nrow(peaksData(sps)[[1]]))
HMDBmzScore <- c(HMDBmzScore, HMDBmz)
HMDBint <- mean(1-(df_peaklists[,"diff"]/100))
HMDBintScore <- c(HMDBintScore, HMDBint)
HQMatPeaks <- nrow(df_peaklists)
HQMatchingPeaks <- c(HQMatchingPeaks, HQMatPeaks)
HMDBTPeaks <- nrow(peaksData(hmdb_with_mz[idv[[1]]])[[1]])
HMDBTotalPeaks <- c(HMDBTotalPeaks, HMDBTPeaks)
hQTPeaks<- nrow(peaksData(sps)[[1]])
hQueryTotalPeaks<- c(hQueryTotalPeaks, hQTPeaks)
HMDBID <- hmdb_with_mz[idv[[1]]]$compound_id
HMDBcompoundID <- c(HMDBcompoundID, HMDBID)
Src <- "HMDB"
Source <- c(Source, Src)
}#df_peaklists is not null
}# for each candidate
}# hmdb_scores exists
}
}# second condition ends
else if (length(sps) > 1 && length(hmdb_with_mz) == 1){
# given threshold of 0.70 for HMDB, extract top candidates
res_top <- which(res > res[res>0.70], arr.ind = TRUE)
if (length(res_top) > 0){
res_topdf <- data.frame(res_top)
# top store the scores to add to res_topdf
hmdb_scores <- c()
# for all rows and columns in res_topdf
for (i in 1:nrow(res_topdf)){
# store the scores
hmdb_scores <- c(hmdb_scores, res[(res_topdf[i, "res_topdf"])])
}
if (length(hmdb_scores)>0){
# add the score column to res_top
hmdb_res <- cbind(res_top, hmdb_scores)
hmdb_res <- data.frame(hmdb_res)
# sort in descending order
ordered_hmdb_res <- hmdb_res[order(-hmdb_res[,"hmdb_scores"]),]
df_ord_hmdb_res <- data.frame(ordered_hmdb_res)
if (nrow(df_ord_hmdb_res)>no_of_candidates){
df_ord_hmdb_res <- df_ord_hmdb_res[1:no_of_candidates,]
}
for (k in 1:nrow(df_ord_hmdb_res)){
idv <- df_ord_hmdb_res[k,]
df_peaklists <- peakdf(hmdb_with_mz, sps[idv[[1]]], ppmx)
if (!(is.null(df_peaklists))){
HMDBscore <- idv[1, "hmdb_scores"]
HMDBmax_similarity <- c(HMDBmax_similarity, HMDBscore)
HMDBmz <- (nrow(df_peaklists)*2)/(nrow(peaksData(hmdb_with_mz)[[1]])+nrow(peaksData(sps[idv[[1]]])[[1]]))
HMDBmzScore <- c(HMDBmzScore, HMDBmz)
HMDBint <- mean(1-(df_peaklists[,"diff"]/100))
HMDBintScore <- c(HMDBintScore, HMDBint)
HQMatPeaks <- nrow(df_peaklists)
HQMatchingPeaks <- c(HQMatchingPeaks, HQMatPeaks)
HMDBTPeaks <- nrow(peaksData(hmdb_with_mz)[[1]])
HMDBTotalPeaks <- c(HMDBTotalPeaks, HMDBTPeaks)
hQTPeaks<- nrow(peaksData(sps[idv[[1]]])[[1]])
hQueryTotalPeaks<- c(hQueryTotalPeaks, hQTPeaks)
HMDBID <- hmdb_with_mz$compound_id