## ----setup, include = FALSE---------------------------------------------------
knitr::opts_chunk$set(collapse = TRUE, comment = "#>", fig.width = 7,
                      fig.height = 5, fig.align = "center")
and_list <- function(x) {
  if (length(x) < 2L) return(x)
  paste(paste(x[-length(x)], collapse = ", "), "and", x[length(x)])
}
caps <- list(
  overview = paste("Neighbourhood statistics of every gene. Each panel plots",
                   "the up-seeded pulldown (x) against the down-seeded one",
                   "(y); genes on the diagonal have equal values."),
  cltcl1 = paste("Predicted neighbourhoods of the up- and down-labelled",
                 "CLTCL1 isoforms, one node per gene. The CLTCL1 node",
                 "(diamond) holds both seeds. Genes and edges are green when",
                 "reached only from the up-labelled isoform, orange with",
                 "dashed edges when reached only from the down-labelled",
                 "isoform, and blue when reached from both."),
  component = paste("The largest mixed component. Diamonds are seeds.",
                    "Every other node is coloured by the seed direction",
                    "it is closest to; purple nodes are equally close to up",
                    "and down seeds."),
  diagnostics = paste("Diagnostics of the bundled network after",
                      "decay-transcript exclusion.")
)

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

## ----load---------------------------------------------------------------------
library(IsoNetAnalyzeR)

## ----session------------------------------------------------------------------
obj <- IsoNetAnalyzeR("GSE141432")
obj

## ----eligibility--------------------------------------------------------------
eligibility <- get_metadata(obj, "network_biotype_filter")
unlist(eligibility[c("vertices_before", "excluded_nmd", "excluded_nsd",
                     "vertices_after", "edges_after")])

## ----cutoff-------------------------------------------------------------------
unname(get_metadata(obj, "network_cutoff"))

## ----seeds--------------------------------------------------------------------
seeds <- read.csv(system.file("extdata", "gse141432_t2d_vs_lean_seeds.csv",
                              package = "IsoNetAnalyzeR"))
head(seeds)
table(seeds$direction)
length(unique(seeds$gene_id))

## ----pulldown-----------------------------------------------------------------
obj <- run_differential_pulldown(
  obj, "t2d", seeds,
  order = 1, confirm = FALSE, verbose = FALSE,
  seed_padj_col = "within_gene_padj", seed_fdr = 0.05
)

## ----coverage-----------------------------------------------------------------
coverage <- get_metadata(obj, "analysis_network_coverage")$t2d
coverage$by_direction[, c("direction", "n_input",
                          "n_mapped_with_predicted_edge",
                          "n_mapped_no_predicted_edge", "n_unmapped")]
support <- get_metadata(obj, "analysis_seed_support")$t2d$gene_audit
table(support$reason)

## ----cross-gene---------------------------------------------------------------
gene_names <- isonet_gene_names()
cgs <- get_cross_gene_summary(obj, "t2d")
cgs$gene_name <- gene_names$gene_name[match(cgs$gene_id, gene_names$gene_id)]
cgs$delta_nodes <- cgs$up_nodes - cgs$down_nodes
head(cgs[order(-abs(cgs$delta_nodes)),
         c("gene_name", "up_nodes", "down_nodes", "up_edges", "down_edges",
           "jaccard")], 8)

## ----overview-plot, fig.height = 6, fig.cap = caps$overview-------------------
plot_cross_gene_overview(obj, "t2d")

## ----cltcl1-------------------------------------------------------------------
cltcl1 <- get_gene_result(obj, "t2d", "ENSG00000070371")
cltcl1
stats <- get_isoform_stats(obj, "t2d", "ENSG00000070371")
stats[stats$is_seed, c("direction", "isoform", "degree", "mean_pi")]

## ----cltcl1-counts, include = FALSE-------------------------------------------
up_graph <- get_pulldown_graph(cltcl1, "up")
down_graph <- get_pulldown_graph(cltcl1, "down")
partner_genes <- function(g) {
  genes <- setdiff(unique(igraph::V(g)$gene), "ENSG00000070371")
  and_list(sort(gene_names$gene_name[match(genes, gene_names$gene_id)]))
}

## ----cltcl1-plot, fig.height = 6, fig.cap = caps$cltcl1-----------------------
plot_network(cltcl1, direction = "overlay", level = "gene",
             node_size = 3.5, label_size = 3)

## ----labels, eval = FALSE-----------------------------------------------------
# plot_network(cltcl1, direction = "overlay")                       # isoforms
# plot_network(cltcl1, direction = "overlay", node_labels = "id")   # IDs
# plot_network(cltcl1, direction = "overlay", node_labels = "none") # no labels

## ----components---------------------------------------------------------------
obj <- run_component_analysis(obj, "t2d", label = "comp")
overview <- get_component_overview(obj, "t2d", "comp")
head(overview[, c("component_id", "n_nodes", "n_edges", "n_seeds_up",
                  "n_seeds_down", "mixed", "n_shared_nodes",
                  "topology_class")])

