## ----lib, echo=FALSE----------------------------------------------------------
library(ReactomeGraph4R)

## ----setup, eval=FALSE--------------------------------------------------------
#  library(ReactomeGraph4R)
#  login()

## ----getData, echo=FALSE------------------------------------------------------
load("data/vignette.Rdata")

## ----basic-id, eval=FALSE-----------------------------------------------------
#  # Retrieve the object of PER2 gene
#  # NOTE: if you're unsure which database to specify, you have to leave it as NULL
#  matchObject(id = "PER2", databaseName = NULL)

## ----basic-id-data, echo=FALSE------------------------------------------------
per2

## ----basic-id-2, eval=FALSE---------------------------------------------------
#  matchObject(id = 'R-HSA-400219')

## ----basic-id-2-data, echo=FALSE----------------------------------------------
HSA_400219

## ----multi-ids, eval=FALSE----------------------------------------------------
#  # retrieve multiple objects
#  ids <- c('R-HSA-74158', 'R-HSA-1566977', 'R-HSA-3000157', 'R-HSA-3000178', 'R-HSA-216083')
#  multiObjects(ids)

## ----multi-ids-data, echo=FALSE-----------------------------------------------
multiObj

## ----basic-name, eval=FALSE---------------------------------------------------
#  matchObject(displayName = "SUMO1:TOP1 [nucleoplasm]", species = "C. elegans")

## ----basic-name-data, echo=FALSE----------------------------------------------
sumo

## ----basic-class, eval=FALSE--------------------------------------------------
#  # Get 5 instance in Class EntitySet and return displayName & stId
#  entity.set <- matchObject(schemaClass = "EntitySet", species = "human",
#                            returnedAttributes = c("displayName", "stId"), limit = 5)
#  entity.set[["databaseObject"]] # show as dataframe

## ----basic-class-data, echo=FALSE---------------------------------------------
entity.set[["databaseObject"]]

## ----basic-property, eval=FALSE-----------------------------------------------
#  # Get instances with conditions of properties that are stored in a list
#  matchObject(property = list(isChimeric = TRUE, isInDisease = TRUE), limit = 10)[["databaseObject"]]

## ----basic-property-data, echo=FALSE------------------------------------------
property

## ----basic-rel, eval=FALSE----------------------------------------------------
#  # Get nodes connected with 'hasComponent'
#  matchObject(relationship = "hasComponent", limit = 3)

## ----basic-rel-data, echo=FALSE-----------------------------------------------
rleObj

## ----hierarchy, eval=FALSE----------------------------------------------------
#  # Get hierarchy data of R-HSA-500358
#  pou5f1.hierarchy <- matchHierarchy(id = "R-HSA-500358", type = "row")
#  str(pou5f1.hierarchy, max.level = 1)

## ----hierarchy-data, echo=FALSE-----------------------------------------------
str(pou5f1.hierarchy, max.level = 1)

## ----hierarchy-2--------------------------------------------------------------
# select essential columns to show
pou5f1.hierarchy$relationships[,c(2,4,5,7,8)]

## ----r-in-p, eval=FALSE-------------------------------------------------------
#  # Find Reactions connected with R-HSA-8983688
#  rle <- matchReactionsInPathway(event.id = "R-HSA-8983688", type = "row")

## ----r-in-p-data--------------------------------------------------------------
str(rle, max.level = 1)

# The one in reactionLikeEvent is what we search for
rle$reactionLikeEvent

# Take a look at the connected Pathway
rle$pathway

## ----r-in-p-2-----------------------------------------------------------------
# Show displayNames of other RLEs
rle$otherReactionLikeEvent[["displayName"]]

## ----export-img---------------------------------------------------------------
library(ReactomeContentService4R)

# Export pathway diagram of "OAS antiviral response"
exportImage(id = "R-HSA-8983711", output = "diagram", 
            sel = "R-HSA-8983688", format = "png", quality = 8)

## ----p-f-event, eval=FALSE----------------------------------------------------
#  # Retrieve RLE context with depth = 2
#  rle.context <- matchPrecedingAndFollowingEvents(event.id = "R-HSA-8983688", depth = 2, type = "row")
#  str(rle.context, max.level = 1)

## ----p-f-event-data, echo=FALSE-----------------------------------------------
str(rle.context, max.level = 1)

## ----referral, eval=FALSE-----------------------------------------------------
#  # Find referrals of the given Regulation
#  matchReferrals(id = 6810147, type = "row")

## ----referral-data, echo=FALSE------------------------------------------------
referral

## ----interactor, eval=FALSE---------------------------------------------------
#  # Retrieve interaction data of the given PE
#  interactors <- matchInteractors(pe.id = "R-HSA-419535")

## ----interactor-2-------------------------------------------------------------
str(interactors, max.level = 1)
interactors$interaction

## ----PEroles, eval=FALSE------------------------------------------------------
#  # Find possible roles of the given PE
#  roles <- matchPEroles(pe.displayName = "HSBP1 oligomer [cytosol]")

## ----PEroles-data-------------------------------------------------------------
str(roles, max.level = 1)

# get the roles (relationships type)
unique(roles$relationships$type)

