%\VignetteEngine{knitr::knitr}
%\VignetteIndexEntry{Workflow for Metabolomics}
%\VignetteKeywords{Mass Spectrometry, MS, MSMS, Metabolomics, Visualization}
%\VignettePackage{MetCirc-vignette}

\documentclass[11pt,a4paper,english,arial,twoside]{article}
\usepackage{caption}
\usepackage{subcaption}
\usepackage{geometry}
\geometry{verbose,
    tmargin=25mm,
    bmargin=25mm,
    lmargin=25mm,
    rmargin=25mm}
\setlength\parindent{0pt}

\usepackage{amsmath,amsfonts,amssymb,amsthm}
\usepackage{mathtools}
\usepackage{textcomp}
\usepackage{longtable}

%\definecolor{red}{rgb}{1,0,0}
%\definecolor{blue}{rgb}{0,0,1}

%\usepackage{breakurl}
\usepackage{hyperref}
\hypersetup{%
  pdfusetitle,
  bookmarks = {true},
  bookmarksnumbered = {true},
  bookmarksopen = {true},
  bookmarksopenlevel = 2,
  unicode = {true},
  breaklinks = {false},
  hyperindex = {true},
  colorlinks = {true},
  linktocpage = {true},
  plainpages = {false},
  linkcolor = {blue},
  citecolor = {blue},
 % urlcolor = {red},
  pdfstartview = {Fit},
  pdfpagemode = {UseOutlines},
  pdfview = {XYZ null null null}
}

\widowpenalty10000
\clubpenalty10000

