forked from sneumann/RMassBank
-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathcreateMassBank.R
executable file
·1902 lines (1716 loc) · 70.8 KB
/
createMassBank.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
# Script for writing MassBank files
#testtest change
#' Load MassBank compound information lists
#'
#' Loads MassBank compound information lists (i.e. the lists which were created
#' in the first two steps of the MassBank \code{\link{mbWorkflow}} and
#' subsequently edited by hand.).
#'
#' \code{resetInfolists} clears the information lists, i.e. it creates a new
#' empty list in \code{mbdata_archive}. \code{loadInfolist} loads a single CSV
#' file, whereas \code{loadInfolists} loads a whole directory.
#'
#' @aliases loadInfolists loadInfolist resetInfolists
#' @usage loadInfolists(mb, path)
#'
#' loadInfolist(mb, fileName)
#'
#' resetInfolists(mb)
#' @param path Directory in which the namelists reside. All CSV files in this
#' directory will be loaded.
#' @param fileName A single namelist to be loaded.
#' @param mb The \code{mbWorkspace} to load/reset the lists in.
#' @return The new workspace with loaded/reset lists.
#' @author Michael Stravs
#' @examples
#'
#' #
#' \dontrun{mb <- resetInfolists(mb)
#' mb <- loadInfolist(mb, "my_csv_infolist.csv")}
#'
#' @export
loadInfolists <- function(mb, path)
{
archivefiles <- list.files(path, ".csv", full.names=TRUE)
for(afile in archivefiles)
mb <- loadInfolist(mb, afile)
return(mb)
}
# Load an "infolist". This loads a CSV file which should contain the entries
# edited and controlled by hand. All compound infos from fileName are added into the
# global mbdata_archive. Entries with a cpdID which was already present, are substituted
# by new entries from the fileName file.
#' @export
loadInfolist <- function(mb, fileName)
{
# Prime a new infolist if it doesn't exist
if(ncol(mb@mbdata_archive) == 0)
mb <- resetInfolists(mb)
mbdata_new <- read.csv(fileName, sep=",", stringsAsFactors=FALSE)
# Legacy check for loading the Uchem format files.
# Even if dbname_* are not used downstream of here, it's still good to keep them
# for debugging reasons.
n <- colnames(mbdata_new)
cols <- c("id","dbcas","dataused")
# Check if comma-separated or semicolon-separated
d <- setdiff(cols, n)
if(length(d)>0){
mbdata_new <- read.csv2(fileName, stringsAsFactors=FALSE)
n <- colnames(mbdata_new)
d2 <- setdiff(cols, n)
if(length(d2) > 0){
stop("Some columns are missing in the infolist.")
}
}
if("dbname_d" %in% colnames(mbdata_new))
{
colnames(mbdata_new)[[which(colnames(mbdata_new)=="dbname_d")]] <- "dbname"
# dbname_e will be dropped because of the select= in the subset below.
}
if("COMMENT.EAWAG_UCHEM_ID" %in% colnames(mbdata_new))
colnames(mbdata_new)[[which(colnames(mbdata_new)== "COMMENT.EAWAG_UCHEM_ID")]] <-
"COMMENT.ID"
# Clear from padding spaces and NAs
mbdata_new <- as.data.frame(x = t(apply(mbdata_new, 1, function(r)
{
# Substitute empty spaces by real NA values
r[which(r == "")] <- NA
# Trim spaces (in all non-NA fields)
r[which(!is.na(r))] <- sub(pattern = "^ *([^ ]+) *$", replacement = "\\1", x = r[which(!is.na(r))])
return(r)
})), stringsAsFactors = FALSE)
# use only the columns present in mbdata_archive, no other columns added in excel
colNames <- colnames(mb@mbdata_archive)
commentColNames <- colnames(mbdata_new)[grepl(x = colnames(mbdata_new), pattern = "^COMMENT\\.(?!CONFIDENCE)(?!ID)", perl = TRUE)]
colNames <- c(colNames, commentColNames)
## The read infolists might not have all required / expected columns
missingColNames <- colNames[! colNames %in% colnames(mbdata_new)]
if (length(missingColNames >0)) {
missingCols <- matrix(NA, ncol=length(missingColNames))
colnames(missingCols) <- missingColNames
mbdata_new <- cbind(mbdata_new, missingCols)
}
mbdata_new <- mbdata_new[, colNames]
# substitute the old entires with the ones from our files
# then find the new (previously inexistent) entries, and rbind them to the table
new_entries <- setdiff(mbdata_new$id, mb@mbdata_archive$id)
old_entries <- intersect(mbdata_new$id, mb@mbdata_archive$id)
for(colname in colnames(mb@mbdata_archive))
mb@mbdata_archive[, colname] <- as.character(mb@mbdata_archive[, colname])
for(entry in old_entries)
mb@mbdata_archive[mb@mbdata_archive$id == entry,] <- mbdata_new[mbdata_new$id == entry,]
mb@mbdata_archive <- rbind(mb@mbdata_archive, mbdata_new[mbdata_new$id==new_entries,])
for(colname in colnames(mb@mbdata_archive))
mb@mbdata_archive[, colname] <- as.factor(mb@mbdata_archive[, colname])
return(mb)
}
# Resets the mbdata_archive to an empty version.
#' @export
resetInfolists <- function(mb)
{
mb@mbdata_archive <-
structure(list(X = integer(0), id = integer(0), dbcas = character(0),
dbname = character(0), dataused = character(0), COMMENT.CONFIDENCE = character(0),
COMMENT.ID = integer(0), CH.NAME1 = character(0),
CH.NAME2 = character(0), CH.NAME3 = character(0), CH.NAME4 = character(0), CH.NAME5 = character(0), CH.COMPOUND_CLASS = character(0),
CH.FORMULA = character(0), CH.EXACT_MASS = numeric(0), CH.SMILES = character(0),
CH.IUPAC = character(0), CH.LINK.CAS = character(0), CH.LINK.CHEBI = integer(0),
CH.LINK.HMDB = character(0), CH.LINK.KEGG = character(0), CH.LINK.LIPIDMAPS = character(0),
CH.LINK.PUBCHEM = character(0), CH.LINK.INCHIKEY = character(0),
CH.LINK.CHEMSPIDER = integer(0), CH.LINK.COMPTOX = character(0),
AUTHORS = character(0)
), .Names = c("X", "id", "dbcas",
"dbname", "dataused", "COMMENT.CONFIDENCE", "COMMENT.ID",
"CH.NAME1", "CH.NAME2", "CH.NAME3", "CH.NAME4", "CH.NAME5", "CH.COMPOUND_CLASS", "CH.FORMULA",
"CH.EXACT_MASS", "CH.SMILES", "CH.IUPAC", "CH.LINK.CAS", "CH.LINK.CHEBI",
"CH.LINK.HMDB", "CH.LINK.KEGG", "CH.LINK.LIPIDMAPS", "CH.LINK.PUBCHEM",
"CH.LINK.INCHIKEY", "CH.LINK.CHEMSPIDER", "CH.LINK.COMPTOX", "AUTHORS"), row.names = integer(0), class = "data.frame")
if(getOption("RMassBank")$include_sp_tags)
{
mb@mbdata_archive["SP.SAMPLE"] <- character(0)
}
return(mb)
}
# The workflow function, i.e. (almost) the only thing you actually need to call.
# See below for explanation of steps.
#' MassBank record creation workflow
#'
#' Uses data generated by \code{\link{msmsWorkflow}} to create MassBank records.
#'
#' See the vignette \code{vignette("RMassBank")} for detailed informations about the usage.
#'
#' Steps:
#'
#' Step 1: Find which compounds don't have annotation information yet. For these
#' compounds, pull information from several databases (using gatherData).
#'
#' Step 2: If new compounds were found, then export the infolist.csv and stop the workflow.
#' Otherwise, continue.
#'
#' Step 3: Take the archive data (in table format) and reformat it to MassBank tree format.
#'
#' Step 4: Compile the spectra. Using the skeletons from the archive data, create
#' MassBank records per compound and fill them with peak data for each spectrum.
#' Also, assign accession numbers based on scan mode and relative scan no.
#'
#' Step 5: Convert the internal tree-like representation of the MassBank data into
#' flat-text string arrays (basically, into text-file style, but still in memory)
#'
#' Step 6: For all OK records, generate a corresponding molfile with the structure
#' of the compound, based on the SMILES entry from the MassBank record. (This molfile
#' is still in memory only, not yet a physical file)
#'
#' Step 7: If necessary, generate the appropriate subdirectories, and actually write
#' the files to disk.
#'
#' Step 8: Create the list.tsv in the molfiles folder, which is required by MassBank
#' to attribute substances to their corresponding structure molfiles.
#'
#' @param steps Which steps in the workflow to perform.
#' @param infolist_path A path where to store newly downloaded compound informations,
#' which should then be manually inspected.
#' @param mb The \code{mbWorkspace} to work in.
#' @param gatherData A variable denoting whether to retrieve information using several online databases \code{gatherData= "online"}
#' or to use the local babel installation \code{gatherData= "babel"}. Note that babel is used either way, if a directory is given
#' in the settings. This setting will be ignored if retrieval is set to "standard"
#' @param filter If \code{TRUE}, the peaks will be filtered according to the standard processing workflow in RMassBank -
#' only the best formula for a peak is retained, and only peaks passing multiplicity filtering are retained. If FALSE, it is assumed
#' that the user has already done filtering, and all peaks in the spectrum should be printed in the record (with or without formula.)
#' @return The processed \code{mbWorkspace}.
#' @seealso \code{\link{mbWorkspace-class}}
#' @author Michael A. Stravs, Eawag <michael.stravs@@eawag.ch>
#' @examples \dontrun{
#' mb <- newMbWorkspace(w) # w being a msmsWorkspace
#' mb <- loadInfolists(mb, "D:/myInfolistPath")
#' mb <- mbWorkflow(mb, steps=c(1:3), "newinfos.csv")
#'
#' }
#' @export
mbWorkflow <- function(mb, steps=c(1,2,3,4,5,6,7,8), infolist_path="./infolist.csv", gatherData = "online", filter = TRUE)
{
# Step 1: Find which compounds don't have annotation information yet. For these
# compounds, pull information from CTS (using gatherData).
if(1 %in% steps)
{
mbdata_ids <- lapply(selectSpectra(mb@spectra, "found", "object"), function(spec) spec@id)
rmb_log_info("mbWorkflow: Step 1. Gather info from several databases")
# Which IDs are not in mbdata_archive yet?
new_ids <- setdiff(as.numeric(unlist(mbdata_ids)), mb@mbdata_archive$id)
mb@mbdata <- lapply(new_ids, function(id)
{
if(findLevel(id,TRUE) == "standard"){
if(gatherData == "online"){
d <- gatherData(id)
}
if(gatherData == "babel"){
# message("mbWorkflow: Step 1. Gather info using babel")
d <- gatherDataBabel(id)
}
} else{
# message("mbWorkflow: Step 1. Gather no info - Unknown structure")
d <- gatherDataUnknown(id, mb@spectra[[1]]@mode, retrieval=findLevel(id,TRUE))
}
rmb_log_info(paste(id, ": ", d$dataused, sep=''))
return(d)
})
}
# Step 2: If new compounds were found, then export the infolist.csv and stop the workflow.
# Otherwise, continue!
if(2 %in% steps)
{
rmb_log_info("mbWorkflow: Step 2. Export infolist (if required)")
if(length(mb@mbdata)>0)
{
mbdata_mat <- flatten(mb@mbdata)
write.csv(as.data.frame(mbdata_mat),infolist_path, na="")
rmb_log_info(paste("The file", infolist_path, "was generated with new compound information. Please check and edit the table, and add it to your infolist folder."))
return(mb)
}
else
rmb_log_info("No new data added.")
}
# Step 3: Take the archive data (in table format) and reformat it to MassBank tree format.
if(3 %in% steps)
{
rmb_log_info("mbWorkflow: Step 3. Data reformatting")
mb@mbdata_relisted <- apply(mb@mbdata_archive, 1, readMbdata)
}
# Step 4: Compile the spectra! Using the skeletons from the archive data, create
# MassBank records per compound and fill them with peak data for each spectrum.
# Also, assign accession numbers based on scan mode and relative scan no.
if(4 %in% steps)
{
rmb_log_info("mbWorkflow: Step 4. Spectra compilation")
mb@compiled <- lapply(
selectSpectra(mb@spectra, "found", "object"),
function(r) {
# guard against NSE warnings from "filter"
filterOK <- NULL
best <- NULL
rmb_log_info(paste("Compiling: ", r@name, sep=""))
mbdata <- mb@mbdata_relisted[[which(mb@mbdata_archive$id == as.numeric(r@id))]]
if(filter)
res <- buildRecord(r, mbdata=mbdata, additionalPeaks=mb@additionalPeaks, filter = filterOK & best)
else
res <- buildRecord(r, mbdata=mbdata, additionalPeaks=mb@additionalPeaks)
return(res)
})
# check which compounds have useful spectra
mb@ok <- which(!is.na(mb@compiled) & !(lapply(mb@compiled, length)==0))
#mb@ok <- which(!is.na(mb@compiled) & !(lapply(mb@compiled, length)==0))
mb@problems <- which(is.na(mb@compiled))
mb@compiled_ok <- mb@compiled[mb@ok]
mb@compiled_notOk <- mb@compiled[!mb@ok]
}
# Step 5: Convert the internal tree-like representation of the MassBank data into
# flat-text string arrays (basically, into text-file style, but still in memory)
if(5 %in% steps)
{
rmb_log_info("mbWorkflow: [Legacy Step 5. Flattening records] ignored")
#mb@mbfiles <- lapply(mb@compiled_ok, function(cpd) toMassbank(cpd, mb@additionalPeaks))
#mb@mbfiles_notOk <- lapply(mb@compiled_notOk, function(c) lapply(c, toMassbank))
}
# Step 6: For all OK records, generate a corresponding molfile with the structure
# of the compound, based on the SMILES entry from the MassBank record. (This molfile
# is still in memory only, not yet a physical file)
if(6 %in% steps)
{
if(RMassBank.env$export.molfiles){
rmb_log_info("mbWorkflow: Step 6. Generate molfiles")
mb@molfile <- lapply(mb@compiled_ok, function(c) createMolfile(as.numeric(c@id)))
} else
warning("RMassBank is configured not to export molfiles (RMassBank.env$export.molfiles). Step 6 is therefore ignored.")
}
# Step 7: If necessary, generate the appropriate subdirectories, and actually write
# the files to disk.
if(7 %in% steps)
{
rmb_log_info("mbWorkflow: Step 7. Generate subdirs and export")
## create folder
filePath_recData_valid <- file.path(getOption("RMassBank")$annotations$entry_prefix, "recdata")
filePath_recData_invalid <- file.path(getOption("RMassBank")$annotations$entry_prefix, "recdata_invalid")
filePath_molData <- file.path(getOption("RMassBank")$annotations$entry_prefix, "moldata")
if(!file.exists(filePath_recData_valid)) if(!dir.create(filePath_recData_valid,recursive=TRUE)) stop(paste("Could not create folder", filePath_recData_valid))
if(RMassBank.env$export.molfiles)
if(!file.exists(filePath_molData)) if(!dir.create(filePath_molData,recursive=TRUE)) stop(paste("Could not create folder", filePath_molData))
if(RMassBank.env$export.invalid & length(mb@mbfiles_notOk) > 0)
if(!file.exists(filePath_recData_invalid)) if(!dir.create(filePath_recData_invalid,recursive=TRUE)) stop(paste("Could not create folder", filePath_recData_invalid))
if(length(mb@molfile) == 0)
mb@molfile <- as.list(rep(x = NA, times = length(mb@compiled_ok)))
## export valid spectra
for(cnt in seq_along(mb@compiled_ok)){
exportMassbank_recdata(
mb@compiled_ok[[cnt]],
recDataFolder = filePath_recData_valid
)
if(RMassBank.env$export.molfiles)
exportMassbank_moldata(
mb@compiled_ok[[cnt]],
molfile = mb@molfile[[cnt]],
molDataFolder = filePath_molData
)
}
## export invalid spectra
for(cnt in seq_along(mb@compiled_notOk))
exportMassbank_recdata(
compiled = mb@mbfiles_notOk[[cnt]],
recDataFolder = filePath_recData_invalid
)
}
# Step 8: Create the list.tsv in the molfiles folder, which is required by MassBank
# to attribute substances to their corresponding structure molfiles.
if(8 %in% steps)
{
if(RMassBank.env$export.molfiles){
rmb_log_info("mbWorkflow: Step 8. Create list.tsv")
makeMollist(compiled = mb@compiled_ok)
} else
warning("RMassBank is configured not to export molfiles (RMassBank.env$export.molfiles). Step 8 is therefore ignored.")
}
return(mb)
}
# Calls openbabel and converts the SMILES code string (or retrieves the SMILES code from
# the ID, and then calls openbabel) to create a molfile in text format.
# If fileName is given, the file is directly stored. Otherwise, it is returned as a
# character array.
#' Create MOL file for a chemical structure
#'
#' Creates a MOL file (in memory or on disk) for a compound specified by the
#' compound ID or by a SMILES code.
#'
#' The function invokes OpenBabel (and therefore needs a correctly set
#' OpenBabel path in the RMassBank settings), using the SMILES code retrieved
#' with \code{findSmiles} or using the SMILES code directly. The current
#' implementation of the workflow uses the latter version, reading the SMILES
#' code directly from the MassBank record itself.
#'
#' @usage createMolfile(id_or_smiles, fileName = FALSE)
#' @param id_or_smiles The compound ID or a SMILES code.
#' @param fileName If the filename is set, the file is written directly to disk
#' using the specified filename. Otherwise, it is returned as a text array.
#' @return A character array containing the MOL/SDF format file, ready to be
#' written to disk.
#' @author Michael Stravs
#' @seealso \code{\link{findSmiles}}
#' @references OpenBabel: \url{http://openbabel.org}
#' @examples
#'
#' # Benzene:
#' \dontrun{
#' createMolfile("C1=CC=CC=C1")
#' }
#'
#' @export
createMolfile <- function(id_or_smiles, fileName = FALSE)
{
.checkMbSettings()
babeldir <- getOption("RMassBank")$babeldir
if(!is.numeric(id_or_smiles)){
smiles <- id_or_smiles
} else{
if(findLevel(id_or_smiles,TRUE) != "standard"){
return(c(" ","$$$$"))
}
smiles <- findSmiles(id_or_smiles)
}
# if no babeldir was set, get the result from cactus.
if(is.na(babeldir))
{
res <- getCactus(smiles, "sdf")
if(any(is.na(res))){
res <- getPcSDF(smiles)
}
if(any(is.na(res))){
stop("Pubchem and Cactus both seem to be down.")
}
if(is.character(fileName))
writeLines(res, fileName)
}
# otherwise use the better-tested OpenBabel toolkit.
else
{
if(!is.character(fileName))
cmd <- paste(babeldir, "obabel -ismi -osdf -d -b --gen2D", sep='')
else
cmd <- paste(babeldir, "obabel -ismi -osdf ", fileName , " -d -b --gen2D", sep='')
res <- system(cmd, intern=TRUE, input=smiles, ignore.stderr=TRUE)
# If we wrote to a file, read it back as return value.
if(is.character(fileName))
res <- readLines(fileName)
}
#return(c(" ","$$$$"))
return(res)
}
# Retrieve annotation data for a compound, from the internet service Pubchem
#' Retrieve supplemental annotation data from Pubchem
#'
#' Retrieves annotation data for a compound from the internet service Pubchem
#' based on the inchikey generated by babel or Cactus
#'
#' The data retrieved is the Pubchem CID, a synonym from the Pubchem database,
#' the IUPAC name (using the preferred if available) and a Chebi link
#'
#' @usage gatherPubChem(key)
#' @param key An Inchi-Key
#' @return Returns a list with 4 slots:
#' \code{PcID} The Pubchem CID
#' \code{Synonym} An arbitrary synonym for the compound name
#' \code{IUPAC} A IUPAC-name (preferred if available)
#' \code{Chebi} The identification number of the chebi database
#' @author Erik Mueller
#' @seealso \code{\link{mbWorkflow}}
#' @references Pubchem REST:
#' \url{https://pubchem.ncbi.nlm.nih.gov/pug_rest/PUG_REST.html}
#' Chebi:
#' \url{http://www.ebi.ac.uk/chebi}
#' @examples
#'
#' # Gather data for compound ID 131
#' \dontrun{gatherPubChem("QEIXBXXKTUNWDK-UHFFFAOYSA-N")}
#'
#' @export
gatherPubChem <- function(key){
PubChemData <- list()
##Trycatches are there because pubchem has connection issues 1 in 50 times.
##Write NA into the respective fields if something goes wrong with the conenction or the data.
##Retrieve Pubchem CID
tryCatch(
PubChemData$PcID <- getPcId(key),
error=function(e){
PubChemData$PcID <<- NA
})
##Retrieve a synonym to the name
tryCatch(
PubChemData$Synonym <- getPcSynonym(key),
error=function(e){
PubChemData$Synonym <<- NA
})
##Retrieve the IUPAC-name
tryCatch(
PubChemData$IUPAC <- getPcIUPAC(key),
error=function(e){
PubChemData$IUPAC <<- NA
})
##Retrieve the Chebi-ID
tryCatch(
PubChemData$Chebi <- getPcCHEBI(key),
error=function(e){
PubChemData$Chebi <<- NA
})
return(PubChemData)
}
# Retrieve annotation data for a compound, from the internet services Cactvs, Pubchem, Chemspider and CTS.
#' Retrieve annotation data
#'
#' Retrieves annotation data for a compound from the internet services CTS, Pubchem, Chemspider and
#' Cactvs, based on the SMILES code and name of the compounds stored in the
#' compound list.
#'
#' Composes the "upper part" of a MassBank record filled with chemical data
#' about the compound: name, exact mass, structure, CAS no., links to PubChem,
#' KEGG, ChemSpider. The instrument type is also written into this block (even
#' if not strictly part of the chemical information). Additionally, index
#' fields are added at the start of the record, which will be removed later:
#' \code{id, dbcas, dbname} from the compound list, \code{dataused} to indicate
#' the used identifier for CTS search (\code{smiles} or \code{dbname}).
#'
#' Additionally, the fields \code{ACCESSION} and \code{RECORD_TITLE} are
#' inserted empty and will be filled later on.
#'
#' @usage gatherData(id)
#' @aliases gatherData
#' @param id The compound ID.
#' @return Returns a list of type \code{list(id= \var{compoundID}, ...,
#' 'ACCESSION' = '', 'RECORD_TITLE' = '', )} etc. %% ...
#' @author Michael Stravs
#' @seealso \code{\link{mbWorkflow}}
#' @references Chemical Translation Service:
#' \url{http://uranus.fiehnlab.ucdavis.edu:8080/cts/homePage}
#' cactus Chemical Identifier Resolver:
#' \url{http://cactus.nci.nih.gov/chemical/structure}
#' MassBank record format:
#' \url{http://www.massbank.jp/manuals/MassBankRecord_en.pdf}
#' Pubchem REST:
#' \url{https://pubchem.ncbi.nlm.nih.gov/pug_rest/PUG_REST.html}
#' Chemspider InChI conversion:
#' \url{https://www.chemspider.com/InChI.asmx}
#' @examples
#'
#' # Gather data for compound ID 131
#' \dontrun{gatherData(131)}
#'
#' @export
gatherData <- function(id)
{
##Preamble: Is a babeldir supplied?
##If yes, use it
.checkMbSettings()
usebabel=TRUE
babeldir <- getOption("RMassBank")$babeldir
if(is.na(babeldir)){
usebabel=FALSE
}
##Get all useful information from the local "database" (from the CSV sheet)
smiles <- findSmiles(id)
mass <- findMass(smiles)
dbcas <- findCAS(id)
dbname <- findName(id)
if(is.na(dbname)) dbname <- ""
if(is.na(dbcas)) dbcas <- ""
iupacName <- dbname
synonym <- dbname
formula <- findFormula(id)
##Convert SMILES to InChI key via Cactvs or babel. CTS doesn't "interpret" the SMILES per se,
##it just matches identical known SMILES, so we need to convert to a "searchable" and
##standardized format beforehand. Other databases are able to interpret the smiles.
if(usebabel){
cmdinchikey <- paste0(babeldir, 'obabel -:"',smiles,'" ', '-oinchikey')
inchikey_split <- system(cmdinchikey, intern=TRUE, input=smiles, ignore.stderr=TRUE)
} else{
inchikey <- getCactus(smiles, 'stdinchikey')
if(!is.na(inchikey)){
##Split the "InChiKey=" part off the key
inchikey_split <- strsplit(inchikey, "=", fixed=TRUE)[[1]][[2]]
} else{
inchikey_split <- getPcInchiKey(smiles)
}
}
##Use Pubchem to retrieve information
PcInfo <- gatherPubChem(inchikey_split)
if(!is.null(PcInfo$Synonym) & !is.na(PcInfo$Synonym)){
synonym <- PcInfo$Synonym
}
if(!is.null(PcInfo$IUPAC) & !is.na(PcInfo$IUPAC)){
iupacName <- PcInfo$IUPAC
}
##Get Chemspider-ID
csid <- getCSID(inchikey_split)
if(is.na(csid)){
##Get ChemSpider ID from Cactus if the Chemspider page is down
csid <- getCactus(inchikey_split, 'chemspider_id')
}
## ##Get CompTox
## comptox <- getCompTox(inchikey_split)
## if(is.null(comptox)){
comptox <- NA
## }
##Use CTS to retrieve information
CTSinfo <- getCtsRecord(inchikey_split)
if((CTSinfo[1] == "Sorry, we couldn't find any matching results") || is.null(CTSinfo[1]))
{
CTSinfo <- NA
}
##List the names
if(iupacName == ""){
warning(paste0("Compound ID ",id,": no IUPAC name could be identified."))
}
if(toupper(dbname) == toupper(synonym)){
synonym <- dbname
}
if(toupper(dbname) == toupper(iupacName)){
iupacName <- dbname
}
if(toupper(synonym) == toupper(iupacName)){
synonym <- iupacName
}
names <- as.list(unique(c(dbname, synonym, iupacName)))
##If no name is found, it must be supplied in one way or another
if(all(sapply(names, function(x) x == ""))){
stop("RMassBank wasn't able to extract a usable name for this compound from any database. Please supply a name manually.")
}
# Start to fill the MassBank record.
# The top 4 entries will not go into the final record; they are used to identify
# the record and also to facilitate manual editing of the exported record table.
mbdata <- list()
mbdata[['id']] <- id
mbdata[['dbcas']] <- dbcas
mbdata[['dbname']] <- dbname
mbdata[['dataused']] <- "smiles"
mbdata[['ACCESSION']] <- ""
mbdata[['RECORD_TITLE']] <- ""
mbdata[['DATE']] <- format(Sys.Date(), "%Y.%m.%d")
mbdata[['AUTHORS']] <- getOption("RMassBank")$annotations$authors
mbdata[['LICENSE']] <- getOption("RMassBank")$annotations$license
mbdata[['COPYRIGHT']] <- getOption("RMassBank")$annotations$copyright
# Confidence annotation and internal ID annotation.
# The ID of the compound will be written like:
# COMMENT: EAWAG_UCHEM_ID 1234
# if annotations$internal_id_fieldname is set to "EAWAG_UCHEM_ID"
mbdata[["COMMENT"]] <- list()
if(findLevel(id) == "0"){
mbdata[["COMMENT"]][["CONFIDENCE"]] <- getOption("RMassBank")$annotations$confidence_comment
} else{
level <- findLevel(id)
if(level %in% c("1","1a")){
mbdata[["COMMENT"]][["CONFIDENCE"]] <- "Reference Standard (Level 1)"
}
if(level == c("2")){
mbdata[["COMMENT"]][["CONFIDENCE"]] <- "Probable structure, tentative identification (Level 2)"
}
if(level == c("2a")){
mbdata[["COMMENT"]][["CONFIDENCE"]] <- "Probable structure via library match, tentative identification (Level 2a)"
}
if(level == c("2b")){
mbdata[["COMMENT"]][["CONFIDENCE"]] <- "Probable structure via diagnostic evidence, tentative identification (Level 2b)"
}
if(level == c("3")){
mbdata[["COMMENT"]][["CONFIDENCE"]] <- "Tentative identification only (Level 3)"
}
if(level == c("3a")){
mbdata[["COMMENT"]][["CONFIDENCE"]] <- "Tentative identification: most likely structure (Level 3)"
}
if(level == c("3b")){
mbdata[["COMMENT"]][["CONFIDENCE"]] <- "Tentative identification: isomers possible (Level 3)"
}
if(level == c("3c")){
mbdata[["COMMENT"]][["CONFIDENCE"]] <- "Tentative identification: substance class known (Level 3)"
}
if(level == c("3d")){
mbdata[["COMMENT"]][["CONFIDENCE"]] <- "Tentative identification: best match only (Level 3)"
}
if(level == c("4")){
mbdata[["COMMENT"]][["CONFIDENCE"]] <- "Tentative identification: molecular formula only (Level 4)"
}
if(level == c("5")){
mbdata[["COMMENT"]][["CONFIDENCE"]] <- "Tentative identification: structure and formula unknown (Level 5)"
}
}
mbdata[["COMMENT"]][["ID"]] = id
## add generic COMMENT information
rowIdx <- which(.listEnvEnv$listEnv$compoundList$ID == id)
properties <- colnames(.listEnvEnv$listEnv$compoundList)
properties2 <- gsub(x = properties, pattern = "^COMMENT ", replacement = "")
theseProperties <- grepl(x = properties, pattern = "^COMMENT ")
theseProperties <- theseProperties & (!(unlist(.listEnvEnv$listEnv$compoundList[rowIdx, ]) == "NA" | is.na(unlist(.listEnvEnv$listEnv$compoundList[rowIdx, ]))))
mbdata[["COMMENT"]][properties2[theseProperties]] <- unlist(.listEnvEnv$listEnv$compoundList[rowIdx, theseProperties])
# here compound info starts
mbdata[['CH$NAME']] <- names
# Currently we use a fixed value for Compound Class, since there is no useful
# convention of what should go there and what shouldn't, and the field is not used
# in search queries.
mbdata[['CH$COMPOUND_CLASS']] <- getOption("RMassBank")$annotations$compound_class
mbdata[['CH$FORMULA']] <- formula
mbdata[['CH$EXACT_MASS']] <- mass
mbdata[['CH$SMILES']] <- smiles
if(usebabel){
cmdinchi <- paste0(babeldir, 'obabel -:"',smiles,'" ', '-oinchi')
mbdata[['CH$IUPAC']] <- system(cmdinchi, intern=TRUE, input=smiles, ignore.stderr=TRUE)
} else{
mbdata[['CH$IUPAC']] <- getCactus(smiles, "stdinchi")
}
# Add all CH$LINK fields present in the compound datasets
link <- list()
# CAS
if(!is.na(CTSinfo[1])){
if("CAS" %in% CTS.externalIdTypes(CTSinfo))
{
# Prefer database CAS if it is also listed in the CTS results.
# otherwise take the shortest one.
cas <- CTS.externalIdSubset(CTSinfo,"CAS")
if(dbcas %in% cas)
link[["CAS"]] <- dbcas
else
link[["CAS"]] <- cas[[which.min(nchar(cas))]]
} else{
if(dbcas != ""){
link[["CAS"]] <- dbcas
}
}
} else{
if(dbcas != ""){
link[["CAS"]] <- dbcas
}
}
# CHEBI
if(is.na(PcInfo$Chebi[1])){
if(!is.na(CTSinfo[1])){
if("ChEBI" %in% CTS.externalIdTypes(CTSinfo))
{
# Cut off front "CHEBI:" if present
chebi <- CTS.externalIdSubset(CTSinfo,"ChEBI")
chebi <- chebi[[which.min(nchar(chebi))]]
chebi <- strsplit(chebi,":")[[1]]
link[["CHEBI"]] <- chebi[[length(chebi)]]
}
}
} else{
chebi <- PcInfo$Chebi
chebi <- chebi[[which.min(nchar(chebi))]]
chebi <- strsplit(chebi,":")[[1]]
link[["CHEBI"]] <- chebi[[length(chebi)]]
}
# HMDB
if(!is.na(CTSinfo[1])){
if("Human Metabolome Database" %in% CTS.externalIdTypes(CTSinfo))
link[["HMDB"]] <- CTS.externalIdSubset(CTSinfo,"HMDB")[[1]]
# KEGG
if("KEGG" %in% CTS.externalIdTypes(CTSinfo))
link[["KEGG"]] <- CTS.externalIdSubset(CTSinfo,"KEGG")[[1]]
# LipidMAPS
if("LipidMAPS" %in% CTS.externalIdTypes(CTSinfo))
link[["LIPIDMAPS"]] <- CTS.externalIdSubset(CTSinfo,"LipidMAPS")[[1]]
}
# PubChem CID
if(is.na(PcInfo$PcID[1])){
if(!is.na(CTSinfo[1])){
if("PubChem CID" %in% CTS.externalIdTypes(CTSinfo))
{
pc <- CTS.externalIdSubset(CTSinfo,"PubChem CID")
link[["PUBCHEM"]] <- paste0(min(pc))
}
}
} else{
link[["PUBCHEM"]] <- PcInfo$PcID[1]
}
if(!is.null(link[["PUBCHEM"]])){
if(substr(link[["PUBCHEM"]],1,4) != "CID:"){
link[["PUBCHEM"]] <- paste0("CID:", link[["PUBCHEM"]])
}
}
link[["INCHIKEY"]] <- inchikey_split
link[["COMPTOX"]] <- comptox
if(length(csid)>0) if(any(!is.na(csid))) link[["CHEMSPIDER"]] <- min(as.numeric(as.character(csid[!is.na(csid)])))
mbdata[['CH$LINK']] <- link
return(mbdata)
}
# Retrieve annotation data for a compound, using only babel
#' Retrieve annotation data
#'
#' Retrieves annotation data for a compound by using babel,
#' based on the SMILES code and name of the compounds stored in the
#' compound list.
#'
#' Composes the "upper part" of a MassBank record filled with chemical data
#' about the compound: name, exact mass, structure, CAS no..
#' The instrument type is also written into this block (even
#' if not strictly part of the chemical information). Additionally, index
#' fields are added at the start of the record, which will be removed later:
#' \code{id, dbcas, dbname} from the compound list.
#'
#' Additionally, the fields \code{ACCESSION} and \code{RECORD_TITLE} are
#' inserted empty and will be filled later on.
#'
#' This function is an alternative to gatherData, in case CTS is down or if information
#' on one or more of the compounds in the compound list are sparse
#'
#' @usage gatherDataBabel(id)
#' @param id The compound ID.
#' @return Returns a list of type \code{list(id= \var{compoundID}, ...,
#' 'ACCESSION' = '', 'RECORD_TITLE' = '', )} etc. %% ...
#' @author Michael Stravs, Erik Mueller
#' @seealso \code{\link{mbWorkflow}}
#' @references MassBank record format:
#' \url{http://www.massbank.jp/manuals/MassBankRecord_en.pdf}
#' @examples
#'
#' # Gather data for compound ID 131
#' \dontrun{gatherDataBabel(131)}
#'
#' @export
gatherDataBabel <- function(id){
.checkMbSettings()
babeldir <- getOption("RMassBank")$babeldir
smiles <- findSmiles(id)
# if no babeldir was set, throw an error that says that either CTS or babel have to be used
if(is.na(babeldir))
{
stop("No babeldir supplied; It is currently not possible to convert the information without either babel or CTS")
} else {
###Babel conversion
cmdinchikey <- paste0(babeldir, 'obabel -:"',smiles,'" ', '-oinchikey')
inchikey <- system(cmdinchikey, intern=TRUE, input=smiles, ignore.stderr=TRUE)
cmdinchi <- paste0(babeldir, 'obabel -:"',smiles,'" ', '-oinchi')
inchi <- system(cmdinchi, intern=TRUE, input=smiles, ignore.stderr=TRUE)
##Read from Compoundlist
smiles <- findSmiles(id)
mass <- findMass(smiles)
dbcas <- findCAS(id)
dbname <- findName(id)
if(is.na(dbname)) dbname <- ""
if(is.na(dbcas)) dbcas <- ""
formula <- findFormula(id)
##Create
mbdata <- list()
mbdata[['id']] <- id
mbdata[['dbcas']] <- dbcas
mbdata[['dbname']] <- dbname
mbdata[['dataused']] <- "smiles"
mbdata[['ACCESSION']] <- ""
mbdata[['RECORD_TITLE']] <- ""
mbdata[['DATE']] <- format(Sys.Date(), "%Y.%m.%d")
mbdata[['AUTHORS']] <- getOption("RMassBank")$annotations$authors
mbdata[['LICENSE']] <- getOption("RMassBank")$annotations$license
mbdata[['COPYRIGHT']] <- getOption("RMassBank")$annotations$copyright
# Confidence annotation and internal ID annotation.
# The ID of the compound will be written like:
# COMMENT: EAWAG_UCHEM_ID 1234
# if annotations$internal_id_fieldname is set to "EAWAG_UCHEM_ID"
mbdata[["COMMENT"]] <- list()
if(findLevel(id) == "0"){
mbdata[["COMMENT"]][["CONFIDENCE"]] <- getOption("RMassBank")$annotations$confidence_comment
} else{
level <- findLevel(id)
if(level %in% c("1","1a")){
mbdata[["COMMENT"]][["CONFIDENCE"]] <- "Reference Standard (Level 1)"
}
if(level == c("2")){
mbdata[["COMMENT"]][["CONFIDENCE"]] <- "Probable structure, tentative identification (Level 2)"
}
if(level == c("2a")){
mbdata[["COMMENT"]][["CONFIDENCE"]] <- "Probable structure via library match, tentative identification (Level 2a)"
}
if(level == c("2b")){
mbdata[["COMMENT"]][["CONFIDENCE"]] <- "Probable structure via diagnostic evidence, tentative identification (Level 2b)"
}
if(level == c("3")){
mbdata[["COMMENT"]][["CONFIDENCE"]] <- "Tentative identification only (Level 3)"
}
if(level == c("3a")){
mbdata[["COMMENT"]][["CONFIDENCE"]] <- "Tentative identification: most likely structure (Level 3)"
}
if(level == c("3b")){
mbdata[["COMMENT"]][["CONFIDENCE"]] <- "Tentative identification: isomers possible (Level 3)"
}
if(level == c("3c")){
mbdata[["COMMENT"]][["CONFIDENCE"]] <- "Tentative identification: substance class known (Level 3)"
}
if(level == c("3d")){
mbdata[["COMMENT"]][["CONFIDENCE"]] <- "Tentative identification: best match only (Level 3)"
}
if(level == c("4")){
mbdata[["COMMENT"]][["CONFIDENCE"]] <- "Tentative identification: molecular formula only (Level 4)"
}
if(level == c("5")){
mbdata[["COMMENT"]][["CONFIDENCE"]] <- "Tentative identification: structure and formula unknown (Level 5)"
}
}
mbdata[["COMMENT"]][["ID"]] <- id
# here compound info starts
mbdata[['CH$NAME']] <- as.list(dbname)
# Currently we use a fixed value for Compound Class, since there is no useful
# convention of what should go there and what shouldn't, and the field is not used
# in search queries.
mbdata[['CH$COMPOUND_CLASS']] <- getOption("RMassBank")$annotations$compound_class
mbdata[['CH$FORMULA']] <- formula
mbdata[['CH$EXACT_MASS']] <- mass
mbdata[['CH$SMILES']] <- smiles
mbdata[['CH$IUPAC']] <- inchi
link <- list()
if(dbcas != "")
link[["CAS"]] <- dbcas
link[["INCHIKEY"]] <- inchikey
mbdata[['CH$LINK']] <- link
}
return(mbdata)
}
# Retrieve annotation data for a compound, using only babel
#' Retrieve annotation data
#'
#' Retrieves annotation data for an unknown compound by using basic information present
#'
#' Composes the "upper part" of a MassBank record filled with chemical data
#' about the compound: name, exact mass, structure, CAS no..
#' The instrument type is also written into this block (even
#' if not strictly part of the chemical information). Additionally, index
#' fields are added at the start of the record, which will be removed later:
#' \code{id, dbcas, dbname} from the compound list.
#'
#' Additionally, the fields \code{ACCESSION} and \code{RECORD_TITLE} are
#' inserted empty and will be filled later on.
#'
#' This function is used to generate the data in case a substance is unknown,
#' i.e. not enough information is present to derive anything about formulas or links
#'
#' @usage gatherDataUnknown(id, mode, retrieval)
#' @param id The compound ID.
#' @param mode \code{"pH", "pNa", "pM", "pNH4", "mH", "mM", "mFA"} for different ions
#' ([M+H]+, [M+Na]+, [M]+, [M+NH4]+, [M-H]-, [M]-, [M+FA]-).
#' @param retrieval A value that determines whether the files should be handled either as "standard",
#' if the compoundlist is complete, "tentative", if at least a formula is present or "unknown"
#' if the only know thing is the m/z
#' @return Returns a list of type \code{list(id= \var{compoundID}, ...,
#' 'ACCESSION' = '', 'RECORD_TITLE' = '', )} etc. %% ...
#' @author Michael Stravs, Erik Mueller
#' @seealso \code{\link{mbWorkflow}}
#' @references MassBank record format:
#' \url{http://www.massbank.jp/manuals/MassBankRecord_en.pdf}
#' @examples
#'
#' # Gather data for compound ID 131
#' \dontrun{gatherDataUnknown(131,"pH")}
#'
#' @export
gatherDataUnknown <- function(id, mode, retrieval){
.checkMbSettings()
##Read from Compoundlist
smiles <- ""
if(retrieval == "unknown"){
mass <- findMass(id, "unknown", mode)
formula <- ""
}
if(retrieval == "tentative"){
mass <- findMass(id, "tentative", mode)
formula <- findFormula(id, "tentative")
}
dbcas <- NA
dbname <- findName(id)
if(is.na(dbname)) dbname <- paste("Unknown ID:",id)
if(is.na(dbcas)) dbcas <- ""