Package 'msPurity'

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

Help Index


Convert, plot and export spectral trees

Description

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.

Usage

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)

Arguments

x

A MassSpectralTrees result from massSpectralTrees(), a PrecursorFragmentTrees result from precursorFragmentTrees(), or its scan or peak view.

structure

Optional "MST" or "PFT". A scan tree defaults to "MST" and a precursor-fragment result defaults to "PFT". Select "MST" on a precursor-fragment result to use its stored scan tree.

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 layout, vertex.size, vertex.label.cex or main.

labels

Optional character vector in node order. A single NA hides every label. Scan labels include the precursor m/z and precursor purity when present. Peak labels give m/z and peak position. Labels are hidden above 30 vertices. All vertices are drawn.

Details

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.

Value

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.

Examples

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

Assess the purity of a single LC-MS/MS or DI-MS/MS file

Description

Given a filepath to an mzML file the precursor purity for any MS/MS scans will be outputed into a dataframe

Usage

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
)

Arguments

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.

Value

a dataframe of the purity score of the ms/ms spectra

See Also

purityA

Examples

filepth <- system.file("extdata", "lcms", "mzML", "LCMSMS_1.mzML", package="msPurityData")

puritydf <- assessPuritySingle(filepth)

Using a purityA object, average and filter MS/MS spectra for each XCMS feature within and across MS data files (ignoring intra and inter relationships)

Description

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.

Usage

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

Arguments

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 pa@cores. Overrides apply to the current call. With param, workers process independent clustering blocks; a single block runs directly.

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 AverageFragSpectraParam object or a named list of them, averaged independently.

Details

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.

Value

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

Examples

#====== 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]]

Complete parameters for fragmentation-spectrum averaging

Description

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.

Usage

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, ...)

Arguments

select

named list of acquisition selectors, as for FilterFragSpectraParam.

combine

character; any of "activationType" and "collisionEnergy".

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. ppm = 0 requires tolerance > 0.

tolerance

numeric; absolute m/z tolerance for fragment peaks and MS3/MS4 precursors, added to the ppm tolerance.

snr

numeric; minimum signal-to-noise ratio of an averaged peak.

ra

numeric; minimum relative abundance of an averaged peak.

av

character; "median" or "mean".

sumi

logical; sum, rather than average, the peak intensities.

x

An averaging parameter object.

...

Ignored.

Details

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.

Value

An AverageFragSpectraParam object. as.list() returns its complete settings as a named list.

See Also

averageAllFragSpectra, FilterFragSpectraParam

Examples

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

Using a purityA object, average and filter fragmentation spectra for each XCMS feature across multiple MS data files

Description

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.

Usage

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

Arguments

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 pa@cores. Overrides apply to the current call. With param, workers process independent clustering blocks; a single block runs directly.

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 AverageFragSpectraParam object or a named list of them, averaged independently.

Details

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.

Value

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

Examples

#====== 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)

Using a purityA object, average and filter fragmentation spectra for each XCMS feature within a MS data file

Description

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.

Usage

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

Arguments

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 pa@cores. Overrides apply to the current call. With param, workers process independent clustering blocks; a single block runs directly.

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 AverageFragSpectraParam object or a named list of them, averaged independently.

Details

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.

Value

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

Examples

#====== 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)

Trace the immediate or original inputs to an averaged spectrum

Description

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.

Usage

averageMembers(object, spectrumId, depth = c("immediate", "original"))

averagePeakMembers(
  object,
  spectrumId,
  peak = NULL,
  depth = c("immediate", "original")
)

Arguments

object

A purityA object or averaged Spectra returned by averagedSpectra(pa, legacy = FALSE), including a subset.

spectrumId

Character spectrumId of an average in the supplied object.

depth

"immediate" for one step or "original" to follow measured inputs through earlier averages.

peak

Optional vector of 1-based stored output peak positions. The default includes all stored peaks.

Details

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.

Value

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.

Examples

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