\newcommand{\email}[1]{\href{mailto:#1}{\normalfont\texttt{#1}}}
\newcommand{\R}{\texttt{R}}
\newcommand{\code}[1]{{\texttt{#1}}}
\newcommand{\Rfunction}[1]{{\texttt{#1}}}
\newcommand{\Robject}[1]{{\texttt{#1}}}
\newcommand{\Rpackage}[1]{{\mbox{\normalfont\textsf{#1}}}}


\newcommand\numberthis{\addtocounter{equation}{1}\tag{\theequation}}

\usepackage[nottoc]{tocbibind}

\usepackage[utf8]{inputenc}
\usepackage{fancyhdr}

\usepackage{graphicx}
%\usepackage[font=footnotesize]{subfig}

\usepackage[english]{babel}
\usepackage{color}

\usepackage[backend=bibtex,natbib,style=authoryear,maxcitenames=2]{biblatex}
\addbibresource{MetCirc-citations}

\usepackage{setspace}
\onehalfspacing

\usepackage{authblk} 
\author[]{Thomas Naake and Emmanuel Gaquerel}



\affil{
    Plant Defense Metabolism \\
    Centre for Organismal Studies
}

\title{MetCirc: Navigating mass spectral similarity in high-resolution 
    MS/MS metabolomics data}
    
\begin{document}

\maketitle

\section{Introduction}
The \Rpackage{MetCirc} package comprises functionalities to display, 
(interactively) explore similarities and annotate features of MS/MS metabolomics 
data. It is especially designed to 
improve the interactive exploration of metabolomics data obtained from 
cross-species/cross-tissues comparative experiments. Notably, \Rpackage{MetCirc} 
includes functions to calculate the similarity between individual MS/MS 
spectra based on a normalised dot product (NDP, see \citet{Li2015} for further 
details) calculation taking into account shared fragments or main neutral 
losses. \newline

Visualisation of molecular networks was pioneered by the 
Dorrestein lab \citep[e.g.][]{Watrous2012} to efficiently organize MS/MS spectra in such a way that 
clusters of MS/MS spectra sharing multiple common fragments are rapidly inferred. \newline
In contrary to the analysis there, the \Rpackage{MetCirc} framework offers two ways for the computation of 
mass spectrum similarity: one way deploys common (shared) fragments and the other
shared neutral losses that are deduced from the spectra. Especially the latter 
approach allows to extract clusters of spectra corresponding to compound families 
facilitating the rapid dereplication of hitherto unknown metabolites. Small 
molecules, as produced by plants, return during fragmentation few fragments.  
Sometimes only a few fragments among them are shared and diagnostic across 
the compound family. Compared to the 
MS/MS similarity scoring based on shared fragments, the second similarity 
measure incorporates, in a non-supervised manner, neutral losses, which 
definitely helps obtaining biochemically-meaningful MS/MS groupings. \newline

The interpretation drawn from network reconstruction highly depends 
from topological parameters applied during the network construction steps. 
\Rpackage{MetCirc} circumvents this confinement. Furthermore, it uses instead
smaller MS/MS datasets obtained from experiments involving 
\textit{a priori} defined biological groups (organisms, tissues, etc.) to 
visualise within and between MS/MS feature similarities on a circular 
layout - inspired by the Circos framework \citep{Krzywinkski2009}. The visualisation
is adjustable (MS/MS ordering and similarity thresholds) via the 
\Rpackage{shiny} interface and does not uniquely emphasize on large clusters 
of MS/MS features (a frequent caveat of network visualisation). Furthermore,
the implemented functionality for annotation may improve 
dereplication of known and unknown molecules. \newline

This vignette uses as a case study indiscriminant MS/MS (idMS/MS) data from \citet{Li2015},
unpublished idMS/MS data 
collected from different organs of tobacco flowers and data from the 
Global Natural Product Social Molecular Networking (GNPS) library
to navigate through the 
analysis pipeline. The pipeline includes creation of an \Rpackage{MSP}-object, 
binning of fragment ions, calculation of a similarity measure (NDP), 
assignment to a similarity matrix and visualisation of similarity based 
on interactive and non-interactive graphical tools using the 
\Rpackage{circlize} framework \citep{Gu2014}. \newline

\Rpackage{MetCirc} is currently under active development. If you 
discover any bugs, typos or develop ideas of improving 
\Rpackage{MetCirc} feel free to raise an issue via 
\href{https://github.com/PlantDefenseMetabolism/MetCirc}{GitHub} or 
send a mail to the developers. 

<<knitr, include=FALSE, cache=FALSE>>=
library("knitr")
@

\section{Prepare the environment}
To install \Rpackage{MetCirc} enter the following to the \R~console
<<eval=FALSE>>=
source("https://bioconductor.org/biocLite.R")
biocLite("MetCirc")
@

Before starting, load the \Rpackage{MetCirc} package. This will also
load the required packages \Rpackage{circlize}, \Rpackage{amap},
\Rpackage{scales} and \Rpackage{shiny}: 
<<eval=TRUE>>=
library(MetCirc)
@

Two options exist to load data for the \Rpackage{MetCirc} workflow: 
(1) loading a data frame with a minimum requirement of a column "id" (comprising unique identifiers
for MS/MS features) and of the columns "mz" and "intensity" comprising the
fragment ions and their intensities, respectively, or 
(2) loading a data frame resembling a .MSP file object. In the following 
we will exemplify the usage of \Rfunction{convert2MSP} and 
\Rfunction{convertMSP2MSP} to load data into the workflow. 

\paragraph{Load example data sets from \citet{Li2015}, tissue idMS/MS data and GNPS data.} 
%sd01\_outputXCMS is the 
%output of the \Rpackage{XCMS} and \Rpackage{CAMERA} processing and statistical
%analysis and \Rpackage{XCMS} and \Rpackage{CAMERA} scripts.
sd02\_deconvoluted comprises 360 idMS/MS 
deconvoluted spectra with fragment ions (m/z, chromatographic retention time, relative
intensity in \%) and a column with unique identifiers for MS/MS features (here, 
the corresponding principal component group with the 
precursor ion). The data set is derived from the study of \citet{Li2015}. 
<<eval=TRUE,echo=c(1:2)>>=
## load data from Li et al., 2015
data("sd02_deconvoluted", package = "MetCirc")

## load binnedMSP
data("sd01_outputXCMS", package = "MetCirc")
data("binnedMSP", package = "MetCirc")
## load similarityMat
data("similarityMat", package = "MetCirc")
@

The second data set comes from the data-independent MS/MS 
collection of different floral organs from tobacco plants. Using our pipeline, 
this data set will be used to visualise shared metabolites between tissues as 
well as structural relationships among within- and between-organ MS/MS spectra.
MS/MS data are merged across floral organs in one unique data file 
\Robject{idMSMStissueproject.Rdata} as \Robject{tissue}. Information on the 
organ-localisation of each MS/MS spectrum is stored in  
\Robject{compartmentTissue}. 

<<eval=TRUE>>=
## load idMSMStissueproject
data("idMSMStissueproject", package = "MetCirc")
@

The third data set comes from the GNPS data base (downloaded at February 11, 2017 from: \\
\href{http://prime.psc.riken.jp/Metabolomics\_Software/MS-DIAL/MSMS-GNPS-Curated-Neg.msp}{http://prime.psc.riken.jp/Metabolomics\_Software/MS-DIAL/MSMS-GNPS-Curated-Neg.msp}). 
It contains 22 MS/MS features (a truncated file of the original one) and
is formatted in the .MSP file format, a typical format for 
MS/MS libraries. The MS/MS spectra are (normally) separated by blank lines
and give information on the metabolite (its name, precursor m/z value, 
retention time, class, adduct ion) and contain additional information. 
<<eval=TRUE,echo=c(1:2)>>=
## load data from GNPS
data("convertMSP2MSP", package = "MetCirc")
@

\section{Prepare data for mass spectral similarity calculations}

The \Robject{MSP}-class in \Rpackage{MetCirc} mimicks the typical MS spectral library file in 
.MSP format in ASCII text format used by mass spectral 
libraries (\href{http://www.nist.gov/srd/upload/NIST1a11Ver2-0Man.pdf}{http://www.nist.gov/srd/upload/NIST1a11Ver2-0Man.pdf}). 
The functions \Rfunction{convert2MSP} and \Rfunction{convertMSP2MSP} create an entry for each MS/MS feature and 
their corresponding spectra including fragment ions and their intensities. Each entry of the
\Robject{MSP}-object has the following accessors: retention time, m/z values, 
metabolite name and class, adduct ion name and further information. The 
\Robject{MSP}-object contains information on the number of peaks
and all fragment ions together with their 
relative intensity in \%. The retention time calculated by the function 
\Rfunction{convert2MSP} is the average value of the retention time values 
of all fragment ions belonging to the specific precursor or the retention 
time value that is stored in the column "id". The 
data frame containing information on the number of peaks, fragments
and their intensities can be accessed by \Robject{peaks(MSP-object)}.

\subsection{Preparing the sd02\_deconvoluted data set for analysis}
Here, we convert the examplatory data from \citet{Li2015} into an \Robject{MSP}-object that
is later used as the input for mass spectral similarity calculations. 
The \Rpackage{MetCirc} workflow requires a data frame
in the form of sd02\_deconvoluted to run the pipeline. Required columns in such
data frames are "mz" (containing the m/z values of fragments), 
"intensity" (intensity values in \% for the respective fragments) and 
"id". The column "id" has to contain information about the precursor ion and 
should be a unique descriptor for the MS/MS features. For instance, this column
may be the derived from the output of the \Rpackage{xcms}/\Rpackage{CAMERA} 
processing creating unique identifiers for each metabolite decoded in the column
"pcgroup". A pcgroup is defined as a peak correlation group obtained by this
workflow. It corresponds to a MS or MS/MS spectrum deconvoluted by \Rpackage{CAMERA}
and contains information about the precursor identity and its isotope cluster. 
The user needs to combine the pcgroup value with the m/z value of the precursor
ion of each parent molecule. The column "id" may additionally contain information 
about the precursor retention time. \newline

Create \Robject{MSP}-object from the data of \citep{Li2015}:
<<eval=c(1:2)>>=
## identify precursor mz
finalMSPLi2015 <- convert2MSP(sd02_deconvoluted, splitPattern = " _ ", 
                                                rt = TRUE, splitIndMZ = 2)
@
The \Robject{splitPattern} argument takes a character string specifying how elements
in the column "id" are separated, \Robject{splitIndMZ} and 
\Robject{splitIndRT} (here not used) take numerical values specifying the position of the 
m/z and retention time value of the precursor ion in the column "mz". Please
note that specification of splitIndRT is optional and the retention time 
values will only be retrieved when rt is set to \Robject{TRUE}. 
Furthermore, \Rfunction{convert2MSP} can take further arguments to retrieve annotation 
data (metabolite name and classes, adduct ion names, further information; 
see \Robject{?convert2MSP} for further information). \newline

\subsection{Preparing the floral organ data set for analysis}

We would like to restrict the proof-of-function analysis to four tissues 
(sepal, SPL; limb, LIM; anther, ANT; 
style, STY). We will truncate \Robject{tissue} in order that it contains only these 
instances belonging to these types of tissue. In a next step, we will 
create a \Rpackage{MSP}-object, \Robject{finalMSP}, comprising the features found 
in the tissues SPL, LIM, ANT and STY. 
<<eval=c(1:18)>>=
## create vectors with precursor names present in tissue
tissueSPL <- compartmentTissue[compartmentTissue[,"SPL"] == TRUE, 1]
tissueLIM <- compartmentTissue[compartmentTissue[,"LIM"] == TRUE, 1]
tissueANT <- compartmentTissue[compartmentTissue[,"ANT"] == TRUE, 1]
tissueSTY <- compartmentTissue[compartmentTissue[,"STY"] == TRUE, 1]

## truncate tissue
tissueSPL <- tissue[tissue[,4] %in% tissueSPL,] 
tissueLIM <- tissue[tissue[,4] %in% tissueLIM,]
tissueANT <- tissue[tissue[,4] %in% tissueANT,]
tissueSTY <- tissue[tissue[,4] %in% tissueSTY,]

## create msp and combine msp objects of different tissues
## here we set splitIndRT = 2 since column "id" is formatted in the 
## following way: m/z value_retention time_pcgroup
finalMSPtissue <- convert2MSP(tissueSPL, rt = TRUE, splitIndRT = 2)
finalMSPtissue <- combine(finalMSPtissue, convert2MSP(tissueLIM, 
                                                rt = TRUE, splitIndRT = 2))
finalMSPtissue <- combine(finalMSPtissue, convert2MSP(tissueANT, 
                                                rt = TRUE, splitIndRT = 2))
finalMSPtissue <- combine(finalMSPtissue, convert2MSP(tissueSTY, 
                                                rt = TRUE, splitIndRT = 2))
@

For the \Rfunction{binning} function used later, we need to pass a vector
containing the groups (compartments, times, species, etc.) of the metabolites.
Here, we will derive a vector, 
\Robject{compartment}, which gives the compartment for each entry of 
\Robject{finalMSPtissue}. \Robject{compartment} refers here to floral organs, but 
could be species names, experimental conditions, etc., too; i.e. the object can
be any biological identifier relevant to the comparative experiment conducted. 
<<eval=TRUE>>=
## create vector with compartments
compSPL <- rep("SPL", length(convert2MSP(tissueSPL)))
compLIM <- rep("LIM", length(convert2MSP(tissueLIM)))
compANT <- rep("ANT", length(convert2MSP(tissueANT)))
compSTY <- rep("STY", length(convert2MSP(tissueSTY)))

compartment <- c(compSPL, compLIM, compANT, compSTY)
@


\subsection{Preparing the GNPS data set for analysis}
Alternatively as mentioned above, an \Robject{MSP}-object can also created from .MSP objects, 
that are typical data formats for storing MS/MS libraries. 
Required properties of such a data frame are the name of the metabolite
(row entry "NAME:"), the m/z value of the precursor ion ("PRECURSORMZ" or 
"EXACTMASS:"), the number of peaks of the feature 
("Num Peaks:") and information on 
fragments and peak areas (see \Robject{?convertMSP2MSP} for further information
and retrieve \Robject{data("convertMSP2MSP", package = "MetCirc")} for a typical
msp data frame). \newline

Create \Robject{MSP}-object from the GNPS .MSP file:
<<eval=TRUE>>=
finalMSPGNSP <- convertMSP2MSP(msp2msp)
@


\section{Binning and calculation of similarity matrix}

\subsection{Workflow for \Robject{tissue} data set using fragment ions}

\paragraph{Binning.} Due to slight differences in m/z values over measurements, 
fragments might have m/z values which differ from other 
fragments even though they are in theory identical. \Rfunction{binning} 
will bin together fragment ions which are similar (set by the parameter
\code{tol} for tolerance). In the following this will allow for comparison
between m/z values. The functions \Rfunction{binning} bins fragments together 
based on minimal distance to bins which were calculated either by the mean or 
the median of fragments which were put in intervals according to the 
\code{tol} parameter. \newline

\Rfunction{binning} expects a vector (\Robject{group}) which comprises 
membership of the entries in the \Robject{msp} object, to a compartment, 
species, individual, etc. If \Robject{group} is not specified 
\Rfunction{binning} will create an internal dummy variable group ("a" with 
the length of the \Robject{msp} object). We use here the \Robject{tissue} data 
set.

<<eval=FALSE>>=
## create data frame with binned fragments
binnedMSP <- binning(msp = finalMSPtissue, tol = 0.01, 
                     group = compartment, method = "median")
@

\paragraph{Calculation of the similarity matrix.} The normalised dot product 
(NDP) calculates the similarity coefficient between two MS/MS features. 
For a considered MS/MS pair, peak intensities of shared m/z values for 
precursor/fragment ions and neutral losses are employed as weights
$W_{S1, i}$ and $W_{S1, i}$ within the following formula: 

\begin{equation*}
    NDP = \frac{\sum(W_{S1, i} \cdot W_{S2, i}) ^ 2}{ \sum(W_{S1, i} ^ 2) * \sum(W_{S2, i} ^ 2) },
\end{equation*}

with S1 and S2 the spectra 1 and 2, respectively, of the i$th$ of j common peaks
differing by the tolerance parameter specified in \texttt{binning}. 
Weights are calculated according to $W = [ peak~intensity] ^{m} \cdot [m/z]^n$,
with m = 0.5 and n = 2 as default values as suggested by MassBank.
For further information see \citet{Li2015}. \newline

\Rfunction{createSimilarityMatrix} calculates all pair-wise NDP coefficients 
between MS/MS features. 
\Rfunction{createSimilarityMatrix} needs a matrix as an argument which 
has the fragment ions as rows (m/z / retention time) and all fragment ions 
as column names. Entries of such a matrix are intensities for a specific 
fragment ion (intensity will be zero if fragment ion does not occur for the 
respective precursor) for a given MS/MS feature. The function 
\Rfunction{binning} will return a matrix with such properties.

<<eval=TRUE>>=
## similarity Matrix 
similarityMat <- createSimilarityMatrix(binnedMSP)
@

\Rfunction{createSimilarityMatrix} returns a square matrix with 
precursor m/z / retention time as column and row names. The entries of 
the returned matrix are NDP scores ranging between 0 and 1 that are  
the pair-wise similarities between the MS/MS features. 

\paragraph{Clustering/visualisation.} At this stage, we would like to visualise 
the pair-wise similarities of MS/MS features after clustering them.
Many functions are available to cluster features such as \Rfunction{hclust}
from \Rpackage{stats}, \Rfunction{Mclust} from \Rpackage{mclust} or 
\Rfunction{hcluster} from \Rpackage{amap}. We would like to use the latter 
to cluster similar features. To cluster features and visualise the result (see 
figure \ref{fig:cluster}) we enter:
<<cluster,eval=TRUE,fig.show='hide'>>=
## load package amap
hClustMSP <- hcluster(similarityMat, method = "spearman")
## visualise clusters
plot(hClustMSP, labels = FALSE, xlab="", sub="")
@

\begin{figure}[h!]
    \center
    \includegraphics[scale=0.6]{./figure/cluster-1}
    \caption{Cluster dendrogramm for similarity matrix based on fragment 
    ion NDP calculation} \label{fig:cluster}
\end{figure}

To promote readibility we will not show labels. These can be printed to the 
\R~console by \code{colnames(similarityMat)[hClustMSP\$order]}. \newline

\paragraph{Extraction of highly-related features using clustering.}
Within the \R~session the similarity matrix can be truncated by using the 
above-mentioned functions to retrieve a similarity matrix that contains 
highly-related MS/MS features. For instance, this might be needed when 
we want to analyse modules of high similarity, representing e.g. a certain 
metabolite class. By way of example, we extract in the following all features
from module 1 when defining three modules in total and define a new 
similarity matrix of highly-related features. This kind of matrix can be 
used in later analysis steps, e.g. in the analysis with \Rfunction{shinyCircos}.

<<truncateGroup1,eval=TRUE,echo=TRUE>>=
## define three clusters
cutTreeMSP <- cutree(hClustMSP, k = 3)
## extract feature identifiers that belong to module 1
module1 <- names(cutTreeMSP)[as.vector(cutTreeMSP) == "1"] 
## create a new similarity matrix that contains only highly related features
similarityMat_module1 <- similarityMat[module1, module1]
@

\subsection{Workflow for \Robject{tissue} data set using neutral losses}
Another way to compare the similarity of metabolites is based on neutral losses
(cf. table \ref{tab:neutrallosses} in the appendix for a selection of common neutral losses):
common neutral losses are shared among structurally-related metabolites. 
\Rpackage{MetCirc} contains functionality to 
calculate neutral losses from \Robject{MSP}-objects. 
To convert a \Robject{MSP}-object with fragments into a \Robject{MSP}-object  
with neutral losses enter:

<<eval=TRUE>>=
nlMSP <- msp2FunctionalLossesMSP(finalMSPtissue)
@

\paragraph{Binning and calculation of the similarity matrix.} Analogously to 
the \Rpackage{MSP}-object with fragments we can bin the \Robject{nlMSP} 
\Robject{MSP}-object with neutral losses and create a similarity matrix:
<<eval=FALSE>>=
## bin msp file with functional losses, create table with same fragments 
## (binning)
nlBinnedMSP <- binning(nlMSP, tol = 0.01, group = compartment, method = "median")
## similarity Matrix
nlSimilarityMat <- createSimilarityMatrix(nlBinnedMSP)
@
The NDP calculation uses here neutral losses corresponding to mass differences
between the precursor and fragment ions within a spectrum. The intensities 
are the respective intensities of the fragments. 

\paragraph{Clustering/visualisation.} Analogously to the \Robject{MSP}-object 
with fragment ions, we are able to 
cluster the similarity matrix based on neutral losses. 
<<eval=FALSE>>=
## Clustering
nlHClustMSP <- hcluster(nlSimilarityMat, method = "spearman")
@

To visualise the clustering enter the following line of code 
(labels will not be displayed due to readibility): 

<<eval=FALSE>>=
plot(nlHClustMSP, labels = FALSE)

## labels can be reproduced by entering in the console
colnames(nlSimilarityMat)[nlHClustMSP$order]
@


\section{Visualisation using the \Rpackage{shiny}/\Rpackage{circlize} framework}

\Rpackage{MetCirc} comprises functionality to visualise metabolomics
data, exploring it interactively and annotate unknown features based on 
similarity to other (known) features. One of the key features of the implemented
interactive framework is, that groups can be compared. A group 
specifies the affiliation of the sample: it can be 
any biological identifier relevant to the comparitive experiment conducted,
e.g. it can be a specific tissue, different
times, different species, etc. The visualisation tools implemented in 
\Rpackage{MetCirc} allow then to display similarity between 
precursor ions between and/or within groups. \newline

\Rfunction{shinyCircos} uses the function \Rfunction{createLinkMatrix} which 
selects these precursor ions that have a normalised dot 
product within the range defined by \Robject{threshold\_low} and 
\Robject{threshold\_high} to a precursor ion. 
Internally, in \Rfunction{shinyCircos}, \Rfunction{createLinkMatrix} will be 
called to produce link matrices based on the given thresholds. 
<<eval=TRUE>>=
linkMat <- createLinkMatrix(similarityMatrix = similarityMat, 
                            threshold_low=0.5, threshold_high=1)
@

As we have calculated similarity coefficients between precursors, we would
like to visualise these connections interactively and explore the data. 
The \Rpackage{MetCirc} package implements \Rfunction{shinyCircos} 
that allows for such kind of exploration. It is based on the \Rpackage{shiny}
and on the \Rpackage{circlize} \citep{Gu2014} framework. Inside of \Rfunction{shinyCircos} 
information of precursor ions are displayed by (single-) clicking over precursors. 
Precursors can also be permanently selected by double-clicking on them. The similarity
coefficients can be thresholded by changing the slider input. Also, on the 
sidebar panel, the type of link to be displayed can be selected: 
should only links between groups be displayed, should only links within groups 
be displayed or should all links be displayed? Ordering inside of groups 
can be changed by selecting the respective option in the sidebar panel. 
Momentarily, there are options to reorder features based on clustering, 
the m/z or the retention time of the precursor ion. In the "Appearance" tab,
the size of the plot can be changed, as well as the precision of the 
displayed values for the m/z and retention time values. Please note, 
that the precision will only be changed in the text output (not in the 
graphical output). Also, the user can decide if the legend is displayed or not.

On exiting the shiny application
via the exit button in the sidebar panel, selected precursors will
be returned which are allocated here to \Robject{selectedFeatures}. 
\Robject{selectedFeatures} is a vector of the precursor names. \newline

To start the shiny app, run
<<eval=FALSE>>=
selectedFeatures <- shinyCircos(similarityMat)
@

To show and modify annotations enter
<<eval=FALSE>>=
selectedFeatures <- shinyCircos(similarityMat, msp = finalMSPtissue)
@
to the console. This will load information stored in the \Robject{MSP}-object
to the \Robject{shinyCircos} interface. Information (metabolite names and
class, adduct ion name and further information) will be printed to the 
interface when (single-)clicking on MS/MS features. Note, that on the 
sidebar on the right side text fields will appear, that allow for changing 
the annotation of the selected feature. Click "update annotation" to save the 
changes to the \Robject{MSP}-object. On exiting \Robject{shinyCircos} via
the exit button, selected precursors and the (updated) \Robject{MSP}-object will
be returned to the console. In the example above, enter 
\Robject{selectedFeatures\$msp} to retrieve the \Robject{MSP}-object. \newline

\Rpackage{MetCirc} allows also to create such figures outside of an
interactive context, which might be helpful to create figures and export them 
e.g. in .pdf or .jpeg format. \Rfunction{shinyCircos} does currently not 
support to export figures as they can be easily rebuilt outside of 
\Rfunction{shinyCircos}; building figures outside of the interactive context
also promotes reproducibility of such figures. \newline 

To rebuild the figure in a non-interactive environment, run 
<<circos,eval=TRUE,results='hide',message=FALSE,fig.show='hide'>>=
## order similarity matrix according to retention time
simM <- createOrderedSimMat(similarityMat, order = "retentionTime")
groupname <- rownames(simM)
## create link matrix
linkMat <- createLinkMatrix(similarityMatrix = simM, 
                    threshold_low = 0.99, threshold_high = 1)
## cut link matrix (here: only display links between groups)
linkMat_cut <- cutLinkMatrix(linkMat, type = "inter")

## set circlize paramters
circos.par(gap.degree = 0, cell.padding = c(0, 0, 0, 0), 
            track.margin = c(0, 0))

## here set indSelected arbitrarily
indSelected <- 1
selectedFeatures <- groupname[1]

## actual plotting
plotCircos(groupname, linkMat_cut, initialize = TRUE, featureNames = TRUE, 
    cexFeatureNames = 0.2, groupSector = TRUE, groupName = FALSE, 
    links = FALSE, highlight = TRUE)

highlight(groupname = groupname, ind = indSelected, LinkMatrix = 
            linkMat_cut)

## plot without highlighting
plotCircos(groupname, linkMat_cut, initialize = TRUE, featureNames = TRUE, 
    cexFeatureNames = 0.2, groupSector = TRUE, groupName = FALSE, links = TRUE, 
    highlight = FALSE)
@

\begin{figure}[h!]
    \center
    \includegraphics{./figure/circos-1}
    \caption{Examplary plot where an arbitrary feature is highlighted. Upon
        highlighting all links will be plotted in grey (expect links to and 
        from highlighted features). The intensity
        of the background colour of features will be reduced as well. Features
        belonging to a group (species, individual, organ, different time) will 
        be indicated by the same background colour.}
\end{figure}

\newpage
\printbibliography

\newpage 
\section*{Appendix}

\subsection*{Session information}

All software and respective versions to build this vignette are listed here:
<<session,eval=TRUE,echo=FALSE>>=
sessionInfo()
@

\newpage
\subsection*{Neutral losses}
\begin{longtable}{l | l } 
    \caption{The table gives examplatory fractionation of precursors 
    into neutral losses (given their m/z and the corresponding atoms):} 
    \label{tab:neutrallosses} \\
    CH$_2$ & 14.0157 \\
    CH$_4$ & 16.0313 \\
    NH$_3$ &  17.0265 \\
    H$_2$O & 18.0106 \\
    K$^+$ to NH$_4$$^+$" & 20.9293 \\
    Na$^+$ to H$^+$ & 21.9819 \\
    C$_2$H$_2$ & 26.0157 \\
    CO & 27.9949 \\
    C$_2$H$_4$ & 28.0313 \\
    CH$_3$N & 29.0266 \\
    CH$_2$O & 30.0106 \\
    CH$_5$N & 31.0422 \\
    S & 31.9721 \\
    H$_2$S & 33.9877 \\
    K$^+$to H$^+$ &  37.9559 \\
    C$_2$H$_2$O & 42.0106 \\
    C$_3$H$_6$ & 42.0470 \\
    CHNO & 43.0058 \\
    CO$_2$ & 43.9898 \\
    CH$_2$ O$_2$ & 46.0055 \\
    C$_4$H$_8$ & 56.0626 \\
    C$_3$H$_9$N & 59.0735 \\
    C$_2$H$_4$ O$_2$ & 60.0211 \\
    CH$_4$N$_2$O & 60.0324 \\
    SO$_2$ & 63.9619 \\
    C$_5$H$_8$ & 68.0626 \\
    C$_3$H$_6$ O$_2$ & 74.0368 \\
    C$_6$H$_6$ & 78.0470 \\
    SO$_3$ & 79.9568 \\
    C$_3$H$_2$O$_3$ & 86.0004 \\
    C$_4$H$_8$O$_2$ & 88.0517 \\
    C$_4$H$_{12}$N$_2$ & 88.1000 \\
    H$_2$(SO)$_4$ & 97.9674 \\
    H$_3$(PO)$_4$ & 97.9769 \\
    C$_5$H$_{10}$O$_2$ & 102.0618 \\
    C$_3$H$_4$O$_4$ & 104.0110 \\
    C$_6$H$_{12}$O$_2$ & 116.0861 \\
    C$_2$H$_5$O$_4$P & 123.9926 \\
    C$_5$H$_8$O$_4$ & 132.0423 \\
    C$_7$H$_{19}$N$_3$ & 145.1579 \\
    C$_6$H$_{10}$O$_4$ & 146.0579 \\
    C$_6$H$_{10}$O$_5$ & 162.0528 \\
    C$_6$H$_{12}$O$_5$ & 164.0685 \\ 
    C$_6$H$_8$O$_6$ & 176.0321 \\
    C$_6$H$_{12}$O$_6$ & 180.0634 \\
    C$_6$H$_{10}$O$_7$ & 194.0427 \\
    C$_8$H$_{12}$O$_6$ & 204.0655 \\
    C$_{11}$H$_{10}$O$_4$ & 206.0579 \\
    C$_{10}$H$_{15}$N$_3$ O$_6$ S & 305.0682 \\
    C$_{10}$H$_{17}$N$_3$ O$_6$ S & 307.0838 \\
    C$_{12}$H$_{20}$O$_{10}$ & 324.1057 \\
    C$_{12}$H$_{22}$O$_{11}$ & 342.1162 \\
    \hline
\end{longtable}


\end{document}