% Generated by roxygen2: do not edit by hand
% Please edit documentation in R/Chromatograms-peaksData.R
\name{peaksData}
\alias{peaksData}
\alias{peaksVariables}
\alias{filterPeaksData}
\alias{imputePeaksData}
\alias{peakBoundary}
\alias{compareChromatograms}
\alias{matchRtime}
\alias{imputePeaksData,Chromatograms-method}
\alias{filterPeaksData,Chromatograms-method}
\alias{intensity,Chromatograms-method}
\alias{intensity<-,Chromatograms-method}
\alias{peaksData,Chromatograms-method}
\alias{peaksData<-,Chromatograms-method}
\alias{peaksVariables,Chromatograms-method}
\alias{rtime,Chromatograms-method}
\alias{rtime<-,Chromatograms-method}
\alias{lengths,Chromatograms-method}
\alias{compareChromatograms,Chromatograms,Chromatograms-method}
\alias{compareChromatograms,Chromatograms,missing-method}
\alias{peakBoundary,Chromatograms-method}
\title{Chromatographic peaks data}
\usage{
\S4method{imputePeaksData}{Chromatograms}(
  object,
  method = c("linear", "spline", "gaussian", "loess"),
  span = 0.3,
  sd = 1,
  window = 2,
  extrapolate = FALSE,
  ...
)

\S4method{filterPeaksData}{Chromatograms}(
  object,
  variables = character(),
  ranges = numeric(),
  match = c("any", "all"),
  keep = TRUE
)

\S4method{intensity}{Chromatograms}(object, ...)

\S4method{intensity}{Chromatograms}(object) <- value

\S4method{peaksData}{Chromatograms}(
  object,
  columns = peaksVariables(object),
  f = processingChunkFactor(object),
  BPPARAM = bpparam(),
  drop = FALSE,
  ...
)

\S4method{peaksData}{Chromatograms}(object) <- value

\S4method{peaksVariables}{Chromatograms}(object, ...)

\S4method{rtime}{Chromatograms}(object, ...)

\S4method{rtime}{Chromatograms}(object) <- value

\S4method{lengths}{Chromatograms}(x)

matchRtime(x, y, tolerance = Inf, ...)

\S4method{compareChromatograms}{Chromatograms,Chromatograms}(
  x,
  y,
  MAPFUN = matchRtime,
  FUN = cor,
  ...,
  minPeaks = 4L,
  BPPARAM = SerialParam()
)

\S4method{compareChromatograms}{Chromatograms,missing}(
  x,
  y = NULL,
  MAPFUN = matchRtime,
  FUN = cor,
  ...,
  minPeaks = 4L,
  labelsColumn = NULL,
  BPPARAM = SerialParam()
)

\S4method{peakBoundary}{Chromatograms}(
  object,
  threshold = 0.1,
  baselineThreshold = 0.1,
  baselineQuantile = 0.1,
  ...
)
}
\arguments{
\item{object}{A \link{Chromatograms} object.}

\item{method}{For \code{imputePeaksData()}: \code{character(1)}: Imputation
method ("linear", "spline", "gaussian", "loess").}

\item{span}{For \code{imputePeaksData}: \code{numeric(1)}, for the loess method:
Smoothing parameter (only used if method == "loess")}

\item{sd}{For \code{imputePeaksData}: \code{numeric(1)}, for the gaussian method:
Standard deviation for Gaussian kernel
(only used if method == "gaussian")}

\item{window}{For \code{imputePeaksData}: \code{integer}, for the gaussian method:
Half-width of Gaussian kernel window (e.g., 2 gives window size 5)}

\item{extrapolate}{For \code{imputePeaksData}: \code{logical(1)} (default \code{FALSE}).
If \code{TRUE}, missing values at the beginning and end of a chromatogram
(outside the range of observed values) will be extrapolated. If
\code{FALSE}, only interpolation is performed and leading/trailing \code{NA}
values remain \code{NA}.}

\item{...}{Additional arguments passed to the method.}

\item{variables}{For \code{filterPeaksData()}: \code{character} vector with the names
of the peaks data variables to filter for. The list of available
peaks data variables can be obtained with \code{peaksVariables()}.}

\item{ranges}{For \code{filterPeaksData()} : a \code{numeric} vector of paired values
(upper and lower boundary) that define the ranges to filter the
\code{object}. These paired values need to be in the same order as the
\code{variables} parameter (see below).}

\item{match}{For \code{filterPeaksData()} : \code{character(1) } defining whether the
condition has to match for all provided \code{ranges} (\code{match = "all"};
the default), or for any of them (\code{match = "any"}).}

\item{keep}{For \code{filterPeaksData()}: \code{logical(1)} defining whether to
keep (\code{keep = TRUE}) or remove (\code{keep = FALSE}) the chromatographic
peaks data that match the condition.}

\item{value}{For \code{rtime()} and \code{intensity()}: \code{numeric} vector with the
values to replace the current values. The length of the vector must
match the number of peaks data pairs in the \code{Chromatograms} object.}

\item{columns}{For \code{peaksData()}: optional \code{character} with column
names (peaks variables) that should be included in the
returned \code{list} of \code{data.frame}. By default, all columns are returned.
Available variables can be found by calling \code{peaksVariables()} on the
object.}

\item{f}{\code{factor} defining the grouping to split the \code{Chromatograms} object.}

\item{BPPARAM}{Parallel setup configuration. See \code{\link[BiocParallel:register]{BiocParallel::bpparam()}}
for more information.}

\item{drop}{\code{logical(1)} For \code{peaksData()}, default to \code{FALSE}. If \code{TRUE},
and one column is called by the user, the method returns a list of
vector of the single column requested.}

\item{x}{For \code{lengths()} and \code{compareChromatograms()}: A \link{Chromatograms}
object. For \code{matchRtime()}: a \code{data.frame} with columns \code{rtime} and
\code{intensity} representing the first chromatogram.}

\item{y}{For \code{compareChromatograms()}: A \link{Chromatograms} object against
which \code{x} is compared. If missing, each chromatogram in \code{x} is
compared with each other chromatogram in \code{x}. For \code{matchRtime()}:
a \code{data.frame} with columns \code{rtime} and \code{intensity} representing
the second chromatogram.}

\item{tolerance}{For \code{matchRtime()}: \code{numeric(1)} (default \code{Inf}). Maximum
RT difference between two measured points to be considered a match.
Controls both the overlap detection and the shared RT grid. Lower
values prevent a peak from being compared against a long interpolated
gap in the other chromatogram. Use \code{Inf} (the default) to consider
all RT points as matching. Can be forwarded via \code{...} in
\code{compareChromatograms()}.}

\item{MAPFUN}{For \code{compareChromatograms()}: \code{function} to align the
retention times of two chromatograms before computing similarity.
Must accept two \code{data.frame}s (with columns \code{rtime} and \code{intensity})
and return a \code{list} with elements \code{x} and \code{y}: numeric vectors of
equal length containing the aligned intensities of the first and
second chromatogram respectively, interpolated onto a common
retention-time grid. Defaults to \code{\link[=matchRtime]{matchRtime()}}. Additional
arguments can be passed via \code{...}.}

\item{FUN}{For \code{compareChromatograms()}: \code{function} to compute the
similarity between two chromatograms from their aligned intensity
vectors (as returned by \code{MAPFUN}). Must accept two numeric vectors
as the first two arguments and return a single numeric value.
Defaults to \code{\link[stats:cor]{stats::cor()}} (Pearson correlation). Additional
arguments can be passed via \code{...} (e.g., \code{method = "spearman"} for
\code{\link[stats:cor]{stats::cor()}}).}

\item{minPeaks}{For \code{compareChromatograms()}: \code{integer(1)} (default \code{4L}).
Minimum number of overlapping retention-time points (as returned by
\code{MAPFUN}) required to compute a similarity score. Pairs whose
retention-time overlap contains fewer than \code{minPeaks} points return
\code{NA} in the score layer; the actual overlap count is still recorded
in the \code{n_peaks} layer. Setting \code{minPeaks = 2L} recovers the
behaviour of always computing a score whenever at least two points
overlap.}

\item{labelsColumn}{For \code{compareChromatograms()}: optional \code{character(1)}
giving the name of a chromatogram variable (column in \code{chromData()})
whose values should be used as row and column names of the returned
array. The column must contain unique values. If \code{NULL} (the
default), the array dimensions are unnamed. Only used when \code{y} is
missing.}

\item{threshold}{For \code{peakBoundary()}: \code{numeric(1)} (default \code{0.1}).
Fraction of the peak height above baseline used as a fallback
cut-off when valley-based boundaries are not suitable. Must be
\verb{>= 0} and \verb{< 1}.}

\item{baselineThreshold}{For \code{peakBoundary()}: \code{numeric(1)} (default
\code{0.1}). Fraction of the peak height above the baseline. Valley
positions returned by \code{MsCoreUtils::valleys()} are accepted only if
the intensity at the valley is at or below
\code{baseline + peak_height * baselineThreshold}. Must be \verb{>= 0} and
\verb{< 1}.}

\item{baselineQuantile}{For \code{peakBoundary()}: \code{numeric(1)} (default
\code{0.1}). Quantile of the intensity distribution used as the
baseline estimate. Must be \verb{>= 0} and \verb{<= 1}.}
}
\value{
Refer to the individual function description for information on the
return value.
}
\description{
As explained in the \link{Chromatograms} class documentation, the \code{Chromatograms}
object is a container for chromatographic data that includes chromatographic
peaks data (\emph{retention time} and related intensity values, also referred to
as \emph{peaks data variables} in the context of \code{Chromatograms}) and metadata of
individual chromatograms (so called \emph{chromatograms variables}).

The \emph{peaks data variables} information can be accessed using the
\code{peaksData()} function. It is also possible to access specific peaks
variables using \code{$}.

The peaks data can be accessed, replaced but also filtered/subsetted. Refer
to the sections below for more details.
}
\section{Filter Peaks Variables}{


Functions that filter a \code{Chromatograms}'s peaks data (i.e., \verb{@peaksData}).
These functions remove peaks data that do not meet the
specified conditions. If a chromatogram in a \code{Chromatograms} object is
filtered, only the corresponding peaks variable pairs (i.e., rows) in the
\code{peaksData} are removed, while the chromatogram itself remains in the object.

The available functions to filter chromatographic peaks data include:
\itemize{
\item \code{filterPeaksData()}: Filters numerical peaks data variables based on the
specified numerical \code{ranges} parameter. This method returns the same input
\code{Chromatograms} object, but the filtering step is added to the processing
queue. The filtered data will be reflected when the user accesses
\code{peaksData}. This function does \emph{not} reduce the number of chromatograms
in the object, but it removes the specified peaks data (e.g., "rtime" and
"intensity" pairs) from the \code{peaksData}.
}

In the case of a read-only backend, (such as the \link{ChromBackendMzR}), the
replacement of the peaks data is not possible. The peaks data can be
filtered, but the filtered data will not be saved in the backend. This means
the original mzML files will not be affected by computations performed on
the \link{Chromatograms}.
}

