| Title: | Tools for LC-MSn-Based Metabolomics: Precursor Ion Purity Assessment, Fragmentation Data and Spectral Tree Processing, and Spectral Matching |
|---|---|
| Description: | Provides tools for precursor ion purity assessment, processing fragmentation data and spectral trees, and spectral matching in LC-MSn-based metabolomics. Precursor ion purity estimates the contribution of a selected precursor to the signal within its isolation window, using neighbouring MS1 measurements for MS2 and linked parent fragmentation spectra for higher MSn levels. Fragmentation spectra can be associated with chromatographic features, filtered and averaged using acquisition-aware settings. Mass Spectral Trees link successive fragmentation spectra, while Precursor-Fragment Trees connect individual precursor and product peaks. Spectral matching compares measured or consensus spectra with experimental spectra and reference libraries, accounting for MS level, precursor relationships and acquisition conditions. The optional BLINK method computes approximate cosine similarity as described by Harwood et al. (2023) <doi:10.1038/s41598-023-40496-9>. Integration with 'Spectra' and 'xcms' connects spectrum handling and chromatographic feature information. Parquet datasets link raw measurements, processed spectra and reference libraries, retaining feature associations, processing settings and measurement provenance. Reusable parameter objects and recorded processing history support reproducible analysis and reopening of processed results. Spectrum selection, linked visualisation, library import and export, and reporting of feature information and spectral matches support downstream interpretation and data exchange. |
| Authors: | Thomas N. Lawson [aut] (ORCID: <https://orcid.org/0000-0002-5915-7980>), Ossama Edbali [aut, cre] (ORCID: <https://orcid.org/0000-0003-0132-8668>), Ralf Weber [aut, ths] (ORCID: <https://orcid.org/0000-0002-8796-4771>), Martin Jones [ctb], Julien Saint-Vanne [ctb], Andris Jankevics [ctb], Mark Viant [ths], Warwick Dunn [ths] |
| Maintainer: | Ossama Edbali <[email protected]> |
| License: | GPL-3 + file LICENSE |
| Version: | 2.1.0 |
| Built: | 2026-11-24 04:33:26 UTC |
| Source: | https://github.com/bioc/msPurity |
Use the node and edge tables of a scan or precursor-fragment tree to create a directed graph, draw it or export it as GraphML.
as_igraph(x, structure = NULL) writeGraphML( x, file, structure = NULL, overwrite = FALSE, max_nodes = 2000L, max_edges = 5000L ) ## S3 method for class 'MassSpectralTrees' plot(x, ..., structure = NULL, labels = NULL) ## S3 method for class 'PrecursorFragmentTrees' plot(x, ..., structure = NULL, labels = NULL) ## S3 method for class 'SpectralTree' plot(x, ..., structure = NULL, labels = NULL)as_igraph(x, structure = NULL) writeGraphML( x, file, structure = NULL, overwrite = FALSE, max_nodes = 2000L, max_edges = 5000L ) ## S3 method for class 'MassSpectralTrees' plot(x, ..., structure = NULL, labels = NULL) ## S3 method for class 'PrecursorFragmentTrees' plot(x, ..., structure = NULL, labels = NULL) ## S3 method for class 'SpectralTree' plot(x, ..., structure = NULL, labels = NULL)
x |
A |
structure |
Optional |
file |
GraphML output path in an existing directory. |
overwrite |
Whether to replace an existing file after export succeeds. |
max_nodes, max_edges
|
Maximum numbers of vertices and edges to export. Increase these limits for larger trees. |
... |
Additional igraph plotting arguments, such as |
labels |
Optional character vector in node order. A single |
Vertex names are the scan lineage IDs or the stored node IDs of the selected view. Each peak occurrence has its own vertex. All node and edge columns are retained as attributes, including the endpoints and relationship types. Edges follow the direction recorded in the tables. Isolated nodes and empty results are retained.
A node annotation named name is stored as annotation_name because
igraph reserves name for vertex identities. Having both annotation
columns is an error.
GraphML stores scalar text, logical and numeric attributes.
Factors are exported as text. An attribute with missing values has a
companion logical flag. The graph attribute
SpectralTrees_missing_json maps attributes to their flags for
vertices and edges. SpectralTrees_metadata_json contains the
selected tree's metadata. Text and attribute names are written as UTF-8.
Square vertices identify nodes marked as context, reference only or unmeasured in the input. A dashed arrow marks a recorded reference or a context edge. The plot uses a neutral grey palette.
as_igraph() returns a directed igraph with graph attribute
structure set to "MST" or "PFT". The plot methods return the
displayed graph invisibly. writeGraphML() returns the output path
invisibly.
if (requireNamespace("igraph", quietly = TRUE)) { data <- S4Vectors::DataFrame( spectrumId = c("scan=2", "scan=3"), dataOrigin = "example.mzML", msLevel = c(2L, 3L), acquisitionNum = c(2L, 3L), scanIndex = c(1L, 2L), precScanNum = c(NA_integer_, 2L), rtime = c(1, 2), precursorMz = c(500, 150)) data$mz <- list(150, 75) data$intensity <- list(10, 5) spectra <- Spectra::Spectra(data, source = Spectra::MsBackendMemory()) trees <- massSpectralTrees(spectra, parentReference = "acquisitionNum") graph <- as_igraph(trees) igraph::as_data_frame(graph, what = "edges") plot(trees) path <- tempfile(fileext = ".graphml") writeGraphML(trees, path) restored <- igraph::read_graph(path, format = "graphml") igraph::V(restored)$lineageScanId unlink(path) }if (requireNamespace("igraph", quietly = TRUE)) { data <- S4Vectors::DataFrame( spectrumId = c("scan=2", "scan=3"), dataOrigin = "example.mzML", msLevel = c(2L, 3L), acquisitionNum = c(2L, 3L), scanIndex = c(1L, 2L), precScanNum = c(NA_integer_, 2L), rtime = c(1, 2), precursorMz = c(500, 150)) data$mz <- list(150, 75) data$intensity <- list(10, 5) spectra <- Spectra::Spectra(data, source = Spectra::MsBackendMemory()) trees <- massSpectralTrees(spectra, parentReference = "acquisitionNum") graph <- as_igraph(trees) igraph::as_data_frame(graph, what = "edges") plot(trees) path <- tempfile(fileext = ".graphml") writeGraphML(trees, path) restored <- igraph::read_graph(path, format = "graphml") igraph::V(restored)$lineageScanId unlink(path) }
Given a filepath to an mzML file the precursor purity for any MS/MS scans will be outputed into a dataframe
assessPuritySingle( filepth, fileid = NA, mostIntense = FALSE, nearest = TRUE, offsets = NA, cores = 1, plotP = FALSE, plotdir = NULL, interpol = "linear", iwNorm = FALSE, iwNormFun = NULL, ilim = 0, mzRback = "pwiz", isotopes = TRUE, im = NULL, ppmInterp = 7 )assessPuritySingle( filepth, fileid = NA, mostIntense = FALSE, nearest = TRUE, offsets = NA, cores = 1, plotP = FALSE, plotdir = NULL, interpol = "linear", iwNorm = FALSE, iwNormFun = NULL, ilim = 0, mzRback = "pwiz", isotopes = TRUE, im = NULL, ppmInterp = 7 )
filepth |
character; mzML file path for MS/MS spectra |
fileid |
numeric; adds a fileid column (primarily for internal use for msPurity) |
mostIntense |
boolean; True if the most intense peak is used for calculation. False if the centered peak is used |
nearest |
logical; TRUE uses the nearest usable MS1 on either side. FALSE requires the reported preceding reference. Missing permitted measurements produce NA purity; a later measurement is not substituted. |
offsets |
numeric; Two nonnegative lower and upper offsets in Da, with positive total width. Explicit offsets set a window around the selected precursor m/z. NA uses each event's recorded absolute bounds. A selected precursor outside those bounds has unavailable purity. |
cores |
numeric; Number of cores to use |
plotP |
boolean; If TRUE a plot of the purity is to be saved |
plotdir |
vector; If plotP is TRUE plots will be saved to this directory |
interpol |
character; Type of interolation to be performed "linear", "spline" or "none" |
iwNorm |
boolean; If TRUE then the intensity of the isolation window will be normalised based on the iwNormFun function |
iwNormFun |
function; Receives m/z offsets from the isolation-window midpoint and returns intensity weights. The default Gaussian accounts for edge effects and spans the resolved isolation bounds. Caller functions are used without shifting or rescaling. |
ilim |
numeric; All peaks less than this percentage of the target peak will be removed from the purity calculation, default is 5% (0.05) |
mzRback |
character; deprecated and ignored. Raw data is read through Spectra, which uses the pwiz reader |
isotopes |
boolean; TRUE if isotopes are to be removed |
im |
matrix; Isotope matrix, default removes C13 isotopes (single, double and triple bonds) |
ppmInterp |
numeric; Set the ppm tolerance for the precursor ion purity interpolation. i.e. the ppm tolerence between the precursor ion found in the neighbouring scans. |
a dataframe of the purity score of the ms/ms spectra
filepth <- system.file("extdata", "lcms", "mzML", "LCMSMS_1.mzML", package="msPurityData") puritydf <- assessPuritySingle(filepth)filepth <- system.file("extdata", "lcms", "mzML", "LCMSMS_1.mzML", package="msPurityData") puritydf <- assessPuritySingle(filepth)
General
Average and filter fragmentation spectra for each XCMS feature within and across MS data files (ignoring intra and inter relationships).
The averaging is performed using hierarchical clustering of the m/z values of each peaks, where m/z values within a set ppm tolerance will be clustered. The clustered peaks are then averaged (or summed).
With param, the tolerance can also include an absolute part (see
AverageFragSpectraParam).
The fragmentation can be filtered on the averaged spectra (with the arguments snr, rsd, minfrac, ra)
Example LC-MS/MS processing workflow
Purity assessments
(mzML files) -> purityA -> (pa)
XCMS processing
(mzML files) -> xcms.findChromPeaks -> (optionally) xcms.adjustRtime -> xcms.groupChromPeaks -> (xcmsObj)
— Older versions of XCMS — (mzML files) -> xcms.xcmsSet -> xcms.group -> xcms.retcor -> xcms.group -> (xcmsObj)
Fragmentation processing
(xcmsObj, pa) -> frag4feature -> filterFragSpectra -> averageAllFragSpectra -> createDatabase -> spectralMatching -> (sqlite spectral database)
Averaging with parameter objects
With param, each parameter set averages the feature-linked MS2, MS3
and MS4 spectra it selects and keeps incompatible acquisition conditions and
precursor paths apart (see AverageFragSpectraParam), so a
feature can have several averaged spectra. The settings come from the
parameter objects: an explicitly supplied minfrac, minnum,
ppm, snr, ra, av or sumi must agree
with them. rmp and cores apply to the whole call.
These averages are available from averagedSpectra(pa, legacy = FALSE).
Each records its parameter set (msPurityParameterSet; a single
object is named "default") and its group within the feature
(msPurityAverageGroup, "<set>/<number>"). With
rmp = FALSE, output peaks include a pass_flag column:
1 for peaks passing the averaging thresholds and 0 for
failed peaks. Retrieve it with Spectra::peaksData(s,
columns = c("mz", "intensity", "pass_flag")), where s is the
averaged Spectra object. With rmp = TRUE, failed peaks are removed.
Empty peak arrays indicate that no output peaks are stored.
Each averaged spectrum has an object-local character spectrumId. Use it with
averageMembers to inspect selected inputs and
averagePeakMembers to trace stored peaks. Measured spectra
keep their existing spectrum identifiers. Use msPurityProcessingId
to retrieve the result's processing record with
processingHistory. In the returned Spectra,
msPurityContributors lists original occurrences supporting stored
peaks, and msPurityClusterContributors maps clusters to those
occurrences. The
acquisition summaries, precursor m/z, retention time and
msPurityPrecursorPath (MS3 and MS4 precursor m/z) describe the
contributing spectra; msPurityAncestorConditions gives the
acquisition conditions of the earlier stages of MS3 and MS4 averages.
A feature linked to the same spectrum more than once contributes it once
per link, as without param.
The legacy list returned by averagedSpectra(pa), createMSP()
with averaged spectra and createDatabase() hold one average per
feature, level and file; they stop with an error while averages computed
with param are present. For MS2-only feature links, averaging again
without param replaces them; averaging without param does not
support MS3/MS4 feature links. Averaging without param stops with an
error while averages computed with param remain at another level.
averageIntraFragSpectra() and averageInterFragSpectra() accept
param in the same way.
## S4 method for signature 'purityA' averageAllFragSpectra( pa, minfrac = 0.5, minnum = 1, ppm = 5, snr = 0, ra = 0, av = "median", sumi = TRUE, rmp = FALSE, cores = 1, blockSize = 5000L, param = NULL )## S4 method for signature 'purityA' averageAllFragSpectra( pa, minfrac = 0.5, minnum = 1, ppm = 5, snr = 0, ra = 0, av = "median", sumi = TRUE, rmp = FALSE, cores = 1, blockSize = 5000L, param = NULL )
pa |
object; purityA object |
minfrac |
numeric;minimum ratio of the peak fraction (peak count / total peaks) across all (ignoring intra and inter relationships) |
minnum |
numeric; minimum number of times peak is present across all fragmentation spectra (ignoring intra and inter relationships) |
ppm |
numeric; ppm threshold to average across all scans (ignoring intra and inter relationships) |
snr |
numeric; minimum signal-to-noise of the peak across all (ignoring intra and inter relationships) |
ra |
numeric; minimum relative abundance of the peak fraction across all (ignoring intra and inter relationships) |
av |
character; type of averaging to use (median or mean) |
sumi |
boolean; TRUE if the intensity for each peak is summed across averaged spectra |
rmp |
boolean; TRUE if peaks are to be removed that do not meet the threshold criteria. Otherwise they will just be flagged |
cores |
Maximum number of workers; defaults to |
blockSize |
numeric; Maximum input peak rows per hierarchical-clustering calculation, as a positive integer (default 5,000). Safe blocks can be smaller; larger groups fitting one tolerance window need no distance matrix. Used only for hierarchical clustering; distance-matrix memory grows quadratically with this limit. |
param |
NULL, one |
With hierarchical clustering, matching peaks stay together. The call stops
with an error if more than blockSize nearby peaks cannot form one group or be
separated without splitting matching peaks.
Returns a purityA object (pa) with the following slots now with data
pa@avSpectra: the averaged spectra as a Spectra object, one spectrum per grouped feature, averaging
level and file, with the averaging statistics as peak variables. With param, a feature can have
several all-spectrum averages, one per parameter set and group.
pa@av_spectra: the legacy list of averaged spectra, filled while options(msPurity.legacySlots = TRUE).
E.g. averagedSpectra(pa)$1$av_all gives the average spectra for grouped feature 1. Averages computed with
param are stored only in pa@avSpectra.
pa@av_all_params: The parameters used are recorded here
Each averaged spectrum in the legacy list contains the following columns (peak variables in pa@avSpectra):
cl: id of clustered (averaged) peak
mz: average m/z
i: average intensity
snr: average signal to noise ratio
rsd: relative standard deviation
count: number of clustered peaks
total: total number of potential scans to be used for averaging
inPurity: average precursor ion purity
ra: average relative abundance
frac: the fraction of clustered peaks (e.g. the count/total)
snr_pass_flag: TRUE if snr threshold criteria met
minfrac_pass_flag: TRUE if minfrac threshold criteria
ra_pass_flag: TRUE if ra threshold criteria met
pass_flag: TRUE if all threshold criteria met
#====== XCMS =================================== ## Read in MS data #msmsPths <- list.files(system.file("extdata", "lcms", "mzML", # package="msPurityData"), full.names = TRUE, pattern = "MSMS") #ms_data = readMSData(msmsPths, mode = 'onDisk', msLevel. = 1) ## Find peaks in each file #cwp <- CentWaveParam(snthresh = 5, noise = 100, ppm = 10, peakwidth = c(3, 30)) #xcmsObj <- xcms::findChromPeaks(ms_data, param = cwp) ## Optionally adjust retention time #xcmsObj <- adjustRtime(xcmsObj , param = ObiwarpParam(binSize = 0.6)) ## Group features across samples #pdp <- PeakDensityParam(sampleGroups = c(1, 1), minFraction = 0, bw = 30) #xcmsObj <- groupChromPeaks(xcmsObj , param = pdp) #====== msPurity ================================ #pa <- purityA(msmsPths) #pa <- frag4feature(pa, xcmsObj) #pa <- filterFragSpectra(pa) #pa <- averageAllFragSpectra(pa) ## Run from previously generated data pa <- readRDS(system.file("extdata", "tests", "purityA", "3_filterFragSpectra_pa.rds", package="msPurity")) pa <- averageAllFragSpectra(pa) ## Keep activation types apart while combining collision energies pa_param <- averageAllFragSpectra(pa, param = AverageFragSpectraParam(combine = "collisionEnergy")) sp <- averagedSpectra(pa_param, legacy = FALSE) i <- 1L averageMembers(pa_param, sp$spectrumId[i]) sp$msPurityContributors[[i]] sp$msPurityClusterContributors[[i]]#====== XCMS =================================== ## Read in MS data #msmsPths <- list.files(system.file("extdata", "lcms", "mzML", # package="msPurityData"), full.names = TRUE, pattern = "MSMS") #ms_data = readMSData(msmsPths, mode = 'onDisk', msLevel. = 1) ## Find peaks in each file #cwp <- CentWaveParam(snthresh = 5, noise = 100, ppm = 10, peakwidth = c(3, 30)) #xcmsObj <- xcms::findChromPeaks(ms_data, param = cwp) ## Optionally adjust retention time #xcmsObj <- adjustRtime(xcmsObj , param = ObiwarpParam(binSize = 0.6)) ## Group features across samples #pdp <- PeakDensityParam(sampleGroups = c(1, 1), minFraction = 0, bw = 30) #xcmsObj <- groupChromPeaks(xcmsObj , param = pdp) #====== msPurity ================================ #pa <- purityA(msmsPths) #pa <- frag4feature(pa, xcmsObj) #pa <- filterFragSpectra(pa) #pa <- averageAllFragSpectra(pa) ## Run from previously generated data pa <- readRDS(system.file("extdata", "tests", "purityA", "3_filterFragSpectra_pa.rds", package="msPurity")) pa <- averageAllFragSpectra(pa) ## Keep activation types apart while combining collision energies pa_param <- averageAllFragSpectra(pa, param = AverageFragSpectraParam(combine = "collisionEnergy")) sp <- averagedSpectra(pa_param, legacy = FALSE) i <- 1L averageMembers(pa_param, sp$spectrumId[i]) sp$msPurityContributors[[i]] sp$msPurityClusterContributors[[i]]
AverageFragSpectraParam holds one complete set of settings for
averageAllFragSpectra, averageIntraFragSpectra
and averageInterFragSpectra. With a parameter object, averaging
keeps acquisition conditions and MS3/MS4 precursor paths apart, so that one
feature can have several averaged spectra.
AverageFragSpectraParam( select = list(), combine = character(), minfrac = 0.5, minnum = 1, ppm = 5, tolerance = 0, snr = 0, ra = 0, av = "median", sumi = TRUE ) ## S4 method for signature 'AverageFragSpectraParam' as.list(x, ...)AverageFragSpectraParam( select = list(), combine = character(), minfrac = 0.5, minnum = 1, ppm = 5, tolerance = 0, snr = 0, ra = 0, av = "median", sumi = TRUE ) ## S4 method for signature 'AverageFragSpectraParam' as.list(x, ...)
select |
named list of acquisition selectors, as for
|
combine |
character; any of |
minfrac |
numeric; minimum ratio of the number of clustered peaks to the number of averaged spectra that have eligible peaks. |
minnum |
numeric; minimum number of clustered peaks. |
ppm |
numeric; relative m/z tolerance in ppm for fragment peaks and
MS3/MS4 precursors, added to |
tolerance |
numeric; absolute m/z tolerance for fragment peaks and
MS3/MS4 precursors, added to the |
snr |
numeric; minimum signal-to-noise ratio of an averaged peak. |
ra |
numeric; minimum relative abundance of an averaged peak. |
av |
character; |
sumi |
logical; sum, rather than average, the peak intensities. |
x |
An averaging parameter object. |
... |
Ignored. |
select chooses the feature-linked spectra this set averages, using
the acquisition fields and matching rules of
FilterFragSpectraParam: all named fields must match, any listed
value of a field matches, and NA matches an unknown value. Spectra
that no set selects are not averaged, and sets may select the same spectra.
An empty select selects every feature-linked spectrum.
Spectra are averaged together only when they belong to the same feature and
MS level and share mass analyzer, scan-filter analyzer, activation type,
collision energy, energy unit and polarity. Activation types are compared
as for select, so names and accessions of one method match.
combine allows the activation type and/or collision energy of the
averaged stage to differ. It never relaxes the conditions of earlier stages:
MS3 and MS4 spectra are averaged together only when every earlier stage of
their precursor paths was acquired under the same conditions. Unknown values
match only unknown values.
Two m/z values agree when they differ by at most
tolerance + ppm * mz / 1e6, where mz is their mean; the
absolute and relative parts add, as for MsCoreUtils::closest(). Each
averaged peak combines fragment peaks that all agree with one another. For
MS3 and MS4 spectra, the precursor m/z of each stage after MS2 must also
agree, for every pair of spectra in an average, so that a chain of small
differences cannot join two distant precursors. Repeated selections of one
precursor that differ by more than this tolerance form separate averages.
The MS2 precursor is not compared again: the association with the feature,
made by frag4feature, already decided it. Spectra are assigned
in order of file, scan number and feature link, each to the first
compatible average.
Ion-trap m/z values vary by a similar absolute amount across the m/z range,
so a separate parameter set for ion-trap spectra, selected with
scanFilterAnalyzer = "ITMS" or massAnalyzer, can use
tolerance (for example 0.2 to 0.5) with ppm = 0. Parameter
sets selected by MS level or collision energy can likewise use their own
tolerances. A wide tolerance can join two peaks of the same spectrum into
one averaged peak; both then count towards minnum and
minfrac, and sumi adds both intensities.
The other settings have the meaning of the corresponding arguments of
averageAllFragSpectra. A single object passed as
param is recorded under the parameter-set name "default"; a
named list uses its names.
An AverageFragSpectraParam object. as.list() returns
its complete settings as a named list.
averageAllFragSpectra,
FilterFragSpectraParam
param <- AverageFragSpectraParam(select = list(msLevel = 3L), combine = "collisionEnergy", sumi = FALSE) as.list(param) alternatives <- list( hcd = AverageFragSpectraParam(select = list(activationType = "HCD")), cid = AverageFragSpectraParam(select = list(activationType = "CID"))) ## FTMS (for example Orbitrap) spectra with a relative and ITMS (ion-trap) ## spectra with an absolute tolerance by_analyzer <- list( ftms = AverageFragSpectraParam( select = list(scanFilterAnalyzer = "FTMS")), itms = AverageFragSpectraParam( select = list(scanFilterAnalyzer = "ITMS"), ppm = 0, tolerance = 0.3))param <- AverageFragSpectraParam(select = list(msLevel = 3L), combine = "collisionEnergy", sumi = FALSE) as.list(param) alternatives <- list( hcd = AverageFragSpectraParam(select = list(activationType = "HCD")), cid = AverageFragSpectraParam(select = list(activationType = "CID"))) ## FTMS (for example Orbitrap) spectra with a relative and ITMS (ion-trap) ## spectra with an absolute tolerance by_analyzer <- list( ftms = AverageFragSpectraParam( select = list(scanFilterAnalyzer = "FTMS")), itms = AverageFragSpectraParam( select = list(scanFilterAnalyzer = "ITMS"), ppm = 0, tolerance = 0.3))
General
Average and filter fragmentation spectra for each XCMS feature across MS data files. This can only be run after averageIntraFragSpectra has been used.
The averaging is performed using hierarchical clustering of the m/z values of each peaks, where m/z values within a set ppm tolerance will be clustered. The clustered peaks are then averaged (or summed).
The fragmentation can be filtered on the averaged spectra (with the arguments snr, rsd, minfrac and ra)
Example LC-MS/MS processing workflow
Purity assessments
(mzML files) -> purityA -> (pa)
XCMS processing
(mzML files) -> xcms.findChromPeaks -> (optionally) xcms.adjustRtime -> xcms.groupChromPeaks -> (xcmsObj)
— Older versions of XCMS — (mzML files) -> xcms.xcmsSet -> xcms.group -> xcms.retcor -> xcms.group -> (xcmsObj)
Fragmentation processing
(xcmsObj, pa) -> frag4feature -> filterFragSpectra -> averageIntraFragSpectra -> averageInterFragSpectra -> createDatabase -> spectralMatching -> (sqlite spectral database)
Averaging with parameter objects
With param, inter-file averaging combines intra-file averages
computed with param. Each parameter set must have an intra-file
parameter set of the same name (a single object is named
"default") with the same select and combine; its
thresholds and tolerances may differ. Intra-file averages of the same
feature are combined when their conditions match as for
averageAllFragSpectra and every MS3/MS4 precursor of the
contributors to passing peaks agrees within the inter-file tolerance. The
call stops if these precursors are incompatible within an intra-file input.
Each file contributes at most one input, and each input counts once.
Only intra-file averages with passing peaks are inputs. Compatibility and
numerical averaging use those same peaks, whether failed intra-file peaks
were flagged or removed. Contributors are traced through the intra-file
clusters: msPurityContributors lists links contributing to retained
final peaks. Use the result's spectrumId with
averageMembers for its immediate intra-file inputs or with
averagePeakMembers to trace a final fragment through
intermediate peaks to the original scans. Without
param,
the function stops with an error while intra-file or all-spectrum averages
computed with param are present.
## S4 method for signature 'purityA' averageInterFragSpectra( pa, minfrac = 0.5, minnum = 1, ppm = 5, snr = 0, ra = 0, av = "median", sumi = TRUE, rmp = FALSE, cores = 1, blockSize = 5000L, param = NULL )## S4 method for signature 'purityA' averageInterFragSpectra( pa, minfrac = 0.5, minnum = 1, ppm = 5, snr = 0, ra = 0, av = "median", sumi = TRUE, rmp = FALSE, cores = 1, blockSize = 5000L, param = NULL )
pa |
object; purityA object |
minfrac |
numeric; minimum ratio of the peak fraction (peak count / total peaks) across files |
minnum |
numeric; minimum number of times peak is present across fragmentation spectra across files |
ppm |
numeric; ppm threshold to average across files |
snr |
numeric; minimum signal-to-noise of the peak across files |
ra |
numeric; minimum relative abundance of the peak across files |
av |
character; type of averaging to use (median or mean) |
sumi |
boolean; TRUE if the intensity for each peak is summed across averaged spectra |
rmp |
boolean; TRUE if peaks are to be removed that do not meet the threshold criteria. Otherwise they will just be flagged |
cores |
Maximum number of workers; defaults to |
blockSize |
numeric; Maximum input peak rows per hierarchical-clustering calculation, as a positive integer (default 5,000). Safe blocks can be smaller; larger groups fitting one tolerance window need no distance matrix. Used only for hierarchical clustering; distance-matrix memory grows quadratically with this limit. |
param |
NULL, one |
With hierarchical clustering, matching peaks stay together. The call stops
with an error if more than blockSize nearby peaks cannot form one group or be
separated without splitting matching peaks.
Returns a purityA object (pa) with the following slots now with data
pa@avSpectra: the averaged spectra as a Spectra object, one spectrum per grouped feature, averaging
level and file, with the averaging statistics as peak variables.
pa@av_spectra: the legacy list of averaged spectra, filled while options(msPurity.legacySlots = TRUE).
e.g. "averagedSpectra(pa)$1$av_inter" gives the average spectra for grouped feature 1
pa@av_intra_params: The parameters used are recorded here
Each averaged spectrum in the legacy list contains the following columns (peak variables in pa@avSpectra): *
cl: id of clustered (averaged) peak
mz: average m/z
i: average intensity
snr: average signal to noise ratio
rsd: relative standard deviation
count: number of clustered peaks
total: total number of potential scans to be used for averaging
inPurity: average precursor ion purity
ra: average relative abundance
frac: the fraction of clustered peaks (e.g. the count/total)
snr_pass_flag: TRUE if snr threshold criteria met
minfrac_pass_flag: TRUE if minfrac threshold criteria
ra_pass_flag: TRUE if ra threshold criteria met
pass_flag: TRUE if all threshold criteria met
#====== XCMS ===================================== ## Read in MS data #msmsPths <- list.files(system.file("extdata", "lcms", "mzML", # package="msPurityData"), full.names = TRUE, pattern = "MSMS") #ms_data = readMSData(msmsPths, mode = 'onDisk', msLevel. = 1) ## Find peaks in each file #cwp <- CentWaveParam(snthresh = 5, noise = 100, ppm = 10, peakwidth = c(3, 30)) #xcmsObj <- xcms::findChromPeaks(ms_data, param = cwp) ## Optionally adjust retention time #xcmsObj <- adjustRtime(xcmsObj , param = ObiwarpParam(binSize = 0.6)) ## Group features across samples #pdp <- PeakDensityParam(sampleGroups = c(1, 1), minFraction = 0, bw = 30) #xcmsObj <- groupChromPeaks(xcmsObj , param = pdp) #====== msPurity ================================= #pa <- purityA(msmsPths) #pa <- frag4feature(pa, xcmsObj) #pa <- averageIntraFragSpectra(pa) #pa <- averageInterFragSpectra(pa) ## Run from previously generated data pa <- readRDS(system.file("extdata", "tests", "purityA", "4_averageIntraFragSpectra_no_filter_pa.rds", package="msPurity")) pa <- averageInterFragSpectra(pa)#====== XCMS ===================================== ## Read in MS data #msmsPths <- list.files(system.file("extdata", "lcms", "mzML", # package="msPurityData"), full.names = TRUE, pattern = "MSMS") #ms_data = readMSData(msmsPths, mode = 'onDisk', msLevel. = 1) ## Find peaks in each file #cwp <- CentWaveParam(snthresh = 5, noise = 100, ppm = 10, peakwidth = c(3, 30)) #xcmsObj <- xcms::findChromPeaks(ms_data, param = cwp) ## Optionally adjust retention time #xcmsObj <- adjustRtime(xcmsObj , param = ObiwarpParam(binSize = 0.6)) ## Group features across samples #pdp <- PeakDensityParam(sampleGroups = c(1, 1), minFraction = 0, bw = 30) #xcmsObj <- groupChromPeaks(xcmsObj , param = pdp) #====== msPurity ================================= #pa <- purityA(msmsPths) #pa <- frag4feature(pa, xcmsObj) #pa <- averageIntraFragSpectra(pa) #pa <- averageInterFragSpectra(pa) ## Run from previously generated data pa <- readRDS(system.file("extdata", "tests", "purityA", "4_averageIntraFragSpectra_no_filter_pa.rds", package="msPurity")) pa <- averageInterFragSpectra(pa)
General
Average and filter fragmentation spectra for each XCMS feature within a MS data file.
The averaging is performed using hierarchical clustering of the m/z values of each peaks, where m/z values within a set ppm tolerance will be clustered. The clustered peaks are then averaged (or summed).
The fragmentation can be filtered on the averaged spectra (with the arguments snr, rsd, minfrac and ra)
Example LC-MS/MS processing workflow
Purity assessments
(mzML files) -> purityA -> (pa)
XCMS processing
(mzML files) -> xcms.xcmsSet -> xcms.merge -> xcms.group -> xcms.retcor -> xcms.group -> (xcmsObj)
XCMS processing (version >= 3)
(mzML files) -> MSnBase.readMSdata -> xcms.findChromPeaks -> xcms.groupChromPeaks-> xcms.adjustRtime -> xcms.groupChromPeaks -> (xcmsObj)
Fragmentation processing
(xcmsObj, pa) -> frag4feature -> filterFragSpectra -> averageIntraFragSpectra -> averageIntraFragSpectra -> createDatabase -> spectralMatching -> (sqlite spectral database)
Averaging with parameter objects
With param, each parameter set averages the feature-linked MS2, MS3
and MS4 spectra it selects within each file, keeping incompatible
acquisition conditions and precursor paths apart, as described for
averageAllFragSpectra and
AverageFragSpectraParam. Spectra of different files are
never averaged together; msPurityAverageGroup is numbered within
each feature and file. The result's sample identifies the acquisition
file in pa@fileList; contributor records retain the XCMS sample
index where available. Grouped feature associations do not need an
individual chromatographic peak. The call replaces earlier intra- and
inter-file averages and keeps all-spectrum averages. Without param, the
function replaces earlier intra- and inter-file averages too, and stops
with an error while all-spectrum averages computed with param are
present.
## S4 method for signature 'purityA' averageIntraFragSpectra( pa, minfrac = 0.5, minnum = 1, ppm = 5, snr = 0, ra = 0, av = "median", sumi = TRUE, rmp = FALSE, cores = 1, blockSize = 5000L, param = NULL )## S4 method for signature 'purityA' averageIntraFragSpectra( pa, minfrac = 0.5, minnum = 1, ppm = 5, snr = 0, ra = 0, av = "median", sumi = TRUE, rmp = FALSE, cores = 1, blockSize = 5000L, param = NULL )
pa |
object; purityA object |
minfrac |
numeric; minimum ratio of the peak fraction (peak count / total peaks) within each file |
minnum |
numeric; minimum number of times peak is present across fragmentation spectra within each file |
ppm |
numeric; ppm threshold to average within each file |
snr |
numeric; minimum signal-to-noise of the peak within each file |
ra |
numeric; minimum relative abundance of the peak within each file |
av |
character; type of averaging to use (median or mean) |
sumi |
boolean; TRUE if the intensity for each peak is summed across averaged spectra |
rmp |
boolean; TRUE if peaks are to be removed that do not meet the threshold criteria. Otherwise they will just be flagged |
cores |
Maximum number of workers; defaults to |
blockSize |
numeric; Maximum input peak rows per hierarchical-clustering calculation, as a positive integer (default 5,000). Safe blocks can be smaller; larger groups fitting one tolerance window need no distance matrix. Used only for hierarchical clustering; distance-matrix memory grows quadratically with this limit. |
param |
NULL, one |
With hierarchical clustering, matching peaks stay together. The call stops
with an error if more than blockSize nearby peaks cannot form one group or be
separated without splitting matching peaks.
Returns a purityA object (pa) with the following slots now with data
pa@avSpectra: the averaged spectra as a Spectra object, one spectrum per grouped feature, averaging
level and file, with the averaging statistics as peak variables.
pa@av_spectra: the legacy list of averaged spectra, filled while options(msPurity.legacySlots = TRUE).
e.g. "averagedSpectra(pa)$1$av_intra$1" gives the average spectra for grouped feature 1 and for file 1.
pa@av_intra_params: The parameters used are recorded here
Each averaged spectrum in the legacy list contains the following columns (peak variables in pa@avSpectra):
cl: id of clustered (averaged) peak
mz: average m/z
i: average intensity
snr: average signal to noise ratio
rsd: relative standard deviation
count: number of clustered peaks
total: total number of potential scans to be used for averaging
inPurity: average precursor ion purity
ra: average relative abundance
frac: the fraction of clustered peaks (e.g. the count/total)
snr_pass_flag: TRUE if snr threshold criteria met
minfrac_pass_flag: TRUE if minfrac threshold criteria
ra_pass_flag: TRUE if ra threshold criteria met
pass_flag: TRUE if all threshold criteria met
#====== XCMS ================================= ## Read in MS data #msmsPths <- list.files(system.file("extdata", "lcms", "mzML", # package="msPurityData"), full.names = TRUE, pattern = "MSMS") #ms_data = readMSData(msmsPths, mode = 'onDisk', msLevel. = 1) ## Find peaks in each file #cwp <- CentWaveParam(snthresh = 5, noise = 100, ppm = 10, peakwidth = c(3, 30)) #xcmsObj <- xcms::findChromPeaks(ms_data, param = cwp) ## Optionally adjust retention time #xcmsObj <- adjustRtime(xcmsObj , param = ObiwarpParam(binSize = 0.6)) ## Group features across samples #pdp <- PeakDensityParam(sampleGroups = c(1, 1), minFraction = 0, bw = 30) #xcmsObj <- groupChromPeaks(xcmsObj , param = pdp) #====== msPurity ============================ #pa <- purityA(msmsPths) #pa <- frag4feature(pa, xcmsObj) #pa <- averageIntraFragSpectra(pa) # Run from previously generated data (where class is 'XCMSnExp'): pa <- readRDS(system.file("extdata", "tests", "purityA", "2_frag4feature_pa.rds", package="msPurity")) pa <- averageIntraFragSpectra(pa)#====== XCMS ================================= ## Read in MS data #msmsPths <- list.files(system.file("extdata", "lcms", "mzML", # package="msPurityData"), full.names = TRUE, pattern = "MSMS") #ms_data = readMSData(msmsPths, mode = 'onDisk', msLevel. = 1) ## Find peaks in each file #cwp <- CentWaveParam(snthresh = 5, noise = 100, ppm = 10, peakwidth = c(3, 30)) #xcmsObj <- xcms::findChromPeaks(ms_data, param = cwp) ## Optionally adjust retention time #xcmsObj <- adjustRtime(xcmsObj , param = ObiwarpParam(binSize = 0.6)) ## Group features across samples #pdp <- PeakDensityParam(sampleGroups = c(1, 1), minFraction = 0, bw = 30) #xcmsObj <- groupChromPeaks(xcmsObj , param = pdp) #====== msPurity ============================ #pa <- purityA(msmsPths) #pa <- frag4feature(pa, xcmsObj) #pa <- averageIntraFragSpectra(pa) # Run from previously generated data (where class is 'XCMSnExp'): pa <- readRDS(system.file("extdata", "tests", "purityA", "2_frag4feature_pa.rds", package="msPurity")) pa <- averageIntraFragSpectra(pa)
A new average receives a decimal string in spectrumId, unique among the
averages of the same object. Independent objects can assign the same ID.
Measured spectra keep their file-native identifiers. Derived IDs persist
after serialization and repeated averaging on the same object assigns fresh
IDs. msPurityProcessingId identifies the execution.
averageMembers(object, spectrumId, depth = c("immediate", "original")) averagePeakMembers( object, spectrumId, peak = NULL, depth = c("immediate", "original") )averageMembers(object, spectrumId, depth = c("immediate", "original")) averagePeakMembers( object, spectrumId, peak = NULL, depth = c("immediate", "original") )
object |
A purityA object or averaged Spectra returned by
|
spectrumId |
Character |
depth |
|
peak |
Optional vector of 1-based stored output peak positions. The default includes all stored peaks. |
averageMembers() follows selected spectrum inputs, including those
supplying no stored peak. At immediate depth, contributes reports
whether that input supplied a peak to the stored output.
averagePeakMembers() follows only the input
peaks of the requested stored output peaks. When failing peaks were kept,
use their pass_flag to select passing positions. An original selected
input can lack a path to any retained final peak.
Peak queries require the unmodified averaged peak arrays. Subsequent
peak processing with Spectra does not update these records. To inspect
particular peaks, pass their original averaged positions to peak.
averageMembers() queries the recorded selection even when peak
arrays are omitted. Spectrum subsetting and reordering preserve the records.
A data frame of memberships or peak connections. merged is the
requested spectrumId and member is the input's spectrumId. For
measured inputs the native ID can repeat across files or be missing.
pid identifies the measured scan, fileid its file and
linkId the selected feature-link occurrence. rank is the input's
rank at its immediately consuming step. Peak connections additionally
give mergedPeak in the requested spectrum, memberPeak at the input,
and its coordinate basis. A filter-input position need not equal a
raw acquisition position. An unknown input peak position is reported as
missing. Unrecorded historical edges cannot be traversed.
pa <- readRDS(system.file("extdata", "tests", "purityA", "2_frag4feature_pa.rds", package = "msPurity")) pa <- averageAllFragSpectra(pa, cores = 1) s <- averagedSpectra(pa, legacy = FALSE) averageMembers(s, s$spectrumId[1L]) averagePeakMembers(s, s$spectrumId[1L], depth = "original")pa <- readRDS(system.file("extdata", "tests", "purityA", "2_frag4feature_pa.rds", package = "msPurity")) pa <- averageAllFragSpectra(pa, cores = 1) s <- averagedSpectra(pa, legacy = FALSE) averageMembers(s, s$spectrumId[1L]) averagePeakMembers(s, s$spectrumId[1L], depth = "original")
Includes the requested averages and earlier averages they selected, the associated measured spectra and filtered inputs, their feature links and immediate membership tables. For disk-backed measured spectra the backend's usual file dependencies apply after serialization. The averaged peak arrays must be the unmodified averaging outputs.
averageProvenance(object, spectrumId)averageProvenance(object, spectrumId)
object |
A purityA object containing recorded average provenance. |
spectrumId |
Character vector of |
A list with averages (including their derived ancestors),
measured, fragments, featureLinks, mergeMembers, mergePeaks,
lineage and processing. Measured spectra include available MSn
precursor scans along recorded paths. In lineage, parentLineageScanId
joins to the measured parent's lineageScanId, and parentPid joins to
its pid. The averaged Spectra carries the restricted graph, so
averageMembers() and averagePeakMembers() also work on its subsets.
The merged and derived member values match averages$spectrumId.
Measured inputs have a pid, fileid and linkId.
Resolve rank in mergePeaks against (merged, rank) in mergeMembers.
pa <- readRDS(system.file("extdata", "tests", "purityA", "2_frag4feature_pa.rds", package = "msPurity")) pa <- averageAllFragSpectra(pa, cores = 1) s <- averagedSpectra(pa, legacy = FALSE) bundle <- averageProvenance(pa, s$spectrumId[1L]) head(bundle$mergeMembers)pa <- readRDS(system.file("extdata", "tests", "purityA", "2_frag4feature_pa.rds", package = "msPurity")) pa <- averageAllFragSpectra(pa, cores = 1) s <- averagedSpectra(pa, legacy = FALSE) bundle <- averageProvenance(pa, s$spectrumId[1L]) head(bundle$mergeMembers)
Select CPU BLINK scoring in spectralMatching() or scoreSpectrumPair().
Positive finite fragment intensities are raised to intensityPower and
L2-normalized before binning (nearest integer, ties to even). The query
bins are blurred using the upstream discrete kernel. With the defaults,
offsets are -9 through +9 bins. Multiple ions can contribute within a
window, so the approximate cosine can exceed one and the estimated count
can exceed the number of distinct ions. Zero matching ions gives two zeros.
The offline reference fixtures compare the cosine to the CPU implementation
of biorack/blink with absolute tolerance 1e-12 and require identical counts.
BlinkMatchingParam( binWidth = 0.001, blurTolerance = 0.01, intensityPower = 0.5, q_ppmPrec = 5, l_ppmPrec = 5, q_daPrec = 0, l_daPrec = 0, collisionEnergyTolerance = 0, q_ppmProd = 0, l_ppmProd = 0, q_daProd = 0, l_daProd = 0 ) ## S4 method for signature 'BlinkMatchingParam' as.list(x, ...)BlinkMatchingParam( binWidth = 0.001, blurTolerance = 0.01, intensityPower = 0.5, q_ppmPrec = 5, l_ppmPrec = 5, q_daPrec = 0, l_daPrec = 0, collisionEnergyTolerance = 0, q_ppmProd = 0, l_ppmProd = 0, q_daProd = 0, l_daProd = 0 ) ## S4 method for signature 'BlinkMatchingParam' as.list(x, ...)
binWidth |
Width of a fragment mass bin in Da, positive. |
blurTolerance |
Fragment blur tolerance in Da, at least one bin wide. |
intensityPower |
Nonnegative exponent. Zero gives equal ion weights. |
q_ppmPrec, l_ppmPrec
|
Query and reference precursor tolerances in ppm. |
q_daPrec, l_daPrec
|
Query and reference precursor tolerances in Da. |
collisionEnergyTolerance |
Maximum absolute difference between collision energies on the same scale, inclusive. Zero requires equal energies. |
q_ppmProd, l_ppmProd, q_daProd, l_daProd
|
Must be zero. Set
|
x |
A matching parameter object. |
... |
Ignored. |
A BlinkMatchingParam extending SpectralMatchingParam.
doi:10.1038/s41598-023-40496-9
p <- BlinkMatchingParam(blurTolerance = 0.02) d <- S4Vectors::DataFrame(msLevel = 2L, precursorMz = 200) d$mz <- list(c(50, 80)) d$intensity <- list(c(100, 20)) sp <- Spectra::Spectra(d, source = Spectra::MsBackendMemory()) result <- spectralMatching(sp, sp, param = p, referenceRole = "library") result$matchedResults[c("blinkCosine", "blinkMatchingIonCount", "rank")]p <- BlinkMatchingParam(blurTolerance = 0.02) d <- S4Vectors::DataFrame(msLevel = 2L, precursorMz = 200) d$mz <- list(c(50, 80)) d$intensity <- list(c(100, 20)) sp <- Spectra::Spectra(d, source = Spectra::MsBackendMemory()) result <- spectralMatching(sp, sp, param = p, referenceRole = "library") result$matchedResults[c("blinkCosine", "blinkMatchingIonCount", "rank")]
Combine the annotation results from msPurity spectral matching, MetFrag, Sirius CSI:FingerID, probmetab and any generic MS1 lookup software (e.g. results from the BEAMS software)
The annotation results are then aligned by inchikey and XCMS grouped feature.
The tool has to be run with a local compound database (available on request - contact [email protected])
combineAnnotations( sm_resultPth, compoundDbPth, metfrag_resultPth = NA, sirius_csi_resultPth = NA, probmetab_resultPth = NA, ms1_lookup_resultPth = NA, ms1_lookup_dbSource = "hmdb", ms1_lookup_checkAdducts = FALSE, ms1_lookup_keepAdducts = c("[M+H]+", "[M-H]-"), weights = list(sm = 0.3, metfrag = 0.2, sirius_csifingerid = 0.2, probmetab = 0, ms1_lookup = 0.05, biosim = 0.25), compoundDbType = "sqlite", compoundDbName = NA, compoundDbHost = NA, compoundDbPort = NA, compoundDbUser = NA, compoundDbPass = NA, outPth = NA, summaryOutput = TRUE, format = c("sqlite", "parquet") )combineAnnotations( sm_resultPth, compoundDbPth, metfrag_resultPth = NA, sirius_csi_resultPth = NA, probmetab_resultPth = NA, ms1_lookup_resultPth = NA, ms1_lookup_dbSource = "hmdb", ms1_lookup_checkAdducts = FALSE, ms1_lookup_keepAdducts = c("[M+H]+", "[M-H]-"), weights = list(sm = 0.3, metfrag = 0.2, sirius_csifingerid = 0.2, probmetab = 0, ms1_lookup = 0.05, biosim = 0.25), compoundDbType = "sqlite", compoundDbName = NA, compoundDbHost = NA, compoundDbPort = NA, compoundDbUser = NA, compoundDbPass = NA, outPth = NA, summaryOutput = TRUE, format = c("sqlite", "parquet") )
sm_resultPth |
character; Path to the msPurity SQLite database used for spectral matching |
compoundDbPth |
character; Path to local compound database with pubchem, hmdb, KEGG and metab_compound summary table (full database available on request - contact [email protected]). This is only applicable if using "compoundDbType sqlite") |
metfrag_resultPth |
character; Path to the tsv table of metfrag results |
sirius_csi_resultPth |
character; Path to the tsv table of Sirius CSI:Finger ID results |
probmetab_resultPth |
character; Path to the tsv table of Probmetab results |
ms1_lookup_resultPth |
character; Path to generic tsv table of MS1 lookup results |
ms1_lookup_dbSource |
character; Source of the compound database used for ms1_lookup (currently only supports HMDB, KEGG or PubChem) |
ms1_lookup_checkAdducts |
boolean; Check if adducts match to those found in CAMERA (requires the database to have been created with CAMERA object) |
ms1_lookup_keepAdducts |
vecotr; Keep only adducts found from the MS1 lookup that are found in this vector |
weights |
list; |
compoundDbType |
character; Database type for compound database can be either (sqlite, postgres or mysql) |
compoundDbName |
character; Database name (only applicable for postgres and mysql) |
compoundDbHost |
character; Database host (only applicable for postgres and mysql) |
compoundDbPort |
character; Database port (only applicable for postgres and mysql) |
compoundDbUser |
character; Database user (only applicable for postgres and mysql) |
compoundDbPass |
character; Database pass (only applicable for postgres and mysql) - Note this is not secure! |
outPth |
character; For SQLite, the path of a copy of |
summaryOutput |
boolean; If a summary dataframe is to be created |
format |
character; |
purityA object with slots for fragmentation-XCMS links
metfrag_resultPth <- system.file("extdata", "tests", "external_annotations", "metfrag.tsv", package="msPurity") # run the standard spectral matching workflow to get the sm_resultPth sm_resultPth <- system.file("extdata","tests", "sm", "spectralMatching_result.sqlite", package="msPurity") compoundDbPth <- system.file("extdata", "tests", "db", "metab_compound_subset.sqlite", package="msPurity") combined <- combineAnnotations(sm_resultPth, metfrag_resultPth, outPth=file.path(tempdir(), 'combined.sqlite'), compoundDbPth=compoundDbPth)metfrag_resultPth <- system.file("extdata", "tests", "external_annotations", "metfrag.tsv", package="msPurity") # run the standard spectral matching workflow to get the sm_resultPth sm_resultPth <- system.file("extdata","tests", "sm", "spectralMatching_result.sqlite", package="msPurity") compoundDbPth <- system.file("extdata", "tests", "db", "metab_compound_subset.sqlite", package="msPurity") combined <- combineAnnotations(sm_resultPth, metfrag_resultPth, outPth=file.path(tempdir(), 'combined.sqlite'), compoundDbPth=compoundDbPth)
Writes a spectral library as a Parquet library dataset (one native run
per source library file) for use with
spectralMatching(format = "parquet").
format = "msp2db": an msp2db SQLite library, such as the default
library of spectralMatching(); one run per library source.
format = "msp": MSP files, one run per file. dialect must be
declared: "massbank", "mona" (NIST/MoNA) or "mspurity" (files
written by createMSP()). Unknown keys are an error.
format = "spectra", the default when x is a Spectra object: a
library read with any Spectra backend, such as MsBackendMsp,
MsBackendMassbank or MsBackendMgf; one run per data origin. Spectra
variables are mapped to library fields by mapping, and those with no
field are dropped and recorded as such in the dataset's provenance.
Retention times are taken as seconds, the Spectra convention, unless
rtUnit says otherwise.
Peaks keep their source order and exact values. Collision energy is kept
as written, with a numeric value only for plain numbers (35, 35 eV).
Retention time is converted to minutes only when rtUnit is given.
Licence and attribution fields are kept.
convertLibraryToParquet( x, path, format = c("msp2db", "msp", "spectra"), dialect = NULL, version = NULL, rtUnit = NA_character_, runIds = NULL, overwrite = FALSE, mapping = NULL )convertLibraryToParquet( x, path, format = c("msp2db", "msp", "spectra"), dialect = NULL, version = NULL, rtUnit = NA_character_, runIds = NULL, overwrite = FALSE, mapping = NULL )
x |
|
path |
|
format |
|
dialect |
|
version |
|
rtUnit |
|
runIds |
named |
overwrite |
|
mapping |
named |
The path of the dataset, invisibly.
spectralMatching(), validateParquet()
msp <- system.file("extdata", "tests", "msp", "av_all.msp", package = "msPurity") out <- file.path(tempdir(), "library.parquet") convertLibraryToParquet(msp, out, format = "msp", dialect = "mspurity", overwrite = TRUE) validateParquet(out) if (requireNamespace("MsBackendMsp", quietly = TRUE)) { mona <- system.file("extdata", "tests", "library", "mini_mona.msp", package = "msPurity") sp <- Spectra::Spectra(mona, source = MsBackendMsp::MsBackendMsp(), mapping = c(name = "Name", accession = "DB#", precursorMz = "PrecursorMZ", adduct = "Precursor_type", inchikey = "InChIKey", formula = "Formula", polarity = "Ion_mode"), BPPARAM = BiocParallel::SerialParam()) out <- file.path(tempdir(), "library-spectra.parquet") convertLibraryToParquet(sp, out, overwrite = TRUE) }msp <- system.file("extdata", "tests", "msp", "av_all.msp", package = "msPurity") out <- file.path(tempdir(), "library.parquet") convertLibraryToParquet(msp, out, format = "msp", dialect = "mspurity", overwrite = TRUE) validateParquet(out) if (requireNamespace("MsBackendMsp", quietly = TRUE)) { mona <- system.file("extdata", "tests", "library", "mini_mona.msp", package = "msPurity") sp <- Spectra::Spectra(mona, source = MsBackendMsp::MsBackendMsp(), mapping = c(name = "Name", accession = "DB#", precursorMz = "PrecursorMZ", adduct = "Precursor_type", inchikey = "InChIKey", formula = "Formula", polarity = "Ion_mode"), BPPARAM = BiocParallel::SerialParam()) out <- file.path(tempdir(), "library-spectra.parquet") convertLibraryToParquet(sp, out, overwrite = TRUE) }
Converts a database written by createDatabase() to a Parquet results
dataset, as createDatabase(format = "parquet") would write it. The
database is not modified.
MS2 scans are referenced, not copied. With study, each scan resolves to
its spectrum in that dataset, matched by scan number from the study's own
metadata, and its parent to the study's MS1 scan; otherwise each source
file is an external source and scans are identified by mzML native id. The
database holds no MS3/MS4 results or acquisition lineage, which only
createDatabase() writes from a purityA object.
Historical raw peak identities are resolved from file and spectrum position.
A warning reports stored identities that disagree with that mapping.
This warning has class msPurity_parquet_identity_warning. Existing
filtering flags are retained; flags previously applied to the wrong spectrum
and destructively removed peaks are not automatically repaired. Reprocess
affected data from the original measurements when reliable flags are needed.
Ambiguous averaged-peak membership is an error, not an empty spectrum.
Processing parameters are not stored in the database, which is recorded
in tool_provenance and the loss ledger. Unmapped tables are an error.
convertSqliteToParquet( db, path, study = NULL, studyKey = "study", fileMap = NULL, overwrite = FALSE )convertSqliteToParquet( db, path, study = NULL, studyKey = "study", fileMap = NULL, overwrite = FALSE )
db |
|
path |
|
study |
|
studyKey |
|
fileMap |
named |
overwrite |
|
The path of the dataset, invisibly.
createDatabase(), validateParquet()
db <- system.file("extdata", "tests", "db", "createDatabase_example.sqlite", package = "msPurity") out <- file.path(tempdir(), "converted.parquet") convertSqliteToParquet(db, out, overwrite = TRUE) validateParquet(out)db <- system.file("extdata", "tests", "db", "createDatabase_example.sqlite", package = "msPurity") out <- file.path(tempdir(), "converted.parquet") convertSqliteToParquet(db, out, overwrite = TRUE) validateParquet(out)
Create and SQLite database of an LC-MS(/MS) experiment
msPurity::create_database is deprecated. Please use msPurity::createDatabase for future use
create_database( pa, xset, xsa = NULL, out_dir = ".", grp_peaklist = NA, db_name = NA )create_database( pa, xset, xsa = NULL, out_dir = ".", grp_peaklist = NA, db_name = NA )
pa |
purityA object; Needs to be the same used for frag4feature function |
xset |
xcms object; Needs to be the same used for frag4feature function (this will be ignored when using xsa parameter) |
xsa |
CAMERA object [optional]; if CAMERA object is used, we ignore the xset parameter input and obtain all information from the xset object nested with the CAMERA xsa object. Adduct and isotope information will be included into the database when using this parameter. The underlying xset object must be the one used for the frag4feature function |
out_dir |
character; Out directory for the SQLite result database |
grp_peaklist |
dataframe [optional]; Can use any peak dataframe. Still needs to be derived from the xset object though |
db_name |
character [optional]; Name of the result database |
path to SQLite database and database name
#msmsPths <- list.files(system.file("extdata", "lcms", "mzML", # package="msPurityData"), full.names = TRUE, pattern = "MSMS") #xset <- xcms::xcmsSet(msmsPths) #xset <- xcms::group(xset) #pa <- purityA(msmsPths) #pa <- frag4feature(pa, xset) #pa <- averageAllFragSpectra(pa) #db_pth <- create_database(pa, xset) # Run from previously generated data pa <- readRDS(system.file("extdata", "tests", "purityA", "9_averageAllFragSpectra_with_filter_pa_OLD.rds", package="msPurity")) xset <- readRDS(system.file("extdata","tests", "xcms", "msms_only_xset_OLD.rds", package="msPurity")) # Need to ensure the filelists are matching msmsPths <- list.files(system.file("extdata", "lcms", "mzML", package="msPurityData"), full.names = TRUE, pattern = "MSMS") pa@fileList[1] <- msmsPths[basename(msmsPths)=="LCMSMS_1.mzML"] pa@fileList[2] <- msmsPths[basename(msmsPths)=="LCMSMS_2.mzML"] xset@filepaths[1] <- msmsPths[basename(msmsPths)=="LCMSMS_1.mzML"] xset@filepaths[2] <- msmsPths[basename(msmsPths)=="LCMSMS_2.mzML"] db_pth <- create_database(pa, xset, out_dir = tempdir())#msmsPths <- list.files(system.file("extdata", "lcms", "mzML", # package="msPurityData"), full.names = TRUE, pattern = "MSMS") #xset <- xcms::xcmsSet(msmsPths) #xset <- xcms::group(xset) #pa <- purityA(msmsPths) #pa <- frag4feature(pa, xset) #pa <- averageAllFragSpectra(pa) #db_pth <- create_database(pa, xset) # Run from previously generated data pa <- readRDS(system.file("extdata", "tests", "purityA", "9_averageAllFragSpectra_with_filter_pa_OLD.rds", package="msPurity")) xset <- readRDS(system.file("extdata","tests", "xcms", "msms_only_xset_OLD.rds", package="msPurity")) # Need to ensure the filelists are matching msmsPths <- list.files(system.file("extdata", "lcms", "mzML", package="msPurityData"), full.names = TRUE, pattern = "MSMS") pa@fileList[1] <- msmsPths[basename(msmsPths)=="LCMSMS_1.mzML"] pa@fileList[2] <- msmsPths[basename(msmsPths)=="LCMSMS_2.mzML"] xset@filepaths[1] <- msmsPths[basename(msmsPths)=="LCMSMS_1.mzML"] xset@filepaths[2] <- msmsPths[basename(msmsPths)=="LCMSMS_2.mzML"] db_pth <- create_database(pa, xset, out_dir = tempdir())
General
Create an SQLite database of an LC-MS(/MS) experiment (replaces the create_database function).
Schema details can be found here.
Example LC-MS/MS processing workflow
Purity assessments
(mzML files) -> purityA -> (pa)
XCMS processing
(mzML files) -> xcms.findChromPeaks -> (optionally) xcms.adjustRtime -> xcms.groupChromPeaks -> (xcmsObj)
— Older versions of XCMS — (mzML files) -> xcms.xcmsSet -> xcms.group -> xcms.retcor -> xcms.group -> (xcmsObj)
Fragmentation processing
(xcmsObj, pa) -> frag4feature -> filterFragSpectra -> averageAllFragSpectra -> createDatabase -> spectralMatching -> (sqlite spectral database)
createDatabase( pa, xcmsObj, xsa = NULL, outDir = ".", grpPeaklist = NA, dbName = NA, metadata = NA, xset = NA, format = c("sqlite", "parquet"), study = NULL, studyKey = "study", fileMap = NULL, overwrite = FALSE )createDatabase( pa, xcmsObj, xsa = NULL, outDir = ".", grpPeaklist = NA, dbName = NA, metadata = NA, xset = NA, format = c("sqlite", "parquet"), study = NULL, studyKey = "study", fileMap = NULL, overwrite = FALSE )
pa |
purityA object; Needs to be the same used for frag4feature function |
xcmsObj |
xcms object of class XcmsExperiment, XCMSnExp or xcmsSet; Needs to be the same used for frag4feature function (this will be ignored when using xsa parameter) |
xsa |
CAMERA object (optional); if CAMERA object is used, we ignore the xset parameter input and obtain all information from the xset object nested with the CAMERA xsa object. Adduct and isotope information will be included into the database when using this parameter. The underlying xset object must be the one used for the frag4feature function |
outDir |
character; Out directory for the SQLite result database |
grpPeaklist |
dataframe (optional); Can use any peak dataframe. Still needs to be derived from the xset object though |
dbName |
character (optional); Name of the result database |
metadata |
list; A list of metadata to add to the s_peak_meta table |
xset |
xcms object of class XCMSnExp or xcmsSet; (Deprecated - if provided, will replace variable 'obj') |
format |
character; |
study |
character (optional, parquet only); path of the Parquet dataset the mzML files were converted into with
MsBackendParquet::mzMLToParquet(). Scans and their parent scans are then referenced by their spectrum ids
in that dataset. By default, when |
studyKey |
character (parquet only); the key the study is declared under in the results dataset. |
fileMap |
named character (optional, parquet only); source file path (as in |
overwrite |
logical (parquet only); replace an existing dataset at the destination. |
Parquet output (experimental)
With format = "parquet", the results are written as a results dataset (a directory of Parquet
files with an mzStack.json manifest), following part 4 of the mzStack specification:
xcms features, chromatographic peaks and their per-sample abundances become the feature,
chromatographic_peak, chromatographic_peak_feature and abundance tables, with
assay and sample for the source files;
the links between MS2 scans and features become spectrum_feature, with the precursor m/z,
error, retention time and purity each scan was matched at and how its retention time was mapped;
MS3 and MS4 scans linked through their MS2 scan are in x_mspurity_msn_feature;
averaged fragmentation spectra become spectra of the dataset, one run per source file for spectra
averaged within a file (av_intra_<run>) and one run each for spectra averaged across files
(av_inter, av_all), with their per-peak statistics. Averages computed with
AverageFragSpectraParam, at MS2 to MS4, keep their MS level, parameter set, acquisition
conditions and precursor path. A computed average with zero retained peaks has empty m/z and
intensity arrays and keeps its selected members. An attempted scalar average that produced no
spectrum has a loss ledger entry identifying its feature and, when available, sample;
the scans and averages each averaged spectrum was made from are recorded in merge_member.
Where the averaging provenance is recorded, these are the inputs it selected, with whether each
contributed a peak (x_mspurity_contributes), and x_mspurity_merge_peak gives the input
peak each averaged peak came from; otherwise the members are reconstructed from the feature links;
every assessed MS2 to MS4 scan is listed in x_mspurity_scan with its MS2 precursor purity or
MSn stage purity, the scan it fragments and the MS2 scan its path starts from, and the activation
method msPurity used with where that came from; peaks flagged by filterFragSpectra() are in
x_mspurity_scan_peak. Raw scans are referenced, not copied;
the processing parameters and history, what was converted and anything that could not be mapped are
recorded in tool_provenance, conversion, source_identifier and loss_ledger.
Raw data in a Parquet study
Raw MS1-MS4 files converted with MsBackendParquet::mzMLToParquet() are read by passing
purityA() a Spectra on the dataset; msPurity then reads their peaks from the dataset, never
from the mzML files. A scan is linked to the study by the dataset's own key when purityA() read it
there, otherwise by native id, then by scan number at the same position, all from the study's own metadata.
An MS2 scan's parent is the study's MS1 scan its precursor scan number names. Acquisition conditions the
study does not record, such as the activation method of mzXML input, are reported in the loss ledger as
unavailable rather than inferred; where msPurity used a method named by a scan's filter string,
activation_type_basis says so.
The dataset is written to file.path(outDir, dbName); the default name ends in .parquet. It is built
beside its destination and moved into place only once complete, so an interrupted write leaves nothing behind.
CAMERA annotation (xsa) and a custom grpPeaklist are not mapped to the Parquet output and are refused.
The SQLite database holds MS2 results only and refuses MS3/MS4
feature links and processed spectra, and averages computed with
AverageFragSpectraParam; the Parquet dataset holds MS2-MS4 scans,
links, filtered spectra and averages. Averages computed with
AverageFragSpectraParam are exported with the provenance their
averaging recorded, and not after their peaks were processed further.
For format = "sqlite", the path to the SQLite database. For format = "parquet", the path of
the Parquet results dataset, invisibly.
#====== XCMS ================================= ## Read in MS data #msmsPths <- list.files(system.file("extdata", "lcms", "mzML", # package="msPurityData"), full.names = TRUE, pattern = "MSMS") #ms_data = readMSData(msmsPths, mode = 'onDisk', msLevel. = 1) ## Find peaks in each file #cwp <- CentWaveParam(snthresh = 5, noise = 100, ppm = 10, peakwidth = c(3, 30)) #xcmsObj <- xcms::findChromPeaks(ms_data, param = cwp) ## Optionally adjust retention time #xcmsObj <- adjustRtime(xcmsObj , param = ObiwarpParam(binSize = 0.6)) ## Group features across samples #pdp <- PeakDensityParam(sampleGroups = c(1, 1), minFraction = 0, bw = 30) #xcmsObj <- groupChromPeaks(xcmsObj , param = pdp) #====== msPurity ============================ #pa <- purityA(msmsPths) #pa <- frag4feature(pa = pa, xcmsObj = xcmsObj) #pa <- filterFragSpectra(pa, allfrag=TRUE) #pa <- averageAllFragSpectra(pa) ## Run from previously generated data msmsPths <- list.files(system.file("extdata", "lcms", "mzML", package="msPurityData"), full.names = TRUE, pattern = "MSMS") pa <- readRDS(system.file("extdata", "tests", "purityA", "9_averageAllFragSpectra_with_filter_pa.rds", package="msPurity")) xcmsObj <- readRDS(system.file("extdata", "tests", "xcms", "msms_only_xcmsnexp.rds", package="msPurity")) ## The saved objects record the file paths of the machine that made them pa@fileList[1:2] <- msmsPths xcmsObj@processingData@files <- msmsPths db_pth <- createDatabase(pa, xcmsObj, outDir = tempdir(), metadata = list(polarity = "positive", instrument = "Q-Exactive"))#====== XCMS ================================= ## Read in MS data #msmsPths <- list.files(system.file("extdata", "lcms", "mzML", # package="msPurityData"), full.names = TRUE, pattern = "MSMS") #ms_data = readMSData(msmsPths, mode = 'onDisk', msLevel. = 1) ## Find peaks in each file #cwp <- CentWaveParam(snthresh = 5, noise = 100, ppm = 10, peakwidth = c(3, 30)) #xcmsObj <- xcms::findChromPeaks(ms_data, param = cwp) ## Optionally adjust retention time #xcmsObj <- adjustRtime(xcmsObj , param = ObiwarpParam(binSize = 0.6)) ## Group features across samples #pdp <- PeakDensityParam(sampleGroups = c(1, 1), minFraction = 0, bw = 30) #xcmsObj <- groupChromPeaks(xcmsObj , param = pdp) #====== msPurity ============================ #pa <- purityA(msmsPths) #pa <- frag4feature(pa = pa, xcmsObj = xcmsObj) #pa <- filterFragSpectra(pa, allfrag=TRUE) #pa <- averageAllFragSpectra(pa) ## Run from previously generated data msmsPths <- list.files(system.file("extdata", "lcms", "mzML", package="msPurityData"), full.names = TRUE, pattern = "MSMS") pa <- readRDS(system.file("extdata", "tests", "purityA", "9_averageAllFragSpectra_with_filter_pa.rds", package="msPurity")) xcmsObj <- readRDS(system.file("extdata", "tests", "xcms", "msms_only_xcmsnexp.rds", package="msPurity")) ## The saved objects record the file paths of the machine that made them pa@fileList[1:2] <- msmsPths xcmsObj@processingData@files <- msmsPths db_pth <- createDatabase(pa, xcmsObj, outDir = tempdir(), metadata = list(polarity = "positive", instrument = "Q-Exactive"))
General
Create an MSP file for all the fragmentation spectra that has been linked to an XCMS feature via frag4feature. Can export all the associated scans individually or the averaged fragmentation spectra can be exported.
Additional metadata can be included in a dataframe (each column will be added to metadata of the MSP spectra). The dataframe must contain the column "grpid" corresponding to the XCMS grouped feature.
Example LC-MS/MS processing workflow
Purity assessments
(mzML files) -> purityA -> (pa)
XCMS processing
(mzML files) -> xcms.findChromPeaks -> (optionally) xcms.adjustRtime -> xcms.groupChromPeaks -> (xcmsObj)
— Older versions of XCMS — (mzML files) -> xcms.xcmsSet -> xcms.group -> xcms.retcor -> xcms.group -> (xcmsObj)
Fragmentation processing
(xcmsObj, pa) -> frag4feature -> filterFragSpectra -> averageIntraFragSpectra -> averageIntraFragSpectra -> createMSP -> (MSP file)
## S4 method for signature 'purityA' createMSP( pa, msp_file_pth = NULL, metadata = NULL, metadata_cols = NULL, xcms_groupids = NULL, method = "all", adduct_split = TRUE, filter = TRUE, msp_schema = "massbank", intensity_ra = "intensity_ra", include_adducts = "" )## S4 method for signature 'purityA' createMSP( pa, msp_file_pth = NULL, metadata = NULL, metadata_cols = NULL, xcms_groupids = NULL, method = "all", adduct_split = TRUE, filter = TRUE, msp_schema = "massbank", intensity_ra = "intensity_ra", include_adducts = "" )
pa |
object; purityA object |
msp_file_pth |
character; Name of the output msp file, if NULL the file "frag_spectra_time stamp.msp" will be created in the current directory |
metadata |
data.frame; Data frame with additional coumpound infomation to include in msp output |
metadata_cols |
vector; Column names of meta data to incorporate into name |
xcms_groupids |
vector; XCMS group id's to extract ms/ms data for |
method |
character; "all" will export all matching ms/ms spectra to xcms features, "max" will use spectra with the highest inensity, "av_intra" will use the intra file averaged spectra (within file), "av_inter" will use the inter file (across file) averaged spectra, "av_all" will use the averaged spectra (ignoring inter and intra) |
adduct_split |
boolean; If either "adduct" or MS$FOCUSED_ION: PRECURSOR_TYPE column is in metadata then each adduct will have it's own MSP spectra. (Useful, if the MSP file will be used for further annotation) |
filter |
boolean; TRUE if filtered peaks are to be removed |
msp_schema |
character; Either MassBank (Europe) or MoNA style of MSP file format to be used ('massbank' or 'mona') |
intensity_ra |
character; Either 'intensity', 'ra' (relative abundance) or 'intensity_ra' (intensity and relative abundance) to be written to the MSP file |
include_adducts |
character; Additional adducts to include as a string seperated by white a space (e.g. [M+H]+ [M+Na]+) |
Returns a MSP file with the selected spectra and metadata
#====== XCMS ================================= ## Read in MS data #msmsPths <- list.files(system.file("extdata", "lcms", "mzML", # package="msPurityData"), full.names = TRUE, pattern = "MSMS") #ms_data = readMSData(msmsPths, mode = 'onDisk', msLevel. = 1) ## Find peaks in each file #cwp <- CentWaveParam(snthresh = 5, noise = 100, ppm = 10, peakwidth = c(3, 30)) #xcmsObj <- xcms::findChromPeaks(ms_data, param = cwp) ## Optionally adjust retention time #xcmsObj <- adjustRtime(xcmsObj , param = ObiwarpParam(binSize = 0.6)) ## Group features across samples #pdp <- PeakDensityParam(sampleGroups = c(1, 1), minFraction = 0, bw = 30) #xcmsObj <- groupChromPeaks(xcmsObj , param = pdp) #====== msPurity ============================ #pa <- purityA(msmsPths) #pa <- frag4feature(pa = pa, xcmsObj = xcmsObj) #pa <- filterFragSpectra(pa, allfrag=TRUE) #pa <- averageAllFragSpectra(pa) #createMSP(pa) pa <- readRDS(system.file("extdata", "tests", "purityA", "9_averageAllFragSpectra_with_filter_pa.rds", package="msPurity")) createMSP(pa, msp_file_pth = file.path(tempdir(), "frag_spectra.msp"))#====== XCMS ================================= ## Read in MS data #msmsPths <- list.files(system.file("extdata", "lcms", "mzML", # package="msPurityData"), full.names = TRUE, pattern = "MSMS") #ms_data = readMSData(msmsPths, mode = 'onDisk', msLevel. = 1) ## Find peaks in each file #cwp <- CentWaveParam(snthresh = 5, noise = 100, ppm = 10, peakwidth = c(3, 30)) #xcmsObj <- xcms::findChromPeaks(ms_data, param = cwp) ## Optionally adjust retention time #xcmsObj <- adjustRtime(xcmsObj , param = ObiwarpParam(binSize = 0.6)) ## Group features across samples #pdp <- PeakDensityParam(sampleGroups = c(1, 1), minFraction = 0, bw = 30) #xcmsObj <- groupChromPeaks(xcmsObj , param = pdp) #====== msPurity ============================ #pa <- purityA(msmsPths) #pa <- frag4feature(pa = pa, xcmsObj = xcmsObj) #pa <- filterFragSpectra(pa, allfrag=TRUE) #pa <- averageAllFragSpectra(pa) #createMSP(pa) pa <- readRDS(system.file("extdata", "tests", "purityA", "9_averageAllFragSpectra_with_filter_pa.rds", package="msPurity")) createMSP(pa, msp_file_pth = file.path(tempdir(), "frag_spectra.msp"))
General
Flag and filter features based on signal-to-noise ratio, relative abundance, intensity threshold and purity of the precursor ion.
Example LC-MS/MS processing workflow
Purity assessments
(mzML files) -> purityA -> (pa)
XCMS processing
(mzML files) -> xcms.findChromPeaks -> (optionally) xcms.adjustRtime -> xcms.groupChromPeaks -> (xcmsObj)
— Older versions of XCMS — (mzML files) -> xcms.xcmsSet -> xcms.group -> xcms.retcor -> xcms.group -> (xcmsObj)
Fragmentation processing
(xcmsObj, pa) -> frag4feature -> filterFragSpectra -> averageAllFragSpectra -> createDatabase -> spectralMatching -> (sqlite spectral database)
## S4 method for signature 'purityA' filterFragSpectra( pa, ilim = 0, plim = 0.8, ra = 0, snr = 3, cores = 1, rmp = FALSE, snmeth = "median", allfrag = FALSE, param = NULL, msLevel = 2L )## S4 method for signature 'purityA' filterFragSpectra( pa, ilim = 0, plim = 0.8, ra = 0, snr = 3, cores = 1, rmp = FALSE, snmeth = "median", allfrag = FALSE, param = NULL, msLevel = 2L )
pa |
object; purityA object |
ilim |
numeric; min intensity of a peak |
plim |
numeric; minimum precursor purity. An explicit value applies
to all requested MS levels unless a matching parameter object supplies
different settings. Without an explicit value or matching object, the
default threshold applies to MS2 only. Purity must be strictly greater
than the threshold; an unavailable assessment fails an active threshold.
Use |
ra |
numeric; minimum relative abundance of a peak |
snr |
numeric; minimum signal-to-noise of a peak within each spectrum |
cores |
numeric; Accepted for compatibility. Fragment filtering is serial. |
rmp |
boolean; TRUE if peaks are to be removed that do not meet the threshold criteria. Otherwise they will just be flagged. |
snmeth |
character; estimate noise from the median or mean peak intensity within each spectrum. |
allfrag |
logical; consider all retained fragmentation spectra when
TRUE, or only feature-associated spectra when FALSE. In either case,
|
param |
NULL, a complete |
msLevel |
nonempty numeric vector of integer MS levels from 2 to 4.
Defaults to MS2. Use Level selection narrows processed spectra and feature associations,
retaining source measurements and ancestry. Start alternatives from the
same linked object: filtering cannot restore excluded associations.
Parameter |
Returns a purityA object. The flags are stored in pa@fragSpectra: purity_pass_flag as a spectra
variable and the others as peak variables (stored as 1 and 0). groupedSpectra(pa), and the legacy
pa@grped_ms2 slot while options(msPurity.legacySlots = TRUE), give the spectra matrices with the
following columns
snr: Signal to noise ratio (calculated at scan level)
ra: Relative abundance (calculated at scan level)
purity_pass_flag: Precursor ion purity flag (1 pass, 0 fail)
intensity_pass_flag: Intensity flag (1 pass, 0 fail)
snr_pass_flag: Signal-to-noise pass flag (1 pass, 0 fail)
ra_pass_flag: Relative abundance pass flag (1 pass, 0 fail)
pass_flag: Overall pass flag, all flags must pass for this to pass (1 pass, 0 fail)
Each spectrum uses its own purity assessment from purityA().
msPurityFilterThreshold and msPurityFilterDecision record
the threshold and whether purity passed, failed, was missing or was skipped.
Skipping purity sets purity_pass_flag to TRUE; fragment-peak criteria
still apply. Assessment status remains in msPurityPurityStatus.
Filtering a spectrum does not automatically exclude its descendants.
#====== XCMS ================================= ## Read in MS data #msmsPths <- list.files(system.file("extdata", "lcms", "mzML", # package="msPurityData"), full.names = TRUE, pattern = "MSMS") #ms_data = readMSData(msmsPths, mode = 'onDisk', msLevel. = 1) ## Find peaks in each file #cwp <- CentWaveParam(snthresh = 5, noise = 100, ppm = 10, peakwidth = c(3, 30)) #xcmsObj <- xcms::findChromPeaks(ms_data, param = cwp) ## Optionally adjust retention time #xcmsObj <- adjustRtime(xcmsObj , param = ObiwarpParam(binSize = 0.6)) ## Group features across samples #pdp <- PeakDensityParam(sampleGroups = c(1, 1), minFraction = 0, bw = 30) #xcmsObj <- groupChromPeaks(xcmsObj , param = pdp) #====== msPurity ============================ #pa <- purityA(msmsPths) #pa <- frag4feature(pa, xcmsObj) #pa <- filterFragSpectra(pa) ## Run from previously generated data pa <- readRDS(system.file("extdata", "tests", "purityA", "2_frag4feature_pa.rds", package="msPurity")) pa <- filterFragSpectra(pa)#====== XCMS ================================= ## Read in MS data #msmsPths <- list.files(system.file("extdata", "lcms", "mzML", # package="msPurityData"), full.names = TRUE, pattern = "MSMS") #ms_data = readMSData(msmsPths, mode = 'onDisk', msLevel. = 1) ## Find peaks in each file #cwp <- CentWaveParam(snthresh = 5, noise = 100, ppm = 10, peakwidth = c(3, 30)) #xcmsObj <- xcms::findChromPeaks(ms_data, param = cwp) ## Optionally adjust retention time #xcmsObj <- adjustRtime(xcmsObj , param = ObiwarpParam(binSize = 0.6)) ## Group features across samples #pdp <- PeakDensityParam(sampleGroups = c(1, 1), minFraction = 0, bw = 30) #xcmsObj <- groupChromPeaks(xcmsObj , param = pdp) #====== msPurity ============================ #pa <- purityA(msmsPths) #pa <- frag4feature(pa, xcmsObj) #pa <- filterFragSpectra(pa) ## Run from previously generated data pa <- readRDS(system.file("extdata", "tests", "purityA", "2_frag4feature_pa.rds", package="msPurity")) pa <- filterFragSpectra(pa)
A complete filtering parameter set extending ProtGenerics::Param.
Defaults are fixed when the object is constructed. Supply one object or a
named list of objects to filterFragSpectra(param = ). Scalar calls
remain available. Call-wide rmp, allfrag, msLevel
and cores
are not fields of this object; parameter-set filtering requires one core.
Input scope (msLevel, allfrag), flag retention versus peak
removal (rmp) and execution controls stay on the call, allowing the
same scientific settings to be reused for different processing choices.
Processing history records both; see processingParameters.
FilterFragSpectraParam( select = list(), ilim = 0, plim = 0.8, ra = 0, snr = 3, snmeth = "median" ) ## S4 method for signature 'FilterFragSpectraParam' as.list(x, ...)FilterFragSpectraParam( select = list(), ilim = 0, plim = 0.8, ra = 0, snr = 3, snmeth = "median" ) ## S4 method for signature 'FilterFragSpectraParam' as.list(x, ...)
select |
Named list of exact acquisition-metadata selectors. |
ilim |
Minimum peak intensity in recorded units. |
plim |
Minimum precursor purity, between zero and one, for each
spectrum matched by this object, including MS3/MS4. Purity must be
strictly greater than this value; an unavailable assessment fails an
active threshold. |
ra |
Minimum relative abundance on the existing 0 to 100 scale. |
snr |
Minimum signal-to-noise ratio, using the existing statistic. |
snmeth |
Noise statistic: |
x |
A filtering parameter object. |
... |
Ignored. |
select assigns settings within the spectra selected by the call;
it does not discard spectra or include levels beyond the call's
msLevel argument, which defaults to MS2.
Fields are combined with AND and values within a field with OR. Supported
fields are msLevel, massAnalyzer, scanFilterAnalyzer,
activationType, collisionEnergy, collisionEnergyUnit
and polarity. CID, HCD and ETD can be selected by abbreviation,
recognized CV name or accession. Source labels and accessions are retained.
Available structured activation metadata take precedence over scan filters;
contradictory known labels and accessions are rejected. Combined or
unrecognized methods are not reduced to individual methods.
When metadata are unknown, ordinary serial scan filters
can supply the final CID/HCD activation type and an FTMS or
ITMS analyzer category. This category is stored as
scanFilterAnalyzer; it does not identify the exact
massAnalyzer. Existing known metadata take precedence. Unsupported
or ambiguous filters leave the activation type unknown. Collision energies
and their units are not inferred from scan filters.
Use NA to select unknown metadata. Spectra matched by no parameter
set receive the filtering call's scalar settings. For unmatched MS3/MS4,
purity filtering is skipped unless the call explicitly supplies
plim. Overlapping sets must have the same complete effective settings.
A FilterFragSpectraParam object. as.list() returns
its complete settings, including the selectors.
filterFragSpectra, processingHistory
filter_param <- FilterFragSpectraParam(plim = 0.7, snr = 3) as.list(filter_param) hcd_param <- FilterFragSpectraParam( select = list(activationType = "HCD"), snr = 2) hcd_paramfilter_param <- FilterFragSpectraParam(plim = 0.7, snr = 3) as.list(filter_param) hcd_param <- FilterFragSpectraParam( select = list(activationType = "HCD"), snr = 2) hcd_param
Filter, flag and remove unwanted peaks from xcms object (xcmsObj) of class XCMSnExp, xcmsSet or xsAnnotate. When the peaks are removed, the xcmsObj object can be regrouped (originally using xcms::group, now using xcms::groupChromPeaks). The function then checks if any blank peaks are still present and the process is repeated.
The output is a list object containing: 1) the updated xcms object, 2) the grouped peaklist and 3) the blank removed peaks
flag_remove( xcmsObj, pol = NA, rsd_i_blank = NA, minfrac_blank = 0.5, rsd_rt_blank = NA, ithres_blank = NA, s2b = 10, ref.class = "blank", egauss_thr = NA, rsd_i_sample = NA, minfrac_sample = 0.7, rsd_rt_sample = NA, ithres_sample = NA, minfrac_xcms = 0.7, mzwid = 0.017, bw = 5, out_dir = ".", temp_save = FALSE, remove_spectra_bool = TRUE, grp_rm_ids = NA, xset = NA )flag_remove( xcmsObj, pol = NA, rsd_i_blank = NA, minfrac_blank = 0.5, rsd_rt_blank = NA, ithres_blank = NA, s2b = 10, ref.class = "blank", egauss_thr = NA, rsd_i_sample = NA, minfrac_sample = 0.7, rsd_rt_sample = NA, ithres_sample = NA, minfrac_xcms = 0.7, mzwid = 0.017, bw = 5, out_dir = ".", temp_save = FALSE, remove_spectra_bool = TRUE, grp_rm_ids = NA, xset = NA )
xcmsObj |
object; XCMSnExp, xcmsSet or xsAnnotate object |
pol |
str; polarity (just used for naming purpose for files being saved) [positive, negative, NA] |
rsd_i_blank |
numeric; RSD threshold for the blank |
minfrac_blank |
numeric; minimum fraction of files for features needed for the blank |
rsd_rt_blank |
numeric; RSD threshold for the RT of the blank |
ithres_blank |
numeric; Intensity threshold for the blank |
s2b |
numeric; fold change (sample/blank) needed for sample peak to be allowed. e.g. if s2b set to 10 and the recorded sample 'intensity' value was 100 and blank = 10. 1000/10 = 100 so sample has fold change higher than the threshold and the peak is not considered a blank |
ref.class |
str; A string representing the class that will be used for the blank. |
egauss_thr |
numeric; Threshold for filtering out non gaussian shaped peaks. Note this only works if the verbose option was set for XCMS; |
rsd_i_sample |
numeric; RSD threshold for the sample |
minfrac_sample |
numeric; minimum fraction of files for features needed for the sample |
rsd_rt_sample |
numeric; RSD threshold for the RT of the sample |
ithres_sample |
numeric; Intensity threshold for the sample |
minfrac_xcms |
numeric; minfrac for xcms grouping |
mzwid |
numeric; xcms grouping parameter (corresponds to variable 'binSize' in XCMS3) |
bw |
numeric; xcms grouping parameter |
out_dir |
str; out directory |
temp_save |
boolean; Assign True if files for each step saved (for testing purpsoses) |
remove_spectra_bool |
bool; TRUE if flagged spectra is to be removed |
grp_rm_ids |
vector; vector of grouped_xcms peaks to remove (corresponds to the row from xcms::group output) |
xset |
object, DEPRECATED; xcmsSet object |
list(xset, grp_peaklist, removed_peaks)
library(xcms) #read in files and data #msPths <-list.files(system.file("extdata", "lcms", "mzML", package="msPurityData"), full.names = TRUE) #ms_data = readMSData(msPths, mode = 'onDisk', msLevel. = 1) #subset the data to focus on retention times 30-90 seconds and m/z values between 100 and 200 m/z. #rtr = c(30, 90) #mzr = c(100, 200) #ms_data = ms_data %>% filterRt(rt = rtr) %>% filterMz(mz = mzr) ##### perform feature detection in individual files #cwp <- CentWaveParam(snthresh = 3, noise = 100, ppm = 10, peakwidth = c(3, 30)) #xcmsObj <- findChromPeaks(ms_data, param = cwp) #xcmsObj@phenoData@data$class = c('blank', 'blank', 'sample', 'sample') #xcmsObj@phenoData@varMetadata = data.frame('labelDescription' = 'sampleNames', 'class') #pdp <- PeakDensityParam(sampleGroups = xcmsObj@phenoData@data$class, minFraction = 0, bw = 5, binSize = 0.017) #xcmsObj <- groupChromPeaks(xcmsObj, param = pdp) ##### load the result of the steps above from existing data xcmsObj = readRDS(system.file("extdata", "tests", "purityA", "10_input_filterflagremove.rds", package="msPurity")) ## The saved object records the file paths of the machine that made it mzmlDir <- system.file("extdata", "lcms", "mzML", package="msPurityData") xcmsObj@processingData@files <- file.path(mzmlDir, c("LCMS_1.mzML", "LCMS_2.mzML", "LCMSMS_1.mzML", "LCMSMS_2.mzML")) #### flag, filter and remove peaks, returning an updated xcmsObj (XCMSnExp or xcmsSet class), grouped_peaklist (data.frame) and removed_peaks (data.frame) fr <- flag_remove(xcmsObj)library(xcms) #read in files and data #msPths <-list.files(system.file("extdata", "lcms", "mzML", package="msPurityData"), full.names = TRUE) #ms_data = readMSData(msPths, mode = 'onDisk', msLevel. = 1) #subset the data to focus on retention times 30-90 seconds and m/z values between 100 and 200 m/z. #rtr = c(30, 90) #mzr = c(100, 200) #ms_data = ms_data %>% filterRt(rt = rtr) %>% filterMz(mz = mzr) ##### perform feature detection in individual files #cwp <- CentWaveParam(snthresh = 3, noise = 100, ppm = 10, peakwidth = c(3, 30)) #xcmsObj <- findChromPeaks(ms_data, param = cwp) #xcmsObj@phenoData@data$class = c('blank', 'blank', 'sample', 'sample') #xcmsObj@phenoData@varMetadata = data.frame('labelDescription' = 'sampleNames', 'class') #pdp <- PeakDensityParam(sampleGroups = xcmsObj@phenoData@data$class, minFraction = 0, bw = 5, binSize = 0.017) #xcmsObj <- groupChromPeaks(xcmsObj, param = pdp) ##### load the result of the steps above from existing data xcmsObj = readRDS(system.file("extdata", "tests", "purityA", "10_input_filterflagremove.rds", package="msPurity")) ## The saved object records the file paths of the machine that made it mzmlDir <- system.file("extdata", "lcms", "mzML", package="msPurityData") xcmsObj@processingData@files <- file.path(mzmlDir, c("LCMS_1.mzML", "LCMS_2.mzML", "LCMSMS_1.mzML", "LCMSMS_2.mzML")) #### flag, filter and remove peaks, returning an updated xcmsObj (XCMSnExp or xcmsSet class), grouped_peaklist (data.frame) and removed_peaks (data.frame) fr <- flag_remove(xcmsObj)
Assign fragmentation spectra (MS/MS) stored within a purityA class object to grouped features within an XCMS xset object.
XCMS calculates individual chromatographic peaks for each mzML file (retrieved using xcms::chromPeaks(xcmsObj)), these are then grouped together (using xcms::groupChromPeaks). Ideally the mzML files that contain the MS/MS spectra also contain sufficient MS1 scans for XCMS to detect MS1 chromatographic features. If this is the case, to determine if a MS2 spectra is to be linked to an XCMS grouped feature, the associated acquisition time of the MS/MS event has to be within the retention time window defined for the individual peaks associated for each file. The precursor m/z value also has to be within the user ppm tolerance to XCMS feature.
See below for representation of the linking (the * —— * represent a many-to-many relationship) e.g. 1 or more MS/MS events can be linked to 1 or more individual feature and an individual XCMS feature can be linked to 1 or more grouped XCMS features
[grouped XCMS feature - across files] * —— * [individual XCMS feature - per file] * —— * [MS/MS spectra]
Alternatively, if the "useGroup" argument is set to TRUE, the full width of the grouped peak (determined as the minimum rtmin
and maximum rtmax of the representative peak of each sample, see groupWindow) will be used. This option should be used if the mzML file with
MS/MS has very limited MS1 data and so individual chromatographic peaks might not be detected with the mzML files containing the
MS/MS data. However, it should be noted this may lead to potential inaccurate linking.
[grouped XCMS peaks] * —— * [MS/MS spectra]
With msLevel = 2:4, MS3 and MS4 inherit feature membership through
validated, same-file acquisition relationships. Root MS2 associations are
established before plim is applied, so a rejected MS2 precursor does
not remove valid descendant links. Higher levels retain their own precursor
and acquisition metadata and their own recorded purity assessments.
Missing or invalid ancestry does not establish a descendant feature link.
Only MS2 precursors are compared with peak and feature windows; the
precursor time of an MS3/MS4 row is mapped to the adjusted scale of its file
for reference.
Selecting only higher levels, such as msLevel = 4L, retains their
required MS2/MS3 source context while returning only the selected feature
links.
MS/MS times are raw times read from each mzML file, while XCMS peak and feature windows are on the adjusted scale once
retention time correction has been applied. With convert2RawRT = TRUE, the time of each MS/MS scan is mapped to the
adjusted scale of its file, by linear interpolation between the raw and adjusted scan times XCMS holds for that file, and is
compared there, in both linking modes. A time equal to an XCMS scan time maps exactly to the adjusted time XCMS gave that scan.
Files are matched to XCMS samples by name, so the MS/MS files can be any subset of the XCMS samples in any order. Each file gets a
mapping status, stored with the other diagnostics in pa@params$frag4feature$rt_diagnostics:
aligned: the file is in the XCMS object, which holds its adjusted times;
unaligned: no retention time correction was applied, times are used unchanged;
external: the mapping comes from ms2RtMap;
estimated: the mapping was estimated from the MS/MS precursors (estimateRtMap = TRUE);
missing: the features are aligned but nothing maps this file, so its raw times are compared with adjusted windows (with a warning);
not_converted: convert2RawRT = FALSE.
When the MS/MS files were not part of the retention time correction (for example DDA files processed apart from the full-scan
samples), supply their mapping with ms2RtMap. The most reliable route is landmark alignment in xcms: run
findChromPeaks on the DDA files, then
adjustRtime(ddaObj, LamaParama(lamas = featureDefinitions(ms1Obj)[, c("mzmed", "rtmed")])), and pass ddaObj.
When XCMS fits the correction, it is best fitted on the full-scan samples only, with
PeakGroupsParam(subset = <MS1 samples>, subsetAdjust = "average"), as DDA files have sparse MS1 data.
Purity assessments
(mzML files) -> purityA -> (pa)
XCMS processing
(mzML files) -> xcms.findChromPeaks -> (optionally) xcms.adjustRtime -> xcms.groupChromPeaks -> (xcmsObj)
— Older versions of XCMS — (mzML files) -> xcms.xcmsSet -> xcms.group -> xcms.retcor -> xcms.group -> (xcmsObj)
Fragmentation processing
(xcmsObj, pa) -> frag4feature -> filterFragSpectra -> averageAllFragSpectra -> createDatabase -> spectralMatching -> (sqlite spectral database)
If using only a single file, then grouping still needs to be performed within XCMS before frag4feature can be used.
Fragmentation spectra below a certain precursor ion purity can be be removed (see plim argument).
Peaks added by xcms::fillChromPeaks are not used for linking unless includeFilled = TRUE.
One MS/MS scan can be linked to several peaks, so it can appear more than once for a feature when the feature holds two peaks
of the same file. matchRank orders the matches of each scan.
A SQLite database can be created directly here but the functionality has been deprecated and the createDatabase function should now be used
## S4 method for signature 'purityA' frag4feature( pa, xcmsObj, ppm = 5, plim = NA, intense = TRUE, convert2RawRT = TRUE, useGroup = FALSE, createDb = FALSE, outDir = ".", dbName = NA, grpPeaklist = NA, ms2RtMap = NULL, rtTol = 0, rtSource = c("precursor", "ms2"), groupWindow = c("full", "median"), includeFilled = FALSE, estimateRtMap = FALSE, use_group = NA, out_dir = NA, create_db = NA, grp_peaklist = NA, db_name = NA, xset = NA, msLevel = 2L, parentReference = "auto", param = NULL )## S4 method for signature 'purityA' frag4feature( pa, xcmsObj, ppm = 5, plim = NA, intense = TRUE, convert2RawRT = TRUE, useGroup = FALSE, createDb = FALSE, outDir = ".", dbName = NA, grpPeaklist = NA, ms2RtMap = NULL, rtTol = 0, rtSource = c("precursor", "ms2"), groupWindow = c("full", "median"), includeFilled = FALSE, estimateRtMap = FALSE, use_group = NA, out_dir = NA, create_db = NA, grp_peaklist = NA, db_name = NA, xset = NA, msLevel = 2L, parentReference = "auto", param = NULL )
pa |
object; purityA object |
xcmsObj |
object; XcmsExperiment, XCMSnExp, xcmsSet or xsAnnotate object derived from the same files as those used to create the purityA object |
ppm |
numeric; ppm tolerance between precursor mz and XCMS feature mz |
plim |
numeric; minimum MS2 precursor purity to be included. This threshold does not apply to MS3/MS4 diagnostic purity. |
intense |
boolean; If TRUE the most intense precursor (iMz) will be used. If FALSE the precursor closest to the center of the isolation window (aMz) will be used. Missing values fall back to aMz and then to the precursor m/z of the mzML file. Applies to both linking modes. |
convert2RawRT |
boolean; If TRUE, MS/MS times are mapped to the adjusted retention time scale before being compared with XCMS windows. If FALSE, raw MS/MS times are compared with the XCMS windows as they are. |
useGroup |
boolean; Ignore individual peaks and just find matching fragmentation spectra within the (full) rtmin rtmax of each grouped feature |
createDb |
boolean; if yes, generate a database of MS2 spectra |
outDir |
string; path where (optionally generated) database file should be saved |
dbName |
character; name to assign to (optionally exported) database. |
grpPeaklist |
dataframe; Can use any peak dataframe to add to databse. Still needs to be derived from the "obj" object though |
ms2RtMap |
object; mapping to the adjusted scale for MS/MS files the XCMS object does not align. Either an XCMS object holding those files
with adjusted retention times, a list of functions from raw to adjusted time, or a numeric vector of offsets (adjusted = raw + offset).
Lists and vectors are named by file. Files aligned in |
rtTol |
numeric; tolerance in seconds added to both sides of each retention time window, to absorb error left after mapping |
rtSource |
character; MS/MS time to compare: "precursor" uses the time of the MS1 survey scan (falling back to the MS/MS scan time), "ms2" uses the time of the MS/MS scan |
groupWindow |
character; window of a feature when |
includeFilled |
boolean; If TRUE, peaks added by xcms::fillChromPeaks are used for linking and flagged in the is_filled column. A link through a filled peak means the MS/MS fell where the feature was expected in that file, not inside a detected peak. DDA files have sparse MS1 data, so many of their features exist only as filled peaks. |
estimateRtMap |
boolean; If TRUE and |
use_group |
boolean; (Deprecated, to be removed - replaced with useGroup argument for style consistency) |
out_dir |
character; (Deprecated, to be removed - use createDatabase function) Path where database will be created |
create_db |
boolean; (Deprecated, to be removed - use createDatabase function) SQLite database will be created of the results |
grp_peaklist |
dataframe; (Deprecated, to be removed - use createDatabase function) Can use any peak dataframe to add to databse. Still needs to be derived from the xset object though |
db_name |
character; (Deprecated, to be removed - use createDatabase function) If create_db is TRUE, a custom database name can be used, default is a time stamp |
xset |
object; (Deprecated, to be removed - use xcmsObj) 'xcmsSet' object derived from the same files as those used to create the purityA object |
msLevel |
Nonempty numeric vector of output levels selected from 2, 3 and 4. The default retains MS2-only links. MS3/MS4 inherit membership through their validated MS2 acquisition ancestors. |
parentReference |
How to interpret parent references. Numeric
|
param |
One complete |
Purity is assessed by purityA(msLevel = 2:4) before feature
association. This function reuses prepared parent relationships and keeps
the recorded assessments when features are relinked; it does not calculate
purity. When requested by msLevel, MS3/MS4 inherit their MS2
ancestors' feature links and retain their own purity values and status.
This function's plim applies only to MS2. Use
filterFragSpectra() for optional purity thresholds at each level.
For unassessed MS2
roots, use intense = FALSE to associate recorded precursor m/z.
MSn averaging and processed export are separate operations.
Processing history records requested and effective workers, whether the retention time mapping was requested and applied, and a fingerprint of the prepared feature bounds and memberships used for association. The mapping is used by both association modes. No XCMS object or peak arrays are copied into history. The fingerprint identifies the prepared association inputs, not the complete original data or a replayable analysis. Association runs as one serial join, so effective workers is one when matching runs and zero when no matching runs because MS2 roots or chromatographic peaks are unavailable.
Returns a purityA object (pa) with the following slots populated:
pa@grped_df: A dataframe of the grouped XCMS features linked to the associated fragmentation spectra precursor details is recorded here. Besides the XCMS columns and the precursor details, it holds
linkId, an integer identifying this association occurrence through filtering, reordering and averaging. Multiple occurrences can refer to the same pid.
precurMtchRTadj: the MS/MS time on the adjusted scale, as compared with the window
rtMapStatus: the mapping status of the file (see above)
precurMzSource: the precursor m/z used (iMz, aMz or precursorMZ)
is_filled: whether the peak was added by fillChromPeaks (individual mode)
rtminWin, rtmaxWin: the feature window used (grouped mode)
rtApexDist: distance from the peak or feature apex, divided by the window width
matchRank: rank of the match among the matches of the scan, by rtApexDist then ppm error
pa@fragSpectra: The linked fragmentation spectra as a Spectra object, each scan once, identified by
its pid. groupedSpectra(pa) returns them as a list per XCMS feature
pa@grped_ms2: The legacy list of fragmentation spectra for each grouped XCMS feature, filled while
options(msPurity.legacySlots = TRUE) (the default)
pa@f4f_link_type: The linking method is recorded here (e.g. individual peaks or grouped - "useGroup=TRUE")
#====== XCMS ================================= ## Read in MS data #msmsPths <- list.files(system.file("extdata", "lcms", "mzML", # package="msPurityData"), full.names = TRUE, pattern = "MSMS") #ms_data = readMSData(msmsPths, mode = 'onDisk', msLevel. = 1) ## Find peaks in each file #cwp <- CentWaveParam(snthresh = 5, noise = 100, ppm = 10, peakwidth = c(3, 30)) #xcmsObj <- xcms::findChromPeaks(ms_data, param = cwp) ## Optionally adjust retention time #xcmsObj <- adjustRtime(xcmsObj , param = ObiwarpParam(binSize = 0.6)) ## Group features across samples #pdp <- PeakDensityParam(sampleGroups = c(1, 1), minFraction = 0, bw = 30) #xcmsObj <- groupChromPeaks(xcmsObj , param = pdp) ## Or if using the old XCMS functions #xcmsObj <- xcms::xcmsSet(msmsPths) #xcmsObj <- xcms::group(xcmsObj) #xcmsObj <- xcms::retcor(xcmsObj) #xcmsObj <- xcms::group(xcmsObj) #====== msPurity ============================ #pa <- purityA(msmsPths) #pa <- frag4feature(pa, xcmsObj) ## Run from previously generated data msmsPths <- list.files(system.file("extdata", "lcms", "mzML", package="msPurityData"), full.names = TRUE, pattern = "MSMS") pa <- readRDS(system.file("extdata", "tests", "purityA", "1_purityA_pa.rds", package="msPurity")) xcmsObj <- readRDS(system.file("extdata", "tests", "xcms", "msms_only_xcmsnexp.rds", package="msPurity")) ## The saved objects record the file paths of the machine that made them pa@fileList[1:2] <- msmsPths xcmsObj@processingData@files <- msmsPths pa <- frag4feature(pa, xcmsObj)#====== XCMS ================================= ## Read in MS data #msmsPths <- list.files(system.file("extdata", "lcms", "mzML", # package="msPurityData"), full.names = TRUE, pattern = "MSMS") #ms_data = readMSData(msmsPths, mode = 'onDisk', msLevel. = 1) ## Find peaks in each file #cwp <- CentWaveParam(snthresh = 5, noise = 100, ppm = 10, peakwidth = c(3, 30)) #xcmsObj <- xcms::findChromPeaks(ms_data, param = cwp) ## Optionally adjust retention time #xcmsObj <- adjustRtime(xcmsObj , param = ObiwarpParam(binSize = 0.6)) ## Group features across samples #pdp <- PeakDensityParam(sampleGroups = c(1, 1), minFraction = 0, bw = 30) #xcmsObj <- groupChromPeaks(xcmsObj , param = pdp) ## Or if using the old XCMS functions #xcmsObj <- xcms::xcmsSet(msmsPths) #xcmsObj <- xcms::group(xcmsObj) #xcmsObj <- xcms::retcor(xcmsObj) #xcmsObj <- xcms::group(xcmsObj) #====== msPurity ============================ #pa <- purityA(msmsPths) #pa <- frag4feature(pa, xcmsObj) ## Run from previously generated data msmsPths <- list.files(system.file("extdata", "lcms", "mzML", package="msPurityData"), full.names = TRUE, pattern = "MSMS") pa <- readRDS(system.file("extdata", "tests", "purityA", "1_purityA_pa.rds", package="msPurity")) xcmsObj <- readRDS(system.file("extdata", "tests", "xcms", "msms_only_xcmsnexp.rds", package="msPurity")) ## The saved objects record the file paths of the machine that made them pa@fileList[1:2] <- msmsPths xcmsObj@processingData@files <- msmsPths pa <- frag4feature(pa, xcmsObj)
Supply one complete object to frag4feature(param = ). Explicit
scalar association arguments supplied alongside the object must agree with
its settings. The deprecated use_group argument must also agree.
Named lists and acquisition-metadata selectors are not supported.
Frag4FeatureParam( ppm = 5, plim = NA_real_, intense = TRUE, convert2RawRT = TRUE, useGroup = FALSE, parentReference = "auto", rtTol = 0, rtSource = "precursor", groupWindow = "full", includeFilled = FALSE, estimateRtMap = FALSE )Frag4FeatureParam( ppm = 5, plim = NA_real_, intense = TRUE, convert2RawRT = TRUE, useGroup = FALSE, parentReference = "auto", rtTol = 0, rtSource = "precursor", groupWindow = "full", includeFilled = FALSE, estimateRtMap = FALSE )
ppm |
Mass tolerance in ppm for matching an MS2 precursor to an XCMS feature. |
plim |
Minimum MS2 precursor purity, between zero and one, or
|
intense |
Use the most intense precursor ( |
convert2RawRT |
Map MS2 precursor times to the adjusted XCMS retention-time scale of their file before comparing them with peak and feature windows. |
useGroup |
Use grouped-feature retention-time windows instead of individual chromatographic peaks. |
parentReference |
Parent-reference interpretation used by
|
rtTol |
Tolerance in seconds added to both sides of each retention-time window. |
rtSource |
MS2 time to compare: |
groupWindow |
Feature window when |
includeFilled |
Use peaks added by |
estimateRtMap |
Estimate a retention-time map for files without one (grouped association only). |
The call-wide msLevel argument selects feature-link output levels.
MS3/MS4 inherit the feature membership of their validated MS2 ancestors;
association retains the source spectra needed to resolve that ancestry.
Purity is assessed separately by purityA.
A Frag4FeatureParam extending ProtGenerics::Param.
as.list() returns all eleven settings.
frag4feature, processingParameters
feature_param <- Frag4FeatureParam(ppm = 5, plim = 0.7) as.list(feature_param) feature_paramfeature_param <- Frag4FeatureParam(ppm = 5, plim = 0.7) as.list(feature_param) feature_param
List the direct precursor-product links of a peak tree
fragmentLinks(x)fragmentLinks(x)
x |
A |
A data frame in stored fragmentation-edge order. Edge columns,
including exact source and target IDs, are retained. An edge annotation
with a reserved output name receives an edge_ prefix. Added columns
give the product run, and each endpoint's acquisition number, original
peak position and measured m/z. delta_mz is the signed difference
precursor_mz - fragment_mz. It is missing when either endpoint is
unmeasured. For ions retaining the same known charge and adduct, multiply
delta_mz by the absolute charge to screen for a neutral loss in Da.
Older views without scan numbers retain their IDs.
Repeated masses and parallel observations each retain their own rows.
f <- system.file("extdata", "msn-standards", "kynurenine-pft.rds", package = "msPurity") links <- fragmentLinks(readRDS(f)) subset(links, abs(fragment_mz - 118.10124) <= 118.10124 * 5 / 1e6) # Candidate loss for a singly charged series retaining the same adduct. subset(links, abs(delta_mz - 18.010565) <= 0.002)f <- system.file("extdata", "msn-standards", "kynurenine-pft.rds", package = "msPurity") links <- fragmentLinks(readRDS(f)) subset(links, abs(fragment_mz - 118.10124) <= 118.10124 * 5 / 1e6) # Candidate loss for a singly charged series retaining the same adduct. subset(links, abs(delta_mz - 18.010565) <= 0.002)
Creates a function based on a gaussian curve shape that will normalise any intensity values within a defined isolation window.
The function that is created will output a value between 0 to 1 based on the position between the minOff and maxOff params. (The value 1.0 being equivalent to 100% efficient)
iwNormGauss(sdlim = 3, minOff = -0.5, maxOff = +0.5)iwNormGauss(sdlim = 3, minOff = -0.5, maxOff = +0.5)
sdlim |
numerical; Standard deviation limit for gaussian curve |
minOff |
numerical; Offset to the 'left' for the precursor range. (Should be negative) |
maxOff |
character; Offset to the 'left' for the precursor range. (Should be positive) |
normalisation function for selected range.
iwNormFun <- iwNormGauss(minOff=-0.5, maxOff=0.5) pm <- data.frame(mz=c(99.5, 99.9, 100, 100.1, 100.5),i=c(1000, 1000, 1000, 1000, 1000)) mzmax = 100.5 mzmin = 99.5 middle <- mzmax-(mzmax-mzmin)/2 adjustmz = pm$mz-middle # normalise the intensities pm$normi = pm$i*iwNormFun(adjustmz)iwNormFun <- iwNormGauss(minOff=-0.5, maxOff=0.5) pm <- data.frame(mz=c(99.5, 99.9, 100, 100.1, 100.5),i=c(1000, 1000, 1000, 1000, 1000)) mzmax = 100.5 mzmin = 99.5 middle <- mzmax-(mzmax-mzmin)/2 adjustmz = pm$mz-middle # normalise the intensities pm$normi = pm$i*iwNormFun(adjustmz)
Creates a function based on a previous experimental analysis of a Q-Exactive at +/- 0.5 isolation window efficiency. See http://pubs.acs.org/doi/abs/10.1021/acs.analchem.6b04358
The function that is created will output a value between 0 to 1 based on the position between the minOff and maxOff params
NOTE: The resulting function will work for values greater that 0.5 and less than -0.5.
This is because (on our instrument tested at least) when using a window of +/- 0.5, the isolation is NOT confined to the +/-0.5 Da window. Resulting in ions from outside the window being isolated. For this reason the function can normalise values outside of the the +/- 1 Da range. Please see above paper figure 3 for more details.
iwNormQE.5()iwNormQE.5()
normalisation function for +/- 0.5 range for Q-Exactive
iwNormFun <- iwNormQE.5() pm <- data.frame(mz=c(99.5, 99.9, 100, 100.1, 100.5),i=c(1000, 1000, 1000, 1000, 1000)) mzmax = 100.5 mzmin = 99.5 middle <- mzmax-(mzmax-mzmin)/2 adjustmz = pm$mz-middle # normalise the intensities pm$normi = pm$i*iwNormFun(adjustmz)iwNormFun <- iwNormQE.5() pm <- data.frame(mz=c(99.5, 99.9, 100, 100.1, 100.5),i=c(1000, 1000, 1000, 1000, 1000)) mzmax = 100.5 mzmin = 99.5 middle <- mzmax-(mzmax-mzmin)/2 adjustmz = pm$mz-middle # normalise the intensities pm$normi = pm$i*iwNormFun(adjustmz)
Creates a function based on a rasied cosine curve shape that will normalise any intensity values within a defined isolation window
The function that is created will output a value between 0 to 1 based on the position between the minOff and maxOff params
iwNormRcosine(minOff = -0.5, maxOff = +0.5)iwNormRcosine(minOff = -0.5, maxOff = +0.5)
minOff |
numerical; Offset to the 'left' for the precursor range. (Should be negative) |
maxOff |
character; Offset to the 'left' for the precursor range. (Should be positive) |
normalisation function for selected range
iwNormFun <- iwNormRcosine() pm <- data.frame(mz=c(99.5, 99.9, 100, 100.1, 100.5),i=c(1000, 1000, 1000, 1000, 1000)) mzmax = 100.5 mzmin = 99.5 middle <- mzmax-(mzmax-mzmin)/2 adjustmz = pm$mz-middle # normalise the intensities pm$normi = pm$i*iwNormFun(adjustmz)iwNormFun <- iwNormRcosine() pm <- data.frame(mz=c(99.5, 99.9, 100, 100.1, 100.5),i=c(1000, 1000, 1000, 1000, 1000)) mzmax = 100.5 mzmin = 99.5 middle <- mzmax-(mzmax-mzmin)/2 adjustmz = pm$mz-middle # normalise the intensities pm$normi = pm$i*iwNormFun(adjustmz)
Represent measured spectra and their validated acquisition parents as portable node and edge tables using spectrum metadata.
massSpectralTrees( object, parentReference = c("auto", "acquisitionNum", "scanIndex", "spectrumId", "sourceSpectrumId") )massSpectralTrees( object, parentReference = c("auto", "acquisitionNum", "scanIndex", "spectrumId", "sourceSpectrumId") )
object |
A |
parentReference |
Interpretation of recorded parent references. One of
|
Each supplied scan becomes one node. Only valid parent relationships resolved
within the supplied scans become edges. Missing, excluded and invalid parents
retain their resolution status in parentStatus.
The supported acquisition levels are MS1 through MS4.
For purityA inputs, the source scans and their retained acquisition
preparation define the tree. Valid cached preparation is reused, and its
stored scan order determines node order. Changes to acquisition metadata
invalidate that preparation. Feature links and filtering flags do not remove
source scans from this tree. Supply a subset of the measured Spectra
instead when a smaller eligible set is required.
For Spectra inputs, nodes follow input order. Each scan needs a known
run, supplied by run_id, dataOrigin or fileid. Existing
source keys or lineageScanId values are retained. Otherwise lineage
identifiers use the run and native spectrumId, or a complete set of
positive integer scanIndex values. With neither native field,
retained pid values preserve msPurity's existing lineage keys.
Generic inputs without pid can use per-run acquisitionNum.
Partial native identity fields require an explicit lineage key.
Native spectrum identifiers, source keys and object-local pid values
remain separate columns.
Averaged and consensus spectra are outside this acquisition-tree interface.
Inputs carrying an averaging level or a combineSpectra processing
record are rejected. Other derived inputs must not be supplied as measured
scans. Peak filtering of measured scans is allowed and does not change
acquisition relationships.
A MassSpectralTrees list containing:
nodes: one row per scan, keyed by lineageScanId, with
original identity fields, acquisition metadata and parent status. A stored
inPurity score is included when supplied. The
pid column is NA when the input did not provide it.
edges: directed acquisition relationships from
parentLineageScanId to lineageScanId, with the recorded
parent reference and its interpretation.
metadata: the structure, input type, requested parent reference
and resolved parentReference convention.
Empty inputs return the same columns with zero rows.
metadata <- S4Vectors::DataFrame( spectrumId = c("scan=10", "scan=20", "scan=30"), dataOrigin = "example.mzML", msLevel = 1:3, acquisitionNum = c(10L, 20L, 30L), scanIndex = 1:3, precScanNum = c(0L, 10L, 20L), rtime = c(1, 2, 3), precursorMz = c(NA_real_, 300, 150)) metadata$mz <- list(300, 150, 75) metadata$intensity <- list(100, 80, 40) spectra <- Spectra::Spectra(metadata) trees <- massSpectralTrees(spectra, parentReference = "acquisitionNum") trees$nodes[, c("lineageScanId", "msLevel", "parentStatus")] trees$edgesmetadata <- S4Vectors::DataFrame( spectrumId = c("scan=10", "scan=20", "scan=30"), dataOrigin = "example.mzML", msLevel = 1:3, acquisitionNum = c(10L, 20L, 30L), scanIndex = 1:3, precScanNum = c(0L, 10L, 20L), rtime = c(1, 2, 3), precursorMz = c(NA_real_, 300, 150)) metadata$mz <- list(300, 150, 75) metadata$intensity <- list(100, 80, 40) spectra <- Spectra::Spectra(metadata) trees <- massSpectralTrees(spectra, parentReference = "acquisitionNum") trees$nodes[, c("lineageScanId", "msLevel", "parentStatus")] trees$edges
This page documents the DIMS functions and the purityD class and
methods retained for compatibility. Shared functions used by the LC-MS
workflows remain supported. The purityD method for
updatePeaks() is also deprecated.
get_additional_mzml_meta(mzml_pth) ## S4 method for signature 'purityD' getP(x) ## S4 method for signature 'purityD' show(object) ## S4 method for signature 'purityD' initialize(.Object, fileList, cores = 1, mzML = TRUE, mzRback = "pwiz") ## S4 method for signature 'purityD' averageSpectra( Object, rtscn = "all", scanRange = NA, timeRange = NA, clustType = "hc", ppm = 1.5, snthr = 3, av = "median", missingV = "zero", minfrac = 0.6667, normTIC = FALSE, snMeth = "median", mzRback = "pwiz", cores = 1, blockSize = 5000L ) averageSpectraSingle( filePth, rtscn = "all", scanRange = NA, timeRange = NA, clustType = "hc", ppm = 1.5, snthr = 3, cores = 1, av = "median", missingV = "ignore", minfrac = 0.6667, snMeth = "median", csvFile = FALSE, normTIC = FALSE, mzRback = "pwiz", MSFileReader = FALSE, blockSize = 5000L ) ## S4 method for signature 'purityD' groupPeaks( Object, ppm = 3, sampleOnly = FALSE, clustType = "hc", cores = 1, blockSize = 5000L ) groupPeaksEx( peak_list, cores = 1, clustType = "hc", ppm = 2, blockSize = 5000L ) ## S4 method for signature 'purityD' dimsPredictPurity( Object, ppm = 1.5, minOffset = 0.5, maxOffset = 0.5, iwNorm = FALSE, iwNormFun = NULL, ilim = 0.05, sampleOnly = FALSE, isotopes = TRUE, im = NULL ) dimsPredictPuritySingle( mztargets, filepth, minOffset = 0.5, maxOffset = 0.5, ppm = 2.5, mzML = TRUE, iwNorm = FALSE, iwNormFun = NULL, ilim = 0.05, mzRback = "pwiz", isotopes = TRUE, im = NULL, sim = FALSE ) Getfiles( projectFolder = NULL, recursive = FALSE, pattern = ".csv", check = TRUE, raw = FALSE, peakout = NA, cStrt = TRUE, mzml_out = FALSE ) ## S4 method for signature 'purityD' filterp(Object, thr = 5000, rsd = 20, sampleOnly = TRUE) ## S4 method for signature 'purityD' updateObject(object, ..., verbose = FALSE) ## S4 method for signature 'purityD' averagedPeaks(pd, legacy = TRUE) ## S4 method for signature 'purityD' subtract( Object, byClass = TRUE, mapping = c("sample", "blank"), ppm = 5, s2bthres = 10 ) subtractMZ(mz1, mz2, i1, i2, ppm = 5, s2bthres = 10) ## S4 method for signature 'purityD' writeOut(Object, outDir, original)get_additional_mzml_meta(mzml_pth) ## S4 method for signature 'purityD' getP(x) ## S4 method for signature 'purityD' show(object) ## S4 method for signature 'purityD' initialize(.Object, fileList, cores = 1, mzML = TRUE, mzRback = "pwiz") ## S4 method for signature 'purityD' averageSpectra( Object, rtscn = "all", scanRange = NA, timeRange = NA, clustType = "hc", ppm = 1.5, snthr = 3, av = "median", missingV = "zero", minfrac = 0.6667, normTIC = FALSE, snMeth = "median", mzRback = "pwiz", cores = 1, blockSize = 5000L ) averageSpectraSingle( filePth, rtscn = "all", scanRange = NA, timeRange = NA, clustType = "hc", ppm = 1.5, snthr = 3, cores = 1, av = "median", missingV = "ignore", minfrac = 0.6667, snMeth = "median", csvFile = FALSE, normTIC = FALSE, mzRback = "pwiz", MSFileReader = FALSE, blockSize = 5000L ) ## S4 method for signature 'purityD' groupPeaks( Object, ppm = 3, sampleOnly = FALSE, clustType = "hc", cores = 1, blockSize = 5000L ) groupPeaksEx( peak_list, cores = 1, clustType = "hc", ppm = 2, blockSize = 5000L ) ## S4 method for signature 'purityD' dimsPredictPurity( Object, ppm = 1.5, minOffset = 0.5, maxOffset = 0.5, iwNorm = FALSE, iwNormFun = NULL, ilim = 0.05, sampleOnly = FALSE, isotopes = TRUE, im = NULL ) dimsPredictPuritySingle( mztargets, filepth, minOffset = 0.5, maxOffset = 0.5, ppm = 2.5, mzML = TRUE, iwNorm = FALSE, iwNormFun = NULL, ilim = 0.05, mzRback = "pwiz", isotopes = TRUE, im = NULL, sim = FALSE ) Getfiles( projectFolder = NULL, recursive = FALSE, pattern = ".csv", check = TRUE, raw = FALSE, peakout = NA, cStrt = TRUE, mzml_out = FALSE ) ## S4 method for signature 'purityD' filterp(Object, thr = 5000, rsd = 20, sampleOnly = TRUE) ## S4 method for signature 'purityD' updateObject(object, ..., verbose = FALSE) ## S4 method for signature 'purityD' averagedPeaks(pd, legacy = TRUE) ## S4 method for signature 'purityD' subtract( Object, byClass = TRUE, mapping = c("sample", "blank"), ppm = 5, s2bthres = 10 ) subtractMZ(mz1, mz2, i1, i2, ppm = 5, s2bthres = 10) ## S4 method for signature 'purityD' writeOut(Object, outDir, original)
mzml_pth |
character; mzML path |
x |
object; purityD object |
object |
purityD object. |
.Object |
object; purityD object |
fileList |
A data frame from |
cores |
numeric; Maximum number of workers, as a positive integer. More workers can increase memory use. |
mzML |
Logical; use mzML input when TRUE and CSV input when FALSE. |
mzRback |
character; deprecated and ignored. Raw data is read through Spectra, which uses the pwiz reader |
Object |
object; purityD object |
rtscn |
character; Whether it is scans or retention time to be filtered. Use "all" if all scans to be used. ['rt', 'scns', 'all'] |
scanRange |
vector; Scan range (if rtscn='scns') e.g. c(40, 69) |
timeRange |
vector; Time range (if rtscn='rt) e.g. c(10.3, 400.8) (only if using mzML file) |
clustType |
= if 'hc' the hierarchical clustering, if 'simple' the mz values will just be grouped using a simple 1D method |
ppm |
numeric = ppm tolerance |
snthr |
numeric; Signal to noise ratio threshold |
av |
character; What type of averaging to do between peaks |
missingV |
character; What to do with missing values (zero or ignore) |
minfrac |
numeric; Min fraction of scans with a grouped peak to be an accepted averaged peak |
normTIC |
boolean; If TRUE then RSD calculation will use the normalised intensity (intensity divided by TIC) if FALSE will use standard intensity |
snMeth |
character; Type of snMethod to use ['mean', 'median', 'precalc']. Precalc only applicable when using the csvFile parameter as TRUE |
blockSize |
numeric; Maximum input peak rows per hierarchical-clustering calculation, as a positive integer (default 5,000). Safe blocks can be smaller; larger groups fitting one tolerance window need no distance matrix. Used only for hierarchical clustering; distance-matrix memory grows quadratically with this limit. |
filePth |
character; Path of the file to be processed |
csvFile |
boolean; A csv file can be used as input. Useful for thermo files where the MSFileReader API can extract peaklist. This can consist of an .csv file with the following columns c('mz', 'i', 'scanid', 'snr') |
MSFileReader |
boolean; Deprecapted. Use csvFile parameter |
sampleOnly |
Logical; apply filtering, grouping or purity prediction only to sample peak lists, excluding blanks. |
peak_list |
list = A list (named) of dataframes consiting of a least the following columns ['peakID', 'mz'] |
minOffset |
numeric = isolation window minimum offset |
maxOffset |
numeric = isolation window maximum offset |
iwNorm |
boolean = if TRUE then the intensity of the isolation window will be normalised based on the iwNormFun function |
iwNormFun |
function = A function to normalise the isolation window intensity. The default function is very generalised and just accounts for edge effects |
ilim |
numeric = All peaks less than this percentage of the target peak will be removed from the purity calculation, default is 5% (0.05) |
isotopes |
boolean = TRUE if isotopes are to be removed |
im |
matrix = Isotope matrix, default removes C13 isotopes (single, double and triple bonds) |
mztargets |
vector = mz targets to get predicted purity for |
filepth |
character = mzML file path or .csv file path |
sim |
boolean = TRUE if file is from sim stitch experiment. Default FALSE |
projectFolder |
character; Directory path |
recursive |
boolean; Recursively check for files |
pattern |
character; File suffix to check for |
check |
boolean; Check with a GUI the files |
raw |
(REDUNDANT) |
peakout |
(REDUNDANT) |
cStrt |
boolean; Use the first word as the class name for files |
mzml_out |
(REDUNDANT) |
thr |
numeric; intensity threshold |
rsd |
numeric; rsd threshold |
... |
unused. |
verbose |
logical; unused. |
pd |
purityD object. |
legacy |
logical; TRUE for the avPeaks list, FALSE for |
byClass |
boolean; subtract within each class |
mapping |
parameter not functional (TODO) |
s2bthres |
numeric = threshold for the samp2blank (i1/i2) |
mz1 |
vector = mz values to start with |
mz2 |
vector = mz values to subtract |
i1 |
vector = i values for mz1 |
i2 |
vector = i values for mz2 |
outDir |
character; Directory to save text files |
original |
boolean; If the original (unprocessed) files are to be saved to text files |
With hierarchical clustering, matching peaks stay together. The call stops
with an error if more than blockSize nearby peaks cannot form one group or be
separated without splitting matching peaks.
Return values depend on the function; see the individual sections.
The DIMS workflow is deprecated and will receive no further bug fixes or feature development. There is no direct replacement in msPurity. Calls remain functional during deprecation; the interfaces will become defunct and be removed in subsequent release cycles.
Extract the filter strings 'accession MS:1000512' from an mzML file. Called header in thermo software. Enables quick access to various information regarding each scan
Value: dataframe of meta info
The class used to assess anticipated purity from a DI-MS run
Value: purityD object
output peak list for a purityD object
Value: peaks
Show method for purityD object
Value: a print statement of regarding object
The class used to predict purity from an DI-MS dataset.
Value: purityD object. The files and their sample information are also kept as an MsExperiment in
the experiment slot, and the averaged peak lists of later steps as Spectra in the avSpectra slot
(see averagedPeaks)
If cores is omitted, the call uses Object@cores
without changing that stored setting.
Uses a purityD object with references to multiple MS files. For each file: Averages multiple scans together, see averageSpectraSingle for more information
Value: purityD object with averaged spectra
Averages multiple scans of mass spectrometry data together. Each scan consisting of a minimum of intensity and mz values.
Works for either mzML or a .csv file consisting of mz, i, scanid, (optional: noise, backgroun, snr)
Signal-to-noise (SNR) can be calculated a number of ways. Default is to calculate the SN for every scan as the "Intensity of peak / the median intensity of the scan".
Alternatively if using a .csv file as input (and assigning the csvFile parameter to TRUE), a precalculated SNR can be one of the columns. The precalculated SNR can then be chosen by using the option 'precalc' for the parameter snMethod
The function will work for both LC-MS or DI-MS datasets.
Value: dataframe of the median mz, intensity, signal-to-noise ratio.
If cores is omitted, the call uses Object@cores
without changing that stored setting.
Uses a purityD object to group all the peaklists in the 'avPeaks$processing' slot
Value: data.frame of peaklists grouped together by mz
Group a list of dataframes by their m/z values
Value: data.frame of peaklists grouped together by mz
Assess the precursor purity of anticpated MS/MS spectra. i.e. it 'predicts' the precursor purity of the DI-MS peaks for a future MS/MS run.
Value: purityD object with predicted purity of peaks
Given a an DI-MS dataset (either mzML or .csv file) calculate the predicted purity for a vector of mz values.
Calculated at a given offset e.g. for 0.5 +/- Da the minOffset would be 0.5 and the maxOffset of 0.5.
A ppm tolerance is used to find the target mz value in each scan.
Value: a dataframe of the target mz values and the predicted purity score
Takes in a folder path and outputs the a data frame structure for purityD. Function modified from mzmatch.
Value: dataframe of files
Uses a purityD object remove peaks from either (or both) samples and blanks that are either below an intensity threshold or greater than a Relative Standard Deviation (RSD) threshold
Value: purityD object
Objects saved before msPurity stored the averaged DIMS peak lists in a
Spectra object lack the avSpectra and experiment
slots. updateObject() builds them from avPeaks and
fileList. Every purityD method updates its input this way.
Value: An updated purityD object.
The averaged peak list of each file, as the avPeaks list (a list
with elements orig and processed, each with one data frame
per file; legacy = TRUE, the default) or as a Spectra
object with one spectrum per file and stage, with the other columns as
peak variables (legacy = FALSE). The legacy avPeaks slot is
only filled while options(msPurity.legacySlots = TRUE), the
default for this release.
Value: A list or a Spectra object.
Uses a purityD object with references to multiple MS files. Subtract blank peaks from the sample peaks see subtractMZ for more information
Value: purityD object with averaged spectra
This function is intended for blank subtraction of mz values from two peaklists. It takes in 2 vectors of mz values and 2 coresponding vectors of Intensity values.
The second mz values are subtracted from the first set within an MZ tolerance.
However, if the mz match but the intensity is above a defined threshold then they are not subtracted
Value: a vector of the remaining mz values
Writes processed peak lists to CSV files, and also writes the original
peak lists when original = TRUE.
Value: purityD object
Reports what msPurity's Parquet backend can do, as a capability set
conforming to capabilities.schema.json: the conformance classes it
claims, the run kinds it reads and writes, the results entities it writes,
the source formats it converts and how each error class is surfaced.
The backend is experimental. A capability set is a declaration, not a conformance claim.
parquetCapabilities()parquetCapabilities()
A named list; jsonlite::toJSON(x, auto_unbox = TRUE) gives the
JSON document.
str(parquetCapabilities(), max.level = 1)str(parquetCapabilities(), max.level = 1)
This is the main purity calculation that is performed in purityX, purityD and purityA.
Takes in a matrix of peaks
gets isolation window based on mzmin mzmax
locates the mz target in the peak matrix
removes isotopic peaks
removes any peaks below limit (percentage of target peak intensity)
normalises
Calculates purity: Divides the target peak intensity by the total peak intensity for the isolation window
pcalc( peaks, mzmin, mzmax, mztarget, ppm = NA, iwNorm = FALSE, iwNormFun = NULL, ilim = 0, targetMinMZ = NA, targetMaxMZ = NA, isotopes = FALSE, im = NULL )pcalc( peaks, mzmin, mzmax, mztarget, ppm = NA, iwNorm = FALSE, iwNormFun = NULL, ilim = 0, targetMinMZ = NA, targetMaxMZ = NA, isotopes = FALSE, im = NULL )
peaks |
matrix; Matrix of peaks consisting of 2 columns: mz and i |
mzmin |
numeric; Isolation window (min) |
mzmax |
numeric; Isolation window (max) |
mztarget |
numeric; The mz window to target in the isolation window |
ppm |
numeric; PPM tolerance for the target mz value. If NA will presume targetMinMZ and targetMaxMZ will be used |
iwNorm |
boolean; If TRUE then the intensity of the isolation window will be normalised based on the iwNormFun function |
iwNormFun |
function; A function to normalise the isolation window intensity. The default function is very generalised and just accounts for edge effects |
ilim |
numeric; All peaks less than this percentage of the target peak will be removed from the purity calculation, default is 5% (0.05) |
targetMinMZ |
numeric; Range to look for the mztarget (min) |
targetMaxMZ |
numeric; Range to look for the mztarget (max) |
isotopes |
boolean; TRUE if isotopes are to be removed |
im |
matrix; Isotope matrix, default removes C13 isotopes (single, double and triple bonds) |
a vector of the purity score and the number of peaks in the window e.g c(purity, pknm)
pm <- rbind(c(100, 1000),c(101.003, 10)) pcalc(pm, mzmin = 98, mzmax = 102, mztarget=100, ppm=5) pcalc(pm, mzmin = 98, mzmax = 102, mztarget=100, ppm=5, isotopes = TRUE)pm <- rbind(c(100, 1000),c(101.003, 10)) pcalc(pm, mzmin = 98, mzmax = 102, mztarget=100, ppm=5) pcalc(pm, mzmin = 98, mzmax = 102, mztarget=100, ppm=5, isotopes = TRUE)
Link each fragmentation scan's observed products to a measured peak in
its acquisition parent. A purityA input reuses recorded parent peak
assignments from MS3/MS4 purity assessments.
precursorFragmentTrees( object, ppm = 5, tolerance = 0, parentReference = "auto", spectra = NULL, passingOnly = FALSE )precursorFragmentTrees( object, ppm = 5, tolerance = 0, parentReference = "auto", spectra = NULL, passingOnly = FALSE )
object |
Measured |
ppm, tolerance
|
For scans without a recorded assignment, the
nonnegative relative tolerance in ppm and absolute
tolerance in Da, defaulting to 5 ppm and 0 Da. The inclusive half-window is
|
parentReference |
Interpretation of recorded parent references. One of
|
spectra |
For a stored scan tree, supply the corresponding measured spectra. Acquisition metadata and directed links must agree. The supplied peak arrays define the measurements for this call. |
passingOnly |
Use only products whose stored |
With a purityA object, the active assessment for each scan
supplies its recorded parent, peak position and measured m/z. These
must agree with the available parent measurement. A recorded unresolved
selection keeps its status. If the recorded peak is no longer available,
its products remain linked to an unmeasured selection. MS2 scans and
older results without a peak observation use the mass window when the
parent spectrum is present.
With measured Spectra, exactly one parent peak in the window supplies a measured
precursor. Multiple candidates, no candidate or an unresolved parent
produce an unmeasured selection with an explicit status. Purity scores
describe the original isolation assessment. Known profile data and multiple isolated precursors
per scan are unsupported. Subset large runs with
Spectra::filterPrecursorScan() before reading peak arrays.
Peak IDs combine the scan lineage and the one-based peak position. Stored original positions take precedence. For queued processing they must be retained or recoverable. In-memory input without earlier position information uses the positions in the supplied measurement.
A PrecursorFragmentTrees list. Its mst holds the scan tree,
including empty scans. Its pft holds peak nodes and fragmentation
edges. Its selections table has one row per fragmentation scan,
including scans with zero products. Its assignment_source column
distinguishes purityA observations, mz_window matching and
unavailable parents. Use fragmentLinks() for a table
of products with measured masses and subsetTree() to follow a branch.
f <- system.file("extdata", "msn-standards", "msPurity_L_kynurenine_161166_MSn.mzML.gz", package = "msPurity") s <- Spectra::Spectra(f, source = Spectra::MsBackendMzR(), BPPARAM = BiocParallel::SerialParam()) four <- s[match(c(966L, 977L, 985L, 987L), Spectra::acquisitionNum(s))] trees <- precursorFragmentTrees(four) products <- subsetTree(trees, scan = 985L, peak = 44L, mode = "out", depth = 1L) fragmentLinks(products)f <- system.file("extdata", "msn-standards", "msPurity_L_kynurenine_161166_MSn.mzML.gz", package = "msPurity") s <- Spectra::Spectra(f, source = Spectra::MsBackendMzR(), BPPARAM = BiocParallel::SerialParam()) four <- s[match(c(966L, 977L, 985L, 987L), Spectra::acquisitionNum(s))] trees <- precursorFragmentTrees(four) products <- subsetTree(trees, scan = 985L, peak = 44L, mode = "out", depth = 1L) fragmentLinks(products)
Read processed spectra and their provenance from a Parquet results dataset
processedSpectrumInfo( path, featureId = NULL, msLevel = NULL, method = NULL, runId = NULL, sourcePaths = NULL ) readProcessedSpectra( path, featureId = NULL, msLevel = NULL, method = NULL, runId = NULL, sourcePaths = NULL, includeRaw = FALSE ) readProcessedProvenance( path, featureId = NULL, msLevel = NULL, method = NULL, runId = NULL, sourcePaths = NULL )processedSpectrumInfo( path, featureId = NULL, msLevel = NULL, method = NULL, runId = NULL, sourcePaths = NULL ) readProcessedSpectra( path, featureId = NULL, msLevel = NULL, method = NULL, runId = NULL, sourcePaths = NULL, includeRaw = FALSE ) readProcessedProvenance( path, featureId = NULL, msLevel = NULL, method = NULL, runId = NULL, sourcePaths = NULL )
path |
Directory written by |
featureId |
Exported numeric feature identifiers ( |
msLevel |
Integer MS levels. |
method |
Averaging methods: |
runId |
Character results run identifiers. |
sourcePaths |
Named paths to relocated sources, keyed by manifest source. |
includeRaw |
Also return the referenced study scans. |
Values within a selector are alternatives. Selectors intersect, with NULL selecting all values. Stored spectra follow manifest run and spectrum order. An empty average has a stored ID and zero peaks. An unavailable attempt has no spectrum and appears only in metadata.
processedSpectrumInfo() returns a data frame including exported
and xcms feature identifiers, acquisition metadata, availability, immediate
contributing input counts and original measured occurrence counts for
retained peaks (contributing_inputs and used_measurements). Unknown counts are NA. Its source_runs list column
holds source/run, resolution status and the original typed condition
(mzstack_capability for an external source, mzstack_reference for
a missing or wrong dataset, and mzstack_stale for a changed run).
readProcessedSpectra() returns a Spectra with an MsBackendParquet backend.
With includeRaw = TRUE, it returns a list of processed Spectra and
raw Spectra grouped by source. Unresolvable raw references signal their
mzStack condition. Scan-only datasets return their selected measured scans.
readProcessedProvenance() returns dataset activities, tool settings and
history, software, selected feature links, measured inputs, membership,
peak edges, source status and loss records. Dataset-wide activity and loss
records retain their original scope.
createDatabase(), averageMembers(), averagePeakMembers()
db <- system.file("extdata", "tests", "db", "createDatabase_example.sqlite", package = "msPurity") path <- tempfile("results-") convertSqliteToParquet(db, path) info <- processedSpectrumInfo(path) feature <- info$feature_id_[1L] sp <- readProcessedSpectra(path, featureId = feature) cols <- intersect(c("mz", "intensity", "sn"), Spectra::peaksVariables(sp)) head(Spectra::peaksData(sp[1L], columns = cols)[[1L]]) head(readProcessedProvenance(path, featureId = feature)$mergeMembers)db <- system.file("extdata", "tests", "db", "createDatabase_example.sqlite", package = "msPurity") path <- tempfile("results-") convertSqliteToParquet(db, path) info <- processedSpectrumInfo(path) feature <- info$feature_id_[1L] sp <- readProcessedSpectra(path, featureId = feature) cols <- intersect(c("mz", "intensity", "sn"), Spectra::peaksVariables(sp)) head(Spectra::peaksData(sp[1L], columns = cols)[[1L]]) head(readProcessedProvenance(path, featureId = feature)$mergeMembers)
Retrieve processing records from a purityA or purityX object or an
extracted Spectra object. Records are named by unique processing step
identifiers. Repeated calls retain earlier records. For Spectra,
only records reachable from the retained spectra are returned, including
their input steps. Subsetting therefore selects the corresponding history.
The optional msPurityFilterProcessingId links exposed
purity_pass_flag values to their filtering operation. On raw spectra,
it does not replace the primary processing identifier or indicate that their
peak arrays were filtered. Older objects may lack this flag-specific link.
Concatenating subsets with the same processing history is supported;
histories from independently processed Spectra objects are not merged.
Retrieve their histories separately before combining spectra.
processingHistory(object, step = NULL) processingParameters(object, step = NULL) ## S4 method for signature 'purityX' processingHistory(object, step = NULL) ## S4 method for signature 'purityX' processingParameters(object, step = NULL)processingHistory(object, step = NULL) processingParameters(object, step = NULL) ## S4 method for signature 'purityX' processingHistory(object, step = NULL) ## S4 method for signature 'purityX' processingParameters(object, step = NULL)
object |
A purityA, purityX or Spectra object. |
step |
NULL for all steps, or processing function names such as "filterFragSpectra" and "averageAllFragSpectra". |
Each record contains the processing operation as step, its unique
execution identifier as step_id, effective parameters (including
defaults), software version, execution times, and input/output references.
Records store settings and input/output references rather than explicit
copies of peak arrays. Function-valued settings remain functions and survive
RDS serialization. Their R environments are retained, not deep-copied, and
can contain other objects. Avoid capturing large or mutable analysis objects
in parameter functions. Older objects are imported with known settings
marked incomplete; dates and missing settings stay unknown.
Where worker settings differ, cores records the requested value and
effective_cores records the execution used. Imported settings do not
invent missing execution information.
When parameter objects assign settings by acquisition metadata, the
top-level scalar settings are fallbacks, not settings applied to every
spectrum. Use parameters$configuration$assignments to find each
spectrum's parameter_id, then retrieve that entry from
parameters$configuration$parameter_sets. Matching parameter objects
supply complete settings. Call-wide scope and execution controls remain
at the top level. For scalar-only calls, no assignment lookup is needed.
For new purity assessments, parameters$resolved contains one settings
list per input file, keyed by file position. Each list identifies the file,
the isolation offsets actually selected, their source and selection method,
and the iwNormFun function when normalization was applied. With
iwNorm = FALSE, the resolved function is NULL and its source is
not_used. Call arguments remain available at the parameter
list's top level and in the original phase-specific settings.
Sources distinguish caller overrides, recorded metadata and approximations.
When assessment cannot use these settings because MS1 or MS2 measurements
are absent, their source is not_used and the status explains why.
Averaged Spectra retain msPurityContributors for the original feature-link
occurrences supporting their retained peaks. The
msPurityClusterContributors list maps averaged peak clusters to those
occurrences' contributorIndex values within the feature. These mappings
store occurrence references, not copies of peak arrays. Historical averaged
inputs without cluster mappings retain unknown fine-grained contributors.
Use the output's spectrumId with averageMembers() or
averagePeakMembers() for its selected inputs or exact stored peak
connections. The averaging record identifies the output spectra and preceding
processing steps. To inspect the originally
eligible inputs of an inter average, trace the passing peaks of its
immediate file averages. Historical spectrum references keep their recorded
identifiers. An earlier integer average identifier is returned as a character
spectrumId when no spectrum ID was recorded.
For purityX, each prediction call creates a new result with its own execution record. Its input references identify the MS1 observations and chromatographic peaks actually used. Predictions are feature summaries; they are not converted to Spectra. Retrieve histories separately when comparing results from independent calls. Saved older results expose only their known settings as incomplete historical records.
A named list of records for processingHistory(), or a named list of their effective parameter lists for processingParameters().
pa <- readRDS(system.file("extdata", "tests", "purityA", "2_frag4feature_pa.rds", package = "msPurity")) pa <- filterFragSpectra(pa, plim = 0.7) records <- processingHistory(pa, step = "filterFragSpectra") records[[length(records)]]$parameters processingParameters(groupedSpectra(pa, legacy = FALSE), step = "filterFragSpectra") pa <- averageAllFragSpectra(pa, param = AverageFragSpectraParam(minfrac = 0)) sp <- averagedSpectra(pa, legacy = FALSE) i <- 1L record <- processingHistory(sp)[[sp$msPurityProcessingId[i]]] averageMembers(sp, sp$spectrumId[i]) sp$msPurityContributors[[i]] sp$msPurityClusterContributors[[i]]pa <- readRDS(system.file("extdata", "tests", "purityA", "2_frag4feature_pa.rds", package = "msPurity")) pa <- filterFragSpectra(pa, plim = 0.7) records <- processingHistory(pa, step = "filterFragSpectra") records[[length(records)]]$parameters processingParameters(groupedSpectra(pa, legacy = FALSE), step = "filterFragSpectra") pa <- averageAllFragSpectra(pa, param = AverageFragSpectraParam(minfrac = 0)) sp <- averagedSpectra(pa, legacy = FALSE) i <- 1L record <- processingHistory(sp)[[sp$msPurityProcessingId[i]]] averageMembers(sp, sp$spectrumId[i]) sp$msPurityContributors[[i]] sp$msPurityClusterContributors[[i]]
Given a vector of LC-MS/MS or DI-MS/MS mzML file paths calculate the precursor ion purity of each MS/MS scan.
The precursor ion purity represents the measure of the contribution of a selected precursor peak in an isolation window used for fragmentation and can be used as away of assessing the spectral quality and level of "contamination" of fragmentation spectra.
The calculation involves dividing the intensity of the selected precursor peak by the total intensity of the isolation window and is performed before and after the MS/MS scan of interest and interpolated at the recorded time of the MS/MS acquisition.
Additionally, isotopic peaks are annotated and omitted from the calculation, low abundance peaks are removed that are thought to have minor contribution to the resulting MS/MS spectra and the isolation efficiency of the mass spectrometer can be used to normalise the intensities used for the calculation.
The output is a purityA S4 class object (referred to as pa for convenience throughout the manual). The object contains a slot (pa@puritydf) where the details of the purity assessments for each MS/MS scan. The purityA object can then be used for further processing including linking the fragmentation spectra to XCMS features, averaging fragmentation, database creation and spectral matching (from the created database).
The purityA object can be used for further processing including linking the fragmentation spectra to XCMS features, averaging fragmentation, database creation and spectral matching (from the created database). See below for an example workflow:
Purity assessments
(mzML files) -> purityA -> (pa)
XCMS processing
(mzML files) -> xcms.findChromPeaks -> (optionally) xcms.adjustRtime -> xcms.groupChromPeaks -> (xcmsObj)
— Older versions of XCMS — (mzML files) -> xcms.xcmsSet -> xcms.group -> xcms.retcor -> xcms.group -> (xcmsObj)
Fragmentation processing
(xcmsObj, pa) -> frag4feature -> filterFragSpectra -> averageAllFragSpectra -> createDatabase -> spectralMatching -> (sqlite spectral database)
When the isolation efficiency of an MS instrument is known the peak intensities within an isolation window can be normalised for the precursor purity calculation. The isolation efficiency can be estimated by measuring a single precursor across a sliding window. See figure 3 from the original msPurity paper (Lawson et al 2017). This has been experimentally measured for a Thermo Fisher Q-Exactive Mass spectrometer using 0.5 Da windows and can be set within msPurity by using msPurity::iwNormQE.5() as the input to the iwNormFunc argument.
Other options to model the isolation efficiency the gaussian isolation window msPurity::iwNormGauss(minOff=-0.5, maxOff = 0.5) or a R-Cosine window msPurity::iwNormRCosine(minOff=-0.5, maxOff=0.5). Where the minOff and maxOff can be altered depending on the isolation window size.
A user can also define their own normalisation function. The only requirement of the function is that given a value between the minOff and maxOff a normalisation value between 0-1 is returned.
Each MS2 event uses its recorded isolation bounds. If bounds are missing or
invalid, its purity is NA and a warning identifies the affected count.
Supply explicit lower and upper offsets when the acquisition settings are
known; no instrument-specific width is assumed. For example,
offsets = c(0.65, 0.65) is appropriate only for a known 1.3 Da window.
Resolved bounds and their sources are retained in processing history.
purityA( fileList, cores = 1, mostIntense = FALSE, nearest = TRUE, offsets = NA, plotP = FALSE, plotdir = NULL, interpol = "linear", iwNorm = FALSE, iwNormFun = NULL, ilim = 0.05, mzRback = "pwiz", isotopes = TRUE, im = NULL, ppmInterp = 7, msLevel = 2L, parentReference = "auto", param = NULL )purityA( fileList, cores = 1, mostIntense = FALSE, nearest = TRUE, offsets = NA, plotP = FALSE, plotdir = NULL, interpol = "linear", iwNorm = FALSE, iwNormFun = NULL, ilim = 0.05, mzRback = "pwiz", isotopes = TRUE, im = NULL, ppmInterp = 7, msLevel = 2L, parentReference = "auto", param = NULL )
fileList |
vector of mzML file paths, or a |
cores |
numeric; Number of cores to use |
mostIntense |
boolean; True if the most intense peak is used for calculation. Set to FALSE if the peak closest to mz value detailed in mzML meta data. |
nearest |
logical; TRUE uses the nearest usable MS1 measurement on either side. FALSE requires the reported preceding MS1 reference. When references are absent throughout a file, the preceding MS1 is used. A later measurement never substitutes for an unavailable preceding reference. Missing permitted measurements produce NA purity; one usable measurement supports a single estimate. |
offsets |
numeric; Two nonnegative lower and upper offsets in Da, with positive total width. Explicit offsets set a window around the selected precursor m/z. NA uses each event's recorded absolute bounds. A selected precursor outside those bounds has unavailable purity. |
plotP |
boolean; If TRUE a plot of the purity is to be saved |
plotdir |
vector; If plotP is TRUE plots will be saved to this directory |
interpol |
character; type of interolation to be performed "linear" or "spline" (Spline option is only included for testing purposes, linear should be used for all standard cases, isotope removal is also not available for the spline option) |
iwNorm |
boolean; If TRUE then the intensity of the isolation window will be normalised based on the iwNormFun function |
iwNormFun |
function; Receives m/z offsets from the isolation-window midpoint and returns intensity weights. The default Gaussian accounts for edge effects and spans the resolved isolation bounds. Caller functions are used without shifting or rescaling. |
ilim |
numeric; All peaks less than this percentage of the target peak will be removed from the purity calculation, default is 5% (0.05) |
mzRback |
character; deprecated and ignored. Raw data is read through Spectra, which uses the pwiz reader |
isotopes |
boolean; TRUE if isotopes are to be removed |
im |
matrix; Isotope matrix, default removes C13 isotopes (single, double and triple bonds) |
ppmInterp |
numeric; Set the ppm tolerance for the precursor ion purity interpolation. i.e. the ppm tolerence between the precursor ion found in the neighbouring scans. |
msLevel |
nonempty numeric vector of levels to assess, from 2 to 4.
Defaults to MS2. Use |
parentReference |
interpretation of parent identifiers for MS3/MS4.
See |
param |
A |
MS2 purity uses neighbouring MS1 measurements. MS3/MS4 purity uses
the linked parent fragmentation spectrum and the child's isolation window,
independently of chromatographic features. Supplied Spectra peak processing
is evaluated before assessment. The recorded precursor intensity helps
select the parent peak; otherwise its closest in-window mass is used.
mostIntense = TRUE selects the strongest in-window peak instead.
Ambiguous, invalid or unavailable parent measurements give NA and
an explanatory msPurityPurityStatus. Known profile parents are not
assessed. No additional ppm or Da cutoff is applied to parent peaks.
Higher levels use no interpolation or isolation-efficiency weighting.
Request intensity and isotope corrections with PurityAParam;
choose an isotope model appropriate to the measured parent peaks.
Their results are
available as inPurity on pa@spectra; purityTable(pa)
retains its MS2 table format. Processing history records the selected
levels, parent measurements, bounds and settings. Association thresholds
apply to MS2 only. In filterFragSpectra(), explicit or assigned
purity thresholds can also apply to MS3/MS4.
Returns a purityA object (pa). The MS/MS scans and their purity are
stored as a Spectra object in the pa@spectra slot, with the columns
below as spectra variables. purityTable(pa) returns them as a data
frame, which is also kept in the legacy pa@puritydf slot while
options(msPurity.legacySlots = TRUE) (the default).
The purity dataframe (purityTable(pa)) consists of the following columns:
pid: unique id for MS/MS scan
fileid: unique id for mzML file
seqNum: scan number
precursorIntensity: precursor intensity value as defined in the mzML file
precursorMZ: precursor m/z value as defined in the mzML file
precursorRT: precursor RT value as defined in the mzML file
precursorScanNum: precursor scan number value as defined in mzML file
id: unique id (redundant)
filename: mzML filename
precursorNearest: MS1 scan nearest to the MS/MS scan
aMz: The m/z value in the "precursorNearest" MS1 scan which most closely matches the precursorMZ value provided from the mzML file
aPurity: The purity score for aMz
apkNm: The number of peaks in the isolation window for aMz
iMz: The m/z value in the precursorNearest MS1 scan that is the most intense within the isolation window.
iPurity: The purity score for iMz
ipkNm: The number of peaks in the isolation window for iMz
inPurity: The interpolated purity score (the purity score is calculated at neighbouring MS1 scans and interpolated at the point of the MS/MS acquisition)
inpkNm: The interpolated number of peaks in the isolation window
The remaining slots for purityA class include
pa@cores: The number of CPUs to be used for any further processing with this purityA object
pa@fileList: list of the mzML files that have been processed
pa@mzRback: The backend library used by mzR to extract information from the mzML file (e.g. pwiz)
pa@grped_df: If frag4feature has been performed, a dataframe of the grouped XCMS features linked to the associated fragmentation spectra precursor details is recorded here
pa@grped_ms2: If frag4feature has been performed, a list of fragmentation spectra associated with each grouped XCMS feature is recorded here
pa@f4f_link_type: If frag4feature has been performed, the 'linking method' is recorded here, e.g. 'group' or 'individual'. Default is 'individual', see frag4feature documentation for more details
pa@av_spectra: if averageIntraFragSpectra, averageInterFragSpectra, or averageAllFragSpectra have been performed, the average spectra is recorded here
pa@av_intra_params: If averageIntraFragSpectra has been performed, the parameters are recorded here
pa@av_inter_params: if averageInterFragSpectra has been performed, the parameters are recorded here]
pa@av_all_params: If averageAllFragSpectra has been performed, the parameters are recorded here
pa@db_path: If create_database has been performed, the resulting path to the database is recorded here
filepths <- system.file("extdata", "lcms", "mzML", "LCMSMS_1.mzML", package="msPurityData") pa <- purityA(filepths)filepths <- system.file("extdata", "lcms", "mzML", "LCMSMS_1.mzML", package="msPurityData") pa <- purityA(filepths)
Accessors for the results stored in a purityA object. Each returns either
a Spectra object (legacy = FALSE) or the shape the
corresponding legacy slot has always had (legacy = TRUE, the
default). Use these instead of reading slots directly: the legacy slots
are only filled while options(msPurity.legacySlots = TRUE), the
default for this release.
pa |
purityA object. |
legacy |
logical; TRUE for the legacy shape, FALSE for |
purityTable(): the MS2 spectra with their precursor ion
purity, as the puritydf data frame or as Spectra with the
purity results as spectra variables.
groupedSpectra(): the spectra linked to XCMS features by
frag4feature(), as the grped_ms2 list (one list of peak
matrices per feature) or as Spectra holding each scan once. The
links themselves are in pa@grped_df, keyed by pid.
allFragSpectra(): the spectra at the requested levels with
flags from filterFragSpectra(allfrag = TRUE), as the
all_frag_scans data frame or as Spectra with peak flags.
Filtering defaults to MS2; request msLevel = 2:4 for MS2-MS4.
averagedSpectra(): the averaged spectra, as the nested
av_spectra list or as Spectra with one spectrum per
feature, averaging level and sample. Averages computed with a
param argument (see AverageFragSpectraParam) can
be several per feature and are available only as Spectra;
legacy = TRUE then stops with an error.
A data frame, list or Spectra object.
pa <- readRDS(system.file("extdata", "tests", "purityA", "9_averageAllFragSpectra_with_filter_pa.rds", package = "msPurity")) head(purityTable(pa)) purityTable(pa, legacy = FALSE) averagedSpectra(pa, legacy = FALSE)pa <- readRDS(system.file("extdata", "tests", "purityA", "9_averageAllFragSpectra_with_filter_pa.rds", package = "msPurity")) head(purityTable(pa)) purityTable(pa, legacy = FALSE) averagedSpectra(pa, legacy = FALSE)
Supply one object or a named list to purityA(param = ). A matching
object supplies complete settings; unmatched MS2 events use the scalar
call settings. Unmatched MS3/MS4 events use the scalar mostIntense
and offsets, with no isotope or low-intensity exclusion.
PurityAParam( select = list(), mostIntense = FALSE, nearest = TRUE, offsets = NA_real_, interpol = "linear", iwNorm = FALSE, iwNormFun = NULL, ilim = 0.05, isotopes = TRUE, im = NULL, ppmInterp = 7 ) ## S4 method for signature 'PurityAParam' as.list(x, ...)PurityAParam( select = list(), mostIntense = FALSE, nearest = TRUE, offsets = NA_real_, interpol = "linear", iwNorm = FALSE, iwNormFun = NULL, ilim = 0.05, isotopes = TRUE, im = NULL, ppmInterp = 7 ) ## S4 method for signature 'PurityAParam' as.list(x, ...)
select |
Named list of exact acquisition-metadata selectors. |
mostIntense |
Select the strongest in-window peak instead of the recorded-intensity/closest-mass target. |
nearest |
Select the nearest permitted MS1 measurement; MS2 only. |
offsets |
Lower and upper isolation offsets in Da, or |
interpol |
MS2 interpolation: |
iwNorm |
Enable MS2 isolation-efficiency weighting. |
iwNormFun |
MS2 weighting function receiving offsets from the window
midpoint, or |
ilim |
Fraction of the selected precursor intensity used as the low-intensity cutoff, between zero and one. |
isotopes |
Exclude isotope peaks using the selected model. |
im |
Isotope-model matrix accepted by |
ppmInterp |
MS2 mass tolerance in ppm for tracking the selected peak across neighbouring MS1 measurements. |
x |
A purity parameter object. |
... |
Ignored. |
The object stores reusable scientific settings. The call's msLevel
selects the spectra to assess; select only assigns settings within
that selection. Worker counts, plotting and output destinations remain
call-wide arguments. Processing history records these controls alongside
the resolved settings; see processingParameters.
Selectors assign settings to requested child events without discarding
their parent measurements. They use the acquisition fields and matching
rules described for FilterFragSpectraParam. Overlapping sets
must agree on the settings applicable to the matched MS level.
MS3/MS4 use one validated parent and no interpolation or isolation-efficiency
weighting. Their effective settings mark MS2-only controls as not applicable.
A parameter object assigned to these levels must have iwNorm = FALSE
and iwNormFun = NULL. Other constructor defaults are fixed regardless
of selectors: an object assigned to higher levels requests its ilim
and isotopes settings. Isotope exclusion needs a model appropriate
for the measured parent spectrum.
A PurityAParam extending ProtGenerics::Param.
as.list() returns all settings, including selectors and functions.
ms2 <- PurityAParam(select = list(msLevel = 2L), interpol = "linear") higher <- PurityAParam(select = list(msLevel = 3:4), ilim = 0, isotopes = FALSE) as.list(higher) ms2ms2 <- PurityAParam(select = list(msLevel = 2L), interpol = "linear") higher <- PurityAParam(select = list(msLevel = 3:4), ilim = 0, isotopes = FALSE) as.list(higher) ms2
Constructor for the purityX class.
Given an XCMS object get the anticipated precursor purity of the grouped peaks
purityX( xset, purityType = "purityFWHMmedian", offsets = c(0.5, 0.5), fileignore = NULL, cores = 1, xgroups = NULL, iwNorm = FALSE, iwNormFun = NULL, ilim = 0.05, plotP = FALSE, mzRback = "pwiz", isotopes = FALSE, im = NULL, singleFile = 0, rtrawColumns = FALSE, saveEIC = FALSE, sqlitePth = NULL, param = NULL )purityX( xset, purityType = "purityFWHMmedian", offsets = c(0.5, 0.5), fileignore = NULL, cores = 1, xgroups = NULL, iwNorm = FALSE, iwNormFun = NULL, ilim = 0.05, plotP = FALSE, mzRback = "pwiz", isotopes = FALSE, im = NULL, singleFile = 0, rtrawColumns = FALSE, saveEIC = FALSE, sqlitePth = NULL, param = NULL )
xset |
An |
purityType |
character; Area and average used for the purity predictions. Options are "purityFWHMmedian", "purityFWmedian", "purityFWHMmean", "purityFWmean" |
offsets |
Isolation-window offsets in Da, in historical upper, lower
order. For example, |
fileignore |
vector; vector of files to ignore for the prediction calculation |
cores |
numeric; number of cores to use |
xgroups |
vector; vector of xcms groups to perform prediction on |
iwNorm |
boolean; if TRUE then the intensity of the isolation window will be normalised based on the iwNormFun function |
iwNormFun |
function; A function to normalise the isolation window intensity. The default function is very generalised and just accounts for edge effects |
ilim |
numeric; All peaks less than this percentage of the target peak will be removed from the purity calculation, default is 5% (0.05) |
plotP |
boolean; TRUE if plot of the EIC of feature and associated contamination is the be save to the working directory |
mzRback |
character; deprecated and ignored. Raw data is read through Spectra, which uses the pwiz reader |
isotopes |
boolean; TRUE if isotopes are to be removed |
im |
matrix; Isotope matrix, default removes C13 isotopes (single, double and triple bonds) |
singleFile |
numeric; If just a single file for purity is to be calculated (rather than the grouped XCMS peaks). Uses the index of the files in xcmsSet object. If zero this is ignored. |
rtrawColumns |
Use explicit |
saveEIC |
Save chromatograms for grouped predictions to SQLite. Ignored
when |
sqlitePth |
character; If saveEIC True, then a path to sqlite database can be used. If NULL then a database will be created in the working directory called eics |
param |
One complete |
Predictions use the selected MS1 observations, including their
surrounding isolation-window signal. Modern inputs retain Spectra subsets
and pending peak processing. Removing interfering peaks before prediction
can change the result. Full-width predictions summarize the chromatographic
peak interval; FWHM predictions use its nearest half-height bounds. Missing
flanks or absent signal leave FWHM predictions unavailable.
Acquisition retention times are retained where available. If the caller
has already applied adjusted times, original acquisition times cannot be
recovered; the legacy EIC column rt_raw then contains the available
input spectrum times.
processingParameters() and processingHistory() retrieve
effective settings and the feature/sample observations used. Prediction
estimates anticipated isolation purity, not fragmentation quality.
a purityX object containing a dataframe of predicted purity scores
msPths <- list.files(system.file("extdata", "lcms", "mzML", package="msPurityData"), full.names = TRUE, pattern = "LCMS_") xset <- readRDS(system.file("extdata", "tests", "xcms", "ms_only_xset_OLD.rds", package="msPurity")) xset@filepaths[1] <- msPths[basename(msPths)=="LCMS_1.mzML"] xset@filepaths[2] <- msPths[basename(msPths)=="LCMS_2.mzML"] ## Keep the example short: predict only the peaks between m/z 100 and 200 xset@peaks <- xset@peaks[xset@peaks[, "mz"] >= 100 & xset@peaks[, "mz"] <= 200, ] px <- purityX(xset, singleFile = 1)msPths <- list.files(system.file("extdata", "lcms", "mzML", package="msPurityData"), full.names = TRUE, pattern = "LCMS_") xset <- readRDS(system.file("extdata", "tests", "xcms", "ms_only_xset_OLD.rds", package="msPurity")) xset@filepaths[1] <- msPths[basename(msPths)=="LCMS_1.mzML"] xset@filepaths[2] <- msPths[basename(msPths)=="LCMS_2.mzML"] ## Keep the example short: predict only the peaks between m/z 100 and 200 xset@peaks <- xset@peaks[xset@peaks[, "mz"] >= 100 & xset@peaks[, "mz"] <= 200, ] px <- purityX(xset, singleFile = 1)
Supply one complete parameter object to purityX(param = ).
Explicit scientific arguments supplied alongside it must agree with its
settings. With param = NULL, purityX() uses its scalar
arguments. Sample/feature selection, workers and output choices remain
arguments of purityX(), rather than settings in this object.
PurityXParam( purityType = "purityFWHMmedian", offsets = c(0.5, 0.5), iwNorm = FALSE, iwNormFun = NULL, ilim = 0.05, isotopes = FALSE, im = NULL ) ## S4 method for signature 'PurityXParam' as.list(x, ...)PurityXParam( purityType = "purityFWHMmedian", offsets = c(0.5, 0.5), iwNorm = FALSE, iwNormFun = NULL, ilim = 0.05, isotopes = FALSE, im = NULL ) ## S4 method for signature 'PurityXParam' as.list(x, ...)
purityType |
Summary of per-scan purity: |
offsets |
Upper and lower isolation offsets in Da, in that order.
Thus |
iwNorm |
Apply isolation-efficiency weighting. |
iwNormFun |
Weighting function receiving offsets from the isolation
window midpoint, or |
ilim |
Fraction of the target intensity used as the low-intensity cutoff, between zero and one. |
isotopes |
Exclude isotope peaks using the selected isotope model. |
im |
Isotope-model matrix accepted by |
x |
A purity-prediction parameter object. |
... |
Ignored. |
Prediction uses MS1 measurements. The assumed isolation window describes the surrounding signal that would be isolated with the feature; it does not require an acquired fragmentation spectrum. Use separate calls to compare alternative settings.
A PurityXParam extending ProtGenerics::Param.
as.list() retains all seven settings, including NULLs and functions.
prediction_param <- PurityXParam(offsets = c(0.5, 0.5), ilim = 0.05) as.list(prediction_param) prediction_paramprediction_param <- PurityXParam(offsets = c(0.5, 0.5), ilim = 0.05) as.list(prediction_param) prediction_param
Both entries must have the same supported MS level and overlapping, positive immediate precursor masses. At each stage, known polarity, activation, analyzer and collision energy are compared. The instrument analyzer and scan-filter analyzer are independent fields. Energy values are compared only with a shared known unit (e.g. eV or normalized energy). Uniform controlled-vocabulary identifiers resolve different source labels. An unrecognized identifier paired with free text leaves that field partial. Different known units conflict. Unknown fields, including absent units or missing parents in an external library, leave the comparison partial. Disjoint known values conflict. Overlapping mixed contributor values leave the comparison partial because individual contributors may differ.
scoreSpectrumPair( query, reference, param = SpectralMatchingParam(), queryIndex = 1L, referenceIndex = 1L )scoreSpectrumPair( query, reference, param = SpectralMatchingParam(), queryIndex = 1L, referenceIndex = 1L )
query, reference
|
Measured or consensus |
param |
Tolerances from |
queryIndex, referenceIndex
|
One-based positions in the supplied objects. |
Measured parents are resolved inside each supplied object using same-run identifiers. Ambiguous or unavailable parents leave the stage unknown. Consensus entries use the precursor path and ancestor conditions saved by msPurity. Each earlier stage back to MS2 is compared by MS level, so different source files can have compatible paths. Keep parent entries in the supplied objects and select the desired children with the index arguments.
A list with eligible, reason, a checks data
frame (stage, field, outcome), and scores named dpc, rdpc, cdpc,
mcount, allcount and mpercent for the default scorer, or blinkCosine and
blinkMatchingIonCount for BLINK. A rejected pair reports the first failed
requirement and has missing scores. Eligible pairs report compatible or
compatible_partial. If either selected spectrum has no usable signal
after queued processing, eligibility is retained, the reason is
no_usable_peaks and scores are missing.
d <- S4Vectors::DataFrame(msLevel = 2L, precursorMz = 200) d$mz <- list(c(50, 80)) d$intensity <- list(c(100, 20)) sp <- Spectra::Spectra(d, source = Spectra::MsBackendMemory()) scoreSpectrumPair(sp, sp)$scoresd <- S4Vectors::DataFrame(msLevel = 2L, precursorMz = 200) d$mz <- list(c(50, 80)) d$intensity <- list(c(100, 20)) sp <- Spectra::Spectra(d, source = Spectra::MsBackendMemory()) scoreSpectrumPair(sp, sp)$scores
print statement for purityA class
## S4 method for signature 'purityA' show(object)## S4 method for signature 'purityA' show(object)
object |
object; purityA object |
a print statement of regarding object
Show method for purityX object
## S4 method for signature 'purityX' show(object)## S4 method for signature 'purityX' show(object)
object |
object; purityX object |
a print statement of regarding object
Perform spectral matching to spectral libraries using dot product cosine on a LC-MS/MS dataset and link to XCMS features.
msPurity::spectral_matching is deprecated - please use msPurity::spectralMatching for future use
spectral_matching( query_db_pth, ra_thres_l = 0, ra_thres_q = 2, cores = 1, pol = "positive", ppm_tol_prod = 10, ppm_tol_prec = 5, score_thres = 0.6, topn = NA, db_name = NA, library_db_pth = NA, instrument_types = NA, library_sources = "massbank", scan_ids = NA, pa = NA, xset = NA, grp_peaklist = NA, out_dir = ".", ra_w = 0.5, mz_w = 2, spectra_type_q = "scans", ra_thres_t = NA, target_db_pth = NA, rt_range = c(NA, NA), rttol = NA, match_alg = "dpc" )spectral_matching( query_db_pth, ra_thres_l = 0, ra_thres_q = 2, cores = 1, pol = "positive", ppm_tol_prod = 10, ppm_tol_prec = 5, score_thres = 0.6, topn = NA, db_name = NA, library_db_pth = NA, instrument_types = NA, library_sources = "massbank", scan_ids = NA, pa = NA, xset = NA, grp_peaklist = NA, out_dir = ".", ra_w = 0.5, mz_w = 2, spectra_type_q = "scans", ra_thres_t = NA, target_db_pth = NA, rt_range = c(NA, NA), rttol = NA, match_alg = "dpc" )
query_db_pth |
character; Path of the database of targets (queries) that will be searched against the library spectra. Generated either from frag4feature or from create_database functions. |
ra_thres_l |
numeric; Relative abundance threshold for library spectra |
ra_thres_q |
numeric; Relative abundance threshold for target (query) spectra (Peaks below this RA threshold will be excluded) |
cores |
numeric; Number of cores to use |
pol |
character; Polarity ['positive' or 'negative'] |
ppm_tol_prod |
numeric; PPM tolerance to match to product |
ppm_tol_prec |
numeric; PPM tolerance to match to precursor |
score_thres |
numeric; Dot product cosine score threshold |
topn |
numeric [optional]; Only use top n matches |
db_name |
character [optional]; Name of the result database (e.g. can use CAMERA peaklist) |
library_db_pth |
character [optional]; path to library spectral SQLite database. Defaults to msPurityData package data. |
instrument_types |
vector [optional]; Vector of instrument types, defaults to all |
library_sources |
vector [optional]; Vector of library sources. Default option is for massbank only but the 'lipidblast' library is also available |
scan_ids |
vector [optional]; Vector of unique scan ids calculated from msPurity "pid". These scans will on used for the spectral matching. All scans will be used if set to NA |
pa |
purityA object [optional]; If target_db_pth set to NA, a new database can be created using pa, xset and grp_peaklist |
xset |
xcms object [optional]; If target_db_pth set to NA, a new database can be created using pa, xset and grp_peaklist |
grp_peaklist |
dataframe [optional]; If target_db_pth set to NA, a new database can be created using pa, xset and grp_peaklist |
out_dir |
character [optional]; If target_db_pth set to NA, Out directory for the SQLite result database |
ra_w |
numeric; Relative abundance weight for spectra |
mz_w |
numeric; mz weight for spectra |
spectra_type_q |
character; Type of fragmentation spectra from query to match with "scans" = all individual scans, "av_intra" = averaged spectra (intra), "av_inter" = averaged spectra (inter), "av_all" = averaged all spectra ignoring inter-intra relationships |
ra_thres_t |
numeric [deprecated]; The relative abundance threshold for the query spectra (use ra_thres_q for future use) |
target_db_pth |
character [deprecated]; The query database path (use query_db_pth for future use) |
rt_range |
vector [optional]; Vector of rention time range to filter the library spectra (rtmin, rtmax). Default is to ignore retention time range |
rttol |
numeric [optional]; Tolerance in time range between the Library and Query database retention time (in seconds) NA to ignore |
match_alg |
character; Can either use dot product cosine (dpc) or match factor (mf) for spectral matching. Defaults to dpc |
list of database details and dataframe summarising the results for the xcms features
#msmsPths <- list.files(system.file("extdata", "lcms", "mzML", # package="msPurityData"), full.names = TRUE, # pattern = "MSMS") #xset <- xcms::xcmsSet(msmsPths) #xset <- xcms::group(xset) #xset <- xcms::retcor(xset) #xset <- xcms::group(xset) #pa <- purityA(msmsPths) #pa <- frag4feature(pa, xset) #pa <- averageAllFragSpectra(pa) #db_pth <- create_database(pa, xset) #q_dbPth <- system.file("extdata", "tests", "db", # "create_database_example.sqlite", package="msPurity") #result <- spectral_matching(q_dbPth, spectra_type_q="av_all")#msmsPths <- list.files(system.file("extdata", "lcms", "mzML", # package="msPurityData"), full.names = TRUE, # pattern = "MSMS") #xset <- xcms::xcmsSet(msmsPths) #xset <- xcms::group(xset) #xset <- xcms::retcor(xset) #xset <- xcms::group(xset) #pa <- purityA(msmsPths) #pa <- frag4feature(pa, xset) #pa <- averageAllFragSpectra(pa) #db_pth <- create_database(pa, xset) #q_dbPth <- system.file("extdata", "tests", "db", # "create_database_example.sqlite", package="msPurity") #result <- spectral_matching(q_dbPth, spectra_type_q="av_all")
General
Perform spectral matching to spectral libraries for an LC-MS/MS dataset.
With format = "parquet", search a Parquet results dataset against a
Spectra library or a converted dataset. The default SQLite route
searches a query SQLite database against a library SQLite database.
The SQLite schema of the spectral database can be detailed Schema details can be found here.
The query spectral-database in most cases should contain be the "unknown" spectra database generated the msPurity function createDatabase as part of a msPurity-XCMS data processing workflow.
The library spectral-database in most cases should contain the "known" spectra from either public or user generated resources. The library SQLite database by default contains data from MoNA including Massbank, HMDB, LipidBlast and GNPS. A larger database can be downloaded from here. To create a user generated library SQLite database the following tool can be used to generate a SQLite database from a collection of MSP files: msp2db. It should be noted though, that as long as the schema of the spectral-database is as described here , then any database can be used for either the library or query - even allowing for the same database to be used.
The spectral matching functionality has four main components, spectral filtering, spectral alignment, spectral matching, and summarising the results.
Spectral filtering is simply filtering both the library and query spectra to be search against (e.g. choosing the library source, instrument, retention time, precursor PPM tolerance etc).
The spectral alignment stage involves aligning the query peaks to the library peaks. The approach used is similar to modified pMatch algorithm described in Zhou et al 2015.
The spectral matching of the aligned spectra is performed against a combined intensity and m/z weighted vector - created for both the query and library spectra (wq and wl). See below:
Where x and y represent weight factors, defaults to x=0.5 and y=2 as per MassBank. These can be adjusted by the user though.
The aligned weighted vectors are then matched using dot product cosine, reverse dot product cosine and the composite dot product. See below for dot product cosine equation.
See the vigenttes for more details regarding matching algorithms used.
Example LC-MS/MS processing workflow
Purity assessments
(mzML files) -> purityA -> (pa)
XCMS processing
(mzML files) -> xcms.findChromPeaks -> (optionally) xcms.adjustRtime -> xcms.groupChromPeaks -> (xcmsObj)
— Older versions of XCMS — (mzML files) -> xcms.xcmsSet -> xcms.group -> xcms.retcor -> xcms.group -> (xcmsObj)
Fragmentation processing
(xcmsObj, pa) -> frag4feature -> filterFragSpectra -> averageAllFragSpectra -> createDatabase -> spectralMatching -> (sqlite spectral database)
spectralMatching( q_dbPth, l_dbPth = NA, q_purity = NA, q_ppmProd = 10, q_ppmPrec = 5, q_raThres = NA, q_pol = NA, q_instrumentTypes = NA, q_instruments = NA, q_sources = NA, q_spectraTypes = c("av_all", "inter"), q_pids = NA, q_rtrange = c(NA, NA), q_spectraFilter = TRUE, q_xcmsGroups = NA, q_accessions = NA, l_purity = NA, l_ppmProd = 10, l_ppmPrec = 5, l_raThres = NA, l_pol = "positive", l_instrumentTypes = NA, l_instruments = NA, l_sources = NA, l_spectraTypes = NA, l_pids = NA, l_rtrange = c(NA, NA), l_spectraFilter = FALSE, l_xcmsGroups = NA, l_accessions = NA, usePrecursors = TRUE, raW = 0.5, mzW = 2, rttol = NA, q_dbType = "sqlite", q_dbName = NA, q_dbHost = NA, q_dbUser = NA, q_dbPass = NA, q_dbPort = NA, l_dbType = "sqlite", l_dbName = NA, l_dbHost = NA, l_dbUser = NA, l_dbPass = NA, l_dbPort = NA, cores = 1, updateDb = FALSE, copyDb = FALSE, outPth = "sm_result.sqlite", format = c("sqlite", "parquet"), topn = NA, sourcePaths = NULL, libraryVersion = NULL, libraryChecksum = NULL, param = NULL, referenceRole = NULL )spectralMatching( q_dbPth, l_dbPth = NA, q_purity = NA, q_ppmProd = 10, q_ppmPrec = 5, q_raThres = NA, q_pol = NA, q_instrumentTypes = NA, q_instruments = NA, q_sources = NA, q_spectraTypes = c("av_all", "inter"), q_pids = NA, q_rtrange = c(NA, NA), q_spectraFilter = TRUE, q_xcmsGroups = NA, q_accessions = NA, l_purity = NA, l_ppmProd = 10, l_ppmPrec = 5, l_raThres = NA, l_pol = "positive", l_instrumentTypes = NA, l_instruments = NA, l_sources = NA, l_spectraTypes = NA, l_pids = NA, l_rtrange = c(NA, NA), l_spectraFilter = FALSE, l_xcmsGroups = NA, l_accessions = NA, usePrecursors = TRUE, raW = 0.5, mzW = 2, rttol = NA, q_dbType = "sqlite", q_dbName = NA, q_dbHost = NA, q_dbUser = NA, q_dbPass = NA, q_dbPort = NA, l_dbType = "sqlite", l_dbName = NA, l_dbHost = NA, l_dbUser = NA, l_dbPass = NA, l_dbPort = NA, cores = 1, updateDb = FALSE, copyDb = FALSE, outPth = "sm_result.sqlite", format = c("sqlite", "parquet"), topn = NA, sourcePaths = NULL, libraryVersion = NULL, libraryChecksum = NULL, param = NULL, referenceRole = NULL )
q_dbPth |
An experimental |
l_dbPth |
For SQLite, the library database path (defaults to the msPurityData library).
For Parquet, supply a |
q_purity |
character; Precursor ion purity threshold for the query spectra |
q_ppmProd |
numeric; ppm tolerance for query product |
q_ppmPrec |
numeric; ppm tolerance for query precursor |
q_raThres |
numeric; Relative abundance threshold for query spectra |
q_pol |
character; Polarity of query spectra ('positive', 'negative', NA). |
q_instrumentTypes |
vector; Instrument types for query spectra. |
q_instruments |
vector; Instruments for query spectra (note that this is used in combination with q_instrumentTypes - any spectra matching either q_instrumentTypes or q_instruments will be used). |
q_sources |
vector; Sources of query spectra (e.g. massbank, hmdb). |
q_spectraTypes |
character; Spectra types of query spectra to perfrom spectral matching e.g. ('scan', 'av_all', 'intra', 'inter') |
q_pids |
vector; pids for query spectra (correspond to column 'pid; in s_peak_meta) |
q_rtrange |
vector; retention time range (in secs) of query spectra, first value mininum time and second value max e.g. c(0, 10) is between 0 and 10 seconds |
q_spectraFilter |
boolean; For query spectra, if prior filtering performed with msPurity, flag peaks will be removed from spectral matching |
q_xcmsGroups |
vector; XCMS group ids for query spectra |
q_accessions |
vector; accession ids to filter query spectra |
l_purity |
character; Precursor ion purity threshold for the library spectra (uses interpolated purity - inPurity) |
l_ppmProd |
numeric; ppm tolerance for library product |
l_ppmPrec |
numeric; ppm tolerance for library precursor |
l_raThres |
numeric; Relative abundance threshold for library spectra |
l_pol |
character; Polarity of library spectra ('positive', 'negative', NA) |
l_instrumentTypes |
vector; Instrument types for library spectra. |
l_instruments |
vector; Instruments for library spectra (note that this is used in combination with q_instrumentTypes - any spectra matching either q_instrumentTypes or q_instruments will be used). |
l_sources |
vector; Sources of library spectra (e.g. massbank, hmdb). |
l_spectraTypes |
vector; Spectra type of library spectra to perfrom spectral matching with e.g. ('scan', 'av_all', 'intra', 'inter') |
l_pids |
vector; pids for library spectra (correspond to column 'pid; in s_peak_meta) |
l_rtrange |
vector; retention time range (in secs) of library spectra, first value mininum time and second value max e.g. c(0, 10) is between 0 and 10 seconds |
l_spectraFilter |
boolean; For library spectra, if prior filtering performed with msPurity, flag peaks will be removed from spectral matching |
l_xcmsGroups |
vector; XCMS group ids for library spectra |
l_accessions |
vector; accession ids to filter library spectra |
usePrecursors |
boolean; If TRUE spectra will be filtered by similarity of precursors based on ppm range defined by l_ppmPrec and q_ppmPrec |
raW |
numeric; Relative abundance weight for spectra (default to 0.5 as determined by massbank for ESI data) |
mzW |
numeric; mz weight for spectra (default to 2 as determined by massbank for ESI data) |
rttol |
numeric ; Tolerance in time range between the library and query spectra retention time |
q_dbType |
character; Query database type for compound database can be either (sqlite, postgres or mysql) |
q_dbName |
character; Query database name (only applicable for postgres and mysql) |
q_dbHost |
character; Query database host (only applicable for postgres and mysql) |
q_dbUser |
character; Query database user (only applicable for postgres and mysql) |
q_dbPass |
character; Query database pass - Note this is not secure! use with caution (only applicable for postgres and mysql) |
q_dbPort |
character; Query database port (only applicable for postgres and mysql) |
l_dbType |
character; Library database type for compound database can be either (sqlite, postgres or mysql) |
l_dbName |
character; Library database name (only applicable for postgres and mysql) |
l_dbHost |
character; Library database host (only applicable for postgres and mysql) |
l_dbUser |
character; Library database user (only applicable for postgres and mysql) |
l_dbPass |
character; Library database pass - Note this is not secure! use with caution (only applicable for postgres and mysql) |
l_dbPort |
character; Library database port (only applicable for postgres and mysql) |
cores |
numeric; Number of cores to use |
updateDb |
boolean; Update the Query SQLite database with the results |
copyDb |
boolean; If updating the database - perform on a copy rather thatn the original query database |
outPth |
character; If copying the database - the path of the new database file |
format |
character; |
topn |
integer (Parquet or Spectra queries); keep, per query spectrum, the matches ranked |
sourcePaths |
named character (parquet only); source key -> location, for a study dataset that has moved since the results dataset was written. |
libraryVersion |
Optional release name for a |
libraryChecksum |
Optional SHA-256 digest of the release, supplied as 64 hexadecimal
digits with an optional |
param |
Optional |
referenceRole |
For a Spectra query and a Spectra reference, use
|
For a Spectra query, the list described under Experimental Spectra queries. For a database query, a list containing the following elements
q_dbPth
Path of the query database (this will have been updated with the annotation results if updateDb argument used)
xcmsMatchedResults
If the qeury spectra had XCMS based chromotographic peaks tables (e.g c_peak_groups, c_peaks) in the sqlite database - it will be possible to summarise the matches for each XCMS grouped feature. The dataframe contains the following columns
lpid - id in database of library spectra
qpid - id in database of query spectra
dpc - dot product cosine of the match
rdpc - reverse dot product cosine of the match
cdpc - composite dot product cosine of the match
mcount - number of matching peaks
allcount - total number of peaks across both query and library spectra
mpercent - percentage of matching peaks across both query and library spectra
library_rt - retention time of library spectra
query_rt - retention time of query spectra
rtdiff - difference between library and query retention time
library_precursor_mz - library precursor mz
query_precursor_mz - query precursor mz
library_precursor_ion_purity - library precursor ion purity
query_precursor_ion_purity - query precursor ion purity
library_accession - library accession value (unique string or number given to eith MoNA or Massbank data entires)
library_precursor_type - library precursor type (i.e. adduct)
library_entry_name - Name given to the library spectra
inchikey - inchikey of the matched library spectra
library_source_name - source of the spectra (e.g. massbank, gnps)
library_compound_name - name of compound spectra was obtained from
matchedResults
All matched results from the query spectra to the library spectra. Contains the same columns as above but without the XCMS details. This table is useful to observe spectral matching results for all MS/MS spectra irrespective of if they are linked to XCMS MS1 features.
list of database details and dataframe summarising the results for the xcms features
Supply measured or consensus MS2-MS4 spectra directly on either
experimental side. Each scored pair passes the metadata checks described
in scoreSpectrumPair. Keep parent scans in the object to make
measured ancestry available. Both objects retain their supplied selections
and queued peak processing, including subsets from readProcessedSpectra().
By default the entire selection is considered, with no polarity restriction.
Use q_pol, l_pol, q_rtrange, l_rtrange, rttol or library l_accessions to
narrow the comparison. The topn cut includes all ties at its boundary.
These in-memory searches require an explicit reference and usePrecursors
set to TRUE. Database writes and database-specific selectors are unsupported.
The result contains query and reference Spectra objects, referenceRole and matchedResults (NULL when no hit is retained). Each hit includes one-based queryIndex and referenceIndex into those objects, available run, native and dataset identifiers, library accession, MS level, compatibility reason, method-specific scores and within-query rank. Use the indices to retrieve the original acquisition and provenance fields, including for anonymous spectra.
Each retained hit identifies its queryType and referenceType
as measured, consensus or library. Join the hit to
queryStatus by queryIndex. This table has one row per supplied
query, including duplicates, in input order. A filtered query fell
outside the requested polarity or retention-time selection. An
invalid_query lacks a supported MS level or valid precursor mass.
For a valid query, no_eligible_reference means no reference passed
selection and compatibility checks. An unscorable query had eligible
references but no pair had usable peaks on both sides. A scored query
can still have zero retained hits after the rank cut, for example with
topn = 0. Inspect reason, nEligible, nScored
and nRetained to distinguish these outcomes.
For experimental pairs, sharedMeasurement and sharedSourceFile
each report TRUE for established overlap, FALSE for known disjoint sources
and NA when the available identities cannot decide. Two scans can share a
file while having distinct measurement identities. The file is identified
by its recorded absolute origin path or URI, or by a run within an identified
Parquet dataset. Within that scope use the dataset spectrum ID, native ID or
acquisition number, in that order when both sides have it. A bare file name,
local feature link or unqualified scan number cannot establish overlap.
External library entries have unknown measurement provenance.
Inspect sourceMeasurements by side ("query" or "reference")
and inputIndex. Each participating spectrum lists its distinct measured
contributors once, with their file, dataset, run and scan identifiers.
fileComplete and measurementComplete describe the available
identities for the whole spectrum. An unknown branch is represented by missing
identifiers. For a consensus, the contributors supplied peaks to the stored
average, including through intermediate averages. Subsequent peak filtering
affects the score, while the reported provenance describes the stored average.
For example, compare a contributing scan and a scan with a different precursor against one consensus from the bundled LC-MS/MS data.
pa <- readRDS(system.file("extdata", "tests", "purityA",
"2_frag4feature_pa.rds", package = "msPurity"))
pa <- averageAllFragSpectra(pa, param = AverageFragSpectraParam(
minfrac = 0, minnum = 0, snr = 0))
ref <- averagedSpectra(pa, legacy = FALSE)[1L]
scans <- groupedSpectra(pa, legacy = FALSE)
members <- averagePeakMembers(ref, ref$spectrumId, depth = "original")
measured <- match(members$pid[1L], scans$pid)
other <- which(abs(scans$precursorMz - ref$precursorMz) > 1)[1L]
res <- spectralMatching(scans[c(measured, other)], ref, q_ppmPrec = 50)
res$queryStatus[, c("queryIndex", "status", "nEligible", "nRetained")]
res$matchedResults[, c("queryIndex", "sharedMeasurement", "sharedSourceFile")]
subset(res$sourceMeasurements, side == "reference")
The contributing scan has both overlap flags set to TRUE. The second query
has status no_eligible_reference and zero retained hits.
Direct library searches use precursorMz, polarity (0 negative, 1 positive)
and rtime (seconds). The entry and compound names come from name, the
precursor type from adduct, and structure and mass from inchikey,
formula, smiles, inchi and exactmass. Library filters use
instrument, instrument_type, dataOrigin and precursorPurity.
Corresponding stored x_mspurity_* variables take precedence when available.
Identifiers are chosen per spectrum from accession, spectrumId and
splash, in that order. Entries missing all three receive a SHA-256 identifier
derived from precursor mass, polarity and ordered peak values.
For default scoring of a Parquet results query against a direct library, only the precursor index spans the full library. BLINK also retains selection and compatibility metadata. Both read candidate peaks in batches and accept any input row order. Memory for scoring results depends on the number of matches before the top-n cut.
For example, given a Parquet results path query_path, search an MSP library directly:
msp <- MsBackendMsp::MsBackendMsp()
lib <- Spectra::Spectra("library.msp", source = msp,
mapping = Spectra::spectraVariableMapping(msp, "mona"))
spectralMatching(query_path, lib, format = "parquet", libraryVersion = "MoNA release")
d <- S4Vectors::DataFrame(msLevel = 2L, precursorMz = 200) d$mz <- list(c(50, 80)) d$intensity <- list(c(100, 20)) query <- Spectra::Spectra(d, source = Spectra::MsBackendMemory()) replicate <- query spectralMatching(query, replicate)$matchedResults libraryEntry <- query libraryEntry$accession <- "example-1" spectralMatching(query, libraryEntry, referenceRole = "library")$matchedResults #====== XCMS ================================= ## Read in MS data #msmsPths <- list.files(system.file("extdata", "lcms", "mzML", # package="msPurityData"), full.names = TRUE, pattern = "MSMS") #ms_data = readMSData(msmsPths, mode = 'onDisk', msLevel. = 1) ## Find peaks in each file #cwp <- CentWaveParam(snthresh = 5, noise = 100, ppm = 10, peakwidth = c(3, 30)) #xcmsObj <- xcms::findChromPeaks(ms_data, param = cwp) ## Optionally adjust retention time #xcmsObj <- adjustRtime(xcmsObj , param = ObiwarpParam(binSize = 0.6)) ## Group features across samples #pdp <- PeakDensityParam(sampleGroups = c(1, 1), minFraction = 0, bw = 30) #xcmsObj <- groupChromPeaks(xcmsObj , param = pdp) #====== msPurity ============================ #pa <- purityA(msmsPths) #pa <- frag4feature(pa = pa, xcmsObj = xcmsObj) #pa <- filterFragSpectra(pa, allfrag=TRUE) #pa <- averageAllFragSpectra(pa) #q_dbPth <- createDatabase(pa, xcmsObj, metadata=list('polarity'='positive','instrument'='Q-Exactive')) #sm_result <- spectralMatching(q_dbPth, cores=4, l_pol='positive') td <- tempdir() q_dbPth <- system.file("extdata", "tests", "db", "createDatabase_example.sqlite", package="msPurity") ## A small library with the spectra used here. Leave l_dbPth as NA to use the ## full reference library, which is downloaded and cached on first use. l_dbPth <- system.file("extdata", "tests", "library", "mini_library.sqlite", package="msPurity") rid <- paste0(paste0(sample(LETTERS, 5, TRUE), collapse=""), paste0(sample(9999, 1, TRUE), collapse=""), ".sqlite") sm_out_pth <- file.path(td, rid) result <- spectralMatching(q_dbPth, l_dbPth = l_dbPth, q_xcmsGroups = c(53, 89, 410), cores=1, l_accessions = c('PR100407', 'ML005101', 'CCMSLIB00003740024'), q_spectraTypes = 'av_all', updateDb = TRUE, copyDb = TRUE, outPth = sm_out_pth)d <- S4Vectors::DataFrame(msLevel = 2L, precursorMz = 200) d$mz <- list(c(50, 80)) d$intensity <- list(c(100, 20)) query <- Spectra::Spectra(d, source = Spectra::MsBackendMemory()) replicate <- query spectralMatching(query, replicate)$matchedResults libraryEntry <- query libraryEntry$accession <- "example-1" spectralMatching(query, libraryEntry, referenceRole = "library")$matchedResults #====== XCMS ================================= ## Read in MS data #msmsPths <- list.files(system.file("extdata", "lcms", "mzML", # package="msPurityData"), full.names = TRUE, pattern = "MSMS") #ms_data = readMSData(msmsPths, mode = 'onDisk', msLevel. = 1) ## Find peaks in each file #cwp <- CentWaveParam(snthresh = 5, noise = 100, ppm = 10, peakwidth = c(3, 30)) #xcmsObj <- xcms::findChromPeaks(ms_data, param = cwp) ## Optionally adjust retention time #xcmsObj <- adjustRtime(xcmsObj , param = ObiwarpParam(binSize = 0.6)) ## Group features across samples #pdp <- PeakDensityParam(sampleGroups = c(1, 1), minFraction = 0, bw = 30) #xcmsObj <- groupChromPeaks(xcmsObj , param = pdp) #====== msPurity ============================ #pa <- purityA(msmsPths) #pa <- frag4feature(pa = pa, xcmsObj = xcmsObj) #pa <- filterFragSpectra(pa, allfrag=TRUE) #pa <- averageAllFragSpectra(pa) #q_dbPth <- createDatabase(pa, xcmsObj, metadata=list('polarity'='positive','instrument'='Q-Exactive')) #sm_result <- spectralMatching(q_dbPth, cores=4, l_pol='positive') td <- tempdir() q_dbPth <- system.file("extdata", "tests", "db", "createDatabase_example.sqlite", package="msPurity") ## A small library with the spectra used here. Leave l_dbPth as NA to use the ## full reference library, which is downloaded and cached on first use. l_dbPth <- system.file("extdata", "tests", "library", "mini_library.sqlite", package="msPurity") rid <- paste0(paste0(sample(LETTERS, 5, TRUE), collapse=""), paste0(sample(9999, 1, TRUE), collapse=""), ".sqlite") sm_out_pth <- file.path(td, rid) result <- spectralMatching(q_dbPth, l_dbPth = l_dbPth, q_xcmsGroups = c(53, 89, 410), cores=1, l_accessions = c('PR100407', 'ML005101', 'CCMSLIB00003740024'), q_spectraTypes = 'av_all', updateDb = TRUE, copyDb = TRUE, outPth = sm_out_pth)
Each side has its own closed interval centred on its m/z. Its half-width is Da + m/z * ppm / 1000000. Intersecting intervals, including a single shared endpoint, match. Product endpoints are rounded to ten decimal places before comparison, as in the original peak aligner. Precursor endpoints are compared at native precision at every fragmentation stage.
SpectralMatchingParam( q_ppmPrec = 5, l_ppmPrec = 5, q_daPrec = 0, l_daPrec = 0, q_ppmProd = 10, l_ppmProd = 10, q_daProd = 0, l_daProd = 0, collisionEnergyTolerance = 0 ) ## S4 method for signature 'SpectralMatchingParam' as.list(x, ...)SpectralMatchingParam( q_ppmPrec = 5, l_ppmPrec = 5, q_daPrec = 0, l_daPrec = 0, q_ppmProd = 10, l_ppmProd = 10, q_daProd = 0, l_daProd = 0, collisionEnergyTolerance = 0 ) ## S4 method for signature 'SpectralMatchingParam' as.list(x, ...)
q_ppmPrec, l_ppmPrec
|
Query and reference precursor tolerances in ppm. |
q_daPrec, l_daPrec
|
Query and reference precursor tolerances in Da. |
q_ppmProd, l_ppmProd
|
Query and reference product tolerances in ppm. |
q_daProd, l_daProd
|
Query and reference product tolerances in Da. |
collisionEnergyTolerance |
Maximum absolute difference between collision energies on the same scale, inclusive. Zero requires equal energies. |
x |
A matching parameter object. |
... |
Ignored. |
A SpectralMatchingParam object. All nine settings must be
finite, nonnegative numeric scalars. as.list() returns their values.
as.list(SpectralMatchingParam(q_daProd = 0.01))as.list(SpectralMatchingParam(q_daProd = 0.01))
Follow the recorded edges of a scan or precursor-fragment tree. Select a scan by acquisition number or a peak occurrence by acquisition number and stored peak position. An exact node ID works for either type of tree.
subsetTree( x, scan = NULL, run = NULL, peak = NULL, node = NULL, mode = c("all", "out", "in"), depth = Inf, includeParent = FALSE, structure = NULL, max_nodes = 2000L, max_edges = 5000L )subsetTree( x, scan = NULL, run = NULL, peak = NULL, node = NULL, mode = c("all", "out", "in"), depth = Inf, includeParent = FALSE, structure = NULL, max_nodes = 2000L, max_edges = 5000L )
x |
A |
scan |
One nonnegative acquisition number. |
run |
Exact run identifier. Required for scan lookup in a multi-run view. For ordinary mzML input the run identifier is usually the file path. |
peak |
Positive, one-based |
node |
One exact node ID ( |
mode |
|
depth |
Maximum number of edges from the start, or |
includeParent |
In |
structure |
Optional |
max_nodes, max_edges
|
Maximum numbers of nodes and edges in the selection. Exceeding either limit raises an error. |
The default selects the whole weakly connected component. Selection uses the stored tables and works with the raw files offline. For prepared results, saved spectrum metadata can supply acquisition numbers. These are carried onto the returned nodes for subsequent lookup.
A MassSpectralTrees result for a measured scan tree, or the
selected MST or PFT view for a prepared result. Node and edge rows
retain their original order and annotations. Edges have both endpoints
in the selection. Parent references on nodes still describe the original
acquisition. Use as_igraph(), plot() or writeGraphML() on the result.
massSpectralTrees(), Spectra::filterPrecursorScan()
file <- system.file("extdata", "msn-standards", "msPurity_L_kynurenine_161166_MSn.mzML.gz", package = "msPurity") spectra <- Spectra::Spectra(file, source = Spectra::MsBackendMzR(), BPPARAM = BiocParallel::SerialParam()) trees <- massSpectralTrees(spectra) branch <- subsetTree(trees, scan = 977L, mode = "out", includeParent = TRUE) branch$nodes$acquisitionNum example <- system.file("extdata", "msn-standards", "kynurenine-pft.rds", package = "msPurity") products <- subsetTree(readRDS(example), scan = 985L, peak = 44L, mode = "out", depth = 1L) products$nodes[, c("acquisitionNum", "peak_index", "mz")]file <- system.file("extdata", "msn-standards", "msPurity_L_kynurenine_161166_MSn.mzML.gz", package = "msPurity") spectra <- Spectra::Spectra(file, source = Spectra::MsBackendMzR(), BPPARAM = BiocParallel::SerialParam()) trees <- massSpectralTrees(spectra) branch <- subsetTree(trees, scan = 977L, mode = "out", includeParent = TRUE) branch$nodes$acquisitionNum example <- system.file("extdata", "msn-standards", "kynurenine-pft.rds", package = "msPurity") products <- subsetTree(readRDS(example), scan = 985L, peak = 44L, mode = "out", depth = 1L) products$nodes[, c("acquisitionNum", "peak_index", "mz")]
Objects saved before msPurity stored spectra in Spectra objects
lack the spectra, fragSpectra and avSpectra slots.
updateObject() builds them from the legacy slots, without access to
the original files: scan information comes from puritydf, the peaks
of grouped scans from grped_ms2 (or all_frag_scans), and the
averaged spectra from av_spectra. The legacy slots are kept. Every
purityA method updates its input this way, so calling it is only needed to
convert saved objects explicitly.
## S4 method for signature 'purityA' updateObject(object, ..., verbose = FALSE)## S4 method for signature 'purityA' updateObject(object, ..., verbose = FALSE)
object |
purityA object. |
... |
unused. |
verbose |
logical; unused. |
An updated purityA object.
Add processing-history storage to older purityX objects without recalculating their predictions. Only settings stored in the saved object are imported. Execution times, software versions, missing settings and input references remain unknown, and the imported record is marked incomplete.
## S4 method for signature 'purityX' updateObject(object, ..., verbose = FALSE)## S4 method for signature 'purityX' updateObject(object, ..., verbose = FALSE)
object |
A purityX object. |
... |
Unused. |
verbose |
Logical; unused. |
An updated purityX object retaining its saved predictions.
The method is used to validate the precursor purity predictions made from an LC-MS dataset
## S4 method for signature 'purityA' validate(pa, ppLCMS)## S4 method for signature 'purityA' validate(pa, ppLCMS)
pa |
object; purityA object |
ppLCMS |
object; purityX object |
purityA object
Checks a Parquet dataset against the validation rules of the mzStack specification: the manifest, runs and spectra files of every dataset, and the tables, references, keys, sort orders, coverage, loss ledger, naming and CV bindings of a results or library dataset. Every failure is reported, not only the first.
Referenced sources need not be resolvable; an unresolvable source is reported at SHOULD level.
The append-only rule for results tables cannot be checked: a rewritten Parquet part is indistinguishable from a new one.
validateParquet(path, sourcePaths = NULL)validateParquet(path, sourcePaths = NULL)
path |
|
sourcePaths |
named |
A data.frame with columns level ("MUST", "SHOULD" or
"INFO"), requirement (the identifier in the mzStack
specification), table and message; zero rows for a dataset with no
findings.
db <- system.file("extdata", "tests", "db", "createDatabase_example.sqlite", package = "msPurity") out <- file.path(tempdir(), "validate-example.parquet") convertSqliteToParquet(db, out, overwrite = TRUE) validateParquet(out)db <- system.file("extdata", "tests", "db", "createDatabase_example.sqlite", package = "msPurity") out <- file.path(tempdir(), "validate-example.parquet") convertSqliteToParquet(db, out, overwrite = TRUE) validateParquet(out)