## ----fig1, echo=FALSE, fig.cap="Schematic representation of RedeR calls. Complex graphs with many attributes can be transferred from-and-to R using *addGraph()* and *getGraph()* functions.", out.width = '80%'----
knitr::include_graphics("fig1.png", dpi=300)

## ----label='Load packages', eval=TRUE, message=FALSE--------------------------
#--- Load required packages
library("RedeR")
library("igraph")

## ----label='Set the R-to-Java interface', eval=TRUE---------------------------
#--- Set the R-to-Java interface
rdp <- RedPort()

## ----label='Initialize the R-to-Java interface', eval=FALSE-------------------
#  #--- Initialize the R-to-Java interface
#  calld(rdp)

## ----fig2, echo=FALSE, fig.cap="RedeR's graphical user interface. The calld() function initializes the R-to-Java interface. RedeR >=2.0.0 will need the Java Runtime Environment (JRE) version 11 or higher (Java >=11). The package will also run on earlier Java versions (Java >=8), but with reduced functionality. In order to check the Java on your system, see the System Requirements section.", out.width = '70%'----
knitr::include_graphics("fig2.png", dpi=300)

## ----label='Add a graph', eval=TRUE-------------------------------------------
#--- Add a graph
g1 <- graph.lattice(c(3,3,3))
addGraph(rdp, g=g1, layout=layout_with_kk(g1))

## ----fig3, echo=FALSE, fig.cap="A toy example generated by the *addGraph()* function.", out.width = '60%'----
knitr::include_graphics("fig3.png")

## ----label='Get a graph', eval=FALSE------------------------------------------
#  #--- Get a graph
#  g2 <- getGraph(rdp)
#  summary(g2)
#  # IGRAPH f22cf52 UN-- 125 300 --
#  # + attr: zoom (g/n), name (v/c), coordX (v/n), coordY (v/n)

## ----label='Reset application (1)', eval=TRUE---------------------------------
#--- Reset the application:
resetd(rdp)

## ----label='Generate two scale-free graphs', eval=TRUE------------------------
#--- Generate two scale-free graphs
g1 <- sample_pa(7)
g2 <- sample_pa(5)

#--- Set names to graph vertices
V(g1)$name <- paste("m",1:7,sep="")
V(g2)$name <- paste("n",1:5,sep="")

#--- Nest graphs into containers
addGraph(rdp, g=g1, isNested=TRUE, gcoord=c(30,30), gscale=50)
addGraph(rdp, g=g2, isNested=TRUE, gcoord=c(70,70), gscale=50)

## ----fig4, echo=FALSE, fig.cap="Nested graphs in *RedeR* using the *addGraph()* function.", out.width = '70%'----
knitr::include_graphics("fig4.png")

## ----label='Get a subgraph', eval=FALSE---------------------------------------
#  #--- Select nodes within a container
#  selectNodes(rdp, nodes="N2")
#  
#  #--- Get selected nodes
#  getGraph(rdp, status="selected")
#  # IGRAPH 36b1f75 UN-- 5 4 --
#  # + attr: zoom (g/n), name (v/c), coordX (v/n), coordY (v/n)
#  # + edges from 36b1f75 (vertex names):
#  # [1] n1--n2 n1--n3 n1--n4 n4--n5

## ----label='Reset application (2)', eval=TRUE---------------------------------
#--- Reset the application:
resetd(rdp)

## ----label='Generate a larger scale-free graph', eval=TRUE--------------------
#--- Generate a larger scale-free graph
g1 <- sample_pa(300, directed=FALSE)

#--- Set names to igraph vertices
V(g1)$name <- paste0("V",1:vcount(g1))

#--- Check attributes in the 'g1' graph
summary(g1)

## ----label='Send the g1 graph to RedeR', eval=TRUE----------------------------
#--- Send the 'g1' graph to RedeR
addGraph(rdp, g=g1, gzoom=50)

## ----label='Run the interactive layout', eval=TRUE----------------------------
#--- Run RedeR's interactive layout
relax(rdp, p1=20, p2=150, p3=20, p4=100, p5=10)