\section{Impute Peaks Variables}{


\code{imputePeaksData} will impute missing values in a \code{Chromatograms}'s peaks data
(i.e., \verb{@peaksData}). This functions replace missing peaks data values with
specified imputation methods using various methods such as linear
interpolation, spline interpolation, Gaussian kernel smoothing, or LOESS
smoothing. This method modifies the peaks data in place and returns the
same \code{Chromatograms} object with imputed values.
}

\section{Peak Boundary Detection}{


\code{peakBoundary()} determines the retention time boundaries of the tallest
peak in each chromatogram. The function uses \code{MsCoreUtils::valleys()} to
locate the valleys (local minima) flanking the apex. If the valley
intensities exceed a baseline-relative threshold (controlled by
\code{baselineThreshold}), it falls back to a threshold-based boundary search
using \code{threshold}. The baseline is estimated as the \code{baselineQuantile}
quantile of the chromatogram's intensity values.
The result is a \code{matrix} with one row per
chromatogram and columns \code{left_boundary} and \code{right_boundary}
(retention times). Chromatograms that are empty, have fewer than 3 data
points, contain only \code{NA} or all-zero intensities return \code{NA} for both
boundaries.
}

\section{Compare Chromatograms}{


\code{compareChromatograms()} compares chromatograms in two steps:
\enumerate{
\item \strong{Align} – \code{MAPFUN} (default \code{\link[=matchRtime]{matchRtime()}}) maps two chromatograms
onto a common retention-time grid and returns \code{list(x, y)}, where
\code{x} and \code{y} are numeric vectors of equal length containing the aligned
intensities of the first and second chromatogram respectively.
\item \strong{Score} – \code{FUN} (default \code{\link[stats:cor]{stats::cor()}}, Pearson correlation)
computes a single similarity value from those aligned intensity vectors.
}

If \code{y} is missing, each chromatogram in \code{x} is compared against every
other chromatogram in \code{x}; otherwise, each in \code{x} is compared with
each in \code{y}.

The result is a 3-dimensional numeric array with dimensions
\code{length(x)} x \code{length(y)} x 2 (or symmetric \verb{n x n x 2} for
self-comparison). Layer \verb{[, , 1]} (named \code{"score"}) contains pairwise
similarity scores; layer \verb{[, , 2]} (named \code{"n_peaks"}) contains the
number of overlapping retention-time points used to compute each score.
Pairs with fewer overlapping retention-time points than \code{minPeaks} (default
4) return \code{NA} in the score layer; the actual overlap count is still
recorded in the \code{n_peaks} layer. The diagonal of a self-comparison is
always 1 (score) and the number of data points in that chromatogram
(count).

\code{matchRtime()} is the default \code{MAPFUN}. Given two chromatograms as
\code{data.frame}s with \code{rtime} and \code{intensity} columns, it aligns their RT axes
and returns a named list with elements \code{x} and \code{y}: equal-length intensity
vectors evaluated on a shared RT grid, ready for similarity scoring.

The alignment works as follows: \code{matchRtime()} first identifies the RT range
where both chromatograms have measured points within \code{tolerance} of each
other (the \emph{overlap}). Within that range, it builds a shared RT grid from
all of \code{x}'s RT points, adding any RT points from \code{y} that have no close
match in \code{x} (within \code{tolerance}). Both intensity vectors are then linearly
interpolated at grid positions they do not natively cover, using
\code{\link[stats:approxfun]{stats::approx()}}. If either chromatogram has fewer than 2 data points, or
the two chromatograms do not overlap, empty vectors are returned.

The \code{tolerance} parameter (default \code{Inf}, meaning all RT points are
considered matching) controls the strictness of the matching. Lowering it
prevents comparing a measured peak against a long interpolated gap in the
other chromatogram. Pass \code{tolerance} via \code{...} in \code{compareChromatograms()}.

When \code{y} is missing, the \code{labelsColumn} parameter assigns meaningful
row/column names to the output from a \code{chromData()} column (e.g., \code{"mz"}
or a user-defined feature identifier). The column must contain unique
values. To compare groups of chromatograms separately, split the object
with \code{split()} beforehand and apply \code{compareChromatograms()} to each subset.
}

