## ----setup, include=FALSE-----------------------------------------------------
knitr::opts_chunk$set(
  eval = TRUE,
  echo = TRUE,
  message = FALSE,
  warning = FALSE
)

knitr::opts_knit$set(bookdown.internal.label = FALSE)

## ----install, include=TRUE, eval=FALSE----------------------------------------
# if (!requireNamespace("BiocManager", quietly = TRUE))
#     install.packages("BiocManager")
# BiocManager::install("MetaPathNet")

## ----load_package-------------------------------------------------------------
library(MetaPathNet)

## ----compounds_mapping--------------------------------------------------------
## Selected compound names and synonyms
compound_names <- c("choline", "carnitine", "betaine", 
                    "gamma-butyrobetaine", "trimethylamine", "tmao")

## Map compounds to KEGG compound IDs
compound_kegg <- MetaPathNet::findKeggIDs(
  KEGG_database = "compound",
  searchBy      = "name",
  query         = compound_names
)

## View mapped compound IDs
compound_kegg

## ----ko_suggestion------------------------------------------------------------
## Define the mapped metabolite KEGG IDs
compound_tma <- compound_kegg$KEGG_ID

## Suggest candidate KOs from the selected metabolites
ko_candidates <- suggestEntities(
  query  = compound_tma,
  entity = "compound"
)

## View suggested KO candidates
head(ko_candidates)

## ----organism_suggestion------------------------------------------------------
## Define KO candidates of interest
gene_tma <- c("K18277", "K07811", "K00108", "K14156", "K00485", "K20038")

## Suggest candidate organisms from the selected KOs
organism_candidates <- suggestEntities(
  query  = gene_tma,
  entity = "ko"
)

## View suggested organism candidates
head(organism_candidates)

## ----network_construction, eval=FALSE-----------------------------------------
# ## Construct the host-microbiome metabolic network
# network_hostMicrobe <- buildCrossSpeciesNetwork(
#   organism_codes = c("hsa", "eci"),
#   path_type      = "metabolic"
# )

## ----load_hostMicrobe_network, include=FALSE----------------------------------
network_hostMicrobe <- readRDS(
  system.file("extdata", "network_hostMicrobe.rds", package = "MetaPathNet")
)

## ----network_view-------------------------------------------------------------
## Preview the integrated network edge list
head(network_hostMicrobe)       

## ----network_visualisation, eval=FALSE----------------------------------------
# ## Visualise the integrated network in Cytoscape
# viewNetworkCy(
#   network_table     = network_hostMicrobe,
#   category          = TRUE,
#   style_interaction = TRUE,
#   node_compound     = "#9DC7DD",
#   node_gene         = "#9ED17B",
#   network_title     = "Integrated host–microbiome network",
#   collection_title  = "MetaPathNet_Examples"
# )

## ----network_overview, echo=FALSE, message=FALSE, warning=FALSE, out.width="80%", fig.align="center", fig.cap="Figure 1. Integrated host–microbiome metabolic network."----
knitr::include_graphics(system.file("extdata", "tma_integrated_network.png", package = "MetaPathNet"))

## ----network_check------------------------------------------------------------
## Check mapped compounds in the integrated network
compound_mapped <- MetaPathNet::findMappedNodes(
  nodes         = compound_tma,
  network_table = network_hostMicrobe
)

## Check mapped KOs in the integrated network
gene_mapped <- MetaPathNet::findMappedNodes(
  nodes         = gene_tma,
  network_table = network_hostMicrobe
)

## ----network_check_result-----------------------------------------------------
## View mapped and unmapped nodes
compound_mapped
gene_mapped

## ----manual_curation----------------------------------------------------------
## Define a custom FMO-associated TMA-to-TMAO reaction
fmo_reaction <- data.frame(
  reaction_id = "TMA_to_TMAO_FMO",
  substrates  = "cpd:C00565",
  products    = "cpd:C01104",
  ko          = "K00485",
  direction   = "irreversible",
  stringsAsFactors = FALSE
)

## Convert to edge-list format
fmo_extension <- MetaPathNet::addCustomReaction(
  reaction_table = fmo_reaction,
  substrate_col  = "substrates",
  product_col    = "products",
  ko_col         = "ko",
  direction_col  = "direction"
)

## ----network_extension--------------------------------------------------------
## Map MetaCyc reactions to edge-list format
tma_extension <- mapReaction(
  reaction_ids = c("RXN-12900", "RXN-13946"),
  source       = "metacyc"
)

## Preview the mapped reaction edges
head(tma_extension)

## ----refined_network_check----------------------------------------------------
## Merge the reaction extension into the cross-species network
network_mixed <- MetaPathNet::combineNetworks(
  network_hostMicrobe,   ## Initial host–microbiome network
  tma_extension,         ## MetaCyc reaction extension
  fmo_extension          ## Manually curated FMO reaction
)

## Extract mapped compounds in the combined network
compound_tma <- MetaPathNet::findMappedNodes(
  nodes         = compound_tma,
  network_table = network_mixed
)$mapped_nodes

