Correlation networks for metabolomics data with 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.

if (!requireNamespace("BiocManager", quietly = TRUE)) {
    install.packages("BiocManager")
}
BiocManager::install("MetVAE")
torch::install_torch()
library(MetVAE)

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.

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.

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)
#> [1] 100  50
mean(abundance == 0)
#> [1] 0.3
abundance[1:4, 1:5]
#>          f0        f1           f2       f3        f4
#> s0 59211.33       0.0 1830532119.7 10629.73      0.00
#> s1 27777.41 8099839.9     571767.3     0.00 346917.27
#> s2     0.00 6034775.5          0.0     0.00  97376.15
#> s3 75094.99  795624.7          0.0 64480.94  36284.22

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.

library(SummarizedExperiment)
#> Loading required package: MatrixGenerics
#> Loading required package: matrixStats
#> 
#> Attaching package: 'MatrixGenerics'
#> The following objects are masked from 'package:matrixStats':
#> 
#>     colAlls, colAnyNAs, colAnys, colAvgsPerRowSet, colCollapse,
#>     colCounts, colCummaxs, colCummins, colCumprods, colCumsums,
#>     colDiffs, colIQRDiffs, colIQRs, colLogSumExps, colMadDiffs,
#>     colMads, colMaxs, colMeans2, colMedians, colMins, colOrderStats,
#>     colProds, colQuantiles, colRanges, colRanks, colSdDiffs, colSds,
#>     colSums2, colTabulates, colVarDiffs, colVars, colWeightedMads,
#>     colWeightedMeans, colWeightedMedians, colWeightedSds,
#>     colWeightedVars, rowAlls, rowAnyNAs, rowAnys, rowAvgsPerColSet,
#>     rowCollapse, rowCounts, rowCummaxs, rowCummins, rowCumprods,
#>     rowCumsums, rowDiffs, rowIQRDiffs, rowIQRs, rowLogSumExps,
#>     rowMadDiffs, rowMads, rowMaxs, rowMeans2, rowMedians, rowMins,
#>     rowOrderStats, rowProds, rowQuantiles, rowRanges, rowRanks,
#>     rowSdDiffs, rowSds, rowSums2, rowTabulates, rowVarDiffs, rowVars,
#>     rowWeightedMads, rowWeightedMeans, rowWeightedMedians,
#>     rowWeightedSds, rowWeightedVars
#> Loading required package: GenomicRanges
#> Loading required package: stats4
#> Loading required package: BiocGenerics
#> Loading required package: generics
#> 
#> Attaching package: 'generics'
#> The following objects are masked from 'package:base':
#> 
#>     as.difftime, as.factor, as.ordered, intersect, is.element, setdiff,
#>     setequal, union
#> 
#> Attaching package: 'BiocGenerics'
#> The following objects are masked from 'package:stats':
#> 
#>     IQR, mad, sd, var, xtabs
#> The following object is masked from 'package:utils':
#> 
#>     data
#> The following objects are masked from 'package:base':
#> 
#>     anyDuplicated, aperm, append, as.data.frame, basename, cbind,
#>     colnames, dirname, do.call, duplicated, eval, evalq, Filter, Find,
#>     get, grep, grepl, is.unsorted, lapply, Map, mapply, match, mget,
#>     order, paste, pmax, pmax.int, pmin, pmin.int, Position, rank,
#>     rbind, Reduce, rownames, sapply, saveRDS, scale, sequence, table,
#>     tapply, transform, unique, unsplit, which.max, which.min
#> Loading required package: S4Vectors
#> 
#> Attaching package: 'S4Vectors'
#> The following object is masked from 'package:utils':
#> 
#>     findMatches
#> The following objects are masked from 'package:base':
#> 
#>     expand.grid, I, unname
#> Loading required package: IRanges
#> Loading required package: Seqinfo
#> Loading required package: Biobase
#> Welcome to Bioconductor
#> 
#>     Vignettes contain introductory material; view with
#>     'browseVignettes()'. To cite Bioconductor, see
#>     'citation("Biobase")', and for packages 'citation("pkgname")'.
#> 
#> Attaching package: 'Biobase'
#> The following object is masked from 'package:MatrixGenerics':
#> 
#>     rowMedians
#> The following objects are masked from 'package:matrixStats':
#> 
#>     anyMissing, rowMedians
se <- SummarizedExperiment(assays = list(abundance = t(abundance)),
                           colData = meta)