Extract the spectra and recorded inputs behind selected averages

Description

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.

Usage

averageProvenance(object, spectrumId)

Arguments

object

A purityA object containing recorded average provenance.

spectrumId

Character vector of spectrumId values of the averages to extract.

Value

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.

Examples

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)

BLINK fragment scoring parameters

Description

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.

Usage

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, ...)

Arguments

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 blurTolerance in Da to control BLINK fragment matching.

x

A matching parameter object.

...

Ignored.

Value

A BlinkMatchingParam extending SpectralMatchingParam.

References

doi:10.1038/s41598-023-40496-9

Examples

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 Annotations

Description

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

Usage

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

Arguments

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 sm_resultPth to write to (the original is updated in place otherwise). For Parquet, the path of a copy of the results dataset to write to.

summaryOutput

boolean; If a summary dataframe is to be created

format

character; "sqlite" (the default) adds the combined annotations to the SQLite database, and raises a deprecation warning: SQLite output is frozen. "parquet" (experimental) takes a Parquet results dataset with spectral-matching evidence (from spectralMatching(format = "parquet") or convertSqliteToParquet()) in sm_resultPth. It scores exactly as the SQLite route, and records the result without changing any existing row: a new revision of the compound table, the compounds' database references, and the per-tool and combined scores per feature and compound (tables x_mspurity_feature_annotation and x_mspurity_combined_annotation). The tool result files and the compound database are recorded as inputs, with their digests.

Value

purityA object with slots for fragmentation-XCMS links

Examples

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)

Convert a spectral library to a Parquet library dataset

Description

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.

Usage

convertLibraryToParquet(
  x,
  path,
  format = c("msp2db", "msp", "spectra"),
  dialect = NULL,
  version = NULL,
  rtUnit = NA_character_,
  runIds = NULL,
  overwrite = FALSE,
  mapping = NULL
)

Arguments

x

character: path of the msp2db database, or of the MSP files; or a Spectra object.

path

character(1), the library dataset to create.

format

"msp2db", "msp" or "spectra".

dialect

character(1), required for MSP: "massbank", "mona" or "mspurity".

version

character(1), the library release; derived from the source by default.

rtUnit

character(1), retention time unit of the source, "s" or "min", or NA if unknown.

runIds

named character: library source name (msp2db) or file (MSP) -> run id. By default minted from checksum and ordinal.

overwrite

logical(1), whether to replace an existing dataset.

mapping

named character, for format = "spectra": library field (such as x_mspurity_inchikey) -> spectra variable. NULL, the default, maps the variable names used by MsBackendMsp and MsBackendMassbank: name, synonym, adduct, inchikey, inchi, smiles, formula, exactmass, instrument, instrument_type, splash and comment.

Value

The path of the dataset, invisibly.

See Also

spectralMatching(), validateParquet()

Examples

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

Convert an msPurity SQLite database to a Parquet results dataset

Description

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.

Usage

convertSqliteToParquet(
  db,
  path,
  study = NULL,
  studyKey = "study",
  fileMap = NULL,
  overwrite = FALSE
)

Arguments

db

character(1), path of the SQLite database.

path

character(1), the results dataset to create.

study

character(1) or NULL, path of the Parquet dataset the source files were converted into.

studyKey

character(1), source key for the study.

fileMap

named character, fileinfo.filepth -> run id. Required when source file names collide or recorded paths no longer exist.

overwrite

logical(1), whether to replace an existing dataset.

Value

The path of the dataset, invisibly.

See Also

createDatabase(), validateParquet()

Examples

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 database deprecated

Description

Create and SQLite database of an LC-MS(/MS) experiment

msPurity::create_database is deprecated. Please use msPurity::createDatabase for future use

Usage

create_database(
  pa,
  xset,
  xsa = NULL,
  out_dir = ".",
  grp_peaklist = NA,
  db_name = NA
)

Arguments

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

Value

path to SQLite database and database name

Examples

#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())

