msPurity assesses the precursor purity of fragmentation spectra (Lawson et al. 2017), links the spectra to LC-MS features, filters and averages them, stores the results and compares spectra. This vignette applies these steps to MS²–MS⁴ spectra of two standards bundled with the package: L-tryptophan and L-kynurenine, measured as [M+H]⁺ ions at m/z 205.0972 and 209.0921. Each standard was acquired in two positive-mode runs: an MS¹-only run and an MS¹–MS⁴ run with HCD and CID fragmentation at several collision energies. The files were reduced to the targeted isolation windows and the selected fragmentation branches for testing and demonstration purposes.
msPurity reads raw data through Spectra. The MS¹-only runs contain only
MS¹ scans. In the MS¹–MS⁴ runs, each MS³ spectrum fragments a product ion
selected from an MS² spectrum, and each MS⁴ spectrum a product ion from an
MS³ spectrum.
library(msPurity)
library(Spectra)
library(xcms)
library(MsExperiment)
dir <- system.file("extdata", "msn-standards", package = "msPurity")
runs <- data.frame(
file = c("msPurity_L_tryptophan_6305_MSn.mzML.gz",
"msPurity_L_kynurenine_161166_MSn.mzML.gz",
"msPurity_L_tryptophan_6305_MS1.mzML.gz",
"msPurity_L_kynurenine_161166_MS1.mzML.gz"),
sample_id = c("tryptophan MSn", "kynurenine MSn",
"tryptophan MS1", "kynurenine MS1"),
compound = factor(rep(c("tryptophan", "kynurenine"), 2),
levels = c("tryptophan", "kynurenine")),
acquisition = rep(c("MS1-MS4", "MS1 only"), each = 2))
files <- file.path(dir, runs$file)
compound <- function(x) ifelse(grepl("tryptophan", x), "tryptophan",
"kynurenine")
serial <- BiocParallel::SerialParam()
raw <- Spectra(files, source = MsBackendMzR(), BPPARAM = serial)
table(run = runs$sample_id[match(basename(dataOrigin(raw)), runs$file)],
msLevel = msLevel(raw))
#> msLevel
#> run 1 2 3 4
#> kynurenine MS1 191 0 0 0
#> kynurenine MSn 35 51 33 16
#> tryptophan MS1 193 0 0 0
#> tryptophan MSn 34 78 44 20
xcms detects chromatographic peaks in the MS¹ scans of all four runs and groups them into features across runs. For each standard, the peaks of its MS¹-only and MS¹–MS⁴ runs form one feature at the [M+H]⁺ m/z. No retention-time correction was applied.
xe <- readMsExperiment(files, sampleData = runs, BPPARAM = serial)
xe <- findChromPeaks(xe, param = CentWaveParam(ppm = 10, peakwidth = c(3, 30),
snthresh = 10, prefilter = c(3, 100), noise = 0),
msLevel = 1L, BPPARAM = serial)
xe <- groupChromPeaks(xe, param = PeakDensityParam(
sampleGroups = as.character(runs$compound), binSize = 0.005, bw = 5,
minFraction = 0.5))
targets <- c(tryptophan = 205.09715, kynurenine = 209.09207)
fd <- featureDefinitions(xe)
features <- vapply(targets, function(mz)
which(abs(fd$mzmed - mz) <= mz * 10e-6), integer(1))
fd[features, c("mzmed", "rtmed", "npeaks")]
#> mzmed rtmed npeaks
#> FT14 205.0971 343.4971 2
#> FT31 209.0921 347.6457 3
intensities <- featureValues(xe)[features, ]
colnames(intensities) <- runs$sample_id
intensities
#> tryptophan MSn kynurenine MSn tryptophan MS1 kynurenine MS1
#> FT14 1153836501 NA 875871695 NA
#> FT31 NA 320052704 NA 590726728
lcmsPlot draws the ion chromatograms of the two features in each run, with the detected peaks shaded. The MS¹ scans of the MS¹–MS⁴ runs are sparser, because the instrument spends most of each cycle on MS²–MS⁴ scans.
library(lcmsPlot)
lcmsPlot(xe, BPPARAM = serial) +
lp_chromatogram(features = rownames(fd)[features], ppm = 10,
rt_tol = 30, highlight_peaks = TRUE) +
lp_grid(rows = "acquisition", cols = "compound")
With msLevel = 2:4, purityA() estimates MS² purity from the neighbouring
MS¹ scans and MS³/MS⁴ purity from the parent spectrum the precursor was
isolated from. frag4feature() links MS² spectra to features by precursor
m/z and retention time, and links MS³/MS⁴ spectra to the same feature
through their parent spectra. An MS² spectrum excluded by plim does not
exclude its MS³/MS⁴ descendants. purityA() receives the same four runs
as the xcms object; the MS¹-only runs contain no fragmentation spectra and
add no purity results. Without retention-time correction,
convert2RawRT = FALSE.
pa <- purityA(files, msLevel = 2:4, cores = 1L, plotP = FALSE)
pa <- frag4feature(pa, xe, ppm = 10, msLevel = 2:4, convert2RawRT = FALSE)
linked <- groupedSpectra(pa, legacy = FALSE)
table(compound = compound(dataOrigin(linked)), msLevel = msLevel(linked))
#> msLevel
#> compound 2 3 4
#> kynurenine 34 21 12
#> tryptophan 17 11 6
PurityAParam() and Frag4FeatureParam() hold the same settings as
reusable parameter objects.
lcmsPlot also draws purityA results. For tryptophan, each triangle marks
MS² events at the time of their precursor MS¹ scan, coloured by precursor
purity.
precursor <- data.frame(sample_id = "tryptophan MSn",
mz = targets[["tryptophan"]],
rt = fd$rtmed[features[["tryptophan"]]])
lcmsPlot(pa, metadata = runs, BPPARAM = serial) +
lp_chromatogram(features = precursor, sample_ids = "tryptophan MSn",
ppm = 10, rt_tol = 45) +
lp_purity_overlay(sample_ids = "tryptophan MSn", threshold = 0.8)
FilterFragSpectraParam() sets assign filter settings to spectra by MS
level, mass analyzer, activation type, collision energy or polarity; select
does not discard spectra. Here HCD and CID spectra use different
signal-to-noise thresholds. The purity threshold (plim, default 0.8,
dashed line) applies to each spectrum’s own assessment.
filter_sets <- list(
HCD = FilterFragSpectraParam(select = list(activationType = "HCD"),
snr = 2),
CID = FilterFragSpectraParam(select = list(activationType = "CID"),
snr = 3))
pa <- filterFragSpectra(pa, allfrag = TRUE, msLevel = 2:4,
param = filter_sets)
assessed <- allFragSpectra(pa, legacy = FALSE)
table(msLevel = msLevel(assessed), purityPassed = assessed$purity_pass_flag)
#> purityPassed
#> msLevel FALSE TRUE
#> 2 0 129
#> 3 14 63
#> 4 7 29
boxplot(assessed$inPurity ~ msLevel(assessed), xlab = "MS level",
ylab = "Precursor purity")
abline(h = 0.8, lty = 2)
AverageFragSpectraParam() sets select the spectra to average and can
combine acquisition conditions. Here each activation type is averaged
separately, pooling its collision energies. Averages stay separate by
feature, MS level and precursor path, so a feature has one MS² average per
set and several MS³/MS⁴ averages. Averages whose inputs kept no peaks after
filtering are retained as empty spectra.
average_sets <- list(
HCD = AverageFragSpectraParam(select = list(activationType = "HCD"),
combine = "collisionEnergy", minfrac = 0, ppm = 10),
CID = AverageFragSpectraParam(select = list(activationType = "CID"),
combine = "collisionEnergy", minfrac = 0, ppm = 10))
pa <- averageAllFragSpectra(pa, param = average_sets)
averages <- averagedSpectra(pa, legacy = FALSE)
averages$compound <- names(features)[match(averages$grpid, features)]
table(compound = averages$compound, msLevel = msLevel(averages),
set = averages$msPurityParameterSet)
#> , , set = CID
#>
#> msLevel
#> compound 2 3 4
#> kynurenine 1 8 6
#> tryptophan 1 5 3
#>
#> , , set = HCD
#>
#> msLevel
#> compound 2 3 4
#> kynurenine 1 8 5
#> tryptophan 1 5 3
The averaged HCD MS² spectra of the two standards:
ms2_hcd <- msLevel(averages) == 2L & averages$msPurityParameterSet == "HCD"
trp_hcd <- which(ms2_hcd & averages$compound == "tryptophan")
kyn_hcd <- which(ms2_hcd & averages$compound == "kynurenine")
plotSpectra(averages[c(trp_hcd, kyn_hcd)],
main = c("tryptophan", "kynurenine"))
averageAllFragSpectra() averages all spectra of a feature, regardless of
file. For studies with several files, averageIntraFragSpectra() averages
within each file and averageInterFragSpectra() then averages across
files, using each file’s average once per feature. Both accept the same
parameter sets; they are not run here because each standard has one
MS¹–MS⁴ run.
pa <- averageIntraFragSpectra(pa, param = average_sets)
pa <- averageInterFragSpectra(pa, param = average_sets)
averageMembers() lists the spectra an average selected and whether they
contributed peaks; averagePeakMembers() gives the input peaks behind each
averaged peak.
members <- averageMembers(averages, averages$spectrumId[kyn_hcd])
table(contributes = members$contributes)
#> contributes
#> TRUE
#> 20
Each step records its effective settings, software version and references
to the spectra it read and wrote. Spectra extracted from the object, such
as averages, keep their history.
vapply(processingHistory(pa), `[[`, character(1), "step", USE.NAMES = FALSE)
#> [1] "purityA" "frag4feature" "filterFragSpectra"
#> [4] "averageAllFragSpectra"
processingParameters(pa, "filterFragSpectra")[[1L]][c("plim", "msLevel")]
#> $plim
#> [1] 0.8
#>
#> $msLevel
#> [1] 2 3 4
MsBackendParquet’s mzMLToParquet() converts the four raw runs into a
study dataset; purityA() also accepts a Spectra object on this dataset
in place of the mzML files. createDatabase(format = "parquet") writes the
MS²–MS⁴ results, including feature links, filter flags, averages and their
members, linked to the study. The reader functions reopen them by feature,
MS level, averaging method ("all", "intra" or "inter") or run.
study <- file.path(tempdir(), "standards-study")
MsBackendParquet::mzMLToParquet(files, path = study, verbose = FALSE)
results <- createDatabase(pa, xe, outDir = tempdir(),
dbName = "standards.parquet", format = "parquet", study = study)
info <- processedSpectrumInfo(results)
table(method = info$method, msLevel = info$ms_level)
#> msLevel
#> method 2 3 4
#> all 4 26 17
stored <- readProcessedSpectra(results, msLevel = 2L)
provenance <- readProcessedProvenance(results, msLevel = 2L)
A Mass Spectral Tree follows the parent scans recorded by the instrument. The plot shows one tryptophan MS² scan with its MS³ and MS⁴ descendants, labelled with their precursor m/z.
scans <- massSpectralTrees(raw)
ms2_nodes <- subset(scans$nodes,
msLevel == 2L & compound(run_id) == "tryptophan")
children <- table(scans$edges$parentLineageScanId)
start <- ms2_nodes$lineageScanId[which.max(children[ms2_nodes$lineageScanId])]
branch <- subsetTree(scans, node = start, mode = "out")
plot(branch, main = "Tryptophan MS² scan and its descendants",
labels = with(branch$nodes, sprintf("MS%d\n%.4f", msLevel, precursorMz)),
vertex.label.degree = pi / 2, vertex.label.dist = 2.5)
A Precursor–Fragment Tree links each precursor peak to the fragment peaks of the spectrum it was isolated for. Both [M+H]⁺ ions have fragments 17.0265 Da lower, consistent with a loss of NH₃; the mass difference alone does not identify the lost species.
links <- fragmentLinks(precursorFragmentTrees(raw))
nh3 <- subset(links, abs(delta_mz - 17.026549) <= 0.002)
table(compound = compound(nh3$run_id), precursor = round(nh3$precursor_mz, 3))
#> precursor
#> compound 159.092 191.082 205.097 209.092
#> kynurenine 0 1 0 37
#> tryptophan 1 0 61 0
See vignette("measured-spectral-trees", package = "msPurity") for
traversal, plotting and GraphML export.
spectralMatching() accepts measured and consensus MS²–MS⁴ Spectra.
Before reading peaks, each pair is checked for MS level, precursor m/z,
acquisition conditions and available parent paths (scoreSpectrumPair()
reports this check for a single pair). Here every linked spectrum is
compared with the averages of both standards.
res <- spectralMatching(linked, averages)
table(status = res$queryStatus$status, msLevel = msLevel(linked))
#> msLevel
#> status 2 3 4
#> no_eligible_reference 0 7 10
#> scored 51 25 8
hits <- res$matchedResults
table(query = compound(dataOrigin(linked))[hits$queryIndex],
reference = averages$compound[hits$referenceIndex])
#> reference
#> query kynurenine tryptophan
#> kynurenine 67 0
#> tryptophan 0 25
head(hits[, c("msLevel", "reason", "dpc", "rank", "sharedMeasurement")])
#> msLevel reason dpc rank sharedMeasurement
#> 1 2 compatible_partial 0.8433496 1 TRUE
#> 2 2 compatible_partial 0.9230976 1 TRUE
#> 3 2 compatible_partial 0.8686837 1 TRUE
#> 4 2 compatible_partial 0.7471476 1 TRUE
#> 5 2 compatible_partial 0.6655501 1 TRUE
#> 6 2 compatible_partial 0.5475385 1 TRUE
Each spectrum is scored only against averages of its own standard and
activation type. sharedMeasurement reports that the measured spectrum
contributed to the average. queryStatus gives the outcome for every
query, including those without a compatible reference. The mirror plot
compares the best-scoring measured kynurenine MS² spectrum with its HCD
average, each scaled to its base peak.
best <- subset(hits, referenceIndex == kyn_hcd)
best <- best[which.max(best$dpc), ]
plotSpectraMirror(scalePeaks(linked[best$queryIndex], by = max),
scalePeaks(averages[kyn_hcd], by = max), ppm = 10,
main = sprintf("Measured (top) and averaged (bottom): dpc %.2f",
best$dpc))
BlinkMatchingParam() scores with BLINK instead of the dot-product
cosines, and the Parquet results can serve as the reference:
blink <- spectralMatching(linked[msLevel(linked) == 2L], results,
param = BlinkMatchingParam())
head(blink$matchedResults[, c("msLevel", "blinkCosine",
"blinkMatchingIonCount")])
#> msLevel blinkCosine blinkMatchingIonCount
#> 1 2 0.6721850 14
#> 2 2 0.8147947 19
#> 3 2 0.8539018 21
#> 4 2 0.8928427 35
#> 5 2 0.8801984 36
#> 6 2 0.8199492 43
Parquet results can also be searched against spectral libraries, including
Spectra libraries read through other backends; see ?spectralMatching.
sessionInfo()
#> R version 4.6.1 (2026-06-24)
#> Platform: x86_64-pc-linux-gnu
#> Running under: Ubuntu 24.04.5 LTS
#>
#> Matrix products: default
#> BLAS: /home/biocbuild/bbs-3.24-bioc/R/lib/libRblas.so
#> LAPACK: /usr/lib/x86_64-linux-gnu/lapack/liblapack.so.3.12.0 LAPACK version 3.12.0
#>
#> locale:
#> [1] LC_CTYPE=en_US.UTF-8 LC_NUMERIC=C
#> [3] LC_TIME=en_GB LC_COLLATE=C
#> [5] LC_MONETARY=en_US.UTF-8 LC_MESSAGES=en_US.UTF-8
#> [7] LC_PAPER=en_US.UTF-8 LC_NAME=C
#> [9] LC_ADDRESS=C LC_TELEPHONE=C
#> [11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C
#>
#> time zone: America/New_York
#> tzcode source: system (glibc)
#>
#> attached base packages:
#> [1] stats4 stats graphics grDevices utils datasets methods
#> [8] base
#>
#> other attached packages:
#> [1] lcmsPlot_1.2.0 MsExperiment_1.16.0 ProtGenerics_1.46.0
#> [4] MsBackendParquet_1.0.0 xcms_4.12.0 BiocStyle_2.42.0
#> [7] Spectra_1.24.0 BiocParallel_1.48.0 S4Vectors_0.52.0
#> [10] BiocGenerics_0.60.0 generics_0.1.4 msPurity_2.0.0
#> [13] Rcpp_1.1.2
#>
#> loaded via a namespace (and not attached):
#> [1] RColorBrewer_1.1-3 jsonlite_2.0.0
#> [3] MultiAssayExperiment_1.40.0 magrittr_2.0.5
#> [5] magick_2.9.1 farver_2.1.2
#> [7] MALDIquant_1.22.3 rmarkdown_2.32
#> [9] fs_2.1.0 vctrs_0.7.3
#> [11] tinytex_0.61 htmltools_0.5.9
#> [13] S4Arrays_1.14.0 progress_1.2.3
#> [15] SparseArray_1.14.0 mzID_1.52.0
#> [17] sass_0.5.0 bslib_0.12.0
#> [19] plyr_1.8.9 impute_1.88.0
#> [21] cachem_1.1.0 igraph_2.3.4
#> [23] lifecycle_1.0.5 iterators_1.0.14
#> [25] pkgconfig_2.0.3 Matrix_1.7-6
#> [27] R6_2.6.1 fastmap_1.2.0
#> [29] MatrixGenerics_1.26.0 clue_0.3-68
#> [31] digest_0.6.39 ggnewscale_0.5.2
#> [33] pcaMethods_2.6.0 patchwork_1.3.2
#> [35] GenomicRanges_1.66.0 labeling_0.4.3
#> [37] abind_1.4-8 compiler_4.6.1
#> [39] bit64_4.8.6 withr_3.0.3
#> [41] doParallel_1.0.17 S7_1.0.0
#> [43] PTMods_1.2.0 rawrr_1.22.0
#> [45] DBI_1.3.0 Chromatograms_1.4.0
#> [47] duckdb_2.0.1 MASS_7.3-66
#> [49] DelayedArray_0.40.0 mzR_2.48.0
#> [51] tools_4.6.1 PSMatch_1.18.0
#> [53] otel_0.3.0 glue_1.8.1
#> [55] QFeatures_1.24.0 grid_4.6.1
#> [57] cluster_2.1.8.3 reshape2_1.4.5
#> [59] snow_0.4-4 gtable_0.3.6
#> [61] preprocessCore_1.76.0 tidyr_1.3.2
#> [63] data.table_1.18.6.1 hms_1.1.4
#> [65] MetaboCoreUtils_1.22.0 XVector_0.54.0
#> [67] foreach_1.5.2 pillar_1.11.1
#> [69] stringr_1.6.0 limma_4.0.0
#> [71] dplyr_1.2.1 lattice_0.23-1
#> [73] bit_4.6.0 tidyselect_1.2.1
#> [75] knitr_1.52 bookdown_0.48
#> [77] IRanges_2.48.0 Seqinfo_1.4.0
#> [79] SummarizedExperiment_1.44.0 xfun_0.62
#> [81] Biobase_2.74.0 statmod_1.5.2
#> [83] MSnbase_2.40.0 matrixStats_1.5.0
#> [85] stringi_1.8.9 lazyeval_0.2.3
#> [87] yaml_2.3.12 evaluate_1.0.5
#> [89] codetools_0.2-20 MsCoreUtils_1.26.0
#> [91] tibble_3.3.1 BiocManager_1.30.27
#> [93] cli_3.6.6 affyio_1.84.0
#> [95] arrow_26.0.1.1 jquerylib_0.1.4
#> [97] dichromat_2.0-1 MassSpecWavelet_1.80.0
#> [99] doSNOW_1.0.20 dbplyr_2.6.0
#> [101] fastcluster_1.3.0 XML_3.99-0.25
#> [103] parallel_4.6.1 ggplot2_4.0.4
#> [105] assertthat_0.2.1 prettyunits_1.2.0
#> [107] AnnotationFilter_1.38.0 MsFeatures_1.22.0
#> [109] scales_1.4.0 affy_1.92.0
#> [111] ncdf4_1.24 purrr_1.2.2
#> [113] crayon_1.5.3 rlang_1.3.0
#> [115] vsn_3.82.0