%\VignetteIndexEntry{Basic functions for peak-list manipulation and comparison}
%\VignetteDepends{}
%\VignetteKeywords{Mass Spectrometry}
%\VignettePackage{msbase} 
\documentclass[a4paper]{article}

\title{Basic function for peak-list manipulation and comparison}
\author{Witold E. Wolski, mail : \texttt{witek96@users.sourceforge.net}}

\begin{document}

\maketitle

\section{Introduction}

The package provides classes for storing mass spectrometric peak-lists (class \texttt{Massvector}) and collections of such lists (class \texttt{Massvectorlist}). A peak-list are mass-intensity value pairs stored in a two column \texttt{matrix} and
several aditional slots \emph{e.g.}  peak-list name (\texttt{info}), target coordinates (\texttt{tcoor}), gel coordinates (\texttt{gelcoor}), and database accession string (\texttt{access}).
The package provides functions for set operations (union, intersection et cetera) on \texttt{Massvector}s. The mass-spectrometric measurement has a limited accuracy. Hence, the matching of two peak-lists given a measurement error is computed.  Further the package implements several dis/similarity measures on peak-lists. The peak-list matching and the pairwise dissimilarities are implemented in the C programming language.
A \texttt{Massvectorlist} is able to store up to several thousand \texttt{Massvectors}.  Therefore, clustering of several thousand peak-lists using this package, and the various clustering methods (\emph{e.g.} package \texttt{stats} and \texttt{cluster}) given \emph{e.g.} $1G$ RAM is possible.

\section{Reading and Writing}

First we load the library. 
<<LOADLIB>>=
library(msbase)
@

We define some overall experiment constants like the folders with the data and the measurment error.

<<SETTINGVARS>>=
fdat <- system.file("test/20030507a_bl_p_bla2_co1", package="msbase")
# Set the the error
error <- 0.5 #Da
@ 

The example data was measured using a Bruker Reflex III instrument and is stored in an quite complex folder structure
and a XML file (peaklist.xml). The package provides a function to read this format.

<<READDATA>>=
mvl <- readBruker(new("Massvectorlist"),fdat)
mvl
@ 

The package implements also a simple flat file format to store \texttt{Massvectors}.
The mass, intensity value pairs are preceded by a line starting with the symbol ``>'' as the first character. 
The remainder of the line are the info-field and the target coordinates.

\begin{verbatim}
>0_A1_1SRef:1,1
832.819355960755        362.961423469165
839.227609641465        166.621956393718
842.262189000952        219.871886094500
...
\end{verbatim}
<<WRITEDATA>>=
wtest <- system.file("test", package="msbase")
writeMV(mvl,wtest,file="tmp.txt")
readMV(new("Massvectorlist"),wtest,file="tmp.txt")
@
The loaded \texttt{Massvectorlist} contains 18 \texttt{Massvector}s. Subsets can be generated which are Massvectorlists again.
<<SUBSETMV>>=
mvl[1:3]
@
Generating a subset can be of interested if we for example want to discard peak-lists with undesirable properties, {\em e.g.} those without peaks.
This can be easily achieved using \texttt{sapply}.
<<SAPPLY>>=
mvl <- mvl[which(sapply(mvl,length)!=0)]
@ 
Because the \texttt{Massvectorlist} extends (\texttt{contains}) \texttt{list} a single \texttt{Massvector} can be accessed by $[[]]$. The \texttt{Massvector} itself extends (\texttt{contains}) \texttt{Matrix}. Hence it can be subsett using $[]$. 
<<MASSVECTOR>>=
mvl[[1]][1:10,]
@ 
The peaks in the \texttt{Massvector} can be visualized using the \texttt{plot} and \texttt{image} function.
<<plotMV,fig=TRUE>>=
plot(mvl[[1]])
@
The \texttt{plot} of a single \texttt{Massvector} is showing a stick spectrum. The \texttt{plot} of two \texttt{Massvector}s shows the residues of matching masses plotted against the average of their mass. The green and blue vertical dashed lines are drawn to show the non-matching masses.
<<plotMV2,fig=TRUE>>=
plot(mvl[[1]],mvl[[2]])
@
The \texttt{image} plot color codes all mass differences between the peaks. Big blue regions are caused by peaks that are close to each other.
<<ImageMV,fig=TRUE>>=
image(mvl[[1]])
<<ImageMV2,fig=TRUE>>=
image(mvl[[1]],mvl[[3]])
@

To take a first glance at the data in the \texttt{Massvectorlist} the methods \texttt{hist}, \texttt{plot} and \texttt{pep.plot} can be used. The \texttt{plot} function draws a strip-chart of all \texttt{Massvectors} in the \texttt{Massvectorlist}. The \texttt{hist} is showing the frequencies of all masses in the \texttt{Massvectorlist}.

<<LOOKATDATA,fig=TRUE>>=
plot(mvl)
@

<<PLOTHIST,fig=TRUE>>=
hist(mvl,accur=2)
@

The \texttt{pep.plot} plots the m mod 1 (\texttt{m\%\%1}) against the remainder of the peptide mass (\texttt{x-x\%\%1}). The linear dependence of this two values is known as peptide rule.