Create database

Description

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)

Usage

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
)

Arguments

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; "sqlite" (the default) writes the SQLite database described above, and raises a deprecation warning: SQLite output is frozen and receives bug fixes only. "parquet" writes a Parquet dataset instead (experimental). See Details.

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 purityA() was given a Spectra on that dataset, it is the study; otherwise, and with study = NA, every source file is recorded as an external source.

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 pa@fileList) -> run_id. Required when two source files share a file name, and to match files whose recorded paths no longer exist.

overwrite

logical (parquet only); replace an existing dataset at the destination.

Details

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.

Value

For format = "sqlite", the path to the SQLite database. For format = "parquet", the path of the Parquet results dataset, invisibly.

Examples

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

Using a purityA object, create an MSP file of fragmentation spectra

Description

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)

Usage

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

Arguments

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]+)

Value

Returns a MSP file with the selected spectra and metadata

Examples

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

Filter fragmentation spectra associated with an XCMS feature

Description

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)

Usage

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

Arguments

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 NA to skip the purity criterion.

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, msLevel selects the levels included in the processed result.

param

NULL, a complete FilterFragSpectraParam, or a named list of complete parameter objects. Parameter-set filtering requires one core.

msLevel

nonempty numeric vector of integer MS levels from 2 to 4. Defaults to MS2. Use msLevel = 2:4 for all supported levels. Requested levels with no eligible spectra produce an empty result.

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 select assigns settings within the selected levels. History records requested msLevel and actual effective_msLevel.

Value

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.

Examples

#====== 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)

Complete parameters for fragmentation-spectrum filtering

Description

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.

Usage

FilterFragSpectraParam(
  select = list(),
  ilim = 0,
  plim = 0.8,
  ra = 0,
  snr = 3,
  snmeth = "median"
)

## S4 method for signature 'FilterFragSpectraParam'
as.list(x, ...)

Arguments

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. NA skips purity filtering. Each spectrum uses its own assessment from purityA(), independently of its ancestors.

ra

Minimum relative abundance on the existing 0 to 100 scale.

snr

Minimum signal-to-noise ratio, using the existing statistic.

snmeth

Noise statistic: "median" or "mean".

x

A filtering parameter object.

...

Ignored.

Details

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.

Value

A FilterFragSpectraParam object. as.list() returns its complete settings, including the selectors.

See Also

filterFragSpectra, processingHistory

Examples

filter_param <- FilterFragSpectraParam(plim = 0.7, snr = 3)
as.list(filter_param)
hcd_param <- FilterFragSpectraParam(
    select = list(activationType = "HCD"), snr = 2)
hcd_param

Flag and remove unwanted peaks

Description

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

Usage

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
)

Arguments

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

Value

list(xset, grp_peaklist, removed_peaks)

Examples

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)

Using a purityA object, link MS/MS data to XCMS features

Description

General

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.

Retention time correction

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.

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)

Additional notes

  • 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

Usage

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

Arguments

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 xcmsObj keep that alignment.

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 useGroup = TRUE: "full" uses the minimum rtmin and maximum rtmax of the representative peak of each sample, "median" their median rtmin and rtmax

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 useGroup = TRUE, files with no mapping get one estimated from their precursors. Scans matching exactly one feature are landmarks: a first pass looks 60 seconds (or rtTol if wider) either side of each feature rtmed and takes the median offset, and two more passes look 15 and 8 seconds around the current estimate. A robust loess of the offset against time is used when it fits the landmarks clearly better than a constant offset. The method and the number of landmarks are reported in the diagnostics. An estimate is weaker than a mapping from xcms, so it is off by default

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 precScanNum values can refer to "acquisitionNum", retained original file positions ("scanIndex"), or backend source keys ("sourceSpectrumId"). The last option is msPurity-specific and uses the dataset's spectrum_id_ when available. For custom inputs, lineageScanId identifies each ancestry row and sourceSpectrumId supplies its parent-reference key. The key defaults to the supplied lineageScanId when missing. "spectrumId" matches native spectrumRef metadata to native spectrumId; it requires these fields to have been supplied by the reader. No new metadata extraction is performed. None of these identifiers is the current position in a filtered object. All matches use the same run. "auto" tries these interpretations and accepts a consistent mapping; conflicting valid parents or inconsistent conventions raise an error. Missing references remain unresolved. No parent is inferred from peak similarity or proximity in retention time.