se
#> class: SummarizedExperiment 
#> dim: 50 100 
#> metadata(0):
#> assays(1): abundance
#> rownames(50): f0 f1 ... f48 f49
#> rowData names(0):
#> colnames(100): s0 s1 ... s98 s99
#> colData names(2): age batch

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.

fit <- metvae(se, assay_name = "abundance",
              continuous_covariate_keys = "age",
              categorical_covariate_keys = "batch", learning_rate = 1e-2,
              verbose = FALSE)
fit
#> MetVAE fit
#>   samples:  100 (of 100)
#>   features: 50 (of 50)
#>   zeros imputed: 30.0%
#>   covariates: age, batch_B
#>   latent dimension: 50; encoder: linear
#>   training: 1000 epochs, final loss 69.4099
#>   correlations: 455 nonzero pairs

The training loss decreases quickly and then varies with the cyclic learning rate.

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.

fit <- get_corr(fit)
fit$corr$estimate[1:5, 1:5]
#> 5 x 5 sparse Matrix of class "dgCMatrix"
#>           f0          f1          f2         f3          f4
#> f0 1.0000000  0.55658085  .           .          .         
#> f1 0.5565809  1.00000000 -0.03451687  .         -0.03690548
#> f2 .         -0.03451687  1.00000000 -0.5203634  .         
#> f3 .          .          -0.52036340  1.0000000  .         
#> f4 .         -0.03690548  .           .          1.00000000

Sparsification

Fisher z-tests

res_p <- sparse_by_p(fit, p_adj_method = "fdr_bh", cutoff = 0.05)
names(res_p)
#> [1] "estimate"        "p_value"         "q_value"         "sparse_estimate"
res_p$sparse_estimate[1:5, 1:5]
#> 5 x 5 sparse Matrix of class "dgCMatrix"
#>           f0        f1         f2         f3 f4
#> f0 1.0000000 0.5565809  .          .          .
#> f1 0.5565809 1.0000000  .          .          .
#> f2 .         .          1.0000000 -0.5203634  .
#> f3 .         .         -0.5203634  1.0000000  .
#> f4 .         .          .          .          1

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.

res_sec <- sparse_by_sec(fit)
res_sec$best_rho
#> [1] 1.406495
head(res_sec$scores_by_rho)
#>   c       rho    score
#> 1 1 0.1977883 137.8119
#> 2 2 0.3955767 126.4050
#> 3 3 0.5933650 118.9286
#> 4 4 0.7911534 117.2391
#> 5 5 0.9889417 117.3956
#> 6 6 1.1867301 116.9338

Comparison with the simulated 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)
#>         TPR   FPR FDR
#> p_value 0.9 0.001 0.1
#> sec     0.7 0.000 0.0

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.

graphs <- export_graphml(res_p, cutoffs = 0.5)
g <- graphs[[1]]
g
#> IGRAPH ae616d0 UNW- 12 6 -- 
#> + attr: name (v/c), correlation (e/n), weight (e/n), EdgeScore (e/n),
#> | EdgeType (e/c), id (e/c)
#> + edges from ae616d0 (vertex names):
#> [1] f0 --f1  f2 --f3  f6 --f7  f10--f11 f12--f13 f14--f15
plot(g, vertex.size = 6, vertex.label.cex = 0.6,
     edge.color = ifelse(igraph::E(g)$correlation > 0, "firebrick",
                         "steelblue"))
#> Warning: Non-positive edge weight found, ignoring all weights during graph
#> layout.

An edge list for a spreadsheet:

head(igraph::as_data_frame(g, what = "edges")[, c("from", "to",
                                                  "correlation")])