<<PEPPLOT,fig=TRUE>>=
pep.plot(mvl,cex=0.6)
@ 


A \texttt{Massvectorlist} can be transformed into R data structures:

\begin{itemize}
\item
data.frame

<<TODataFrame>>=
df<-as(mvl,"data.frame")
names(df)
@

\item
matrix

<<TOMATRIX>>=
df<-as(mvl,"matrix")
colnames(df)
@ 

\end{itemize}

This is done by calling the \texttt{summary} function on the masses and intensities of the \texttt{Massvector}.
This information can be colorcoded and visualized depending the target position.
(As we mentioned each \texttt{Massvector} stores the mass spectrometric target coordinates.)

<<TARCOOR>>=
mvl[[1]]@tcoor
@
 
<<IMAGE,fig=TRUE>>=
image(mvl,what="Min.mass")
@ 

The figure above looks quite ugly because only one row from the target are provided by the sample data.

The \texttt{Massvector} can also store gel coordinates.

<<GELCOOR>>=
mvl[[1]]@gelcoor
@ 


\section{Set functions on Massvectors}

There are two methods which return the indices of matching peaks. \texttt{fmatch} returns the indices of matching peaks and the residues.
\texttt{fmatchall} returns the indices of matching and not matching peaks.
Because this methods were first implemented to be used in calibration functions, where a peak-list is compared with a 
calibration list, the returned indices associated with the first argument are called \texttt{plind} (peak-list indices) while that associated with the second argument are called \texttt{calind} (calibration-list indices).

<<FMATCH>>=
pl1 <- mvl[[1]]
pl2 <- mvl[[2]]
fmatch(pl1,pl2,error=400,ppm=T)
fmatchall(pl1,pl2,error=400,ppm=T)
@ 

The package provides functions to compute the union, intersection, difference, equality and membership of two \texttt{Massvectors}.
A mass spectrometric measurement has an error. Therefore, the functions have additional parameters to specify the error and their names are preceded by the letter \texttt{f} (fuzzy). The error can be specified in the units of the measurement (absolute error) or as relative error in parts per million (ppm). If one peak in peak-list x matches multiple peaks in list y the optimal alignment can be computed by setting \texttt{uniq=T}.


<<SETOPERATIONS>>=
funion(pl1,pl2,error=400,ppm=T)
fintersect(pl1,pl2,error=400,ppm=T,uniq=T)
fsetdiff(pl1,pl2,error=400,ppm=T,uniq=T)
fsetequal(pl1,pl2,error=400,ppm=T)
fis.element(pl1,pl2,error=400,ppm=T)
@ 

The \texttt{msbase} package function are equivalent to the following  methods in the \texttt{base} package:
\texttt{union},\texttt{intersect},\texttt{setdiff},\texttt{setequal},\texttt{is.element}.



\section{Pairwise comparison of peaklists -- dis/similarities}

The package provides methods to compute pair-wise dis/similarities of peak-lists.

\subsection{Binary measures.}

The binary measures numerated in Table \ref{tab:binm} are implemented.

\begin{table}
\begin{center}
\begin{tabular}{|c|c|c|c|}
\hline
abbreviation & name & type & range \\
\hline
rmi & Relative mutual information & S & $[0,1]$\\
hg & Huberts $\Gamma$ & S & $[-1, 1]$\\
fm & Fowlkes Mallows Statistiks & S & $[0,1]$\\
gower & gower (jaccard) coefficient & D & $[0,1]$\\
\hline
\end{tabular}
\end{center}
\caption{Binary measures. type :  S -- similarity or D -- dissimilarity.}
\label{tab:binm}
\end{table}

The measures are in addition parametrized. We can adjust by \texttt{theta} how strongly non-matching peaks will contribute to the final score.
Furthermore, the mass agreement of matching peaks can be weighted by a triangular weighting function (\texttt{weight=T}).

\begin{equation}
w=\frac{a-|m_x-m_y|}{a}
\end{equation}
$m_x$ and $m_y$ are the masses of matching peaks and $a$ are the measurement accuracy.
<<FBINARY>>=
fbinary(pl1,pl2,error=400,ppm=T,theta=1,weight=F,method="rmi",uniq=T)
fbinary(pl1,pl2,error=400,ppm=T,theta=0.2,weight=F,method="rmi")
fbinary(pl1,pl2,error=400,ppm=T,theta=0.2,weight=F,method="hg")
fbinary(pl1,pl2,error=400,ppm=T,theta=0.2,weight=T,method="gower")
fbinary(pl1,pl2,error=400,ppm=T,theta=0.2,weight=T,method="fm")
@

\subsection{Intensity Based dissimilarities}
The package implements two groups of intensity based dis/similarities.
\subsubsection{Dot product based dissimilarities}
This group includes the Pearson correlation coefficient, spectral angle and spearman correlation. The only difference between the spectral angle and the Pearson correlation are the scaling of the peak intensities. The type of scaling of the intensities can be selected by setting the parameter \texttt{scale} to one of the character strings given in the first column of Table \ref{tab:scale}.

