## ---- echo = FALSE---------------------------------------------------------
knitr::opts_chunk$set(
  eval=FALSE
)

## --------------------------------------------------------------------------
#  if(!"rWikiPathways" %in% installed.packages()){
#      if (!requireNamespace("BiocManager", quietly = TRUE))
#          install.packages("BiocManager")
#      BiocManager::install("rWikiPathways", update = FALSE)
#  }
#  library(rWikiPathways)

## --------------------------------------------------------------------------
#  load.libs <- c(
#    "DOSE",
#    "GO.db",
#    "GSEABase",
#    "org.Hs.eg.db",
#    "clusterProfiler",
#    "dplyr",
#    "tidyr",
#    "ggplot2",
#    "stringr",
#    "RColorBrewer",
#    "rWikiPathways",
#    "RCy3")
#  options(install.packages.check.source = "no")
#  options(install.packages.compile.from.source = "never")
#  if (!require("pacman")) install.packages("pacman"); library(pacman)
#  p_load(load.libs, update = TRUE, character.only = TRUE)
#  status <- sapply(load.libs,require,character.only = TRUE)
#  if(all(status)){
#      print("SUCCESS: You have successfully installed and loaded all required libraries.")
#  } else{
#      cat("ERROR: One or more libraries failed to install correctly. Check the following list for FALSE cases and try again...\n\n")
#      status
#  }

## --------------------------------------------------------------------------
#  cytoscapePing()  #this will tell you if you're able to successfully connect to Cytoscape or not

## --------------------------------------------------------------------------
#  lung.expr <- read.csv(system.file("extdata","data-lung-cancer.csv", package="rWikiPathways"),stringsAsFactors = F)
#  nrow(lung.expr)
#  head(lung.expr)

## --------------------------------------------------------------------------
#  up.genes <- lung.expr[lung.expr$log2FC > 1 & lung.expr$adj.P.Value < 0.05, 1]
#  dn.genes <- lung.expr[lung.expr$log2FC < -1 & lung.expr$adj.P.Value < 0.05, 1]
#  bkgd.genes <- lung.expr[,1]

## --------------------------------------------------------------------------
#  up.genes.entrez <- clusterProfiler::bitr(up.genes,fromType = "ENSEMBL",toType = "ENTREZID",OrgDb = org.Hs.eg.db)
#  cat("\n\nWhich column contains my new Entrez IDs?\n")
#  head(up.genes.entrez)

## --------------------------------------------------------------------------
#  keytypes(org.Hs.eg.db)

## --------------------------------------------------------------------------
#  dn.genes.entrez <- bitr(dn.genes,fromType = "ENSEMBL",toType = "ENTREZID",OrgDb = org.Hs.eg.db)
#  bkgd.genes.entrez <- bitr(bkgd.genes,fromType = "ENSEMBL",toType = "ENTREZID",OrgDb = org.Hs.eg.db)

## --------------------------------------------------------------------------
#  egobp <- clusterProfiler::enrichGO(
#          gene     = up.genes.entrez[[2]],
#          universe = bkgd.genes.entrez[[2]],
#          OrgDb    = org.Hs.eg.db,
#          ont      = "BP",
#          pAdjustMethod = "fdr",
#          pvalueCutoff = 0.05, #p.adjust cutoff (https://github.com/GuangchuangYu/clusterProfiler/issues/104)
#          readable = TRUE)
#  
#  head(egobp,10)

## --------------------------------------------------------------------------
#  barplot(egobp, showCategory = 20)
#  dotplot(egobp, showCategory = 20)
#  emapplot(egobp, showCategory = 20)
#  goplot(egobp)

## --------------------------------------------------------------------------
#  ggplot(egobp[1:20], aes(x=reorder(Description, -pvalue), y=Count, fill=-p.adjust)) +
#      geom_bar(stat = "identity") +
#      coord_flip() +
#      scale_fill_continuous(low="blue", high="red") +
#      labs(x = "", y = "", fill = "p.adjust") +
#      theme(axis.text=element_text(size=11))

## --------------------------------------------------------------------------
#  wp.hs.gmt <- rWikiPathways::downloadPathwayArchive(organism="Homo sapiens", format = "gmt")
#  
#  # supported organisms (and case-dependent spelling)...
#  listOrganisms()

## --------------------------------------------------------------------------
#  wp2gene <- clusterProfiler::read.gmt(wp.hs.gmt)
#  wp2gene <- wp2gene %>% tidyr::separate(ont, c("name","version","wpid","org"), "%")
#  wpid2gene <- wp2gene %>% dplyr::select(wpid,gene) #TERM2GENE
#  wpid2name <- wp2gene %>% dplyr::select(wpid,name) #TERM2NAME
#  wpid2gene
#  wpid2name

## --------------------------------------------------------------------------
#  ewp.up <- clusterProfiler::enricher(
#          up.genes.entrez[[2]],
#          universe = bkgd.genes.entrez[[2]],
#          pAdjustMethod = "fdr",
#          pvalueCutoff = 0.1, #p.adjust cutoff; relaxed for demo purposes
#          TERM2GENE = wpid2gene,
#          TERM2NAME = wpid2name)
#  
#  head(ewp.up)

## --------------------------------------------------------------------------
#  ewp.up <- DOSE::setReadable(ewp.up, org.Hs.eg.db, keytype = "ENTREZID")
#  head(ewp.up)