param

One complete Frag4FeatureParam object, or NULL to use scalar settings. Explicit scalar association arguments supplied alongside the object must agree, including use_group. ms2RtMap is an input rather than a setting and is always supplied as an argument.

Details

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.

Value

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

Examples

#====== 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)

Complete parameters for feature association

Description

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.

Usage

Frag4FeatureParam(
  ppm = 5,
  plim = NA_real_,
  intense = TRUE,
  convert2RawRT = TRUE,
  useGroup = FALSE,
  parentReference = "auto",
  rtTol = 0,
  rtSource = "precursor",
  groupWindow = "full",
  includeFilled = FALSE,
  estimateRtMap = FALSE
)

Arguments

ppm

Mass tolerance in ppm for matching an MS2 precursor to an XCMS feature.

plim

Minimum MS2 precursor purity, between zero and one, or NA to skip exclusion. A positive threshold retains MS2 links with purity strictly greater than the threshold. Descendant links are retained independently of this exclusion.

intense

Use the most intense precursor (iMz) instead of the closest precursor to the isolation-window centre (aMz), in both association modes.

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 frag4feature.

rtTol

Tolerance in seconds added to both sides of each retention-time window.

rtSource

MS2 time to compare: "precursor" (the MS1 survey scan) or "ms2" (the MS2 scan).

groupWindow

Feature window when useGroup = TRUE: "full" or "median" peak bounds.

includeFilled

Use peaks added by xcms::fillChromPeaks for association.

estimateRtMap

Estimate a retention-time map for files without one (grouped association only).

Details

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.

Value

A Frag4FeatureParam extending ProtGenerics::Param. as.list() returns all eleven settings.

See Also

frag4feature, processingParameters

Examples

feature_param <- Frag4FeatureParam(ppm = 5, plim = 0.7)
as.list(feature_param)
feature_param

Gaussian normalisation for isolation window efficiency

Description

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)

Usage

iwNormGauss(sdlim = 3, minOff = -0.5, maxOff = +0.5)

Arguments

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)

Value

normalisation function for selected range.

Examples

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)

Q-Exactive +/- 0.5 range, normalisation for isolation window efficiency

Description

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.

Usage

iwNormQE.5()

Value

normalisation function for +/- 0.5 range for Q-Exactive

Examples

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)

Raised cosine normalisation for isolation window efficiency

Description

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

Usage

iwNormRcosine(minOff = -0.5, maxOff = +0.5)

Arguments

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)

Value

normalisation function for selected range

Examples

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)

Construct Mass Spectral Trees from measured acquisition metadata

Description

Represent measured spectra and their validated acquisition parents as portable node and edge tables using spectrum metadata.

Usage

massSpectralTrees(
  object,
  parentReference = c("auto", "acquisitionNum", "scanIndex", "spectrumId",
    "sourceSpectrumId")
)

Arguments

object

A Spectra object containing measured scans, or a purityA object whose source scans have retained acquisition metadata.

parentReference

Interpretation of recorded parent references. One of "auto", "acquisitionNum", "scanIndex", "spectrumId" or "sourceSpectrumId". Native spectrumRef values identify parents by spectrumId. Ambiguous automatic interpretations fail with an error.

Details

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.

Value

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.

Examples

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$edges

Deprecated interfaces in msPurity

Description

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.

Usage

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)

Arguments

mzml_pth

character; mzML path

x

object; purityD object

object

purityD object.

.Object

object; purityD object

fileList

