## ----setup, include = FALSE---------------------------------------------------
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
library(punKEGGer)

## ----example-1----------------------------------------------------------------
# usually you'll read from the official database like so
# kgml <- read_xml("https://rest.kegg.jp/get/hsa04210/kgml")
# or use the function fetch_kegg_kgml
# kgml <- fetch_kegg_kgml("hsa04210")
# but for reproducibility purposes you can use 
kgml_file <- system.file("extdata", "hsa04210.xml", package = "punKEGGer")
kgml <- xml2::read_xml(kgml_file)

g <- combine_kegg_network(kgml)
g

## ----example-2----------------------------------------------------------------
node_info <- extract_kegg_nodes(kgml)
dict_path <- system.file("extdata", "example_dict.hsa04210.csv", package = "punKEGGer")
kegg_dict <- read.csv(dict_path)
# creates the dictionary for the metanodes
meta_dict <- create_meta_dict(node_info, kegg_dict)
# expands metanodes and returns a new graph
g_exp <- expand_metagraph(g, node_info, node_types = "gene")
#annotates expanded graph 
g_annot <- annotate_kegg_graph(g_exp, meta_dict, identifiers = "hgnc_symbol")

#show the expanded graph with annotated nodes
tidygraph::as_tibble(g_annot, active = "nodes") |>
  dplyr::select(name, meta_id, type, hgnc_symbol) |>
  head()

## ----example-3a---------------------------------------------------------------
layout_tbl <- layout_kegg(kgml)
g_layout <- add_kegg_layout(g_annot, layout_tbl)
plot_kegg_graph(g_layout, id = hgnc_symbol)

## ----example-3b---------------------------------------------------------------
library(ggraph)
library(tidygraph)

# let's calculate some simple centrality measures
g_annot <- 
  g_annot |> 
  mutate(degree = centrality_degree())

# now we visualize the network using a force-directed layout, and show node size and label size proportional to degree

ggraph(g_annot, layout = "fr") +
  geom_edge_link() +
  geom_node_label(aes(size = degree, 
                     label = hgnc_symbol),
                  fill = "#9D4EDD",
                  color = "white",
                  label.r = unit(0.15,"lines"),
                  label.padding = unit(0.25,"lines"),
                  label.size = 0.2,
                  repel = TRUE
                 ) + 
  theme_void()

## ----example-4----------------------------------------------------------------


#let's identify modules in the network using the Infomap algorithm

g_annot <- 
  as_tbl_graph(g_annot)

g_annot <- 
  g_annot |> 
  mutate(infomap = group_infomap())



#let's calculate degree centrality 
g_annot <- 
  g_annot |> 
  mutate(degree = centrality_degree())

# now, let's identify the gene(s) with highest centrality per module 

df <- 
  g_annot |> 
  as_tibble() |> 
  group_by(infomap) |> 
  filter(degree == max(degree)) |> 
  arrange(infomap)

print(df)

## ----session-info, echo=FALSE-------------------------------------------------
sessionInfo()