\examples{

# Create a Chromatograms object
cdata <- data.frame(
    msLevel = c(1L, 1L, 1L),
    mz = c(112.2, 123.3, 134.4),
    dataOrigin = c("mem1", "mem2", "mem3")
)

pdata <- list(
    data.frame(
        rtime = c(12.4, 12.8, 13.2, 14.6),
        intensity = c(123.3, 153.6, 2354.3, 243.4)
    ),
    data.frame(
        rtime = c(45.1, 46.2),
        intensity = c(100, 80.1)
    ),
    data.frame(
        rtime = c(12.4, 12.8, 13.2, 14.6),
        intensity = c(123.3, 153.6, 2354.3, 243.4)
    )
)

be <- backendInitialize(new("ChromBackendMemory"),
    chromData = cdata,
    peaksData = pdata
)

chr <- Chromatograms(be)

# Access peaks data
peaksData(chr)

# Access specific peaks data variables
peaksData(chr, columns = "rtime")
rtime(chr)

# Replace peaks data
rtime(chr)[[1]] <- c(1, 2, 3, 4)

# Filter peaks data
filterPeaksData(chr, variables = "rtime", ranges = c(12.5, 13.5))

# Pairwise similarity: returns a 3D array [i, j, layer]
res <- compareChromatograms(chr)
res[, , "score"]   ## similarity scores
res[, , "n_peaks"] ## number of overlapping RT points

## Use Spearman correlation (passed to cor() via ...)
compareChromatograms(chr, method = "spearman")[, , "score"]

# Use a chromData column as row/column labels
compareChromatograms(chr, labelsColumn = "mz")[, , "score"]

# Compare two Chromatograms objects
compareChromatograms(chr[1:2], chr[3])

}
\seealso{
\link{Chromatograms} for a general description of the \code{Chromatograms}
object, and \link{chromData} for accessing,substituting and filtering
chromatographic variables. For more information on the queuing
of processings and parallelization for larger dataset processing
see \link{processingQueue}.
}
\author{
Philippine Louail
}
