%\VignetteIndexEntry{NFP}
%\VignetteKeywords{NFP}
%\VignettePackage{NFP}
%\VignetteEngine{knitr::knitr}

\documentclass{article}
\usepackage[utf8]{inputenc}

<<style, eval=TRUE, echo=FALSE, results='asis'>>=
BiocStyle::latex()
@

<<setup, include=FALSE, cache=FALSE, eval = TRUE, echo = FALSE>>=
library(knitr)
opts_chunk$set(
               fig.align='center', fig.show='asis',
               eval = TRUE,
               tidy = FALSE,
               message = FALSE,
               warning = FALSE)
options(replace.assign=TRUE,width=80)
@

\title{NFP:Network fingerprint - a knowledge-based characterization of biomedical networks}
\author{Yang Cao, Fei Li, Haochen He}

\begin{document}
% \SweaveOpts{concordance=TRUE}
%\SweaveOpts{concordance=TRUE}

\maketitle

\tableofcontents

\section{Introduction}

Recent network fingerprint method based on GO knowledge and propagation
clustering mentioned in \cite{NFP} provide a novel representation
of network differentiation known as biological spectra, or Network Fingerprint.
This method was used to describe the relationship between multiple disease
networks and its related pathways, and to visually compare and parse different
diseases by generating a fingerprint overlay. Thus, we achieve the function of
complex network comparison based on network fingerprint on the open scientific
computing platform \R{R}, and present {\it NFP}, an \Bioconductor{Bioconductor} package for fingerprint-based network analyzing and comparison of systems. Driven by the
research needs of customers, {\it NFP} provides a unified interface to three
similarity clustering algorithms. In addition, {\it NFP} can also provide multiscale
statistical analysis and visualization, access to the specific attributes of
different disease networks.

This manual is a brief introduction to structure, functions and usage of
{\it NFP} package. The NFP package provides a set of functions to support
knowledge-based network fingerprint (NFP) framework. A biomedical network is
characterized as a spectrum-like vector called “network fingerprint”, which
contains similarities to basic reference networks. This framework provides a more intuitive way to decipher molecular networks, especially for large-scale network
comparisons and clustering analyses.

The three main features of {\it NFP}:

 \begin{itemize}
    \item Basic reference networks generation.
    \item Network comparison, which encompasses network merging, annotation and
    similarity scoring.
    \item Network standardization.
  \end{itemize}

\subsection{Installation}

{\it NFP} requires these packages: \CRANpkg{magrittr}, \CRANpkg{igraph},
\CRANpkg{plyr}, \CRANpkg{ggplot2}, \CRANpkg{apcluster}, \CRANpkg{dplyr},
\CRANpkg{stringr}, \Biocpkg{graph} and \Biocpkg{KEGGgraph}. To install **NFP**, please note especially two depencies of \CRANpkg{NFP}, \Biocpkg{graph} and \Biocpkg{KEGGgraph} are only available from [Bioconductor](www.bioconductor.org). Appanrantly, function `install.packages` can not insall Biocondutor packages. There is a function `biocLite`, a wrapper around `install.packages`
provided by Bioconductor, can be used to install both CRAN and Bioconductor
packages simply. More details on `biocLite` is available from
https://www.bioconductor.org/install/. Thus, users can install NFP
install the latest released version using `biocLite` directly:

<<install-pkg, eval=FALSE>>==
## install release version of NFP
source("http://bioconductor.org/biocLite.R")
biocLite("NFP")
@

or install the  Bioconductor dependencies package first:

<<install-pkg2, eval=FALSE>>==
## install release version of NFP
source("http://bioconductor.org/biocLite.R")
biocLite(c("graph","KEGGgraph"))
install.packages("NFP")
@

