## ----setup, include=FALSE-----------------------------------------------------
knitr::opts_chunk$set(
    eval = TRUE,
    collapse = TRUE,
    comment = "#>",
    fig.width = 6,
    fig.height = 5
)
library(scGraphVerse)

## ----ground-truth-network, fig.alt="Network visualization gtruth"-------------
# Load the toy ground truth adjacency matrix
data(toy_adj_matrix)
adj_truth <- toy_adj_matrix

# Visualize network
if (requireNamespace("igraph", quietly = TRUE) &&
    requireNamespace("ggraph", quietly = TRUE)) {
    gtruth <- igraph::graph_from_adjacency_matrix(adj_truth,mode="undirected")
    ggraph::ggraph(gtruth, layout = "fr") +
        ggraph::geom_edge_link(color = "gray") +
        ggraph::geom_node_point(color = "steelblue") +
        ggplot2::ggtitle(paste0(
            "Ground Truth: ",
            igraph::vcount(gtruth),
            " nodes, ",
            igraph::ecount(gtruth),
            " edges"
        )) +
        ggplot2::theme_minimal()
}

## ----simulate-----------------------------------------------------------------
# Simulation parameters
nodes <- nrow(adj_truth)
sims <- zinb_simdata(
    n = 50,
    p = nodes,
    B = adj_truth,
    mu_range = list(c(1, 4), c(1, 7)),
    mu_noise = c(1, 3),
    theta = c(1, 0.7),
    pi = c(0.2, 0.2),
    kmat = 2,
    depth_range = c(0.8 * nodes * 3, 1.2 * nodes * 3)
)
# Transpose to cells × genes
count_matrices <- lapply(sims, t)

## ----genie3-------------------------------------------------------------------
# Create MultiAssayExperiment from count matrices
mae <- create_mae(count_matrices)

# Infer networks
networks_joint <- infer_networks(
    count_matrices_list = mae,
    method = "GENIE3",
    nCores = 1
)

# Generate weighted adjacency matrices (returns SummarizedExperiment)
wadj_se <- generate_adjacency(networks_joint)

# Symmetrize weights (returns SummarizedExperiment)
swadj_se <- symmetrize(wadj_se, weight_function = "mean")

## ----roc, fig.alt="ROC curve"-------------------------------------------------
if (requireNamespace("pROC", quietly = TRUE)) {
    roc_res <- plotROC(
        swadj_se,
        adj_truth,
        plot_title = "ROC Curve: GENIE3 Network Inference",
        is_binary = FALSE
    )
    roc_res$plot
    auc_joint <- roc_res$auc
}

## ----cutoff, fig.alt="result Graphs"------------------------------------------
# Binary cutoff at 95th percentile (returns SummarizedExperiment)
binary_se <- cutoff_adjacency(
    count_matrices = mae,
    weighted_adjm_list = swadj_se,
    n = 1,
    method = "GENIE3",
    quantile_threshold = 0.95,
    nCores = 1,
    debug = TRUE
)

# Precision scores
pscores_joint <- pscores(adj_truth, binary_se)
head(pscores_joint)

# Network plot
if (requireNamespace("ggraph", quietly = TRUE)) {
    plotg(binary_se)
}

## ----consensus, fig.alt="consensus Graph"-------------------------------------
# Consensus matrix (returns SummarizedExperiment)
consensus <- create_consensus(binary_se, method = "vote")

# Plot consensus network
if (requireNamespace("ggraph", quietly = TRUE)) {
    plotg(consensus)
}

## ----communities-adj-truth, fig.alt="Community detection adj_truth"-----------
# Compare consensus to truth using classify_edges and plot_network_comparison
if (requireNamespace("ggplot2", quietly = TRUE) &&
    requireNamespace("ggraph", quietly = TRUE)) {
    # Wrap toy_adj_matrix in a SummarizedExperiment for classify_edges
    adj_truth_se <- build_network_se(list(ground_truth = adj_truth))

    # classify_edges expects SummarizedExperiment objects
    edge_classification <- classify_edges(
        consensus_matrix = consensus,
        reference_matrix = adj_truth_se
    )

    print(edge_classification)

    # Visualize network comparison (show_fp = FALSE to hide false positives)
    comparison_plot <- plot_network_comparison(
        edge_classification = edge_classification,
        show_fp = FALSE
    )

    print(comparison_plot)
}

## ----communities-gtruth, fig.alt="Community detection gtruth"-----------------
if (requireNamespace("igraph", quietly = TRUE)) {
    comm_truth <- community_path(adj_truth)
}

## ----communities-consensus, fig.alt="Community detection consensus"-----------
# Detect communities in consensus network
if (requireNamespace("igraph", quietly = TRUE)) {
    comm_cons <- community_path(consensus)
}

## ----community-similarity, fig.alt="Community similarity metrics"-------------
# Calculate community metrics (VI, NMI, ARI)
if (requireNamespace("igraph", quietly = TRUE)) {
    comm_metrics <- compute_community_metrics(comm_truth, list(comm_cons))
    print(comm_metrics)

    # Calculate topology metrics (modularity, density, etc.)
    # Note: compute_topology_metrics expects community_path outputs
    # Returns a list with $topology_measures and $control_topology
    topo_metrics <- compute_topology_metrics(comm_truth, list(comm_cons))
    print(topo_metrics)

    # Visualize community comparison
    if (requireNamespace("fmsb", quietly = TRUE)) {
        plot_community_comparison(
            community_metrics = comm_metrics,
            topology_measures = topo_metrics$topology_measures,
            control_topology = topo_metrics$control_topology
        )
    }
}

## ----edge-mining--------------------------------------------------------------
em <- edge_mining(
    consensus,
    ground_truth = adj_truth,
    query_edge_types = "TP"
)
head(em[[1]])

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