The difference between Spearman correlation and Pearson correlation are the normalization of the intensities. To compute the Spearman correlation
the intensities are replaced by they ranks. This can be easily accomplished using the \textbf{R} function \texttt{rank}. Hence, no special functions are provided by the package. The following code snipped is showing how to log-transform all peak intensities in a \texttt{Massvectorlist}.
<<DEFFUNCTION>>=
mvlog<-function(x)
{
  x[,2] <- log(x[,2])
  x
}
as(mvl,"list") <- lapply(mvl,mvlog)
@ 
As for the binary measures the dot product based measures are parameterized to flexible weight the non-matching peaks and mass measurement accuracy.
\begin{table}
\begin{center}
\begin{tabular}{|c|c|}
\hline
abbreviation & name \\
\hline
no & no scaling \\
tic & total ion current count \\
zscore & centered and divided by the variance\\
student & constant variance \\
\hline
\end{tabular}
\end{center}\caption{Scaling methods for peak intensities.}
\label{tab:scale}
\end{table}
<<FC>>=
fcor(pl1,pl2,error=400,ppm=T,theta=1,weight=F,scale="no",method="dotprod")
fcor(pl1,pl2,error=400,ppm=T,theta=1,weight=F,scale="tic",method="dotprod")
fcor(pl1,pl2,error=400,ppm=T,theta=1,weight=F,scale="student",method="dotprod")
fcor(pl1,pl2,error=400,ppm=T,theta=1,weight=F,scale="zscore",method="dotprod")
@ 
A second method which can be accessed by this function are the sum of agreeing intensities (\texttt{method="soai"}). It puts more emphasis on the agreement of peak intensities then the correlation coefficient. All methods provided by the function \texttt{fcor} are similarity measures.

\subsubsection{Distance measures}
This group of measures covers the two lp-norm based measures: Euclidean and Manhattan distance, as well as the two relative distances Canberra distance, and similarity index. The measure can be chosen by setting the argument \texttt{method} to one of the characters in column one of Table \ref{tab:dist}.
\begin{table}
\begin{center}
\begin{tabular}{|c|c|}
\hline
method & description \\
\hline
euclidean & Euclidean distance \\
manhattan & Manhattan distance \\
canberra & Canberra distance \\
simindex & similarity index\\
\hline
\end{tabular}
\end{center}
\caption{Distance measures.}\label{tab:dist}
\end{table}
All other parameters which can be passed to this function are equal to those for the function \texttt{fcor}.
<<FDIST>>=
fdist(pl1,pl2,error=400,ppm=T,theta=1,weight=F,scale="zscore",method="euclidean")
@
\section{Searching and Clustering}
Building on the pairwise \texttt{Massvector} comparison, functions to search similar spectra in \texttt{Massvectorlist}s or to cluster the \texttt{Massvector}s in \texttt{Massvectorlist} are implemented. Hence, the functions \texttt{fbinary, fcor, fdist} allow not only to compare two peak-lists but also search with one peak-list in a set of peak-lists.

<<SEARCH>>=
res <- fcor(mvl , pl1 , error=400 , ppm=T , theta=1 , weight=F , scale="zscore" , method="dotprod" )
@ 

We can find the most similar peak-list by:
<<FINDMOSTSIMILAR>>=
which( max(res) == res )
@ 

Further we can order all peak-lists according the similarity to \texttt{pl1}.

<<SORTINGACCORDING>>=
mvl<-mvl[order(res)]
@ 

The same function interface can be used to compute a distance matrix (class \texttt{dist}) from a \texttt{Massvectorlist}. In this case the second argument must be \texttt{NULL}. An object of class \texttt{dist} can be passed to variety of clustering functions available in \textbf{R}.

<<CLUSTER,fig=TRUE>>=
pp <- mvl[1:10]
res <- fcor(pp,NULL,error=400,ppm=T,theta=1,weight=F,scale="zscore",method="dotprod")
plot(hclust(res,method="complete"))
@

If the function \texttt{fcor} is called in this way, the similarity measures are automatically transformed into dissimilarities.

\section{Conclusion}

The clustering shows that peak-lists are very similar. This are mainly because of peaks caused by unspecific trypsin and matrix peaks. Furthermore the mass measurement error for this data is large. To calibrate and filter the data the package \emph{mscalib} is developed (see : \texttt{r4proteomics.sourceforge.net}).

\section{Open for contributions}

This document and package is by no means complete. So if you find something missing, unclear or language errors, please send me an e-mail. I don't get offended because of this. The package is free software published under the GNU public license and is hosted on \texttt{r4proteomics.sourceforge.net} to give you the means to contribute to it. So if you think that this package is worth improvement or extending send an e-mail with your contributions. Especially functions in the file \texttt{undocumented-functions.Rd} need to be documented. Also examples to the \texttt{examples} section of the *.Rd files are wellcome. If the contributions are going to happen regularly, and you are a registered \texttt{www.sourceforge.net} user, I will grant you developer permissions so you can check in your changes into the CVS by yourself. By this your contribution will get documented.


\end{document}