A data frame from Getfiles() with file paths and sample class information, or an MsExperiment whose sample data contains filepth, name, sampleType and class. Missing columns are filled from the spectra file names, with sampleType = "sample".

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 Spectra.

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

Details

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.

Value

Return values depend on the function; see the individual sections.

DIMS retirement

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.

get_additional_mzml_meta

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

purityD

The class used to assess anticipated purity from a DI-MS run

Value: purityD object

getP

output peak list for a purityD object

Value: peaks

show (purityD method)

Show method for purityD object

Value: a print statement of regarding object

initialize (purityD method)

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)

averageSpectra

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

averageSpectraSingle

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.

groupPeaks

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

groupPeaksEx

Group a list of dataframes by their m/z values

Value: data.frame of peaklists grouped together by mz

dimsPredictPurity

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

dimsPredictPuritySingle

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

Getfiles

Takes in a folder path and outputs the a data frame structure for purityD. Function modified from mzmatch.

Value: dataframe of files

filterp

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

updateObject (purityD method)

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.

averagedPeaks

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.

subtract

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

subtractMZ

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

writeOut

Writes processed peak lists to CSV files, and also writes the original peak lists when original = TRUE.

Value: purityD object


The capability set of the msPurity Parquet backend

Description

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.

Usage

parquetCapabilities()

Value

A named list; jsonlite::toJSON(x, auto_unbox = TRUE) gives the JSON document.

Examples

str(parquetCapabilities(), max.level = 1)

Perform purity calculation on a peak matrix

Description

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

Usage

pcalc(
  peaks,
  mzmin,
  mzmax,
  mztarget,
  ppm = NA,
  iwNorm = FALSE,
  iwNormFun = NULL,
  ilim = 0,
  targetMinMZ = NA,
  targetMaxMZ = NA,
  isotopes = FALSE,
  im = NULL
)

Arguments

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)

Value

a vector of the purity score and the number of peaks in the window e.g c(purity, pknm)

Examples

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)

Construct a precursor-fragment tree from measured spectra

Description

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.

Usage

precursorFragmentTrees(
  object,
  ppm = 5,
  tolerance = 0,
  parentReference = "auto",
  spectra = NULL,
  passingOnly = FALSE
)

Arguments

object

Measured Spectra, a purityA result (its retained source spectra), or a scan tree from massSpectralTrees().

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 tolerance + abs(precursorMz) * ppm / 1e6.

parentReference

Interpretation of recorded parent references. One of "auto", "acquisitionNum", "scanIndex", "spectrumId" or "sourceSpectrumId". Native spectrumRef values identify parents by spectrumId. Ambiguous automatic interpretations fail with an error.

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 pass_flag equals one. Supply flagged spectra or the result of filterFragSpectra(). A parent peak retained in the source can supply precursor context even when filtering removed it from the products.

Details

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.

Value

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.

Examples

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

Description

Read processed spectra and their provenance from a Parquet results dataset

Usage

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
)

Arguments

path

Directory written by createDatabase(format = "parquet") or convertSqliteToParquet().

featureId

Exported numeric feature identifiers (feature_id_).

msLevel

Integer MS levels.

method

Averaging methods: "intra", "inter" or "all".

runId

Character results run identifiers.

sourcePaths

Named paths to relocated sources, keyed by manifest source.

includeRaw

Also return the referenced study scans.

Details

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.

Value

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.

See Also

createDatabase(), averageMembers(), averagePeakMembers()

Examples

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)

Processing history and effective settings

Description

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.

Usage

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)

Arguments

object

A purityA, purityX or Spectra object.

step

NULL for all steps, or processing function names such as "filterFragSpectra" and "averageAllFragSpectra".

Details

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.

Value

A named list of records for processingHistory(), or a named list of their effective parameter lists for processingParameters().

Examples

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]]

Assess the acquired precursor ion purity of MS/MS spectra (constructor)

Description

General

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

Example LC-MS/MS processing workflow

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)

Isolation efficiency

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.

