--- title: "levi: Calibration and a real dataset" author: - name: José Rafael Pilan affiliation: São Paulo State University (UNESP) - name: Agnes Alessandra Sekijima Takeda affiliation: São Paulo State University (UNESP) - name: José Luiz Rybarczyk Filho affiliation: São Paulo State University (UNESP) email: jose.luiz@unesp.br date: "`r Sys.Date()`" bibliography: bibliography.bib link-citations: true output: BiocStyle::html_document: toc: true toc_depth: 2 toc_float: true number_sections: true vignette: > %\VignetteIndexEntry{levi: Calibration and a real dataset} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r 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") ``` # Scope The unit tests of levi verify that the code computes what the documentation states. They do not verify that a nominal p-value has its stated meaning. This requires simulation: data generated without any effect should yield p-values that are uniform or conservative, and the family-wise error rate (FWER) should not exceed the nominal level. This vignette reports a simulation study of three tests and applies the same tests to a real RNA-seq experiment. The three calibrated tests are the node-label regional test of `levi()`, the sample-label regional test of `leviReplicateInference()` and the graph TFCE test of `leviGraphTFCEInference()`. The other inferential functions (`leviGraphClusterInference()`, `leviGraphMoran()`, `leviGraphGetisOrd()`, `leviGraphSpectrum()`, `leviGraphWeightedTopology()`, `leviGraphRewiringInference()`, `leviGraphTFCEFreedmanLane()` and the bulk and single-cell wrappers) were not calibrated in this study. In the manuscript, Moran's I, Getis-Ord G, the spectral statistic, the Freedman-Lane variant and the rewiring null were neither calibrated nor used on real data. The rewiring example in the airway section below illustrates the interface only. Bioconductor builds every vignette on every commit within a time budget. The simulations of `inst/scripts/10-calibration.R` took 192 minutes on four cores and are therefore not run at build time. Only summary tables are installed with the package, and the chunks of this vignette read and plot them. The summary of the selection simulation (`circularity.csv`) was produced by a separate script of the manuscript analyses and is not regenerated by `10-calibration.R`. For the real dataset, DESeq2 and the STRING query were run once by `inst/scripts/11-airway-preprocess.R`, and the vignette reads a few kilobytes of text files. Both scripts are self-contained and are run with `Rscript`. ```{r calibration-files} val <- extdata("validation") list.files(val) ``` # Type I error under the global null Each replicate is a dataset without any effect: independent standard normal values for every gene (node-label test) or 4 vs 4 samples drawn from the same distribution (sample-label tests). The FWER is the fraction of replicates in which the smallest p-value of the test was at most 0.05. A replicate in which no region beyond the threshold was detected is counted as a non-rejection (column *No region*). Each of the three calibrated tests takes the maximum of its statistic over regions or genes, and over both directions, in every permutation. This controls the search across regions or genes [@Westfall1993; @Nichols2002]. The FWER of these tests is therefore expected not to exceed the nominal 0.05 beyond Monte Carlo error. In the 4 vs 4 exact design the attainable p-values are 2j/70 (complementary arrangements tie), and the only value at or below 0.05 is the floor 2/70. The probability of that value is at most 1/35 = 0.029 for any statistic, which is the benchmark for those rows. The benchmark is 0.05 for the node-label rows, which use Monte Carlo shuffles. Two networks were used: the 30-node network shipped as `medusa.dat`, and a 300-node scale-free graph (Barabási-Albert, m = 2) laid out with Kamada-Kawai [@Kamada1989], which is closer in size and degree distribution to a STRING module. ```{r 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.") ``` The empirical cumulative distribution of the smallest p-value per replicate is shown below. Replicates without a detected region have no p-value and are omitted. A valid permutation test has a curve on or below the diagonal: the p-value is discrete, and ties between the observed and the permuted statistics increase it, so that the probability of a p-value at most x does not exceed x. In the 4 vs 4 exact design the p-values take the values 2j/70, and the curve is a step function whose first step is at 2/70 = 0.029 and whose height there is at most 1/35. For the node-label test the p-values are multiples of 1/1000. A curve above the diagonal at small p-values would indicate anti-conservative p-values. ```{r 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 against effect size Two responding modules of eight genes were used. The hub module consists of the node of highest degree and its seven nearest neighbours by shortest-path distance. The path module is a path of eight nodes that starts at the node of lowest degree from which such a path can be grown and is extended through the unvisited neighbour of lowest degree. It is not required to be an induced path: the eight nodes share 15 edges in the 30-node network and 7 edges (those of the path) in the 300-node network. The hub module has 22 edges among its nodes in the 30-node network and 13 in the 300-node network. The treated samples of the module were shifted by `effect` in a 4 vs 4 design. The unit of `effect` is the standard deviation of the per-gene noise: the values are independent standard normal (SD = 1) and the shift is added to the treated samples. The simulated values are treated as log-scale values, so the shift is also the difference between the group means in log units. Power is the fraction of datasets in which at least one region (or, for TFCE, at least one gene) reached p <= 0.05. Three tests were applied to the same data: the sample-label regional test (landscape), graph TFCE (both under the sample-label null with exact enumeration, floor 2/70) and the node-label regional test applied to the log fold change of the 4 vs 4 comparison, with 999 shuffles. Each cell of the figure has 100 datasets for the sample-label regional test and graph TFCE and 20 datasets for the node-label test (`replicates` in `power.csv`). ```{r 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") ``` The pattern in `power.csv` is as follows. * **Hub module.** Graph TFCE had a power greater than or equal to that of the sample-label regional test at every effect size on both networks. On the 30-node network the powers at effect 1, 1.5 and 2 were 0.20, 0.72 and 0.95 for TFCE and 0.14, 0.40 and 0.83 for the regional test. On the 300-node network they were 0.19, 0.56 and 0.86 for TFCE and 0.03, 0.03 and 0.04 for the regional test. * **Path module on the 30-node network.** The two tests were close: 0.24 (both) at effect 1, 0.49 (regional) and 0.58 (TFCE) at 1.5, and 0.76 and 0.88 at 2. * **Path module on the 300-node network.** The regional test had power 0.04 or less at every effect size, and TFCE reached 0.40 at effect 1.5 and 0.89 at effect 2. * **Node-label test.** It detected the shift in 0 to 3 of 20 datasets per cell (power 0 to 0.15). It tests the position of the signal given the layout and not whether a module is shifted. The simulation does not isolate the cause of the low power of the regional test on the 300-node network. The mass of the region is area-weighted, the module of eight genes is small relative to the network, and the edge midpoints that join shifted and unshifted nodes carry intermediate signals; with the default `edge_weighting = "midpoint"` the weighting of the landscape by degree is described in `?levi`. The effect of `edge_weighting` on power was not evaluated here. When the question is whether a module responds across replicates, `leviGraphTFCEInference()` and `leviGraphClusterInference()` address it without the landscape, and the landscape shows the position of the responding region. In the 4 vs 4 design a result at the 0.05 level requires the observed arrangement to be the most extreme of the 35 pairs of complementary arrangements (p = 2/70). Power at a given effect is the probability of that event. The power of the two sample-label tests at effect 0.5 ranged from 0.00 to 0.10 across the four cells, which is near the null rejection rates of the type I table. # Selection before testing A sample-label test is a replication test only if the network and its gene set are fixed independently of the labels that are permuted (`vignette("levi_inference")`, section *Validity condition for sample-label tests*). The simulation below quantifies the consequence of violating this condition. The data were 2000 independent standard normal genes without any effect, with 4 vs 4 samples (exact enumeration, 70 arrangements) or 8 vs 8 samples (Monte Carlo with 199 draws). The 30 genes with the largest absolute t statistic were placed on the `medusa` network through a random bijection drawn once per dataset, and the sample-label regional test and graph TFCE were computed with three procedures, with 200 datasets per design: * **fixed selection**: the genes were selected on the observed labels and held fixed during the permutations; * **closed loop**: the selection was repeated inside every permutation, on the permuted labels; * **split sample**: the genes were selected on one half of the samples and the test was performed on the other half (4 vs 4, exact). The simulation models the selection of values on a fixed topology. It does not model the selection of connectivity. ```{r 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.") ``` Holding the selected genes fixed gave rejection rates of 0.850 to 0.870 with 4 vs 4 samples, every rejection at p = 2/70, and 0.990 to 1.000 with 8 vs 8 samples, with 72 to 75 % of the datasets at the Monte Carlo floor 1/200. The Wilson limits of these rows are far from the benchmark. Re-selection inside each permutation gave 0.015 to 0.060, and selection on separate samples gave 0.045 and 0.055 with 200 datasets and 0.031 and 0.034 with 2000 datasets. The Wilson limits cover the benchmark in every closed-loop and split-sample row except the split-sample TFCE row with 200 datasets (11 of 200; limits 0.031 to 0.096; benchmark 0.029). With 2000 datasets the limits of that row are 0.027 to 0.042 and cover the benchmark, and the excess in the 200-dataset row is consistent with Monte Carlo variation. Consequently, sample-label and graph TFCE results on a network built from genes selected on the tested samples are descriptive. The valid designs are a network fixed a priori, closed-loop selection by rank and split-sample selection. The airway example below belongs to none of these categories, because its genes were selected on the tested samples. # Dependence on the layout The landscape is computed over node coordinates, and force-directed layouts are stochastic. The same 300-node graph and the same expression data were laid out twenty times with Fruchterman-Reingold [@Fruchterman1991], and the node-label regional test was run on each layout. A comparison of the genes attributed to significant regions is informative only if the test rejects, and the effect was therefore set to a large value: a 20-gene module around the hub shifted by 3 SD (SD of the per-gene noise), with smoothing 20. Per layout the table reports the smallest regional p-value, the number of genes attributed to significant regions (`leviRegionGenes()` with the five strongest supporters per region, so that one significant region yields at most five genes) and the fraction of the true module among them. The summary reports the mean pairwise Jaccard similarity of these gene sets. Graph TFCE uses only the nodes and edges and is invariant to the layout by construction; its smallest p-value is shown for reference. ```{r 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")]) ``` The table quantifies the dependence of the node-label regional test on the layout. The test is conditional on the layout of the network, and the layout is part of the test. Conclusions that must not depend on the layout require the graph-native tests. # A real dataset: dexamethasone in airway smooth muscle The `airway` experiment [@Himes2014] measured RNA-seq in four airway smooth muscle cell lines, each treated with dexamethasone and left untreated. DESeq2 [@Love2014] with the model `~ cell + dex` was run once, offline. The 80 genes with the smallest adjusted p-value (ties broken by the absolute Wald statistic) were retained, and 78 of them were recognised by STRING [@Szklarczyk2021]. Their STRING interactions (combined score >= 400) with a Kamada-Kawai layout and their per-sample log2 CPM were saved as text files. The provenance is documented in `inst/extdata/airway/README.md`. The genes were therefore selected on the same eight samples that are tested below. ```{r 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) ``` The edge table lists each interaction in both directions, so that its 80 rows correspond to 40 distinct edges. ## The landscape and its node-label test ```{r 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) ``` The node-label null is conditional on the network and the layout. It tests whether the 78 fold changes are arranged on this layout more coherently than random assignments of the same values. The result is a valid statement about the spatial organisation of this network: fold changes of similar sign are located together in this layout to a degree that exceeds that of random assignments, if the p-value is small. All genes were selected for their response, and the network contains only the genes that interact in STRING. The node-label result does not address replication. ## Sample-label tests (descriptive) The eight samples allow the sample-label null. The design that matches the DESeq2 model `~ cell + dex` uses the cell line as a block. With the cell line as block, each cell line contributes one within-line swap, which gives 2^4 = 16 arrangements. The complementary arrangement ties the observed statistic, so the p-value floor is 2/16 = 0.125. The package reports that no result of the test can reach 0.05: ```{r 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 ``` The unblocked test has 70 arrangements (floor 2/70 = 0.029). It treats the cell lines as exchangeable, which contradicts the model `~ cell + dex`: the problem is the violated exchangeability, and not the amount of noise. In addition, the genes were selected on the same eight samples (previous section and *Selection before testing*). The output of the unblocked tests is **descriptive** and is not evidence of replication. ```{r 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")] ``` ## Dependence on the wiring (descriptive) ```{r 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")] ``` The rewiring null [@Maslov2002] keeps the Wald statistic of every gene and the degree of every node, and tests whether the clusters of strongly responding genes depend on the specific STRING wiring. A small p-value indicates that the responding genes are connected to one another more than their degrees alone predict. The test is conditional on the gene scores, the genes were selected on the same samples, and the result is descriptive. The rewiring test was not calibrated in this study. # Reproducing the study ```{r 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 information ```{r session} sessionInfo() ``` # References