## ----component-genes, include = FALSE-----------------------------------------
largest_mixed <- overview$component_id[overview$mixed][1]
nodes <- get_component(obj, "t2d", "comp", largest_mixed)
network <- get_network(obj)
seed_genes <- igraph::V(network)$gene[
  match(nodes$node[nodes$is_seed], igraph::V(network)$name)
]
seed_symbols <- sort(unique(
  gene_names$gene_name[match(seed_genes, gene_names$gene_id)]
))

## ----component-plot, fig.width = 9, fig.height = 7, fig.cap = caps$component----
plot_component(obj, "t2d", "comp", component_id = largest_mixed,
               colour_by = "direction", colour_neighbours = TRUE)

## ----ora----------------------------------------------------------------------
msigdb_hs <- msigdb::getMsigdb(org = "hs", id = "SYM", version = "2023.1")
hallmark <- msigdb::subsetCollection(msigdb_hs, "h")
hallmark
obj <- run_component_ora(obj, "t2d", "comp", label = "hallmark",
                         pathways = hallmark)
ora <- get_ora_table(obj, "t2d", "comp", "hallmark", padj_cutoff = 0.05,
                     top_n = 1)
head(ora[, c("component_id", "pathway", "overlap", "padj")], 8)

## ----gsea, warning = FALSE----------------------------------------------------
set.seed(42)
obj <- run_fgsea(obj, "t2d", label = "hallmark_gsea", pathways = hallmark,
                 minSize = 3)
get_gsea_table(obj, "t2d", "hallmark_gsea")[, c("pathway", "size", "NES",
                                                "pval", "padj")]

## ----diagnostics--------------------------------------------------------------
obj <- run_network_diagnostics(obj)
get_network_diagnostics(obj)

## ----diag-plot, fig.width = 10, fig.height = 6, fig.cap = caps$diagnostics----
plot_network_diagnostics(obj)

## ----lookup-------------------------------------------------------------------
obj <- lookup_virtual_pulldown(obj, "cltcl1_down", seed = "ENST00000427926",
                               order = 1)
lookup <- get_lookup_stats(obj, "cltcl1_down")
subgraph <- get_lookup_subgraph(obj, "cltcl1_down")
gene_of <- stats::setNames(igraph::V(subgraph)$gene, igraph::V(subgraph)$name)
lookup$gene_name <- gene_names$gene_name[
  match(gene_of[lookup$isoform], gene_names$gene_id)
]
rownames(lookup) <- NULL
head(lookup[, c("isoform", "gene_name", "is_seed", "degree",
                "distance_from_seed")])

## ----resolve------------------------------------------------------------------
map <- isonet_duplicate_map()
ids <- c("ENST00000427926.5", map$redundant_ENST[map$network_applicable][1])
resolved <- resolve_duplicate_isoforms(ids, network = get_network(obj))
attr(resolved, "dedup_audit")[, c("submitted_id", "resolved_id",
                                  "resolution")]

## ----aggregate----------------------------------------------------------------
counts <- matrix(
  c(10L, 4L, 7L,
    2L, 1L, 3L,
    5L, 5L, 5L),
  nrow = 3, byrow = TRUE,
  dimnames = list(c(map$kept_ENST[1], map$redundant_ENST[1], map$kept_ENST[2]),
                  paste0("sample", seq_len(3)))
)
features <- data.frame(
  gene_id = c(map$kept_ENSG[1], map$redundant_ENSG[1], map$kept_ENSG[2]),
  isoform_id = rownames(counts)
)
aggregated <- aggregate_duplicate_counts(counts, features)
aggregated$object

## ----isolated-----------------------------------------------------------------
vertices <- data.frame(
  name = c("tx_A_up", "tx_A_down", "tx_B", "tx_C"),
  gene = c("gene_A", "gene_A", "gene_B", "gene_C"),
  transcript_biotype = "protein_coding"
)
edges <- data.frame(from = c("tx_A_up", "tx_A_down"), to = "tx_B",
                    interact = 1L, pi = c(0.90, 0.75))
toy <- IsoNetAnalyzeR(
  "toy",
  network = igraph::graph_from_data_frame(edges, directed = FALSE,
                                          vertices = vertices),
  metadata = list(network_cutoff = 0)
)
toy_seeds <- data.frame(
  gene_id = c("gene_A", "gene_A", "gene_C", "gene_D"),
  isoform_id = c("tx_A_up", "tx_A_down", "tx_C", "tx_absent"),
  direction = c("up", "down", "up", "down")
)
toy <- run_differential_pulldown(toy, "toy", toy_seeds, order = 1,
                                 confirm = FALSE, verbose = FALSE)
isolated <- get_pulldown_graph(get_gene_result(toy, "toy", "gene_C"), "up")
c(nodes = igraph::vcount(isolated), edges = igraph::ecount(isolated))
is.null(get_pulldown_graph(get_gene_result(toy, "toy", "gene_D"), "down"))

## ----session-info-------------------------------------------------------------
sessionInfo()