#>   from  to correlation
#> 1   f0  f1   0.5565809
#> 2   f2  f3  -0.5203634
#> 3   f6  f7   0.7040733
#> 4  f10 f11   0.5179404
#> 5  f12 f13   0.5395125
#> 6  f14 f15  -0.5917641

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.

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)
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)
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)
#>            TPR   FPR   FDR
#> adjusted     1 0.001 0.111
#> unadjusted   1 0.345 0.971
head(confound_coef(fit_adj))
#>       batch_B
#> f0  0.9462579
#> f1  0.7028768
#> f2  0.8073133
#> f3 -0.9463296
#> f4 -1.9448077
#> f5 -0.7771308

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.
dim(clr_loading(fit))
#> [1] 50 50
cooccurrence(fit)[1:3, 1:3]
#>           f0        f1       f2
#> f0 0.0000000 0.3565964 1.148094
#> f1 0.3565964 0.0000000 1.171717
#> f2 1.1480939 1.1717170 0.000000

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

sessionInfo()
#> R version 4.6.2 (2026-10-29)
#> Platform: x86_64-pc-linux-gnu
#> Running under: Ubuntu 26.04.1 LTS
#> 
#> Matrix products: default
#> BLAS:   /usr/lib/x86_64-linux-gnu/openblas-pthread/libblas.so.3 
#> LAPACK: /usr/lib/x86_64-linux-gnu/openblas-pthread/libopenblasp-r0.3.32.so;  LAPACK version 3.12.0
#> 
#> locale:
#>  [1] LC_CTYPE=en_US.UTF-8       LC_NUMERIC=C              
#>  [3] LC_TIME=en_US.UTF-8        LC_COLLATE=en_US.UTF-8    
#>  [5] LC_MONETARY=en_US.UTF-8    LC_MESSAGES=en_US.UTF-8   
#>  [7] LC_PAPER=en_US.UTF-8       LC_NAME=C                 
#>  [9] LC_ADDRESS=C               LC_TELEPHONE=C            
#> [11] LC_MEASUREMENT=en_US.UTF-8 LC_IDENTIFICATION=C       
#> 
#> time zone: Etc/UTC
#> tzcode source: system (glibc)
#> 
#> attached base packages:
#> [1] stats4    stats     graphics  grDevices utils     datasets  methods  
#> [8] base     
#> 
#> other attached packages:
#>  [1] SummarizedExperiment_1.43.0 Biobase_2.73.2             
#>  [3] GenomicRanges_1.65.4        Seqinfo_1.3.2              
#>  [5] IRanges_2.47.5              S4Vectors_0.51.10          
#>  [7] BiocGenerics_0.59.13        generics_0.1.4             
#>  [9] MatrixGenerics_1.25.0       matrixStats_1.5.0          
#> [11] MetVAE_0.99.0               BiocStyle_2.41.0           
#> 
#> loaded via a namespace (and not attached):
#>  [1] sass_0.5.0          SparseArray_1.13.5  lattice_0.23-1     
#>  [4] digest_0.6.39       magrittr_2.0.5      evaluate_1.0.5     
#>  [7] grid_4.6.2          fastmap_1.2.0       jsonlite_2.0.0     
#> [10] Matrix_1.7-6        processx_3.10.0     torch_0.17.0       
#> [13] ps_1.9.3            BiocManager_1.30.27 coro_1.1.0         
#> [16] jquerylib_0.1.4     abind_1.4-8         cli_3.6.6          
#> [19] rlang_1.3.0         XVector_0.53.0      bit64_4.8.6        
#> [22] withr_3.0.3         cachem_1.1.0        DelayedArray_0.39.8
#> [25] yaml_2.3.12         otel_0.3.0          S4Arrays_1.13.3    
#> [28] tools_4.6.2         buildtools_1.0.0    R6_2.6.1           
#> [31] lifecycle_1.0.5     bit_4.6.0           pkgconfig_2.0.3    
#> [34] callr_3.8.0         bslib_0.12.0        Rcpp_1.1.2         
#> [37] xfun_0.62           sys_3.4.3           knitr_1.52         
#> [40] igraph_2.3.4        htmltools_0.5.9     rmarkdown_2.32     
#> [43] maketools_1.3.2     compiler_4.6.2