## Extract mapped KOs in the combined network
gene_tma <- MetaPathNet::findMappedNodes(
  nodes         = gene_tma,
  network_table = network_mixed
)$mapped_nodes

## ----topology_analysis--------------------------------------------------------
## Compute the shortest-path distance matrix between selected KOs and compounds
distance_tma <- MetaPathNet::networkDistances(
  network_table = network_mixed,
  source_nodes  = gene_tma,
  target_nodes  = compound_tma,
  mode          = "all",
  name          = TRUE
)

## View distances from selected genes to selected metabolites
distance_tma[1:3, , drop = FALSE]

## Extract the shortest-path subnetwork as a MetaPathNet-style edge list
network_shortestPath <- MetaPathNet::findShortestPaths(
  network_table      = network_mixed,
  source_nodes       = gene_tma,
  target_nodes       = compound_tma,
  mode               = "all",
  output             = "network_matrix",
  name               = FALSE,
  distance_threshold = 12,   # exclude overly long paths
  betweenness        = TRUE
)

## ----network_visualisation_R, message=FALSE, warning=FALSE, fig.width=8, fig.height=6, out.width="80%", fig.align="center", fig.cap="Figure 2. R-based visualisation of the choline–TMA–TMAO shortest-path subnetwork."----
network_tma_R <- MetaPathNet::viewNetworkR(
  network_table = network_shortestPath,
  category      = TRUE,   ## Automatically categorise and colour-code genes and compounds
  name          = FALSE,
  node_size     = 4,      ## Custom node size
  node_compound = "#9DC7DD",
  node_gene     = "#9ED17B",
  network_title = "TMA/TMAO shortest-path subnetwork"
)
print(network_tma_R)

## ----KO_origin_visualisation, eval=FALSE--------------------------------------
# ## Visualise the origin-annotated shortest-path network in Cytoscape
# MetaPathNet::annotateOrigin(
#   network_table     = network_shortestPath,
#   name              = TRUE,
#   export_cytoscape  = TRUE,
#   network_title     = "Origin-annotated shortest-path network",
#   collection_title  = "MetaPathNet_Examples"
# )

## ----SP_network_overview, echo=FALSE, message=FALSE, warning=FALSE, out.width="100%", fig.align="center", fig.cap="Figure 3. Origin-annotated visualisation of the choline–TMA–TMAO shortest-path subnetwork."----
knitr::include_graphics(system.file("extdata", "tma_shortestPath_network.png", package = "MetaPathNet"))

## ----KO_origin_annotation-----------------------------------------------------
## Annotate node origin in the shortest-path subnetwork
origin_shortestPath <- MetaPathNet::annotateOrigin(
  network_table    = network_shortestPath,
  bacteria_codes   = "eci",
  name             = TRUE,
  export_cytoscape = FALSE
)

## View the node-level origin table
head(origin_shortestPath)

## ----permutation_test, message=FALSE, warning=FALSE, fig.width=8, fig.height=6, fig.align="center", fig.cap="Figure 4. Null-model permutation test of gene–metabolite proximity in the reconstructed network."----
## Permutation test: KO set -> TMA-axis-related metabolites
perm_host_tma <- MetaPathNet::permutePaths(
  network_table = network_mixed,
  source_nodes  = gene_tma,
  target_nodes  = compound_tma,
  n_perm        = 1000,
  mode          = "out",
  plot          = TRUE,
  return_perm   = TRUE
)

## ----pathway_retrieval--------------------------------------------------------
## Retrieve KEGG pathways for human and E. coli
paths <- getPathIDs(c("hsa", "eci"))

## Keep shared metabolic pathway IDs only
pathway_hostMicrobe <- names(
  which(table(sub("^[a-zA-Z]+", "map", paths$Path_id[paths$Path_type == "metabolic"])) == 2)
)

## View shared metabolic pathway IDs
head(pathway_hostMicrobe)

## ----enrichment_analysis------------------------------------------------------
## Integrated pathway enrichment on the shortest-path subnetwork
enrich_tma <- enrichPathway(
  test_set       = network_shortestPath,  # accepts a MetaPathNet-style edge list or a node vector
  background_set = network_mixed,
  pathway_set    = pathway_hostMicrobe,
  entity         = "integrated",
  pvalueCutoff   = 0.05,
  add_hits       = TRUE
)

## Preview the enrichment results
head(enrich_tma)

## ----enrichment_dotplot, message=FALSE, warning=FALSE, fig.width=8, fig.height=6, fig.align="center", fig.cap="Figure 5. Integrated pathway enrichment of the choline–TMA–TMAO shortest-path subnetwork, showing the top 10 pathways ranked by adjusted p-value."----
## Visualise the pathway enrichment results
enrichmentDotPlot(
  enrichment_result       = enrich_tma,
  top_n                    = 10,
  alpha                    = 0.05,
  title                    = "Integrated Pathway Enrichment",
  significant_colour      = "#C45745",
  nonsignificant_colour   = "#D1C2C2"
)

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

