LC-MSⁿ data exploration, processing and spectral matching: chemical standards L-tryptophan and L-kynurenine

Introduction

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.

Explore the data

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

Detect features with xcms

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")

Filter and average by acquisition condition

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

Processing history

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

Store and reopen results in Parquet

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)

Explore spectral trees

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.

Compare spectra

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.

Session information

sessionInfo()
#> R version 4.6.2 (2026-10-29)
#> Platform: x86_64-pc-linux-gnu
#> Running under: Ubuntu 26.04.1 LTS
#> 
#> Matrix products: default
#> BLAS:   /usr/lib/x86_64-linux-gnu/openblas-pthread/libblas.so.3 
#> LAPACK: /usr/lib/x86_64-linux-gnu/openblas-pthread/libopenblasp-r0.3.32.so;  LAPACK version 3.12.0
#> 
#> locale:
#>  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
#>  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
#>  [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: Etc/UTC
#> tzcode source: system (glibc)
#> 
#> attached base packages:
#> [1] stats4    stats     graphics  grDevices utils     datasets  methods  
#> [8] base     
#> 
#> other attached packages:
#>  [1] lcmsPlot_1.1.29          MsExperiment_1.15.0      ProtGenerics_1.45.0     
#>  [4] MsBackendParquet_0.99.12 xcms_4.11.5              BiocStyle_2.41.0        
#>  [7] Spectra_1.23.7           BiocParallel_1.47.0      S4Vectors_0.51.10       
#> [10] BiocGenerics_0.59.13     generics_0.1.4           msPurity_2.1.0          
#> [13] Rcpp_1.1.2               rmarkdown_2.32          
#> 
#> loaded via a namespace (and not attached):
#>   [1] DBI_1.3.0                   rlang_1.3.0                
#>   [3] magrittr_2.0.5              clue_0.3-68                
#>   [5] MassSpecWavelet_1.81.0      otel_0.3.0                 
#>   [7] matrixStats_1.5.0           compiler_4.6.2             
#>   [9] PTMods_1.1.2                vctrs_0.7.3                
#>  [11] reshape2_1.4.5              stringr_1.6.0              
#>  [13] crayon_1.5.3                pkgconfig_2.0.3            
#>  [15] MetaboCoreUtils_1.21.2      fastmap_1.2.0              
#>  [17] dbplyr_2.6.0                XVector_0.53.0             
#>  [19] labeling_0.4.3              preprocessCore_1.75.3      
#>  [21] bit_4.6.0                   purrr_1.2.2                
#>  [23] xfun_0.62                   MultiAssayExperiment_1.39.1
#>  [25] cachem_1.1.0                jsonlite_2.0.0             
#>  [27] progress_1.2.3              DelayedArray_0.39.8        
#>  [29] prettyunits_1.2.0           parallel_4.6.2             
#>  [31] cluster_2.1.8.3             R6_2.6.1                   
#>  [33] bslib_0.12.0                stringi_1.8.9              
#>  [35] RColorBrewer_1.1-3          limma_3.99.5               
#>  [37] GenomicRanges_1.67.0        jquerylib_0.1.4            
#>  [39] assertthat_0.2.1            Seqinfo_1.3.2              
#>  [41] SummarizedExperiment_1.43.0 iterators_1.0.14           
#>  [43] knitr_1.52                  snow_0.4-4                 
#>  [45] IRanges_2.47.5              Matrix_1.7-6               
#>  [47] igraph_2.3.4                tidyselect_1.2.1           
#>  [49] abind_1.4-8                 yaml_2.3.12                
#>  [51] doParallel_1.0.17           affy_1.91.0                
#>  [53] codetools_0.2-20            lattice_0.23-1             
#>  [55] tibble_3.3.1                plyr_1.8.9                 
#>  [57] withr_3.0.3                 Biobase_2.73.2             
#>  [59] S7_1.0.0                    evaluate_1.0.5             
#>  [61] affyio_1.83.1               pillar_1.11.1              
#>  [63] BiocManager_1.30.27         MatrixGenerics_1.25.0      
#>  [65] foreach_1.5.2               MSnbase_2.39.6             
#>  [67] MALDIquant_1.22.3           ncdf4_1.24                 
#>  [69] hms_1.1.4                   ggplot2_4.0.4              
#>  [71] scales_1.4.0                glue_1.8.1                 
#>  [73] MsFeatures_1.21.0           lazyeval_0.2.3             
#>  [75] maketools_1.3.2             tools_4.6.2                
#>  [77] mzID_1.51.0                 sys_3.4.3                  
#>  [79] data.table_1.18.6.1         vsn_3.81.1                 
#>  [81] QFeatures_1.23.3            mzR_2.47.2                 
#>  [83] XML_3.99-0.25               buildtools_1.0.0           
#>  [85] fs_2.1.0                    fastcluster_1.3.0          
#>  [87] grid_4.6.2                  impute_1.87.0              
#>  [89] tidyr_1.3.2                 MsCoreUtils_1.25.4         
#>  [91] patchwork_1.3.2             duckdb_2.0.0               
#>  [93] PSMatch_1.17.5              cli_3.6.6                  
#>  [95] S4Arrays_1.13.3             arrow_26.0.1.1             
#>  [97] Chromatograms_1.3.5         dplyr_1.2.1                
#>  [99] AnnotationFilter_1.37.0     doSNOW_1.0.20              
#> [101] pcaMethods_2.5.0            gtable_0.3.6               
#> [103] sass_0.5.0                  digest_0.6.39              
#> [105] SparseArray_1.13.5          farver_2.1.2               
#> [107] htmltools_0.5.9             lifecycle_1.0.5            
#> [109] statmod_1.5.2               bit64_4.8.6                
#> [111] MASS_7.3-66

References

Lawson, Thomas Nigel, Ralf J. M. Weber, Martin R. Jones, et al. 2017. “msPurity: Automated Evaluation of Precursor Ion Purity for Mass Spectrometry Based Fragmentation in Metabolomics.” Analytical Chemistry, acs.analchem.6b04358. https://doi.org/10.1021/acs.analchem.6b04358.