## ----setup, include=FALSE-----------------------------------------------------
knitr::opts_chunk$set(
    collapse  = TRUE,
    comment   = "#>",
    fig.align = "center",
    fig.width = 7,
    fig.height = 4.5,
    message   = FALSE
)
library(levi)
library(ggplot2)
extdata <- function(...) system.file("extdata", ..., package = "levi")

## ----calibration-files--------------------------------------------------------
val <- extdata("validation")
list.files(val)

## ----type1--------------------------------------------------------------------
type1 <- read.csv(file.path(val, "type1_error.csv"))
type1$benchmark <- ifelse(grepl("4 vs 4", type1$design), 1 / 35, 0.05)
type1$limits <- sprintf("%.3f to %.3f", type1$fwer_lo, type1$fwer_hi)
knitr::kable(
    data.frame(type1$test, type1$network, type1$design, type1$replicates,
               sprintf("%.3f", type1$fwer), type1$limits,
               sprintf("%.3f", type1$benchmark),
               sprintf("%.3f", type1$no_region)),
    col.names = c("Test", "Network", "Design", "Replicates",
                  "FWER at 0.05", "Wilson 95% limits", "Benchmark",
                  "No region detected"),
    align = "lllrrrrr",
    caption = "Family-wise error rate under the global null, with 95% Wilson
    limits. Benchmark: 1/35 = 0.029 for the 4 vs 4 exact rows (the only
    rejecting p-value is the floor 2/70) and 0.05 for the node-label rows. The
    last column is the fraction of replicates in which no region beyond the
    threshold was detected; these replicates are non-rejections.")

## ----null-ecdf, fig.height=4--------------------------------------------------
files <- list.files(val, pattern = "^null_pvalues_", full.names = TRUE)
nulls <- do.call(rbind, lapply(files, read.csv))
nulls <- nulls[is.finite(nulls$min_p), ]
ggplot(nulls, aes(x = min_p, colour = test)) +
    stat_ecdf(geom = "step", linewidth = 0.8) +
    geom_abline(slope = 1, intercept = 0, linetype = "dashed",
                colour = "grey40") +
    geom_vline(xintercept = 0.05, linetype = "dotted", colour = "grey40") +
    facet_wrap(~ network) +
    coord_cartesian(xlim = c(0, 1), ylim = c(0, 1)) +
    labs(x = "smallest p-value in a null replicate",
         y = "cumulative fraction of replicates", colour = NULL) +
    theme_minimal(base_size = 12) +
    theme(legend.position = "bottom")

## ----power--------------------------------------------------------------------
power <- read.csv(file.path(val, "power.csv"))
table(power$test, power$replicates)
ggplot(power, aes(x = effect, y = power, colour = test,
              linetype = module, group = interaction(test, module))) +
    geom_line(linewidth = 0.8) +
    geom_point(size = 2) +
    geom_hline(yintercept = 0.05, linetype = "dotted", colour = "grey40") +
    facet_wrap(~ network) +
    scale_y_continuous(limits = c(0, 1)) +
    labs(x = "shift of the module (SD of the per-gene noise)",
         y = "power at alpha = 0.05", colour = NULL, linetype = NULL) +
    theme_minimal(base_size = 12) +
    theme(legend.position = "bottom")

## ----circularity--------------------------------------------------------------
circ <- read.csv(file.path(val, "circularity.csv"))
knitr::kable(
    data.frame(circ$procedure, circ$design, circ$statistic, circ$datasets,
               sprintf("%.3f", circ$fwer),
               sprintf("%.3f to %.3f", circ$wilson_lo, circ$wilson_hi),
               sprintf("%.3f", circ$benchmark),
               sprintf("%.3f", circ$at_floor)),
    col.names = c("Procedure", "Design", "Statistic", "Datasets",
                  "FWER at 0.05", "Wilson 95% limits", "Benchmark",
                  "At floor"),
    align = "lllrrrrr",
    caption = "Rejection rate under the global null when the tested genes
    are selected from 2000 genes by absolute t. Benchmark: 1/35 = 0.029 for
    exact designs (4 vs 4 and the 4 vs 4 test half of the split sample),
    0.05 for Monte Carlo with 199 draws. At floor: fraction of datasets with
    p at the floor of the design, 2/70 for exact designs and 1/200 for Monte
    Carlo with 199 draws.")

## ----layout-------------------------------------------------------------------
lay <- read.csv(file.path(val, "layout_sensitivity.csv"))
lay_summary <- read.csv(file.path(val, "layout_sensitivity_summary.csv"))
knitr::kable(lay_summary, digits = 3,
    col.names = c("Mean pairwise Jaccard of significant genes", "Layouts",
                  "TFCE smallest p (layout-free)"))
summary(lay[, c("min_p", "n_regions", "n_sig_genes", "module_recovered")])

## ----airway-load--------------------------------------------------------------
aw <- function(f) extdata("airway", f)
genes   <- read.delim(aw("airway_dex_genes.tsv"))
logcpm  <- as.matrix(read.delim(aw("airway_dex_logcpm.tsv"), row.names = 1))
samples <- read.delim(aw("airway_dex_samples.tsv"))
nodes   <- read.delim(aw("airway_string_nodes.tsv"))
edges   <- read.delim(aw("airway_string_edges.tsv"))
c(genes = nrow(genes), nodes = nrow(nodes), edges = nrow(edges))
table(samples$cell, samples$dex)

## ----airway-landscape, fig.height=6-------------------------------------------
set.seed(1)
land <- levi(
    expressionInput          = genes,
    networkCoordinatesInput  = nodes,
    networkInteractionsInput = edges,
    fileTypeInput            = "stg",
    geneSymbolInput          = "Symbol",
    readExpColumn            = readExpColumn("log2FoldChange-log2FoldChange"),
    signal_mode              = "logfc",
    logfc_k                  = 0.7,
    resolutionValueInput     = 30,
    smoothValueInput         = 40,
    n_perm                   = 199)
land$regions$summary[, c("Region", "Direction", "Cells", "Mass", "PSpatial",
                         "Significant")]
head(leviRegionGenes(land, top_n = 5), 10)

## ----airway-blocked-----------------------------------------------------------
groups <- samples$dex
tfce_blocked <- tryCatch(
    leviGraphTFCEInference(logcpm, groups, nodes, edges, fileTypeInput = "stg",
        test = "trt", control = "untrt", blocks = samples$cell),
    warning = function(w) conditionMessage(w))
tfce_blocked

## ----airway-unblocked---------------------------------------------------------
# Descriptive: cell lines treated as exchangeable and genes selected on the
# same samples.
tfce <- leviGraphTFCEInference(logcpm, groups, nodes, edges,
    fileTypeInput = "stg", test = "trt", control = "untrt")
head(tfce$statistic[order(tfce$statistic$PGlobal), ], 8)

set.seed(1)
rep_land <- leviReplicateInference(logcpm, groups, test = "trt",
    control = "untrt", networkCoordinatesInput = nodes,
    networkInteractionsInput = edges, fileTypeInput = "stg",
    logfc_k = 0.7, resolutionValueInput = 30, smoothValueInput = 40)
rep_land$regions$summary[, c("Region", "Direction", "Mass", "PSpatial",
                             "Significant")]

## ----airway-rewiring----------------------------------------------------------
scores <- setNames(genes$stat, genes$Symbol)
set.seed(1)
rew <- leviGraphRewiringInference(scores, nodes, edges, fileTypeInput = "stg",
                                  threshold = 4, n_perm = 199)
# The STRING network of 78 genes has 40 distinct edges, so most clusters
# consist of a single gene. The connected clusters are shown.
clusters <- rew$regions$summary
clusters[clusters$Nodes >= 2,
         c("Region", "Direction", "Nodes", "Mass", "PeakGene", "PSpatial")]

## ----scripts, eval=FALSE------------------------------------------------------
# scripts <- system.file("scripts", package = "levi")
# # About 3 hours on four cores (192 minutes in the reported run); writes
# # inst/extdata/validation/*.csv. Arguments: workers, null replicates
# # (sample-label tests), null replicates (node-label test), power replicates
# # per cell, node-label power replicates.
# system2("Rscript", c(file.path(scripts, "10-calibration.R"),
#                      "4", "1000", "100", "100", "20"))
# # A few minutes plus the STRING download; writes inst/extdata/airway/*.tsv
# system2("Rscript", file.path(scripts, "11-airway-preprocess.R"))

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

