/
methods-xcmsRaw.R
executable file
·2327 lines (2103 loc) · 97.9 KB
/
methods-xcmsRaw.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
## All Methods for xcmsRaw should be here.
#' @include functions-xcmsRaw.R functions-utils.R
############################################################
## show
setMethod("show", "xcmsRaw", function(object) {
cat("An \"xcmsRaw\" object with", length(object@scantime),
"mass spectra\n\n")
if (length(object@scantime)>0) {
cat("Time range: ", paste(round(range(object@scantime), 1),
collapse = "-"),
" seconds (", paste(round(range(object@scantime)/60, 1),
collapse = "-"),
" minutes)\n", sep = "")
cat("Mass range:", paste(round(range(object@env$mz), 4),
collapse = "-"), "m/z\n")
cat("Intensity range:", paste(signif(range(object@env$intensity), 6),
collapse = "-"), "\n\n")
}
## summary MSn data
if (!is.null(object@msnLevel)) {
cat("MSn data on ", length(unique(object@msnPrecursorMz)), " mass(es)\n")
cat("\twith ", length(object@msnPrecursorMz)," MSn spectra\n")
}
cat("Profile method:", object@profmethod, "\n")
cat("Profile step: ")
if (is.null(object@env$profile))
cat("no profile data\n")
else {
profmz <- profMz(object)
cat(profStep(object), " m/z (", length(profmz), " grid points from ",
paste(object@mzrange, collapse = " to "), " m/z)\n", sep = "")
}
if (length(object@profparam)) {
cat("Profile parameters: ")
for (i in seq(along = object@profparam)) {
if (i != 1) cat(" ")
cat(names(object@profparam)[i], " = ", object@profparam[[i]], "\n",
sep = "")
}
}
memsize <- object.size(object)
for (key in ls(object@env))
memsize <- memsize + object.size(object@env[[key]])
cat("\nMemory usage:", signif(memsize/2^20, 3), "MB\n")
})
############################################################
## sortMz
setMethod("revMz", "xcmsRaw", function(object) {
for (i in 1:length(object@scanindex)) {
idx <- (object@scanindex[i]+1):min(object@scanindex[i+1],
length(object@env$mz), na.rm=TRUE)
object@env$mz[idx] <- rev(object@env$mz[idx])
object@env$intensity[idx] <- rev(object@env$intensity[idx])
}
})
############################################################
## sortMz
setMethod("sortMz", "xcmsRaw", function(object) {
for (i in 1:length(object@scanindex)) {
idx <- (object@scanindex[i]+1):min(object@scanindex[i+1],
length(object@env$mz), na.rm=TRUE)
ord <- order(object@env$mz[idx])
object@env$mz[idx] <- object@env$mz[idx[ord]]
object@env$intensity[idx] <- object@env$intensity[idx[ord]]
}
})
############################################################
## plotTIC
setMethod("plotTIC", "xcmsRaw", function(object, ident = FALSE, msident = FALSE) {
if (all(object@tic == 0))
points <- cbind(object@scantime, rawEIC(object,mzrange=range(object@env$mz))$intensity) else
points <- cbind(object@scantime, object@tic)
plot(points, type="l", main="TIC Chromatogram", xlab="Seconds",
ylab="Intensity")
if (ident) {
idx <- integer(0)
ticdev <- dev.cur()
if ((dev.cur()+1) %in% dev.list())
msdev <- dev.cur()+1
else
msdev <- integer(0)
while(length(id <- identify(points, labels = round(points[,1], 1), n = 1))) {
idx <- c(idx, id)
if (!length(msdev)) {
options("device")$device()
msdev <- dev.cur()
}
dev.set(msdev)
plotScan(object, id, ident = msident)
dev.set(ticdev)
}
return(idx)
}
invisible(points)
})
############################################################
## getScan
setMethod("getScan", "xcmsRaw", function(object, scan, mzrange = numeric()) {
if (scan < 0)
scan <- length(object@scantime) + 1 + scan
idx <- seq(object@scanindex[scan]+1, min(object@scanindex[scan+1],
length(object@env$mz), na.rm=TRUE))
if (length(mzrange) >= 2) {
mzrange <- range(mzrange)
idx <- idx[object@env$mz[idx] >= mzrange[1] & object@env$mz[idx] <= mzrange[2]]
}
points <- cbind(mz = object@env$mz[idx], intensity = object@env$intensity[idx])
invisible(points)
})
############################################################
## getSpec
setMethod("getSpec", "xcmsRaw", function(object, ...) {
## FIXME: unnecessary dependency on profile matrix?
sel <- profRange(object, ...)
scans <- list(length(sel$scanidx))
uniquemz <- numeric()
for (i in seq(along = sel$scanidx)) {
scans[[i]] <- getScan(object, sel$scanidx[i], sel$mzrange)
uniquemz <- unique(c(uniquemz, scans[[i]][,"mz"]))
}
uniquemz <- sort(uniquemz)
intmat <- matrix(nrow = length(uniquemz), ncol = length(sel$scanidx))
for (i in seq(along = sel$scanidx)) {
scan <- getScan(object, sel$scanidx[i], sel$mzrange)
intmat[,i] <- approx(scan, xout = uniquemz)$y
}
points <- cbind(mz = uniquemz, intensity = rowMeans(intmat))
invisible(points)
})
############################################################
## findPeaks.matchedFilter_orig
## We're keeping this one only for comparison in unit tests; this
## should be removed soon!
setGeneric("findPeaks.matchedFilter_orig", function(object, ...)
standardGeneric("findPeaks.matchedFilter_orig"))
setMethod("findPeaks.matchedFilter_orig", "xcmsRaw",
function(object, fwhm = 30, sigma = fwhm/2.3548, max = 5,
snthresh = 10, step = 0.1, steps = 2,
mzdiff = 0.8 - step*steps, index = FALSE, sleep = 0,
scanrange= numeric()) {
profFun <- match.profFun(object)
scanrange.old <- scanrange
## sanitize if too few or too many scanrange is given
if (length(scanrange) < 2)
scanrange <- c(1, length(object@scantime))
else
scanrange <- range(scanrange)
## restrict and sanitize scanrange to maximally cover all scans
scanrange[1] <- max(1,scanrange[1])
scanrange[2] <- min(length(object@scantime),scanrange[2])
## Mild warning if the actual scanrange doesn't match the scanrange argument
if (!(identical(scanrange.old,scanrange)) && (length(scanrange.old) >0)) {
cat("Warning: scanrange was adjusted to ",scanrange,"\n")
## Scanrange filtering
keepidx <- seq.int(1, length(object@scantime)) %in% seq.int(scanrange[1], scanrange[2])
object <- split(object, f=keepidx)[["TRUE"]]
}
### Create EIC buffer
mrange <- range(object@env$mz)
mass <- seq(floor(mrange[1]/step)*step, ceiling(mrange[2]/step)*step, by = step)
bufsize <- min(100, length(mass))
buf <- profFun(object@env$mz, object@env$intensity, object@scanindex,
bufsize, mass[1], mass[bufsize], TRUE, object@profparam)
bufMax <- profMaxIdxM(object@env$mz, object@env$intensity, object@scanindex,
bufsize, mass[1], mass[bufsize], TRUE,
object@profparam)
bufidx <- integer(length(mass))
idxrange <- c(1, bufsize)
bufidx[idxrange[1]:idxrange[2]] <- 1:bufsize
lookahead <- steps-1
lookbehind <- 1
scantime <- object@scantime
N <- nextn(length(scantime))
xrange <- range(scantime)
x <- c(0:(N/2), -(ceiling(N/2-1)):-1)*(xrange[2]-xrange[1])/(length(scantime)-1)
filt <- -attr(eval(deriv3(~ 1/(sigma*sqrt(2*pi))*exp(-x^2/(2*sigma^2)), "x")), "hessian")
filt <- filt/sqrt(sum(filt^2))
filt <- fft(filt, inverse = TRUE)/length(filt)
cnames <- c("mz", "mzmin", "mzmax", "rt", "rtmin", "rtmax", "into", "intf", "maxo", "maxf", "i", "sn")
rmat <- matrix(nrow = 2048, ncol = length(cnames))
num <- 0
for (i in seq(length = length(mass)-steps+1)) {
if (i %% 500 == 0) {
cat(round(mass[i]), ":", num, " ", sep = "")
flush.console()
}
### Update EIC buffer if necessary
if (bufidx[i+lookahead] == 0) {
bufidx[idxrange[1]:idxrange[2]] <- 0
idxrange <- c(max(1, i - lookbehind), min(bufsize+i-1-lookbehind, length(mass)))
bufidx[idxrange[1]:idxrange[2]] <- 1:(diff(idxrange)+1)
buf <- profFun(object@env$mz, object@env$intensity, object@scanindex,
diff(idxrange)+1, mass[idxrange[1]], mass[idxrange[2]],
TRUE, object@profparam)
bufMax <- profMaxIdxM(object@env$mz, object@env$intensity, object@scanindex,
diff(idxrange)+1, mass[idxrange[1]], mass[idxrange[2]],
TRUE, object@profparam)
}
ymat <- buf[bufidx[i:(i+steps-1)],,drop=FALSE]
ysums <- colMax(ymat)
yfilt <- filtfft(ysums, filt)
gmax <- max(yfilt)
for (j in seq(length = max)) {
maxy <- which.max(yfilt)
noise <- mean(ysums[ysums > 0])
##noise <- mean(yfilt[yfilt >= 0])
sn <- yfilt[maxy]/noise
if (yfilt[maxy] > 0 && yfilt[maxy] > snthresh*noise && ysums[maxy] > 0) {
peakrange <- descendZero(yfilt, maxy)
intmat <- ymat[,peakrange[1]:peakrange[2],drop=FALSE]
mzmat <- matrix(object@env$mz[bufMax[bufidx[i:(i+steps-1)],
peakrange[1]:peakrange[2]]],
nrow = steps)
which.intMax <- which.colMax(intmat)
mzmat <- mzmat[which.intMax]
if (all(is.na(mzmat))) {
yfilt[peakrange[1]:peakrange[2]] <- 0
next
}
mzrange <- range(mzmat, na.rm = TRUE)
massmean <- weighted.mean(mzmat, intmat[which.intMax], na.rm = TRUE)
## This case (the only non-na m/z had intensity 0) was reported
## by Gregory Alan Barding "binlin processing"
if(any(is.na(massmean))) {
massmean <- mean(mzmat, na.rm = TRUE)
}
pwid <- (scantime[peakrange[2]] - scantime[peakrange[1]])/(peakrange[2] - peakrange[1])
into <- pwid*sum(ysums[peakrange[1]:peakrange[2]])
intf <- pwid*sum(yfilt[peakrange[1]:peakrange[2]])
maxo <- max(ysums[peakrange[1]:peakrange[2]])
maxf <- yfilt[maxy]
if (sleep > 0) {
plot(scantime, yfilt, type = "l", main = paste(mass[i], "-", mass[i+1]), ylim=c(-gmax/3, gmax))
points(cbind(scantime, yfilt)[peakrange[1]:peakrange[2],], type = "l", col = "red")
points(scantime, colSums(ymat), type = "l", col = "blue", lty = "dashed")
abline(h = snthresh*noise, col = "red")
Sys.sleep(sleep)
}
yfilt[peakrange[1]:peakrange[2]] <- 0
num <- num + 1
### Double the size of the output matrix if it's full
if (num > nrow(rmat)) {
nrmat <- matrix(nrow = 2*nrow(rmat), ncol = ncol(rmat))
nrmat[seq(length = nrow(rmat)),] = rmat
rmat <- nrmat
}
rmat[num,] <- c(massmean, mzrange[1], mzrange[2], maxy, peakrange, into, intf, maxo, maxf, j, sn)
} else
break
}
}
cat("\n")
colnames(rmat) <- cnames
rmat <- rmat[seq(length = num),]
max <- max-1 + max*(steps-1) + max*ceiling(mzdiff/step)
if (index)
mzdiff <- mzdiff/step
else {
rmat[,"rt"] <- scantime[rmat[,"rt"]]
rmat[,"rtmin"] <- scantime[rmat[,"rtmin"]]
rmat[,"rtmax"] <- scantime[rmat[,"rtmax"]]
}
uorder <- order(rmat[,"into"], decreasing=TRUE)
uindex <- rectUnique(rmat[,c("mzmin","mzmax","rtmin","rtmax"),drop=FALSE],
uorder, mzdiff)
rmat <- rmat[uindex,,drop=FALSE]
invisible(new("xcmsPeaks", rmat))
})
############################################################
## findPeaks.matchedFilter
#' @title Peak detection in the chromatographic time domain
#'
#' @aliases findPeaks.matchedFilter
#'
#' @description Find peaks in the chromatographic time domain of the
#' profile matrix. For more details see
#' \code{\link{do_findChromPeaks_matchedFilter}}.
#'
#' @param object The \code{\linkS4class{xcmsRaw}} object on which peak detection
#' should be performed.
#'
#' @inheritParams findChromPeaks-matchedFilter
#'
#' @param step numeric(1) specifying the width of the bins/slices in m/z
#' dimension.
#'
#' @param sleep (DEPRECATED). The use of this parameter is highly discouraged,
#' as it could cause problems in parallel processing mode.
#'
#' @param scanrange Numeric vector defining the range of scans to which the
#' original \code{object} should be sub-setted before peak detection.
#'
#' @author Colin A. Smith
#'
#' @return A matrix, each row representing an intentified chromatographic peak,
#' with columns:
#' \describe{
#' \item{mz}{Intensity weighted mean of m/z values of the peak across
#' scans.}
#' \item{mzmin}{Minimum m/z of the peak.}
#' \item{mzmax}{Maximum m/z of the peak.}
#' \item{rt}{Retention time of the peak's midpoint.}
#' \item{rtmin}{Minimum retention time of the peak.}
#' \item{rtmax}{Maximum retention time of the peak.}
#' \item{into}{Integrated (original) intensity of the peak.}
#' \item{intf}{Integrated intensity of the filtered peak.}
#' \item{maxo}{Maximum intensity of the peak.}
#' \item{maxf}{Maximum intensity of the filtered peak.}
#' \item{i}{Rank of peak in merged EIC (\code{<= max}).}
#' \item{sn}{Signal to noise ratio of the peak.}
#' }
#'
#' @references
#' Colin A. Smith, Elizabeth J. Want, Grace O'Maille, Ruben Abagyan and
#' Gary Siuzdak. "XCMS: Processing Mass Spectrometry Data for Metabolite
#' Profiling Using Nonlinear Peak Alignment, Matching, and Identification"
#' \emph{Anal. Chem.} 2006, 78:779-787.
#' @family Old peak detection methods
#'
#' @seealso \code{\link{matchedFilter}} for the new user interface.
#' \code{\linkS4class{xcmsRaw}},
#' \code{\link{do_findChromPeaks_matchedFilter}} for the core function
#' performing the peak detection.
setMethod("findPeaks.matchedFilter", "xcmsRaw",
function(object, fwhm = 30, sigma = fwhm/2.3548, max = 5,
snthresh = 10, step = 0.1, steps = 2,
mzdiff = 0.8 - step*steps, index = FALSE, sleep = 0,
scanrange = numeric()) {
## Fix issue #63:
## Sub-set the xcmsRaw based on scanrange
if (length(scanrange) < 2) {
scanrange <- c(1, length(object@scantime))
} else {
scanrange <- range(scanrange)
}
if (min(scanrange) < 1 | max(scanrange) > length(object@scantime)) {
scanrange[1] <- max(1, scanrange[1])
scanrange[2] <- min(length(object@scantime), scanrange[2])
message("Provided scanrange was adjusted to ", scanrange)
}
object <- object[scanrange[1]:scanrange[2]]
scanrange <- c(1, length(object@scantime))
## ## Sub-set the xcmsRaw baesd on scanrange
## scanrange.old <- scanrange
## ## sanitize if too few or too many scanrange is given
## if (length(scanrange) < 2)
## scanrange <- c(1, length(object@scantime))
## else
## scanrange <- range(scanrange)
## ## restrict and sanitize scanrange to maximally cover all scans
## scanrange[1] <- max(1,scanrange[1])
## scanrange[2] <- min(length(object@scantime),scanrange[2])
## ## Mild warning if the actual scanrange doesn't match the scanrange
## ## argument
## if (!(identical(scanrange.old, scanrange)) &&
## (length(scanrange.old) > 0)) {
## cat("Warning: scanrange was adjusted to ",scanrange,"\n")
## ## Scanrange filtering
## keepidx <- seq.int(1, length(object@scantime))
## %in% seq.int(scanrange[1], scanrange[2])
## object <- split(object, f=keepidx)[["TRUE"]]
## }
## Determine the impute method:
imputeMeths <- c("none", "lin", "linbase", "intlin")
names(imputeMeths) <- c("bin", "binlin",
"binlinbase", "intlin")
profFun <- profMethod(object)
profFun <- match.arg(profFun, names(imputeMeths))
imputeMeth <- imputeMeths[profFun]
if (imputeMeth == "linbase") {
profp <- object@profparam
if (length(profp) == 0)
profp <- list()
## Determine the settings for this:
## o distance
## Define the distance argument; that's tricky, as it
## requires the bin_size, not the step.
mrange <- range(object@env$mz)
mass <- seq(floor(mrange[1]/step)*step,
ceiling(mrange[2]/step)*step, by = step)
mlength <- length(mass)
bin_size <- (mass[mlength] - mass[1]) / (mlength - 1)
rm(mass)
if (length(profp$basespace) > 0) {
if (!is.numeric(profp$basespace))
stop("Profile parameter 'basespace' has to be numeric!")
distance <- floor(profp$basespace[1] / bin_size)
} else {
distance <- floor(0.075 / bin_size)
}
## o baseValue
if (length(profp$baselevel) > 0) {
if (!is.numeric(profp$baselevel))
stop("Profile parameter 'baselevel' has to be numeric!")
baseValue <- profp$baselevel[1]
} else {
baseValue <- min(object@env$intensity) / 2
}
} else {
## For other methods these are not used anyway.
distance <- 0
baseValue <- 0
}
res <- do_findChromPeaks_matchedFilter(mz = object@env$mz,
int = object@env$intensity,
scantime = object@scantime,
valsPerSpect = diff(c(object@scanindex,
length(object@env$mz))),
binSize = step,
impute = imputeMeth,
baseValue = baseValue,
distance = distance,
fwhm = fwhm,
sigma = sigma,
max = max,
snthresh = snthresh,
steps = steps,
mzdiff = mzdiff,
index = index,
sleep = sleep
)
invisible(new("xcmsPeaks", res))
})
############################################################
## findPeaks.centWave
setMethod("findPeaks.centWave", "xcmsRaw", function(object, ppm=25,
peakwidth=c(20,50),
snthresh=10,
prefilter=c(3,100),
mzCenterFun="wMean",
integrate=1, mzdiff=-0.001,
fitgauss=FALSE,
scanrange = numeric(),
noise=0, ## noise.local=TRUE,
sleep=0,
verbose.columns=FALSE,
ROI.list=list(),
firstBaselineCheck=TRUE,
roiScales=NULL) {
if (!isCentroided(object))
warning("It looks like this file is in profile mode. centWave can",
" process only centroid mode data !\n")
## Fix issue #64:
## Sub-set the xcmsRaw based on scanrange
if (length(scanrange) < 2) {
scanrange <- c(1, length(object@scantime))
} else {
scanrange <- range(scanrange)
}
if (min(scanrange) < 1 | max(scanrange) > length(object@scantime)) {
scanrange[1] <- max(1, scanrange[1])
scanrange[2] <- min(length(object@scantime), scanrange[2])
message("Provided scanrange was adjusted to ", scanrange)
}
object <- object[scanrange[1]:scanrange[2]]
vps <- diff(c(object@scanindex, length(object@env$mz)))
res <- do_findChromPeaks_centWave(mz = object@env$mz,
int = object@env$intensity,
scantime = object@scantime,
valsPerSpect = vps,
ppm = ppm, peakwidth = peakwidth,
snthresh = snthresh,
prefilter = prefilter,
mzCenterFun = mzCenterFun,
integrate = integrate,
mzdiff = mzdiff, fitgauss = fitgauss,
noise = noise,
verboseColumns = verbose.columns,
roiList = ROI.list,
firstBaselineCheck = firstBaselineCheck,
roiScales = roiScales,
sleep = sleep
)
invisible(new("xcmsPeaks", res))
})
############################################################
## findPeaks.centWaveWithPredictedIsotopeROIs
## Performs first a centWave analysis and based on the identified peaks
## defines ROIs for a second centWave run to check for presence of
## predicted isotopes for the first peaks.
setMethod("findPeaks.centWaveWithPredictedIsotopeROIs", "xcmsRaw",
function(object, ppm = 25, peakwidth = c(20,50), snthresh = 10,
prefilter = c(3,100), mzCenterFun = "wMean", integrate = 1,
mzdiff = -0.001, fitgauss = FALSE, scanrange = numeric(),
noise = 0, sleep = 0, verbose.columns = FALSE,
ROI.list = list(), firstBaselineCheck = TRUE,
roiScales = NULL, snthreshIsoROIs = 6.25, maxcharge = 3,
maxiso = 5, mzIntervalExtension = TRUE) {
if (!isCentroided(object))
warning("It looks like this file is in profile mode. centWave",
" can process only centroid mode data !\n")
## Sub-set the xcmsRaw based on scanrange
if (length(scanrange) < 2) {
scanrange <- c(1, length(object@scantime))
} else {
scanrange <- range(scanrange)
}
if (min(scanrange) < 1 | max(scanrange) > length(object@scantime)) {
scanrange[1] <- max(1, scanrange[1])
scanrange[2] <- min(length(object@scantime), scanrange[2])
message("Provided scanrange was adjusted to ", scanrange)
}
object <- object[scanrange[1]:scanrange[2]]
vps <- diff(c(object@scanindex, length(object@env$mz)))
res <- do_findChromPeaks_centWaveWithPredIsoROIs(mz = object@env$mz,
int = object@env$intensity,
scantime = object@scantime,
valsPerSpect = vps,
ppm = ppm,
peakwidth = peakwidth,
snthresh = snthresh,
prefilter = prefilter,
mzCenterFun = mzCenterFun,
integrate = integrate,
mzdiff = mzdiff,
fitgauss = fitgauss,
noise = noise,
verboseColumns = verbose.columns,
roiList = ROI.list,
firstBaselineCheck = firstBaselineCheck,
roiScales = roiScales,
snthreshIsoROIs = snthreshIsoROIs,
maxCharge = maxcharge,
maxIso = maxiso,
mzIntervalExtension = mzIntervalExtension
)
invisible(new("xcmsPeaks", res))
})
setMethod("findPeaks.addPredictedIsotopeFeatures",
"xcmsRaw", function(object, ppm = 25, peakwidth = c(20,50),
prefilter = c(3,100), mzCenterFun = "wMean",
integrate = 1, mzdiff = -0.001, fitgauss = FALSE,
scanrange = numeric(), noise=0, ## noise.local=TRUE,
sleep = 0, verbose.columns = FALSE,
xcmsPeaks, snthresh = 6.25, maxcharge = 3,
maxiso = 5, mzIntervalExtension = TRUE) {
if (!isCentroided(object))
warning("It looks like this file is in profile mode. ",
"centWave works best for centroided data")
## Sub-set the xcmsRaw based on scanrange
if (length(scanrange) < 2) {
scanrange <- c(1, length(object@scantime))
} else {
scanrange <- range(scanrange)
}
if (min(scanrange) < 1 | max(scanrange) > length(object@scantime)) {
scanrange[1] <- max(1, scanrange[1])
scanrange[2] <- min(length(object@scantime), scanrange[2])
message("Provided scanrange was adjusted to ", scanrange)
}
object <- object[scanrange[1]:scanrange[2]]
if(class(xcmsPeaks) != "xcmsPeaks")
stop("Parameter 'xcmsPeaks' is not of class 'xcmsPeaks'")
vps <- diff(c(object@scanindex, length(object@env$mz)))
res <- do_findChromPeaks_addPredIsoROIs(
mz = object@env$mz, int = object@env$intensity,
scantime = object@scantime, valsPerSpect = vps,
ppm = ppm, peakwidth = peakwidth,
snthresh = snthresh, prefilter = prefilter,
mzCenterFun = mzCenterFun, integrate = integrate,
mzdiff = mzdiff, fitgauss = fitgauss, noise = noise,
verboseColumns = verbose.columns, peaks. = xcmsPeaks@.Data,
maxCharge = maxcharge, maxIso = maxiso,
mzIntervalExtension = mzIntervalExtension
)
invisible(new("xcmsPeaks", res))
})
############################################################
## findPeaks.MSW
#' @title Peak detection for single-spectrum non-chromatography MS data
#'
#' @aliases findPeaks.MSW
#'
#' @description This method performs peak detection in mass spectrometry
#' direct injection spectrum using a wavelet based algorithm.
#'
#' @details This is a wrapper around the peak picker in Bioconductor's
#' \code{MassSpecWavelet} package calling
#' \code{\link{peakDetectionCWT}} and
#' \code{\link{tuneInPeakInfo}} functions.
#'
#' @inheritParams findPeaks-MSW
#'
#' @inheritParams findChromPeaks-centWave
#'
#' @param object The \code{\linkS4class{xcmsRaw}} object on which peak
#' detection should be performed.
#'
#' @param verbose.columns Logical whether additional peak meta data columns
#' should be returned.
#'
#' @return
#' A matrix, each row representing an intentified peak, with columns:
#' \describe{
#' \item{mz}{m/z value of the peak at the centroid position.}
#' \item{mzmin}{Minimum m/z of the peak.}
#' \item{mzmax}{Maximum m/z of the peak.}
#' \item{rt}{Always \code{-1}.}
#' \item{rtmin}{Always \code{-1}.}
#' \item{rtmax}{Always \code{-1}.}
#' \item{into}{Integrated (original) intensity of the peak.}
#' \item{maxo}{Maximum intensity of the peak.}
#' \item{intf}{Always \code{NA}.}
#' \item{maxf}{Maximum MSW-filter response of the peak.}
#' \item{sn}{Signal to noise ratio.}
#' }
#'
#' @seealso \code{\link{MSW}} for the new user interface,
#' \code{\link{do_findPeaks_MSW}} for the downstream analysis
#' function or \code{\link{peakDetectionCWT}} from the
#' \code{MassSpecWavelet} for details on the algorithm and additionally
#' supported parameters.
#'
#' @author Joachim Kutzera, Steffen Neumann, Johannes Rainer
setMethod("findPeaks.MSW", "xcmsRaw",
function(object, snthresh=3, verbose.columns = FALSE, ...) {
if (length(object@scantime) > 1)
stop("MSW works only on single spectrum, direct injection",
" MS data, but 'object' has ", length(object@scantime),
" spectra")
res <- do_findPeaks_MSW(mz = object@env$mz,
int = object@env$intensity,
snthresh = snthresh,
verboseColumns = verbose.columns,
...)
invisible(new("xcmsPeaks", res))
})
############################################################
## findPeaks.MS1
setMethod("findPeaks.MS1", "xcmsRaw", function(object)
{
if (is.null(object@msnLevel)) {
stop("xcmsRaw contains no MS2 spectra\n")
}
## Select all MS2 scans, they have an MS1 parent defined
peakIndex <- object@msnLevel == 2
## (empty) return object
basenames <- c("mz","mzmin","mzmax",
"rt","rtmin","rtmax",
"into","maxo","sn")
peaklist <- matrix(-1, nrow = length(which(peakIndex)),
ncol = length(basenames))
colnames(peaklist) <- c(basenames)
## Assemble result
peaklist[,"mz"] <- object@msnPrecursorMz[peakIndex]
peaklist[,"mzmin"] <- object@msnPrecursorMz[peakIndex]
peaklist[,"mzmax"] <- object@msnPrecursorMz[peakIndex]
if (any(!is.na(object@msnPrecursorScan))&&any(object@msnPrecursorScan!=0)) {
peaklist[,"rt"] <- peaklist[,"rtmin"] <- peaklist[,"rtmax"] <- object@scantime[object@msnPrecursorScan[peakIndex]]
} else {
## This happened with ReAdW mzxml
cat("MS2 spectra without precursorScan references, using estimation")
## which object@Scantime are the biggest wich are smaller than the current object@msnRt[peaklist]?
ms1Rts<-rep(0,length(which(peakIndex)))
i<-1
for (a in which(peakIndex)){
ms1Rts[i] <- object@scantime[max(which(object@scantime<object@msnRt[a]))]
i<-i+1
}
peaklist[,"rt"] <- ms1Rts
peaklist[,"rtmin"] <- ms1Rts
peaklist[,"rtmax"] <- ms1Rts
}
if (any(object@msnPrecursorIntensity!=0)) {
peaklist[,"into"] <- peaklist[,"maxo"] <- peaklist[,"sn"] <- object@msnPrecursorIntensity[peakIndex]
} else {
## This happened with Agilent MzDataExport 1.0.98.2
warning("MS2 spectra without precursorIntensity, setting to zero")
peaklist[,"into"] <- peaklist[,"maxo"] <- peaklist[,"sn"] <- 0
}
cat('\n')
invisible(new("xcmsPeaks", peaklist))
})
############################################################
## findPeaks
setMethod("findPeaks", "xcmsRaw", function(object, method=getOption("BioC")$xcms$findPeaks.method,
...) {
method <- match.arg(method, getOption("BioC")$xcms$findPeaks.methods)
if (is.na(method))
stop("unknown method : ", method)
method <- paste("findPeaks", method, sep=".")
invisible(do.call(method, list(object, ...)))
})
setMethod("getPeaks", "xcmsRaw", function(object, peakrange, step = 0.1) {
if (useOriginalCode())
return(.getPeaks_orig(object, peakrange, step = step))
else
return(.getPeaks_new(object, peakrange, step = step))
})
############################################################
## plotPeaks
setMethod("plotPeaks", "xcmsRaw", function(object, peaks, figs, width = 200) {
if (missing(figs)) {
figs <- c(floor(sqrt(nrow(peaks))), ceiling(sqrt(nrow(peaks))))
if (prod(figs) < nrow(peaks))
figs <- rep(ceiling(sqrt(nrow(peaks))), 2)
}
mzi <- round((peaks[,c("mzmin","mzmax")]-object@mzrange[1])/profStep(object) + 1)
screens <- split.screen(figs)
on.exit(close.screen(all.screens = TRUE))
for (i in seq(length = min(nrow(peaks), prod(figs)))) {
screen(screens[i])
par(cex.main = 1, font.main = 1, mar = c(0, 0, 1, 0) + 0.1)
xlim <- c(-width/2, width/2) + peaks[i,"rt"]
##main <- paste(peaks[i,"i"], " ", round(peaks[i,"mz"]),
main <- paste(round(peaks[i,"mz"]),
" ", round(peaks[i,"rt"]), sep = "")
plot(object@scantime, colMax(object@env$profile[mzi[i,],,drop=FALSE]),
type = "l", xlim = xlim, ylim = c(0, peaks[i,"maxo"]), main = main,
xlab = "", ylab = "", xaxt = "n", yaxt = "n")
abline(v = peaks[i,c("rtmin","rtmax")], col = "grey")
}
})
############################################################
## getEIC
## Issue #74: implement an alternative (improved) getEIC method.
setMethod("getEIC", "xcmsRaw", function(object, mzrange, rtrange = NULL,
step = 0.1) {
profEIC(object, mzrange = mzrange, rtrange = rtrange, step = step)
})
############################################################
## rawMat
#' @description Extracts a matrix with columns time (retention time), mz and
#' intensity from an xcmsRaw object.
#'
#' @noRd
setMethod("rawMat", "xcmsRaw", function(object,
mzrange = numeric(),
rtrange = numeric(),
scanrange = numeric(),
log=FALSE) {
.rawMat(mz = object@env$mz, int = object@env$intensity,
scantime = object@scantime,
valsPerSpect = diff(c(object@scanindex, length(object@env$mz))),
mzrange = mzrange, rtrange = rtrange, scanrange = scanrange,
log = log)
})
############################################################
## plotRaw
setMethod("plotRaw", "xcmsRaw", function(object,
mzrange = numeric(),
rtrange = numeric(),
scanrange = numeric(),
log=FALSE,title='Raw Data' ) {
raw <- rawMat(object, mzrange, rtrange, scanrange, log)
if (nrow(raw) > 0) {
y <- raw[,"intensity"]
ylim <- range(y)
y <- y/ylim[2]
colorlut <- terrain.colors(16)
col <- colorlut[y*15+1]
plot(cbind(raw[,"time"], raw[,"mz"]), pch=20, cex=.5,
main = title, xlab="Seconds", ylab="m/z", col=col,
xlim=range(raw[,"time"]), ylim=range(raw[,"mz"]))
} else {
if (length(rtrange) >= 2) {
rtrange <- range(rtrange)
scanidx <- (object@scantime >= rtrange[1]) & (object@scantime <= rtrange[2])
scanrange <- c(match(TRUE, scanidx),
length(scanidx) - match(TRUE, rev(scanidx)))
} else if (length(scanrange) < 2)
scanrange <- c(1, length(object@scantime)) else
scanrange <- range(scanrange)
plot(c(NA,NA), main = title, xlab="Seconds", ylab="m/z",
xlim=c(object@scantime[scanrange[1]],object@scantime[scanrange[2]]), ylim=mzrange)
}
invisible(raw)
})
############################################################
## profMz
setMethod("profMz", "xcmsRaw", function(object) {
object@mzrange[1]+profStep(object)*(0:(dim(object@env$profile)[1]-1))
})
############################################################
## profMethods
setMethod("profMethod", "xcmsRaw", function(object) {
object@profmethod
})
setReplaceMethod("profMethod", "xcmsRaw", function(object, value) {
if (! (value %in% names(.profFunctions)))
stop("Invalid profile method")
if (length(object@env$mz) == 0) {
warning("MS1 scans empty. Skipping profile matrix creation.")
return(object)
}
have_profmethod <- object@profmethod
## Re-calculate the profile matrix if method differs
if (have_profmethod != value & profStep(object) > 0) {
object@env$profile <- profMat(object, method = value)
}
object@profmethod <- value
object
})
############################################################
## profStep
setMethod("profStep", "xcmsRaw", function(object) {
if (is.null(object@env$profile))
0
else
diff(object@mzrange)/(nrow(object@env$profile)-1)
})
## Update: related to issue #71
setReplaceMethod("profStep", "xcmsRaw", function(object, value) {
if (!is.numeric(value) && value < 0)
stop("'value' has to be a positive number!")
if (length(object@env$mz) == 0) {
warning("MS1 scans empty. Skipping profile matrix creation.")
return(object)
}
if (value == 0) {
if ("profile" %in% ls(object@env)) {
rm("profile", envir = object@env)
message("Removing profile matrix.")
}
return(object)
}
have_step <- profStep(object)
## Check if the value differs from step and only calculate if different.
if (have_step != value) {
## OK, now we're re-calculating
minmass <- round(min(object@env$mz) / value) * value
maxmass <- round(max(object@env$mz) / value) * value
object@mzrange <- c(minmass, maxmass)
## Fix for issue #98: to be in accordance with the "old" code we require
## that the number of rows of the profile matrix matches minmass to
## maxmass in steps of value
## To me that is somewhat problematic, as it means that the @mzrange does
## not correctly correspond to the range(object@env$mz)!
tmp <- seq(minmass, maxmass, by = value)
prf <- profMat(object, step = value)
object@env$profile <- prf[1:min(c(length(tmp), nrow(prf))), ]
}
return(object)
})
############################################################
## profStepPad
## The difference to the profStep? seems only to be the way how the range
## is calculated:
## profStep: minmass <- round(min(object@env$mz)/value)*value
## profStepPad: floor(mzrange(range(object@env$mz))[1])
setReplaceMethod("profStepPad", "xcmsRaw", function(object, value) {
if (!is.numeric(value) && value < 0)
stop("'value' has to be a positive number!")
if (length(object@env$mz) == 0) {
warning("MS1 scans empty. Skipping profile matrix creation.")
return(object)
}
if (value == 0) {
if ("profile" %in% ls(object@env)) {
rm("profile", envir = object@env)
message("Removing profile matrix.")
}
return(object)
}
mzr <- range(object@env$mz)
minmass <- floor(mzr[1])
maxmass <- ceiling(mzr[2])
object@mzrange <- c(minmass, maxmass)
object@env$profile <- profMat(object, step = value,
mzrange. = c(minmass, maxmass))
return(object)
})
############################################################
## profMedFilt
setMethod("profMedFilt", "xcmsRaw", function(object, massrad = 0, scanrad = 0) {
contdim <- dim(object@env$profile)
object@env$profile <- medianFilter(object@env$profile, massrad, scanrad)
})
############################################################
## profRange
setMethod("profRange", "xcmsRaw", function(object,
mzrange = numeric(),
rtrange = numeric(),
scanrange = numeric(), ...) {
if (length(object@env$profile)) {
contmass <- profMz(object)
if (length(mzrange) == 0) {
mzrange <- c(min(contmass), max(contmass))
} else if (length(mzrange) == 1) {
closemass <- contmass[which.min(abs(contmass-mzrange))]
mzrange <- c(closemass, closemass)
} else if (length(mzrange) > 2) {
mzrange <- c(min(mzrange), max(mzrange))
}
massidx <- which((contmass >= mzrange[1]) & (contmass <= mzrange[2]))
} else {
if (length(mzrange) == 0) {
mzrange <- range(object@env$mz)
} else {
mzrange <- c(min(mzrange), max(mzrange))
}
massidx <- integer()
}
if (mzrange[1] == mzrange[2])
masslab <- paste(mzrange[1], "m/z")
else
masslab <- paste(mzrange[1], "-", mzrange[2], " m/z", sep="")
if (length(rtrange) == 0) {
if (length(scanrange) == 0)
scanrange <- c(1, length(object@scanindex))
else if (length(scanrange) == 1)
scanrange <- c(scanrange, scanrange)
else if (length(scanrange) > 2)
scanrange <- c(max(1, min(scanrange)), min(max(scanrange), length(object@scantime)))
rtrange <- c(object@scantime[scanrange[1]], object@scantime[scanrange[2]])
} else if (length(rtrange) == 1) {
closetime <- object@scantime[which.min(abs(object@scantime-rtrange))]
rtrange <- c(closetime, closetime)
} else if (length(rtrange) > 2) {
rtrange <- c(min(rtrange), max(rtrange))
}