## --------------------------------------------------------------------------
#  barplot(ewp.up, showCategory = 20)
#  dotplot(ewp.up, showCategory = 20)
#  emapplot(ewp.up, showCategory = 20)

## --------------------------------------------------------------------------
#  ewp.dn <- enricher(
#    dn.genes.entrez[[2]],
#    #universe = bkgd.genes[[2]],  #hint: comment out to get any results for demo
#    pAdjustMethod = "fdr",
#    pvalueCutoff = 0.1, #p.adjust cutoff; relaxed for demo purposes
#    TERM2GENE = wpid2gene,
#    TERM2NAME = wpid2name)
#  
#   ewp.dn <- setReadable(ewp.dn, org.Hs.eg.db, keytype = "ENTREZID")
#   head(ewp.dn)
#   dotplot(ewp.dn, showCategory = 20)

## --------------------------------------------------------------------------
#  findPathwayNamesByText("lung cancer")

## --------------------------------------------------------------------------
#  lc.pathways <- findPathwaysByText('"lung cancer"')  #quotes inside query to require both terms
#  human.filter <- lapply(lc.pathways, function(x) x$species == "Homo sapiens")
#  human.lc.pathways <- lc.pathways[unlist(human.filter)] # just the human lung cancer pathways
#  sapply(human.lc.pathways, function(x) x$name) # display the pathway titles

## --------------------------------------------------------------------------
#  lc.wpids <- sapply(human.lc.pathways, function(x) x$id)
#  lc.wpids

## --------------------------------------------------------------------------
#  ewp.up.wpids <- ewp.up$ID
#  ewp.up.wpids

## --------------------------------------------------------------------------
#  url <- getPathwayInfo("WP179")[2]
#  browseURL(url)

## --------------------------------------------------------------------------
#  cytoscapePing()

## --------------------------------------------------------------------------
#  commandsRun('wikipathways import-as-pathway id=WP179')

## --------------------------------------------------------------------------
#  toggleGraphicsDetails()

## --------------------------------------------------------------------------
#  loadTableData(lung.expr, data.key.column = "GeneID", table.key.column = "Ensembl")

## --------------------------------------------------------------------------
#  min.lung.expr = min(lung.expr["log2FC"],na.rm=TRUE)
#  max.lung.expr = max(lung.expr["log2FC"],na.rm=TRUE)
#  abs.lung.expr = max(abs(min.lung.expr),max.lung.expr)
#  data.values = c(-abs.lung.expr,0,abs.lung.expr)

## --------------------------------------------------------------------------
#  display.brewer.all(length(data.values), colorblindFriendly=TRUE, type="div") # div,qual,seq,all
#  node.colors <- c(rev(brewer.pal(length(data.values), "RdBu")))

## --------------------------------------------------------------------------
#  setNodeColorMapping("log2FC", data.values, node.colors, default.color = "#FFFFFF", style.name = "WikiPathways")

## --------------------------------------------------------------------------
#  data.values<-c(-5,0,5)
#  setNodeColorMapping("log2FC", data.values, node.colors, default.color = "#FFFFFF", style.name = "WikiPathways")

## --------------------------------------------------------------------------
#  lapply(ewp.up.wpids, function (x) {
#      commandsRun(paste0('wikipathways import-as-pathway id=',x))
#      loadTableData(lung.expr, data.key.column = "GeneID", table.key.column = "Ensembl")
#      toggleGraphicsDetails()
#      })

## --------------------------------------------------------------------------
#  commandsRun('wikipathways import-as-network id=WP179')
#  loadTableData(lung.expr, data.key.column = "GeneID", table.key.column = "Ensembl")
#  setNodeColorMapping("log2FC", data.values, node.colors, default.color = "#FFFFFF", style.name = "WikiPathways-As-Network")

## --------------------------------------------------------------------------
#  unzip(system.file("extdata","drugbank-5.1.0.xgmml.zip", package="rWikiPathways"), exdir = getwd())
#  drugbank <- file.path(getwd(), "drugbank-5.1.0.xgmml")

## --------------------------------------------------------------------------
#  commandsRun(paste0('cytargetlinker extend idAttribute="Ensembl" linkSetFiles="', drugbank, '"') )
#  commandsRun('cytargetlinker applyLayout network="current"')

## --------------------------------------------------------------------------
#  my.drugs <- selectNodes("drug", by.col = "CTL.Type", preserve = FALSE)$nodes #easy way to collect node SUIDs by column value
#  clearSelection()
#  setNodeColorBypass(my.drugs, "#DD99FF")
#  setNodeShapeBypass(my.drugs, "hexagon")
#  
#  drug.labels <- getTableColumns(columns=c("SUID","CTL.label"))
#  drug.labels <- na.omit(drug.labels)
#  mapply(function(x,y) setNodeLabelBypass(x,y), drug.labels$SUID, drug.labels$CTL.label)

## --------------------------------------------------------------------------
#  save(ewp.up, file = "lung_cancer_ewp_up.Rdata")
#  save(ewp.dn, file = "lung_cancer_ewp_down.Rdata")

## --------------------------------------------------------------------------
#  full.path=paste(getwd(),'tutorial_session',sep='/')
#  saveSession(filename=full.path) #.cys

## --------------------------------------------------------------------------
#  full.path=paste(getwd(),'tutorial_image2',sep='/')
#  exportImage(filename=full.path, type='PDF') #.pdf
#  exportImage(filename=full.path, type='PNG', zoom=200) #.png; use zoom or width args to increase size/resolution
#  ?exportImage

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

