-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathspectrum-functions.R
398 lines (343 loc) · 13.7 KB
/
spectrum-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
#' parse synapter Spectrum.xml files
#'
#' Stupid parser for one of the ugliest pseudo-xml formats I have ever seen.
#'
#' @param file file path
#' @param encoding file encoding, seems to be windows specific
#' @param verbose verbose output?
#'
#' @return a list of length == 4; names: ms1, m2, leRows, heRows
#' ms1: matrix of ms1 spectra information
#' ms2: matrix of ms2 spectra information
#' leRows: environment (key == leID), values == LE_ID row index
#' heRows: environment (key == leID), values == HE_ID row index
#' @noRd
.readSynapterSpectrumXml <- function(file, verbose=interactive()) {
stopifnot(file.exists(file))
## helper functions
.extractName <- function(x) {
gsub("^.*NAME=\\\"([[:alpha:]_]+)\\\".*$", "\\1", x)
}
.extractLEID <- function(x) {
gsub("^.*LE_ID=\\\"([[:digit:]]+)\\\".*$", "\\1", x)
}
.extractHEID <- function(x) {
gsub("^.*HE_ID=\\\"([[:digit:],]+)\\\".*$", "\\1", x)
}
.createMsMatrix <- function(x, header, verbose=interactive()) {
x <- paste0(gsub("[[:space:]]+", ",", trimws(x)), collapse="\n")
cols <- intersect(header, c("Mass", "Intensity", "LE_ID", "HE_ID", "Z", "RT"))
as.matrix(read_csv(x, col_names=header,
col_types=do.call(cols_only, as.list(setNames(rep.int("d", length(cols)), cols))),
trim_ws=TRUE, progress=verbose))
}
if (verbose) {
message("Reading ", file)
}
content <- read_lines(file)
if (verbose) {
message("Search line numbers for Header information")
}
linesField <- grep("<FIELD", content[1L:min(200L, length(content))],
fixed=TRUE)
splitPoint <- which(diff(linesField) > 1L)
linesFieldMs1 <- linesField[1:splitPoint]
linesFieldMs2 <- linesField[(splitPoint+1):length(linesField)]
if (verbose) {
message("Read Header information")
}
header1 <- .extractName(content[linesFieldMs1])
header2 <- .extractName(content[linesFieldMs2])
if (verbose) {
message("Search line numbers for MS Data")
}
linesMs <- grep("</?(HE_)?DATA", content)+c(1L, -1L)
if (verbose) {
message("Read MS1 Data (", paste(linesMs[1L:2L], collapse=":"), ")")
}
ms1 <- .createMsMatrix(content[linesMs[1L]:linesMs[2L]], header1)
if (verbose) {
message("Read MS2 Data (", paste(linesMs[3L:4L], collapse=":"), ")")
}
ms2 <- .createMsMatrix(content[linesMs[3L]:linesMs[4L]], header2)
if (verbose) {
message("Search line numbers for MS1 to MS2 assignment")
}
linesAssignment <- grep("</?PRECURSOR_PRODUCT_BIN", content)+c(1L, -1L)
if (verbose) {
message("Read Assignment Data (", paste(linesAssignment, collapse=":"), ")")
}
range <- linesAssignment[1L]:linesAssignment[2L]
if (verbose) {
message(" extract LE_ID information")
}
le_ids <- .extractLEID(content[range])
if (verbose) {
message(" extract HE_ID information")
}
he_ids <- lapply(MSnbase:::utils.ssv2list(
.extractHEID(content[range]), sep=","), as.numeric)
leRows <- new.env(hash=TRUE, parent=emptyenv(), size=length(le_ids))
heRows <- new.env(hash=TRUE, parent=emptyenv(), size=length(le_ids))
if (verbose) {
message(" match LE_ID and HE_ID information")
}
le_rows <- findInterval(le_ids, ms1[, "LE_ID"])
he_rows <- relist(findInterval(unlist(he_ids), ms2[, "HE_ID"]), he_ids)
for (i in seq(along=le_ids)) {
assign(le_ids[i], le_rows[[i]], envir=leRows)
assign(le_ids[i], he_rows[[i]], envir=heRows)
}
list(ms1=ms1, ms2=ms2, leRows=leRows, heRows=heRows)
}
#' read spectrum.xml and turn data into MSnbase::Spectrum2 objects
#' @param df corresponding df from the synapter object ({Ident,Quant}PeptideData)
#' @param file filename
#' @param assaydata environment
#' @param storeAll should all spectra stored? or only the needed ones?
#' @param removePrecursor remove precursor ion from fragments
#' @param tolerance tolerance to look for the precursor ion
#' @param verbose verbose output
#' @return modified assaydata
#' @noRd
.spectrumXml2spectra <- function(df, file, storeAll=TRUE, removePrecursor=TRUE,
tolerance=25e-6, verbose=interactive()) {
xml <- .readSynapterSpectrumXml(file, verbose=verbose)
peptideinfo <- df[!duplicated(df$precursor.leID), ]
if (storeAll) {
uleID <- union(df$precursor.leID, xml$ms1[, "LE_ID"])
} else {
uleID <- intersect(df$precursor.leID, xml$ms1[, "LE_ID"])
}
if (verbose) {
message("Convert spectra data.frames to MSnbase::Spectrum2 objects")
pb <- txtProgressBar(0, length(uleID), style=3)
}
sequences <- rep(NA_character_, length(uleID))
assaydata <- new.env(hash=TRUE, parent=emptyenv(), size=length(uleID))
for (i in seq(along=uleID)) {
assign(as.character(uleID[i]),
.createMs2SpectrumFromSpectrumXml(uleID[i], xml$ms1, xml$ms2,
xml$leRows, xml$heRows,
removePrecursor=removePrecursor,
tolerance=tolerance),
envir=assaydata)
if (i <= nrow(df)) {
## in the xml files are no sequence information that's why we have to use
## information from the df
sequences[i] <- peptideinfo$peptide.seq[i]
}
if (verbose) {
setTxtProgressBar(pb, i)
}
}
if (verbose) {
close(pb)
message("Create MSnExp object")
}
process <- new("MSnProcess",
processing=paste("Data loaded:", date()),
files=file)
nm <- ls(assaydata)
pdata <- new("NAnnotatedDataFrame", data=data.frame(sampleNames=1L,
type="spectrum"))
fdata <- data.frame(spectrum=1:length(nm),
leID=uleID,
peptide.seq=sequences,
row.names=uleID,
stringsAsFactors=FALSE)
## reorder according to assaydata
fdata <- fdata[nm, ]
fdata <- new("AnnotatedDataFrame", data=fdata)
msnexp <- new("MSnExp", assayData=assaydata,
phenoData=pdata,
featureData=fdata,
processingData=process)
if (validObject(msnexp))
return(msnexp)
}
#' create MS2 spectrum from spectrum.xml data
#' @param leID precursor.leID
#' @param ms1 ms1 matrix generated by .readSynapterSpectrumXml
#' @param ms2 ms2 matrix generated by .readSynapterSpectrumXml
#' @param leRows env generated by .readSynapterSpectrumXml
#' @param heRows env generated by .readSynapterSpectrumXml
#' @param removePrecursor remove precursor ion from fragments
#' @param tolerance tolerance to look for the precursor ion
#' @return Spectrum2 object
#' @noRd
.createMs2SpectrumFromSpectrumXml <- function(leID, ms1, ms2, leRows, heRows,
removePrecursor=TRUE,
tolerance=25e-6) {
key <- as.character(leID)
if (exists(key, envir=leRows)) {
lrow <- get(key, envir=leRows)
hrows <- get(key, envir=heRows)
.createMsnbaseSpectrum2(leID=leID,
precursor.mhp=ms1[lrow, "Mass"],
precursor.inten=ms1[lrow, "Intensity"],
precursor.z=ms1[lrow, "Z"],
precursor.retT=ms1[lrow, "RT"],
mass=ms2[hrows, "Mass"],
intensity=ms2[hrows, "Intensity"],
removePrecursor=removePrecursor,
tolerance=tolerance)
} else {
.createEmptyMsnbaseSpectrum2(leID=leID)
}
}
#' create MS2 spectrum from final_fragment.csv data
#' @param leID precursor.leID
#' @param fragments data.frame generated by readFragments
#' @param assignments env
#' @param removePrecursor remove precursor ion from fragments
#' @param tolerance tolerance to look for the precursor ion
#' @return Spectrum2 object
#' @noRd
.createMs2SpectrumFromFragments <- function(leID, fragments, assignments,
removePrecursor=TRUE,
tolerance=25e-6) {
key <- as.character(leID)
if (exists(key, envir=assignments)) {
i <- get(key, envir=assignments)
j <- i[1]
.createMsnbaseSpectrum2(leID,
precursor.mhp=fragments$precursor.mhp[j],
precursor.inten=fragments$precursor.inten[j],
precursor.z=fragments$precursor.z[j],
precursor.retT=fragments$precursor.retT[j],
mass=fragments$product.mhp[i],
intensity=fragments$product.inten[i],
removePrecursor=removePrecursor,
tolerance=25e-6)
} else {
.createEmptyMsnbaseSpectrum2(leID=leID)
}
}
#' create an instance of an MSnbase::Spectrum2 object
#' @param leID precursor.leID
#' @param precursor.mhp precursor mass
#' @param precursor.inten precursor intensity
#' @param precursor.z precursor charge
#' @param precursor.retT precursor retention time
#' @param mass mass/mz
#' @param intensity intensity
#' @param removePrecursor remove precursor ion from fragments
#' @param tolerance tolerance to look for the precursor ion
#' @return Spectrum2 object
#' @noRd
.createMsnbaseSpectrum2 <- function(leID, precursor.mhp, precursor.inten,
precursor.z, precursor.retT,
mass, intensity,
removePrecursor=TRUE, tolerance=25e-6) {
## just to be sure, you can't trust any information in the csv/xml files
o <- order(mass)
if (removePrecursor) {
m <- !as.logical(MSnbase:::relaxedMatch(x=mass[o], table=precursor.mhp,
nomatch=0,
relative=TRUE,
tolerance=tolerance))
o <- o[m]
if (!length(o)) {
return(.createEmptyMsnbaseSpectrum2(leID=leID))
}
}
## use MSnbase:::Spectrum2_mz_sorted to improve speed in class creation;
## see https://github.com/lgatto/MSnbase/issues/171
#new("Spectrum2",
# precScanNum=as.integer(leID),
# precursorMz=precursor.mhp,
# precursorIntensity=precursor.inten,
# precursorCharge=as.integer(precursor.z),
# rt=precursor.retT,
# centroided=TRUE,
# # tic=precursor.inten,
# peaksCount=length(o),
# mz=mass[o], intensity=intensity[o],
# fromFile=1L)
s <- MSnbase:::Spectrum2_mz_sorted(precScanNum=as.integer(leID),
precursorMz=precursor.mhp,
precursorIntensity=precursor.inten,
precursorCharge=as.integer(precursor.z),
rt=precursor.retT,
centroided=TRUE,
peaksCount=length(o),
mz=mass[o], intensity=intensity[o],
fromFile=1L)
if (validObject(s)) {
s
}
}
#' create an empty instance of an MSnbase::Spectrum2 object
#' @param leID precursor.leID
#' @param key character (used in enviroments to access the correct spetrum)
#' @noRd
.createEmptyMsnbaseSpectrum2 <- function(leID, key="spectrum:-1") {
if (missing(leID)) {
leID <- as.integer(tail(strsplit(key, ":")[[1]], 1))
}
## use MSnbase:::Spectrum2_mz_sorted to improve speed in class creation;
## see https://github.com/lgatto/MSnbase/issues/171
#new("Spectrum2", precScanNum=as.integer(leID), fromFile=1L)
MSnbase:::Spectrum2_mz_sorted(precScanNum=as.integer(leID), fromFile=1L)
}
#' @param msexp MSnExp object to filter
#' @param minIntensity minimal intensity
#' @param maxNumber maximal number of fragments to preserve
#' @param verbose verbose output?
#' @return modified MSnExp object
#' @noRd
.filterIntensity <- function(msexp, minIntensity=NULL, maxNumber=NULL,
verbose=interactive()) {
if(is.null(minIntensity) && is.null(maxNumber)) {
stop("At least one of arguments ", sQuote("minIntensity"), " and ",
sQuote("maxNumber"), " must be given!")
}
minIntensity2 <- 0
if (!is.null(maxNumber)) {
cs <- .cumsumIntensities(msexp)
minIntensity2 <- as.double(names(cs)[which(cs > (tail(cs, 1)-maxNumber))[1]])
}
minIntensity <- max(minIntensity, minIntensity2)
if (verbose) {
message("Set peaks with an intensity < ", minIntensity, " to zero")
pcBefore <- .sumAllPeakCounts(msexp)
}
msexp <- removePeaks(msexp, t=minIntensity, verbose=verbose)
## remove corresponding fragment information if available
stopifnot(fData(msexp)$leID == precScanNum(msexp))
if ("fragment.str" %in% colnames(fData(msexp))) {
fragments <- MSnbase:::utils.ssv2list(as.character(fData(msexp)$fragment.str))
fData(msexp)$fragment.str <- MSnbase:::utils.list2ssv(mapply(function(f, i) {
if (length(f) && length(i)) {
as.character(f[i > 0])
} else {
character()
}
}, f=fragments, i=intensity(msexp), SIMPLIFY=FALSE, USE.NAMES=FALSE))
stopifnot(validObject(msexp))
}
if (verbose) {
message("Remove peaks with zero intensity")
pcBefore <- .sumAllPeakCounts(msexp)
}
msexp <- clean(msexp, all=TRUE, verbose=verbose)
if (verbose) {
pcAfter <- .sumAllPeakCounts(msexp)
message(pcBefore - pcAfter, " peaks removed; new total number of peaks: ",
pcAfter)
}
msexp
}
#' @param msexp MSnExp object to filter
#' @noRd
.plotIntensityVsNumber <- function(msexp, what) {
cs <- .cumsumIntensities(msexp)
plot(as.double(names(cs)), cs, log="x", type="l",
main=paste0("Cumulative Number of Fragments (", what, ")"),
xlab="Intensity", ylab="# of Fragments")
grid()
}
.cumsumIntensities <- function(msexp) {
cumsum(table(unlist(intensity(msexp))))
}