Isolation windows

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.

Usage

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
)

Arguments

fileList

vector of mzML file paths, or a Spectra, MsExperiment or XcmsExperiment object holding the spectra of one or more files. Objects are used as they are, so any filtering applied to them also applies to the purity calculation. A Spectra on a Parquet dataset written by MsBackendParquet::mzMLToParquet() is read from that dataset throughout the workflow, never from the mzML files, and is the study createDatabase(format = "parquet") links scans to. Raw peak rows are numbered over the input as given. An activation method the dataset records as a PSI-MS accession is read as its method name, as one named by an mzML filter string is.

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 msLevel = 2:4 to assess all supported levels. Other fragmentation spectra are retained as context; existing assessments and their history remain available without being recalculated.

parentReference

interpretation of parent identifiers for MS3/MS4. See frag4feature for native identifiers, acquisition numbers, original file positions and backend keys. The default is "auto".

param

A PurityAParam object or named list of objects. Matching objects supply complete settings for the child spectrum being assessed. Unmatched MS2 spectra use the scalar arguments. Unmatched higher levels use mostIntense and offsets, without intensity or isotope correction. Parameter-set assessment requires cores = 1.

Details

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.

Value

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

See Also

assessPuritySingle

Examples

filepths <- system.file("extdata", "lcms", "mzML", "LCMSMS_1.mzML", package="msPurityData")
pa <- purityA(filepths)

Results of a purityA object

Description

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.

Arguments

pa

purityA object.

legacy

logical; TRUE for the legacy shape, FALSE for Spectra.

Details

  • 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.

Value

A data frame, list or Spectra object.

Examples

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)

Complete parameters for precursor-purity assessment

Description

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.

Usage

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, ...)

Arguments

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 NA to use each child's recorded bounds.

interpol

MS2 interpolation: "linear", "none", or the legacy "spline" option. Linear is recommended for interpolation.

iwNorm

Enable MS2 isolation-efficiency weighting.

iwNormFun

MS2 weighting function receiving offsets from the window midpoint, or NULL for the default Gaussian.

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 pcalc, or NULL for its default model.

ppmInterp

MS2 mass tolerance in ppm for tracking the selected peak across neighbouring MS1 measurements.

x

A purity parameter object.

...

Ignored.

Details

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.

Value

A PurityAParam extending ProtGenerics::Param. as.list() returns all settings, including selectors and functions.

See Also

purityA, processingParameters

Examples

ms2 <- PurityAParam(select = list(msLevel = 2L), interpol = "linear")
higher <- PurityAParam(select = list(msLevel = 3:4),
    ilim = 0, isotopes = FALSE)
as.list(higher)
ms2

Assessing anticipated purity of XCMS features from an LC-MS run

Description

Constructor for the purityX class.

Given an XCMS object get the anticipated precursor purity of the grouped peaks

Usage

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
)

Arguments

xset

An XcmsExperiment, XCMSnExp or legacy xcmsSet containing detected chromatographic peaks. Grouped prediction also requires feature grouping.

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, c(0.7, 0.3) assesses [target - 0.3, target + 0.7]. This order differs from purityA.

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 rt_raw, rtmin_raw and rtmax_raw peak bounds when supplied. Otherwise compare current chromatographic-peak and spectrum retention times.

saveEIC

Save chromatograms for grouped predictions to SQLite. Ignored when singleFile > 0. SQLite writing is deprecated. Parquet output stores no chromatograms; extract them with xcms::chromatogram().

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 PurityXParam object. Explicit scientific arguments supplied alongside it must agree. Sample/feature selection, execution and output options remain on this call.

Details

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.

Value

a purityX object containing a dataframe of predicted purity scores

Examples

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)

Parameters for chromatographic-feature purity prediction

Description

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.

Usage

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, ...)

Arguments

purityType

Summary of per-scan purity: "purityFWHMmedian", "purityFWmedian", "purityFWHMmean" or "purityFWmean". FWHM uses the chromatographic peak's full width at half maximum; FW uses its full detected boundaries.