## ----disease, eval=FALSE------------------------------------------------------
#  # Fetch Reactome instances associated with 'neuropathy' in human
#  matchDiseases(displayName = "neuropathy", species = "human", type = "row")

## ----disease-data, echo=FALSE-------------------------------------------------
disease

## ----paper, eval=FALSE--------------------------------------------------------
#  # fetch objects by paper title
#  matchPaperObjects(displayName = "Aggresomes: a cellular response to misfolded proteins", type = "row")

## ----paper-data, echo=FALSE---------------------------------------------------
papers

## ----vis-loading--------------------------------------------------------------
# install packages
list.pkg <- c("stringr", "visNetwork", "networkD3", "wesanderson")
new.pkg <- list.pkg[!(list.pkg %in% installed.packages()[ ,"Package"])]
if (length(new.pkg)) {
  install.packages(new.pkg, repos = "https://cloud.r-project.org/")
}
# load
invisible(suppressPackageStartupMessages(lapply(list.pkg, library, character.only = TRUE)))

## ----vis-1, eval=FALSE--------------------------------------------------------
#  # Get graph output data
#  graph <- matchHierarchy(displayName = "UniProt:P33992 MCM5", databaseName = "UniProt", type = "graph")

## ----vis-1-data---------------------------------------------------------------
relationships <- graph[["relationships"]]
nodes <- graph[["nodes"]]
nodes <- unnestListCol(df = nodes, column = "properties") # unnest the 'properties' column of lists
head(nodes); head(relationships)


# Transform into visNetwork format for nodes & edges
vis.nodes <- data.frame(id = nodes$id, 
                        label = str_trunc(nodes$displayName, 20), # truncate the long names
                        group = nodes$schemaClass, 
                        title = paste0("<p><b>", nodes$schemaClass, "</b><br>", 
                                "dbId: ", nodes$dbId, "<br>", nodes$displayName, "</p>"))

vis.edges <- data.frame(from = relationships$startNode,
                        to = relationships$endNode,
                        label = relationships$type,
                        font.size = 16,
                        font.color = 'steelblue')

head(vis.nodes); head(vis.edges)

## ----vis-2--------------------------------------------------------------------
# nodes parameters
## get palette colors with package 'wesanderson'
node.colors <- as.character(wes_palette(n = length(unique(vis.nodes$group)), name = "Darjeeling2"))
names(node.colors) <- levels(factor(vis.nodes$group))
## NOTE: don't use `str_replace_all` here since 'TopLevelPathway' & 'Pathway' share the string 'Pathway' 
vis.nodes$color.background <- node.colors[as.numeric(factor(vis.nodes$group))] # node color
vis.nodes$color.border <- "lightgray"
## highlight the instance we specified
vis.nodes$color.border[vis.nodes$label == "UniProt:P33992 MCM5"] <- "pink" 
vis.nodes$color.highlight.border <- "darkred"
vis.nodes$borderWidth <- 2 # Node border width

# edges parameters
vis.edges$width <- 1.2 # line width
edges.colors <- as.character(wes_palette(n = length(unique(vis.edges$label)), name = "FantasticFox1"))
names(edges.colors) <- unique(vis.edges$label)
vis.edges$color <- str_replace_all(vis.edges$label, edges.colors) # line color  
vis.edges$arrows <- "to" # arrows: 'from', 'to', or 'middle'
vis.edges$smooth <- TRUE    # should the edges be curved?

# height & width of the plot can be set here
visnet <- visNetwork(vis.nodes, vis.edges, main = "The hierarchy of protein MCM5", 
                     height = "500px", width = "100%")
visnet

## ----vis-drop-down------------------------------------------------------------
# Rename column name 'group' to 'Class' for displaying in the window
names(visnet[["x"]][["nodes"]]) <- gsub("group", "Class", names(visnet[["x"]][["nodes"]]))
visOptions(visnet, highlightNearest = TRUE, selectedBy = "Class")

## ----d3-1---------------------------------------------------------------------
# the node ids MUST be numeric, and start from 0
nodes.idx <- as.character(as.numeric(factor(nodes$id)) - 1)
names(nodes.idx) <- nodes$id

# transform into networkD3 format
d3.edges <- data.frame(source = as.numeric(str_replace_all(relationships$startNode, nodes.idx)),
                       target = as.numeric(str_replace_all(relationships$endNode, nodes.idx)),
                       label = relationships$type)
d3.edges <- d3.edges[order(d3.edges$source), ]

d3.nodes <- cbind(idx=as.numeric(nodes.idx), nodes)
d3.nodes <- d3.nodes[order(d3.nodes$idx), ] # the order MUST be consistent with the 'source'

forceNetwork(Links = d3.edges, Nodes = d3.nodes, Source="source", Target="target",
             NodeID = "displayName", Group = "schemaClass", Value = "label", 
             linkColour = "#afafaf", fontSize = 12, zoom = TRUE, legend = TRUE,
             Nodesize = 15, opacity = 0.9, charge = -50)

## ----citation-----------------------------------------------------------------
citation('ReactomeGraph4R')

## ----secinfo------------------------------------------------------------------
sessionInfo()