--- title: "Correlation networks for metabolomics data with MetVAE" author: "Huang Lin" date: "`r Sys.Date()`" output: BiocStyle::html_document vignette: > %\VignetteIndexEntry{Correlation networks for metabolomics data with MetVAE} %\VignetteEngine{knitr::rmarkdown} %\VignetteEncoding{UTF-8} --- ```{r setup, include = FALSE} knitr::opts_chunk$set(collapse = TRUE, comment = "#>") has_torch <- requireNamespace("torch", quietly = TRUE) && torch::torch_is_installed() stored <- readRDS(system.file("extdata", "metvae_example_fits.rds", package = "MetVAE")) ``` # Introduction MetVAE estimates a sparse correlation network among metabolites from an untargeted metabolomics abundance table. Three features of such data are addressed. 1. Zeros. A zero usually means that the metabolite was below the detection limit, not that it was absent. MetVAE treats zeros as left-censored values and imputes them with a variational autoencoder trained on the centered log-ratio (CLR) scale. 2. Covariates. Batch, age, or diet effects shared by many metabolites induce correlations that do not reflect metabolic relationships. MetVAE removes the effects of the covariates you name before estimating correlations. 3. Sparsity. Most metabolite pairs are not associated. MetVAE sets small correlations to zero, either by Fisher z-tests with a multiplicity correction (`sparse_by_p()`) or by the sparse estimation of correlation (SEC) estimator of Cui, Leng and Sun (2016) with a cross-validated penalty (`sparse_by_sec()`). The method and a full protocol are described in Lin et al. (2026). This package is the R implementation; a Python implementation is available as `metvae` on PyPI. # Installation MetVAE fits its model with the R package `torch`. After installing MetVAE, download the LibTorch library once. ```{r install, eval = FALSE} if (!requireNamespace("BiocManager", quietly = TRUE)) { install.packages("BiocManager") } BiocManager::install("MetVAE") torch::install_torch() ``` ```{r load} library(MetVAE) ``` ```{r no-torch-note, echo = FALSE, results = "asis"} if (!has_torch) { cat("LibTorch is not installed on the machine that built this", "vignette. The chunks that fit the model show their code, and the", "results are loaded from fits stored in the package.\n") } ``` # Simulated data We simulate 100 samples and 50 metabolites with 10 correlated pairs, an age effect, and a batch effect, and set the lowest 30 percent of the values of each metabolite to zero to mimic the detection limit. ```{r simulate} set.seed(7) meta <- data.frame(age = rnorm(100, mean = 50, sd = 8), batch = sample(c("A", "B"), 100, replace = TRUE), row.names = paste0("s", 0:99)) sim <- metvae_sim_data(n = 100, d = 50, cor_pairs = 10, mu = 10:14, x = meta, cont_list = "age", cat_list = "batch", seed = 7) censor <- function(y, prop) { th <- apply(y, 2, quantile, probs = prop) y[sweep(y, 2, th, "<")] <- 0 y } abundance <- censor(sim$y, 0.3) dim(abundance) mean(abundance == 0) abundance[1:4, 1:5] ``` MetVAE accepts a `SummarizedExperiment` with metabolites in rows and samples in columns, or a matrix or data.frame with samples in rows. Here we store the data in a `SummarizedExperiment` with the metadata in `colData`. ```{r se} library(SummarizedExperiment) se <- SummarizedExperiment(assays = list(abundance = t(abundance)), colData = meta) se ``` # Fitting the model `metvae()` filters metabolites with more than 30 percent zeros, transforms the data to the CLR scale, estimates the covariate effects with a censored normal model, removes them, and trains the autoencoder. ```{r fit, eval = has_torch} fit <- metvae(se, assay_name = "abundance", continuous_covariate_keys = "age", categorical_covariate_keys = "batch", learning_rate = 1e-2, verbose = FALSE) ``` ```{r fit-stored, include = FALSE, eval = !has_torch} fit <- stored$quickstart ``` ```{r print-fit} fit ``` The training loss decreases quickly and then varies with the cyclic learning rate. ```{r loss, fig.width = 6, fig.height = 3.5} plot(fit$train_loss, type = "l", log = "y", xlab = "Epoch", ylab = "Training loss") ``` # Estimating correlations `get_corr()` imputes the zeros 100 times, computes the correlation matrix of each completed data set, sets correlations below 0.2 in absolute value to zero, and averages the matrices. It returns the fit with the result added. ```{r corr, eval = has_torch} fit <- get_corr(fit) ``` ```{r corr-show} fit$corr$estimate[1:5, 1:5] ``` # Sparsification ## Fisher z-tests ```{r p} res_p <- sparse_by_p(fit, p_adj_method = "fdr_bh", cutoff = 0.05) names(res_p) res_p$sparse_estimate[1:5, 1:5] ``` ## SEC With `rho = NULL`, `sparse_by_sec()` chooses the penalty `rho = c * sqrt(log(p) / n)` by 5-fold cross-validation over `c` in 1, ..., 10 and a finer grid around the best value. ```{r sec, eval = has_torch} res_sec <- sparse_by_sec(fit) ``` ```{r sec-stored, include = FALSE, eval = !has_torch} res_sec <- stored$quickstart_sec ``` ```{r sec-show} res_sec$best_rho head(res_sec$scores_by_rho) ``` ## Comparison with the simulated truth ```{r truth} edge_summary <- function(est, truth) { lt <- lower.tri(truth) e <- as.matrix(est)[lt] != 0 t <- truth[lt] != 0 c(TPR = sum(e & t) / sum(t), FPR = sum(e & !t) / sum(!t), FDR = sum(e & !t) / max(sum(e), 1)) } round(rbind(p_value = edge_summary(res_p$sparse_estimate, sim$cor_matrix), sec = edge_summary(res_sec$sparse_estimate, sim$cor_matrix)), 3) ``` # Networks `export_graphml()` returns one `igraph` network per cutoff and, with `output_dir`, writes GraphML files that Cytoscape opens through File > Import > Network from File. ```{r network, fig.width = 6, fig.height = 5} graphs <- export_graphml(res_p, cutoffs = 0.5) g <- graphs[[1]] g plot(g, vertex.size = 6, vertex.label.cex = 0.6, edge.color = ifelse(igraph::E(g)$correlation > 0, "firebrick", "steelblue")) ``` An edge list for a spreadsheet: ```{r edges} head(igraph::as_data_frame(g, what = "edges")[, c("from", "to", "correlation")]) ``` # Covariate adjustment When a covariate shifts many metabolites at once, unadjusted correlations include the covariate effect. We simulate a batch effect on half of the metabolites and fit the model with and without the batch covariate. ```{r confounded-data} meta2 <- data.frame(batch = rep(c("A", "B"), each = 50), row.names = paste0("s", 0:99)) sim2 <- metvae_sim_data(n = 100, d = 40, cor_pairs = 8, mu = 10:14, x = meta2, cat_list = "batch", da_prop = 0.5, seed = 11) abundance2 <- censor(sim2$y, 0.2) ``` ```{r confounded-fit, eval = has_torch} fit_adj <- metvae(abundance2, meta = meta2, categorical_covariate_keys = "batch", learning_rate = 1e-2, max_epochs = 500, verbose = FALSE) fit_adj <- get_corr(fit_adj) fit_unadj <- metvae(abundance2, learning_rate = 1e-2, max_epochs = 500, verbose = FALSE) fit_unadj <- get_corr(fit_unadj) ``` ```{r confounded-stored, include = FALSE, eval = !has_torch} fit_adj <- stored$confounded_adjusted fit_unadj <- stored$confounded_unadjusted ``` ```{r confounded-compare} round(rbind( adjusted = edge_summary(sparse_by_p(fit_adj)$sparse_estimate, sim2$cor_matrix), unadjusted = edge_summary(sparse_by_p(fit_unadj)$sparse_estimate, sim2$cor_matrix)), 3) head(confound_coef(fit_adj)) ``` # Other outputs * `impute_zeros(fit, seed)` returns one completed CLR data set. * `confound_es(fit)` returns the covariate effect of each sample and metabolite. * `clr_loading(fit)` returns the decoder weights, and `cooccurrence(fit)` the squared distances between the loading vectors of metabolite pairs. ```{r other} dim(clr_loading(fit)) cooccurrence(fit)[1:3, 1:3] ``` # Reproducibility and saving `metvae()` uses `seed` for the model initialization and the batch order, and `get_corr()` uses it for the imputations unless another seed is given. On one machine with one version of the package `torch`, the same seeds give identical results. Different machines, linear algebra libraries, `torch` versions, or numbers of threads (`torch::torch_set_num_threads()`) can change the last digits. A fit contains only R objects and can be stored with `saveRDS(fit, "fit.rds")`. # References Cui Y, Leng C, Sun D (2016). Sparse estimation of high-dimensional correlation matrices. Computational Statistics and Data Analysis 93, 390-403. doi:10.1016/j.csda.2014.10.001 Lin H, Zhang L, Lotfi A, Jarmusch A, Lee I, Kim A, Morton JT, Aksenov A (2026). Protocol for constructing correlation-based molecular networks from large-scale untargeted metabolomics data. bioRxiv. doi:10.1101/2025.04.26.649581 # Session information ```{r session} sessionInfo() ```