offsets

Upper and lower isolation offsets in Da, in that order. Thus c(0.7, 0.3) describes a window from target minus 0.3 to target plus 0.7. This preserves the order used by purityX(), which differs from the lower/upper order of PurityAParam.

iwNorm

Apply isolation-efficiency weighting.

iwNormFun

Weighting function receiving offsets from the isolation window midpoint, or NULL for the default Gaussian.

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 pcalc, or NULL for the default model.

x

A purity-prediction parameter object.

...

Ignored.

Details

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.

Value

A PurityXParam extending ProtGenerics::Param. as.list() retains all seven settings, including NULLs and functions.

See Also

purityX, processingParameters

Examples

prediction_param <- PurityXParam(offsets = c(0.5, 0.5), ilim = 0.05)
as.list(prediction_param)
prediction_param

Check compatibility and score a pair of MS2, MS3 or MS4 spectra

Description

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.

Usage

scoreSpectrumPair(
  query,
  reference,
  param = SpectralMatchingParam(),
  queryIndex = 1L,
  referenceIndex = 1L
)

Arguments

query, reference

Measured or consensus Spectra objects.

param

Tolerances from SpectralMatchingParam.

queryIndex, referenceIndex

One-based positions in the supplied objects.

Details

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.

Value

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.

See Also

spectralMatching

Examples

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)$scores

Show method for purityA class

Description

print statement for purityA class

Usage

## S4 method for signature 'purityA'
show(object)

Arguments

object

object; purityA object

Value

a print statement of regarding object


Show method for purityX

Description

Show method for purityX object

Usage

## S4 method for signature 'purityX'
show(object)

Arguments

object

object; purityX object

Value

a print statement of regarding object


Spectral matching deprecated

Description

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

Usage

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

Arguments

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

Value

list of database details and dataframe summarising the results for the xcms features

Examples

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

Spectral matching for LC-MS/MS datasets

Description

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:

w=intensityx∗mzyw=intensity^x * mz^y

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.

dpc=wq∗wl/∑wq2∗∑wl2dpc = wq * wl / \sqrt{\sum wq^2} * \sqrt{\sum wl^2}

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)

Usage

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
)

Arguments

q_dbPth

An experimental Spectra object, or the path to a query database generated by createDatabase().

l_dbPth

For SQLite, the library database path (defaults to the msPurityData library). For Parquet, supply a Spectra object from any backend, a converted Parquet library path, or a Parquet results dataset path. To search a generic MsBackendParquet dataset, open it as a Spectra object. The search uses its current subset and peak processing.

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; "sqlite" (the default) matches SQLite databases as described above. Writing results with updateDb = TRUE raises a deprecation warning: SQLite output is frozen. "parquet" (experimental) matches the averaged spectra (and, with q_spectraTypes = "scan", the referenced MS2 scans) of a Parquet results dataset in q_dbPth, written by createDatabase(format = "parquet"), against a Spectra library, a converted Parquet library dataset (see convertLibraryToParquet()) or another results dataset. Default scores are computed as for SQLite. With updateDb = TRUE the matches are added to the results dataset as identification evidence, with long-form scores, compounds and per-query coverage; with copyDb = TRUE they are added to a copy at outPth instead. Arguments that select spectra of a SQLite database only (q_pids, q_accessions, q_instruments, q_instrumentTypes, q_sources, q_raThres, l_raThres, l_pids) are refused when set.

topn

integer (Parquet or Spectra queries); keep, per query spectrum, the matches ranked topn or better by dot product cosine or, when selected, BLINK cosine. Tied scores share a rank, and every match tied at the cut is kept. The cut and its boundary score are recorded in the dataset. NA keeps every match.

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 Spectra library. Saved evidence references an external library and its native identifiers. An unnamed release is labelled "Spectra". The returned lpid is the position in the supplied object.