## ----fig5, echo=FALSE, fig.cap="Graph layouts set by *RedeR*'s interactive force-directed algorithm. A) A scale-free graph generated by igraph's *sample_pa()* function. B,C) Examples of flat and nested networks available in the *RedeR* application.", out.width = '100%'----
knitr::include_graphics("fig5.png", dpi=600)

## ----label='Reset application (3)', eval=TRUE---------------------------------
#--- Reset the application:
resetd(rdp)

## ----label='Set new attributes', eval=TRUE------------------------------------
#--- Set a new graph attribute in 'g1'
g1$bgColor <- 'grey90'

#--- Set new node attributes in 'g1'
V(g1)$nodeColor <- "skyblue"
V(g1)$nodeSize <- 50

#--- Set new edge attributes in 'g1'
E(g1)$edgeColor <- "skyblue"
E(g1)$edgeWidth <- 10

## ----label='Check new attributes', eval=TRUE----------------------------------
#--- Check the new attributes in 'g1'
summary(g1)

## ----table1, eval=TRUE, echo=FALSE--------------------------------------------
attribs <- attributes(rdp)
attribs$GraphAttr$Usage <- gsub("$","\\$",attribs$GraphAttr$Usage, fixed=TRUE)
colnames(attribs$GraphAttr)[1] <- "RedeR attribute"
colnames(attribs$GraphAttr)[4] <- "Usage example"
knitr::kable(attribs$GraphAttr, format="html", valign = 't',linesep='', label="tab1", 
             table.attr = "style='width:100%;'",
             caption="**Graph attributes**. 
             Examples of how to set *RedeR*'s graph attributes using *igraph* shortcuts.")

## ----table2, eval=TRUE, echo=FALSE--------------------------------------------
attribs <- attributes(rdp)
attribs$VertexAttr$Usage <- gsub("$","\\$",attribs$VertexAttr$Usage, fixed=TRUE)
colnames(attribs$VertexAttr)[1] <- "RedeR attribute"
colnames(attribs$VertexAttr)[4] <- "Usage example"
knitr::kable(attribs$VertexAttr, format="html", valign = 't',linesep='', label="tab2", 
             table.attr = "style='width:100%;'",
             caption="**Node attributes**. 
             Examples of how to set *RedeR*'s node attributes using *igraph* shortcuts.")

## ----table3, eval=TRUE, echo=FALSE--------------------------------------------
attribs <- attributes(rdp)
attribs$EdgeAttr$Usage <- gsub("$","\\$",attribs$EdgeAttr$Usage, fixed=TRUE)
colnames(attribs$EdgeAttr)[1] <- "RedeR attribute"
colnames(attribs$EdgeAttr)[4] <- "Usage example"
knitr::kable(attribs$EdgeAttr, format="html", valign = 't',linesep='', label="tab3", 
             table.attr = "style='width:100%;'",
             caption="**Edge attributes**. 
             Examples of how to set *RedeR*'s edge attributes using *igraph* shortcuts.")

## ----label='Make sure vertices are named', eval=TRUE--------------------------
#--- Make sure vertices are named!
V(g1)$name[1:5]

## ----label='Using att.addv and att.adde wrapper functions', eval=TRUE---------
#--- Add 'nodeFontSize' attribute from a fixed value
g1 <-  att.addv(g1, to = "nodeFontSize", value = 20)

#--- Same as above, but applied only to three nodes
g1 <- att.addv(g1, to = "nodeFontSize", value = 70, 
              filter = list("name" = V(g1)$name[1:3]))

#--- Add 'edgeType' attribute from a fixed value
g1 <-  att.adde(g1, to = "edgeType", value = "DOTTED")

## ----label='Check new attributes ', eval=TRUE---------------------------------
#--- Check the new attributes added to 'g1'
summary(g1)

## ----label='Load an igraph graph and a data frame', eval=TRUE-----------------
#--- Load an igraph graph and a data frame with compatible identifiers
data(ER.deg)
g2 <- ER.deg$ceg # an igraph graph with named nodes
df <- ER.deg$dat # a data frame

#--- Check attributes already available in the 'g2' graph
summary(g2)

#--- Check colnames in the 'df' data frame
colnames(df)

## ----label='Using att.mapv wrapper function', eval=TRUE-----------------------
#--- Map 'df' to 'g2' using the att.mapv() function
#Note: 'refcol = 0' indicates that 'df' rownames will be used as mapping IDs
g2 <- att.mapv(g=g2, dat=df, refcol=0)

#--- Check the new attributes mapped to 'g2'
summary(g2)

## ----label='Using att.setv and att.sete wrapper functions', eval=TRUE---------
# Set 'nodeAlias' from 'Symbol'
g2 <- att.setv(g2, from="Symbol", to="nodeAlias")

# Set 'nodeColor' from 'logFC.t3'
g2 <- att.setv(g2, from="logFC.t3", to="nodeColor", breaks=seq(-2,2,0.4), pal=2)

# Set 'nodeSize' from 'ERbdist'
g2 <- att.setv(g2, from="ERbdist", to="nodeSize", nquant=10, xlim=c(20,100,1))

# Set 'nodeFontSize' from 'ERbdist'
g2 <- att.setv(g2, from="ERbdist", to="nodeFontSize", nquant=10, xlim=c(1,50,1))

# Set 'edgeWidth' from 'weight'
g2 <- att.sete(g2, from="weight", to="edgeWidth", nquant=5, xlim=c(1,10,1))

#--- Check the new attributes set in 'g2'
summary(g2)

## ----label='Workflow 1: Load required packages', eval=TRUE, message=FALSE-----
#--- Load required packages
library("RedeR")
library("igraph")

## ----label='Workflow 1: Initialize the RedeR application', eval=TRUE----------
#--- If not running, initialize the ReadeR application
# rdp <- RedPort()
# calld(rdp)
resetd(rdp)

## ----label='Workflow 1: Load a dataframe and an interactome', eval=TRUE-------
#--- Load a dataframe and an interactome
data(ER.limma)
data(hs.inter)

## ----label='Workflow 1: Extract a subgraph and set attributes', eval=TRUE-----
#-- Extract a subgraph from the hs.inter graph
gt3  <- subg(g=hs.inter, dat=ER.limma[ER.limma$degenes.t3!=0,], refcol=1)
#-- Set attributes
gt3  <- att.setv(g=gt3, from="Symbol", to="nodeAlias")
gt3  <- att.setv(g=gt3, from="logFC.t3", to="nodeColor", breaks=seq(-2,2,0.4), pal=2)

## ----label='Workflow 1: Extract another subgraph and set attributes', eval=TRUE----
#--- Extract another subgraph from the hs.inter graph
gt6  <- subg(g=hs.inter, dat=ER.limma[ER.limma$degenes.t6!=0,], refcol=1)
#--- Set attributes
gt6  <- att.setv(g=gt6, from="Symbol", to="nodeAlias")
gt6  <- att.setv(g=gt6, from="logFC.t6", to="nodeColor", breaks=seq(-2,2,0.4), pal=2)

## ----label='=Workflow 1: Extract another subgraph and set attributes', eval=TRUE----
#--- Extract another subgraph from the hs.inter graph
gt12 <- subg(g=hs.inter, dat=ER.limma[ER.limma$degenes.t12!=0,], refcol=1)
#--- Set attributes
gt12 <- att.setv(g=gt12, from="Symbol", to="nodeAlias")
gt12 <- att.setv(g=gt12, from="logFC.t12", to="nodeColor", breaks=seq(-2,2,0.4), pal=2)

## ----label='=Workflow 1: Customize subgraph names', eval=TRUE-----------------
#--- Customize subgraph names
gt3$nestAlias <- "3h"
gt6$nestAlias <- "6h"
gt12$nestAlias <- "12h"

## ----label='Workflow 1: Send subgraphs to the RedeR application', eval=TRUE----
#--- Send nested subgraphs to the RedeR application
N1 <- addGraph(rdp, gt3, gcoord=c(10,25), gscale=20, isNested=TRUE, theme='tm1', gzoom=30)
N2 <- addGraph(rdp, gt6, gcoord=c(20,70), gscale=50, isNested=TRUE, theme='tm1', gzoom=30)
N3 <- addGraph(rdp, gt12, gcoord=c(70,55), gscale=80, isNested=TRUE, theme='tm1', gzoom=30)

## ----label='Workflow 1: Nest sub-subgraphs', eval=TRUE------------------------
#--- Nest sub-subgraphs
N4 <- nestNodes(rdp, nodes=V(gt3)$name, parent=N2, theme='tm2')
N5 <- nestNodes(rdp, nodes=V(gt6)$name, parent=N3, theme='tm2')
nestNodes(rdp, nodes=V(gt3)$name, parent=N5, theme='tm3')

## ----label='Workflow 1: Assign edges to containers', eval=TRUE----------------
#--- Assign edges to containers
mergeOutEdges(rdp, nlevels=2)

## ----label='Workflow 1: Relax the network', eval=TRUE-------------------------
relax(rdp, p1=100, p2=100, p3=5, p4=150, p5=5, p8=10, p9=20)

## ----label='Workflow 1: Add a color legend', eval=TRUE------------------------
scl <- gt3$legNodeColor$scale
leg <- gt3$legNodeColor$legend 
addLegend.color(rdp, colvec=scl, labvec=leg, title="Node color (logFC)")

## ----label='Workflow 1: Select a gene', eval=TRUE-----------------------------
selectNodes(rdp,"RET")
#repeat this line to see RET in all graph instances

## ----fig6, echo=FALSE, fig.cap="Nested subnetworks. This graph shows genes differentially expressed in estrogen-treated MCF-7 cells at 3, 6 and 12 h (relative to 0 h). The insets correspond to the overlap between consecutive time points. Adapted from Castro *et al.* (2012, https://doi.org/10.1186/gb-2012-13-4-r29).", out.width = '70%'----
knitr::include_graphics("fig6.png")

## ----label='Workflow 2: Load required packages', eval=TRUE, message=FALSE-----
#--- Load required packages
library("RedeR")
library("igraph")

## ----label='Workflow 2: Initialize the RedeR application', eval=TRUE----------
#--- If not running, initialize the ReadeR application
# rdp <- RedPort()
# calld(rdp)
resetd(rdp)

## ----label='Workflow 2: Load a dataframe and an igraph graph', eval=TRUE------
#--- Load a dataframe and an igraph graph
data(ER.deg)
dat <- ER.deg$dat
ceg <- ER.deg$ceg

## ----label='Workflow 2: Map the dataframe to the igraph graph', eval=TRUE-----
#--- Map the dataframe to the igraph graph
ceg <- att.mapv(ceg, dat=dat, refcol=1)

## ----label='Workflow 2: Set RedeR attributes', eval=TRUE----------------------
#--- Set RedeR attributes
ceg <- att.setv(ceg, from="Symbol", to="nodeAlias")
ceg <- att.setv(ceg, from="logFC.t3", to="nodeColor", breaks=seq(-2,2,0.4), pal=2)	
ceg <- att.setv(ceg, from="ERbdist", to="nodeSize", nquant=10, isrev=TRUE, xlim=c(5,40,1))

## ----label='Workflow 2: Send the ceg graph RedeR', eval=TRUE------------------
#--- Send the ceg graph RedeR
addGraph(rdp, ceg)

## ----label='Workflow 2: Hierarchical clustering on the adjacency matrix', eval=TRUE----
#--- Hierarchical clustering on the adjacency matrix
hc <- hclust(dist(get.adjacency(ceg, attr="weight")))

## ----label='Workflow 2: Map the hclust object onto the network', eval=TRUE----
#--- Map the hclust object onto the network
nesthc(rdp, hc, cutlevel=3, nmemb=5, cex=0.3, labels=V(ceg)$nodeAlias)

## ----fig7, echo=FALSE, fig.cap="Hierarchical networks. This dendrogram is superimposed onto the network depicted in **Figure 8**. Adapted from Castro *et al.* (2012, https://doi.org/10.1186/gb-2012-13-4-r29).", out.width = '80%'----
knitr::include_graphics("fig7.png")

## ----label='Workflow 2: Assign edges to containers', eval=TRUE----------------
#--- Assign edges to containers
mergeOutEdges(rdp, nlevels=2)

## ----label='Workflow 2: Relax the network', eval=TRUE-------------------------
relax(rdp,100,100,100,100,5)

## ----label='Workflow 2: Add color legend', eval=TRUE--------------------------
scl <- ceg$legNodeColor$scale
leg <- ceg$legNodeColor$legend
addLegend.color(rdp, colvec=scl, labvec=leg, title="Diff. Gene Expression (logFC)")

## ----label='Workflow 2: Add node size legend', eval=TRUE----------------------
scl <- ceg$legNodeSize$scale
leg <- ceg$legNodeSize$legend
addLegend.size(rdp, sizevec=scl, labvec=leg, title="TFBS Distance (kb)")

## ----fig8, echo=FALSE, fig.cap="Hierarchical networks. This graph is obtained by superimposing a dendrogram onto a network. Adapted from Castro *et al.* (2012, https://doi.org/10.1186/gb-2012-13-4-r29).", out.width = '70%'----
knitr::include_graphics("fig8.png")

## ----label='Workflow 3: Load TreeAndLeaf', eval=FALSE-------------------------
#  #--- Load required packages
#  library("RedeR")
#  library("igraph")
#  library("TreeAndLeaf")

## ----label='Workflow 3: Initialize the RedeR application', eval=FALSE---------
#  #--- If not running, initialize the ReadeR application
#  # rdp <- RedPort()
#  # calld(rdp)
#  resetd(rdp)

## ----label='Workflow 2: hierarchical clustering', eval=FALSE------------------
#  #-- Generate an 'hclust' object from the 'iris' dataset
#  hc_iris <- hclust(dist(iris[,-5]))

## ----label='Workflow 3: Create a tree-and-leaf object', eval=FALSE------------
#  #-- Convert the 'hclust' object into a 'tree-and-leaf' object
#  tal <- treeAndLeaf(hc_iris)
#  
#  #--- Map 'iris' variables to the tree-and-leaf graph
#  #Note: 'refcol = 0' indicates that 'iris' rownames will be used as mapping IDs
#  tal <- att.mapv(g = tal, dat = iris, refcol = 0)
#  
#  #--- Set node attributes using the 'att.setv' wrapper function
#  cols <- c("#80b1d3","#fb8072","#8dd3c7")
#  tal <- att.setv(tal, from="Species", to="nodeColor", cols=cols)
#  tal <- att.setv(tal, from="Species", to="nodeLineColor", cols=cols)	
#  tal <- att.setv(tal, from="Petal.Width", to="nodeSize", nquant=6, xlim=c(5,50,1))
#  
#  #--- Set other attributes using igraph shortcuts
#  V(tal)$nodeAlias <- ""
#  E(tal)$edgeColor <- "grey70"

## ----label='Workflow 3: Send the tal graph to RedeR', eval=FALSE--------------
#  #--- Send the tree-and-leaf graph to RedeR
#  addGraph(rdp, tal, gzoom=50)
#  
#  #--- Suggestion: anchor inner nodes to adjust the final layout
#  # selectNodes(rdp, V(tal)$name[!V(tal)$isLeaf], anchor=TRUE)
#  
#  #--- Call 'relax' to fine-tune the leaf nodes
#  relax(rdp, p1=10, p2=100, p3=2, p4=120, p5=1)
#  
#  #--- Add legends
#  addLegend.color(rdp, tal, title="Species")
#  addLegend.size(rdp, tal, title="PetalWidth", position="bottomright")

## ----fig9, echo=FALSE, fig.cap="A tree-and-leaf diagram. This graph is obtained by transforming an *hclust* object into a *tree-and-leaf* object.", out.width = '70%'----
knitr::include_graphics("fig9.png")

## ----label='Check Java version', eval=FALSE-----------------------------------
#  RedPort(checkJava=TRUE)
#  # RedeR will need Java Runtime Environment (Java >=11)
#  # Checking Java version installed on this system...
#  # openjdk version "11.0.13" 2021-10-19
#  # OpenJDK Runtime Environment (build 11.0.13+8-Ubuntu-0ubuntu1.20.04)
#  # OpenJDK 64-Bit Server VM (build 11.0.13+8-Ubuntu-0ubuntu1.20.04, mixed mode, sharing)

## ----label='Session information', eval=TRUE, echo=FALSE-----------------------
sessionInfo()