It also allows users to install the latest development version from github, which requires  **devtools** package has been installed on your system (or can be installed using `install.packages("devtools")`). Note that devtools sometimes needs some extra non-R software on your system -- more specifically, an Rtools download for Windows or Xcode for OS X. There's more information about devtools
[here](https://github.com/hadley/devtools).

<<install-pkg-github, eval=FALSE>>==
## install NFP from github, require biocondutor dependencies package pre-installed 
if (!require(devtools))
  install.packages("devtools")
devtools::install_github("yiluheihei/NFP")
@

After installation, the {\it NFP} is ready to load into the current workspace
by the following codes to the current workspace by typing or pasting the
following codes:

<<load-pkg,eval=TRUE, include=FALSE>>==
library(NFP)
@


Moreover, gene similarity data used in our {\it NFP} package is stored in a external data repository {\it NFPdata} \url{https://github.com/yiluheihei/datarepo} for the large size (about 16 MB). More details on how to construct External Data Repositories using the Additional\_repositories field see The Coatless Professor blog post \url{http://thecoatlessprofessor.com/programming/r-data-packages-in-external-data-repositories-using-the-additional\_repositories-field/}. Thus, users must install the {\it NFPdata} before the networkfinger print analyis as following code.

<<data_package,eval=FALSE>>==
if (!require("NFPdata")) {
    install_data_package()
}
@

\section{Analysis Pipeline: from Basic Reference Network Generation to Network
Networkfingerprint Visualization}

We will demonstrate go through an analysis pipeline to illustrate some of the main functions in {\it NFP}. This pipeline consists of several steps:

\begin{enumerate}
\item  Basic Reference Network Generation: prepare the well-known biomedical
netowks as the NFP framework reference networks. Several pathway databases have
been developed for biological network research, e.g. KEGG, Reactome (\url{www.reactome.org}). All of this pathway databases is well-stuied and can be used as the basic reference networks of NFP.

\item Network fingerprint calculation: The similarity between two biomedical
networks is calculated based on the following intition: grouping the nodes in
the merged network into strongly inter-connected communities with high functional similarity score between intra-community nodes in different networks The functional similarity was measured based on GO \cite{GO}. And we employed affinity propagation (AP)
\cite{APcluster} clustering algorithm to detect the aligned functional
modules between the two networks to be compared.

\item Network fingerprint Visualization: Show the network fingerprint along all
the reference networks. We could observe the differences of different biological
networks' fingerprint intuitively from visualization.

\end{enumerate}

\subsection{Generating well-studied basic reference networks}

The basic idea of calculating the network fingerprint is to have the biomedical
networks map to well-studied basic networks. KEGG PATHWAY is a collection of
manually drawn pathway maps representing our knowledge on the molecular
interaction and reaction networks. Since its first introduction in 1995, KEGG
PATHWAY has been widely used as a reference knowledge base for understanding
biological pathways and functions of cellular processes. The knowledge from KEGG
has proven of great value by numerous work in a wide range of fields
\cite{KEGG}. So by default, we take KEGG pathways as basic reference
networks in {\it NFP} by default.

Function \Rfunction{load\_KEGG\_refnet} can be used to retrieve the KEGG pathway maps
with KEGG API http://www.kegg.jp/kegg/rest/keggapi.html. In KEGG pathways, only the pathways of the map are manual drawing, and to different organisms, the map reference helps the automatic generation of organism-specific pathway for each organism. The {\tt organism} (e.g. \Rcode{organsim ="hsa"}) parameter indicate the organism name of KEGG pathway maps.

<<load_kegg_refnet, eval=TRUE, echo=TRUE>>==
## donot run, retrive pathway maps from KEGG database may take several minutes,
## we have pre-stored this data in our package
## kegg_refnet <- load_KEGG_refnet(organism = 'hsa')
data(kegg_refnet)

# show the kegg reference networks
show(kegg_refnet)
@

We defined a new S4 class \textit{NFPrefnet} to store the \emph{NFP} reference
networks. \emph{NFP} also provides five kinds of methods for this S4 class:

1. \Rfunction{net}: Exact the basic reference networks of \Rclass{NFPRefnet}.

2. \Rfunction{group}: Obtain the group information, group names, number and the
size of each group,e.g. KEGG pathway database contains seven group pathway maps.

3.\Rfunction{subnet}: Extract or replace parts of the {\it NFP} basic reference
networks.

4.\Rfunction{show}: Display of  \Rclass{NFPRefnet}.

5.\Rfunction{name}: Extract the names of reference networks.

<<keggrefnet-methods,echo=TRUE,eval=TRUE>>=
## group information of kegg reference networks
refnet_group <- group(kegg_refnet)
show(refnet_group)

## select goup 1 and 2, and subset this two groups
selected_group <- refnet_group$name[c(1,2)]
NFPnet <- subnet(kegg_refnet,selected_group)
NFPnet
@

Detailed instructions for this five methods refer to package function help.

Obviously users can also customize a NFPRefnet as a reference for computing network fingerprint. Users can refer to the documents of \Rclass{NFPRefnet}  about the
composition details of this class. \Biocpkg{graphite} \cite{graphite} allow users
to build \Rclass{graphNEL} object from several pathway databases.

<<reactome-map>>==
## Reactome human pathway maps
require(graphite)
human_pathway <- pathways("hsapiens", "kegg")
## just choose first two pathway maps for testing
p <- human_pathway[1:2]
show(p)
g <- lapply(p, pathwayGraph)
show(g)
@

Then users can create their own customized \Rclass{NFPRefnet} object as following:

<<customize-refnet,echo=TRUE, eval=TRUE>>==
## here, just take the above two reactome pathway maps as NFP basic reference
## networks as example
g_names <- names(human_pathway)[1:2]
## only one group and two reference networks
customized_refnet <- new("NFPRefnet",network = list(g), name = list(g_names),
  group = "test group", organism ='hsa')

## methods of NFPRefnet
show(customized_refnet)
group(customized_refnet)
subnet(customized_refnet, 'test group', 1)
@

\subsection{Network fingerprint calculation}

NFP algorithm consists of three steps: merging network, nodes clustering and
similarity scoring.

Network merging. The two networks to be compared are first merged into one. Given
two networks {\it G1} and {\it G2}, the merged network {\it Gm} is constructed by connecting each node between the { \it G1} and {\it G2} network. Two nodes corresponding to the same protein in the merged network are replaced by a single node that inherited all the interactions from the two individual nodes in the subsequent process.

Clustering in merged network. Grouping the nodes in the merged network into
strongly inter-connected communities with high functional similarity score between
intra-community nodes in different networks. We employed affinity propagation (AP) clustering algorithm to detect the aligned functional modules between the two
networks to be compared. The nodes are grouped on the cluster based on nearest
neighbor analysis.

Similarity scoring. The calculation of similarity score is processed in two steps:
First, local similarity for each cluster and network similarity among cluster.
Second, standardization: the original similarity score depends on the topological properties of query network to some extent. There is implicit bias of network fingerprint, because the outliers could be greatly distorted the relevant pattern presented in the network fingerprint. In order to eliminate the possible topological weight differences, the similarity calculation process of each node are standardized processing and the final network fingerprint facing to users is totally standardized. The standardization process is based on the random distribution of similarity scores. To the number of nodes, the number of edges and node degree, these three topological properties of random network for standardized estimate are consistent with the original network.

To not affect the results of standardization and improve the efficiency of fingerprint calculation, we set limit on the permutation time (the default is 100) of background network randomization in the standardization process. Users can also adjust randomization time of background network according to their own demands for the precision of network fingerprint.

{\it NFP} provides the \Rfunction{calc\_sim\_score} function for calculating the
similarity score between two networks. As the similarity score is subjected to the size of the network, we use the maslov’s method \cite{Standardization} to randomize a network while preserving the degree distribution. The{\tt nperm} parameter is added to
\Rfunction{calc\_sim\_score} refers to the permutation times (the default is 100) of
random network while calculating the similarity score mentioned above. We define
a S4 class \Rclass{NFP} in our package to store the calculation results of network
fingerprints.

Simply, we choose the two pathway maps \Rcode{g} as a query network, and a
subset networks of \Rcode{kegg\_refnet} as the reference networks. Then the NFP
can be calculated as following:

<<calc-NFP, eval=FALSE, echo=TRUE>>==
## set g as the query network
query_net <- g
## a subset of kegg_refnet, select the head five networks of group 1, 2
group_names <- group(kegg_refnet)$name
sample_NFPRefnet <- subnet(kegg_refnet, group_names[1:2],list(1:5,1:5))

## In order to save calculating time, we take nperm = 10
NFP_score <- lapply(query_net, calc_sim_score,NFPnet = sample_NFPRefnet,
  nperm = 10)

## methods of NFP class
show(NFP_score[[1]])
randomized_score  <- perm_score(NFP_score[[1]])
cluster <- cluster_info(NFP_score[[1]])
@

\subsection{Network fingerprint visualization}

{\it NFP} provides the \Rfunction{plot\_NFP\_NFP} function to visualize the network fingerprint of a single query network.

<<plot-nfp,echo=TRUE,eval=FALSE,fig.cap='Plot a NFP object',dev='pdf',fig.show='hold',out.width='.8\\linewidth', out.height='.7\\linewidth'>>==
plot_NFP(NFP_score[[1]])
@

\begin{center} 
\includegraphics[width=0.7\paperwidth]{nfp_plot.png} 
\end{center}


\section*{Session Information}

The version number of R and packages loaded for generating the vignette were:

<<echo=FALSE>>=
sessionInfo()
@

\section*{Cleanup}

This is a cleanup step for the vignette on Windows; typically not
needed for users.

<<closeConnetions>>=
allCon <- showConnections()
socketCon <- as.integer(rownames(allCon)[allCon[, "class"] == "sockconn"])
sapply(socketCon, function(ii) close.connection(getConnection(ii)) )
@

\begin{thebibliography}{9}

\bibitem{KEGG}
  Kanehisa M, Araki M, Goto S, et al.
  KEGG for linking genomes to life and the environment[J].
  Nucleic acids research, 2008, 36(suppl 1): D480-D484.

\bibitem{APcluster}
  Frey B J, Dueck D.
  Clustering by passing messages between data points[J].
  science, 2007, 315(5814): 972-976.

\bibitem{NFP}
  Cui X, He H, He F, et al.
  Network fingerprint: a knowledge-based
  characterization of biomedical networks[J].
  Scientific reports, 2015, 5.

\bibitem{Standardization}
  Maslov S, Sneppen K.
  Specificity and stability in topology of protein networks[J].
  Science, 2002, 296(5569): 910-913.

\bibitem{GO}
  Ashburner M, Ball C A, Blake J A, et al.
  Gene Ontology: tool for the unification of biology[J].
  Nature genetics, 2000, 25(1): 25-29.

\bibitem{graphite}
  Sales G, Calura E, Cavalieri D, et al.
  graphite-a Bioconductor package to convert pathway topology to gene network[J].
  BMC bioinformatics, 2012, 13(1): 20.

\end{thebibliography}

\end{document}