libraryChecksum

Optional SHA-256 digest of the release, supplied as 64 hexadecimal digits with an optional sha256: prefix. The digest is recorded as supplied by the caller. Without a digest each search records a separate source.

param

Optional SpectralMatchingParam for a Spectra query. Without it the four scalar ppm arguments set the tolerances. Explicit scalar ppm settings must agree with a supplied parameter object. Use BlinkMatchingParam with a Spectra query or a Parquet results query to rank by BLINK approximate cosine. BLINK supports measured and consensus MS2-MS4 spectra and uses the same precursor and acquisition checks. The returned scoring record identifies the implementation, version, effective settings and ranking score. Hits expose blinkCosine and blinkMatchingIonCount. Every eligible pair with usable peaks is scored, including pairs with zero matching ions. All references tied at the rank cut are retained. Parquet writes also record these in the matching activity and software record. BLINK scores use separate evidence terms for the cosine and count.

referenceRole

For a Spectra query and a Spectra reference, use "experimental" (default) or "library". For a Parquet path the manifest determines the role. A results path supplies the processed spectra from readProcessedSpectra.

Value

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

Experimental Spectra queries

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.

Spectra library variables

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

Examples

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)

Tolerances for scoring one pair of fragmentation spectra

Description

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.

Usage

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, ...)

Arguments

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.

Value

A SpectralMatchingParam object. All nine settings must be finite, nonnegative numeric scalars. as.list() returns their values.

See Also

scoreSpectrumPair

Examples

as.list(SpectralMatchingParam(q_daProd = 0.01))

Select a component or branch of a scan or peak tree

Description

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.

Usage

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
)

Arguments

x

A MassSpectralTrees result from massSpectralTrees(), a PrecursorFragmentTrees result from precursorFragmentTrees(), or its scan or peak view.

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 peak_index in the prepared peak tree's stored position domain. Required with scan on a peak tree.

node

One exact node ID (lineageScanId or node_id) as an alternative to run, scan and peak. Use this for reference-only nodes or views lacking scan numbers or peak positions.

mode

"all" follows edges in either direction, "out" follows children and "in" follows parents.

depth

Maximum number of edges from the start, or Inf for all reachable nodes. Zero selects the starting node.

includeParent

In "out" mode, also keep the starting node's immediate parents that are present in the view. Their other children are outside this traversal.

structure

Optional "MST" or "PFT". A scan tree defaults to "MST" and a precursor-fragment result defaults to "PFT". Select "MST" on a precursor-fragment result to use its stored scan tree.

max_nodes, max_edges

Maximum numbers of nodes and edges in the selection. Exceeding either limit raises an error.

Details

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.

Value

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.

See Also

massSpectralTrees(), Spectra::filterPrecursorScan()

Examples

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

Update a purityA object to the current class definition

Description

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.

Usage

## S4 method for signature 'purityA'
updateObject(object, ..., verbose = FALSE)

Arguments

object

purityA object.

...

unused.

verbose

logical; unused.

Value

An updated purityA object.

See Also

purityTable


Update saved feature-purity predictions

Description

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.

Usage

## S4 method for signature 'purityX'
updateObject(object, ..., verbose = FALSE)

Arguments

object

A purityX object.

...

Unused.

verbose

Logical; unused.

Value

An updated purityX object retaining its saved predictions.

See Also

processingHistory


Validate precursor purity predictions using LC-MS and LC-MS/MS dataset

Description

The method is used to validate the precursor purity predictions made from an LC-MS dataset

Usage

## S4 method for signature 'purityA'
validate(pa, ppLCMS)

Arguments

pa

object; purityA object

ppLCMS

object; purityX object

Value

purityA object


Validate a Parquet dataset written by msPurity

Description

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.

Usage

validateParquet(path, sourcePaths = NULL)

Arguments

path

character(1), the dataset directory.

sourcePaths

named character, source key -> location, overriding the paths the manifest records.

Value

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.

Examples

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)