Last updated: 2020-04-28

Checks: 7 0

Knit directory: mr_mash_test/

This reproducible R Markdown analysis was created with workflowr (version 1.6.1). The Checks tab describes the reproducibility checks that were applied when the results were created. The Past versions tab lists the development history.


Great! Since the R Markdown file has been committed to the Git repository, you know the exact version of the code that produced these results.

Great job! The global environment was empty. Objects defined in the global environment can affect the analysis in your R Markdown file in unknown ways. For reproduciblity it’s best to always run the code in an empty environment.

The command set.seed(20200328) was run prior to running the code in the R Markdown file. Setting a seed ensures that any results that rely on randomness, e.g. subsampling or permutations, are reproducible.

Great job! Recording the operating system, R version, and package versions is critical for reproducibility.

Nice! There were no cached chunks for this analysis, so you can be confident that you successfully produced the results during this run.

Great job! Using relative paths to the files within your workflowr project makes it easier to run your code on other machines.

Great! You are using Git for version control. Tracking code development and connecting the code version to the results is critical for reproducibility.

The results in this page were generated with repository version 9bdcd02. See the Past versions tab to see a history of the changes made to the R Markdown and HTML files.

Note that you need to be careful to ensure that all relevant files for the analysis have been committed to Git prior to generating the results (you can use wflow_publish or wflow_git_commit). workflowr only checks the R Markdown file, but you know if there are other scripts or data files that it depends on. Below is the status of the Git repository when the results were generated:


Ignored files:
    Ignored:    .sos/
    Ignored:    code/fit_mr_mash.66662433.err
    Ignored:    code/fit_mr_mash.66662433.out
    Ignored:    dsc/.sos/
    Ignored:    dsc/outfiles/
    Ignored:    output/dsc.html
    Ignored:    output/dsc/
    Ignored:    output/dsc_OLD.html
    Ignored:    output/dsc_OLD/

Untracked files:
    Untracked:  code/plot_test.R
    Untracked:  dsc/dsc.scripts.html

Unstaged changes:
    Modified:   dsc/midway2.yml

Note that any generated files, e.g. HTML, png, CSS, etc., are not included in this status report because it is ok for generated content to have uncommitted changes.


These are the previous versions of the repository in which changes were made to the R Markdown (analysis/results_corrX_lowcorrV_indepB_OLD.Rmd) and HTML (docs/results_corrX_lowcorrV_indepB_OLD.html) files. If you’ve configured a remote Git repository (see ?wflow_git_remote), click on the hyperlinks in the table below to view the files as they were in that past version.

File Version Author Date Message
html 3d61182 fmorgante 2020-04-28 Build site.
html 8ed3a7f fmorgante 2020-04-28 Build site.
html f2fa981 fmorgante 2020-04-28 Build site.
Rmd 51cea81 fmorgante 2020-04-28 Add newest results

###Set options
options(stringsAsFactors=FALSE)

###Load libraries
library(dscrutils)
library(ggplot2)
library(cowplot)
library(scales)

###Function to convert dscquery output from list to data.frame suitable for plotting
convert_dsc_to_dataframe <- function(dsc){
  ###Data.frame to store the results after convertion
  dsc_df <- data.frame()
  
  ###Get length of list elements 
  n_elem <- length(dsc$DSC)
  
  ###Loop through the dsc list
  for(i in 1:n_elem){
    ##Prepare vectors making up the final data frame
    r_scalar <- dsc$simulate.r[i]
    repp <- rep(dsc$DSC[i], times=r_scalar)
    n <- rep(dsc$simulate.n[i], times=r_scalar)
    p <- rep(dsc$simulate.p[i], times=r_scalar)
    p_causal <- rep(dsc$simulate.p_causal[i], times=r_scalar)
    r <- rep(dsc$simulate.r[i], times=r_scalar)
    response <- 1:r_scalar
    pve <- rep(dsc$simulate.pve[i], times=r_scalar)
    simulate <- rep(dsc$simulate[i], times=r_scalar)
    fit <- rep(dsc$fit[i], times=r_scalar)
    score <- rep(dsc$score[i], times=r_scalar)
    score.err <- dsc$score.err[[i]]
    timing <- rep(dsc$fit.time[i], times=r_scalar)
    
    ##Build the data frame
    df <- data.frame(rep=repp, n=n, p=p, p_num_caus=p_causal, r=r, response=response, pve=pve,  
                     scenario=simulate, method=fit, score_metric=score, score_value=score.err, time=timing)
    dsc_df <- rbind(dsc_df, df)
  }
  
  return(dsc_df)
}

###Function to compute rmse (relative to mr_mash_consec_em)
compute_rmse <- function(dsc_plot, log10_scale=FALSE){
  dsc_plot <- transform(dsc_plot, experiment=paste(rep, response, scenario, sep="-"))
  t <- 0
  for (i in unique(dsc_plot$experiment)) {
    t <- t+1
    rmse_data  <- dsc_plot[which(dsc_plot$experiment == i & dsc_plot$score_metric=="mse"), ]
    mse_mr_mash_consec_em <- rmse_data[which(rmse_data$method=="mr_mash_consec_em"), "score_value"]
    if(!log10_scale)
      rmse_data$score_value <- rmse_data$score_value/mse_mr_mash_consec_em
    else
      rmse_data$score_value <- log10(rmse_data$score_value/mse_mr_mash_consec_em)
    rmse_data$score_metric <- "rmse"
    if(t>1){
      rmse_data_tot <- rbind(rmse_data_tot, rmse_data)
    } else if(t==1){
      rmse_data_tot <- rmse_data
    }
  }
  
  rmse_data_tot$experiment <- NULL
  
  return(rmse_data_tot)
}

###Function to shift legend in the empty facet
shift_legend <- function(p) {
  library(gtable)
  library(lemon)
  # check if p is a valid object
  if(!(inherits(p, "gtable"))){
    if(inherits(p, "ggplot")){
      gp <- ggplotGrob(p) # convert to grob
    } else {
      message("This is neither a ggplot object nor a grob generated from ggplotGrob. Returning original plot.")
      return(p)
    }
  } else {
    gp <- p
  }
  
  # check for unfilled facet panels
  facet.panels <- grep("^panel", gp[["layout"]][["name"]])
  empty.facet.panels <- sapply(facet.panels, function(i) "zeroGrob" %in% class(gp[["grobs"]][[i]]), 
                               USE.NAMES = F)
  empty.facet.panels <- facet.panels[empty.facet.panels]
  
  if(length(empty.facet.panels) == 0){
    message("There are no unfilled facet panels to shift legend into. Returning original plot.")
    return(p)
  }
  
  # establish name of empty panels
  empty.facet.panels <- gp[["layout"]][empty.facet.panels, ]
  names <- empty.facet.panels$name
  
  # return repositioned legend
  reposition_legend(p, 'center', panel=names)
}

###Set some quantities used in the following plots
colors <- c("skyblue", "dodgerblue", "limegreen", "green", "gold", "orange", "red", "firebrick")
facet_labels <- c(r2 = "r2", bias = "bias", rmse="RMSE (relative to consec_em)")
###Load the dsc results
dsc_out <- dscquery("output/dsc_OLD", c("simulate.n", "simulate.p", "simulate.p_causal", "simulate.r",   
                                 "simulate.pve", "simulate.Sigma_cor_offdiag", "simulate.Sigma_scale",
                                 "simulate.Gamma_cor_offdiag", "simulate.Gamma_scale",
                                 "simulate.V_cor_offdiag", "simulate.V_offdiag_scale", "simulate.prop_testset",
                                 "simulate", "fit", "score", "score.err", "fit.time"), 
                    conditions = "$(simulate) == 'corrX_lowcorrV_indepB'", verbose=FALSE,
                    ignore.missing.files = TRUE )

###Obtain simulation parameters
n <- unique(dsc_out$simulate.n)
p <- unique(dsc_out$simulate.p)
p_causal <- unique(dsc_out$simulate.p_causal)
r <- unique(dsc_out$simulate.r)
k <- 166
pve <- unique(dsc_out$simulate.pve)
prop_testset <- unique(dsc_out$simulate.prop_testset)
Sigma_cor_offdiag <- unique(dsc_out$simulate.Sigma_cor_offdiag)
Sigma_scale <- unique(dsc_out$simulate.Sigma_scale)
Gamma_cor_offdiag <- unique(dsc_out$simulate.Gamma_cor_offdiag)
Gamma_scale <- unique(dsc_out$simulate.Gamma_scale)
V_cor_offdiag <- unique(dsc_out$simulate.V_cor_offdiag)
V_offdiag_scale <- unique(dsc_out$simulate.V_offdiag_scale)

Sigma <- mr.mash.alpha:::create_cov_canonical(r, singletons=FALSE, hetgrid=Sigma_cor_offdiag)[[1]]*Sigma_scale
Gamma <- mr.mash.alpha:::create_cov_canonical(p, singletons=FALSE, hetgrid=Gamma_cor_offdiag)[[1]]*Gamma_scale
V <- mr.mash.alpha:::create_cov_canonical(r, singletons=FALSE, hetgrid=V_cor_offdiag)[[1]]*V_offdiag_scale

###Remove list elements that are not useful anymore
dsc_out$simulate.prop_testset <- NULL
dsc_out$simulate.Sigma_cor_offdiag <- NULL
dsc_out$simulate.Sigma_scale <- NULL
dsc_out$simulate.Gamma_cor_offdiag <- NULL
dsc_out$simulate.Gamma_scale <- NULL
dsc_out$simulate.V_cor_offdiag <- NULL
dsc_out$simulate.V_offdiag_scale <- NULL

The results below are based on 50 simulations with 600 samples, 1000 variables of which 50 were causal, 10 responses with a per-response proportion of variance explained (PVE) of 0.5. Variables, X, were drawn from MVN(0, Gamma), causal effects, B, were drawn from MVN(0, Sigma). The responses, Y, were drawn from MN(XB, I, V). Below are the covariance matrices used. Note that the diagonal elements of V were then adjusted to produce the desired PVE.

cat("Gamma (First 5 elements)")
Gamma (First 5 elements)
Gamma[1:5, 1:5]
     [,1] [,2] [,3] [,4] [,5]
[1,]  0.8  0.4  0.4  0.4  0.4
[2,]  0.4  0.8  0.4  0.4  0.4
[3,]  0.4  0.4  0.8  0.4  0.4
[4,]  0.4  0.4  0.4  0.8  0.4
[5,]  0.4  0.4  0.4  0.4  0.8
cat("Sigma (First 5 elements)")
Sigma (First 5 elements)
Sigma[1:5, 1:5]
     [,1] [,2] [,3] [,4] [,5]
[1,]  0.8  0.0  0.0  0.0  0.0
[2,]  0.0  0.8  0.0  0.0  0.0
[3,]  0.0  0.0  0.8  0.0  0.0
[4,]  0.0  0.0  0.0  0.8  0.0
[5,]  0.0  0.0  0.0  0.0  0.8
cat("V (First 5 elements)")
V (First 5 elements)
V[1:5, 1:5]
     [,1] [,2] [,3] [,4] [,5]
[1,] 1.00 0.15 0.15 0.15 0.15
[2,] 0.15 1.00 0.15 0.15 0.15
[3,] 0.15 0.15 1.00 0.15 0.15
[4,] 0.15 0.15 0.15 1.00 0.15
[5,] 0.15 0.15 0.15 0.15 1.00

mr.mash was fitted to the training data (80% of the data) updating V and updating the prior weights. We investigate a few combinations of methods to update the prior weights (i.e., EM and mixSQP), orderings of the coordinate ascent updates (i.e., consecutive and decreasing logBF from a multivariate simple linear regression with MASH prior), and initialization of the posterior means of the regression coefficients (i.e., 0, from mr.ash assuming independent effects across tissues, and from mr.ash assuming shared effects across tissues). The mixture prior consisted of 166 components defined by a few canonical matrices correpsonding to different settings of effect sharing/specificity (i.e., zero, singletons, independent, low heterogeneity, medium heterogeneity, high heterogeneity, shared) scaled by a grid of values (i.e., from 0.1 to 2.1 in steps of 0.2). The same grid was used in mr.ash with the addition of 0. Convergence was declared when the maximum difference in the posterior mean of the regression coefficients between two successive iterations was smaller than 1e-4.

Then, responses were predicted on the test data (20% of the data).

Here, we evaluate the accuracy of prediction assessed by \(r^2\) and bias (slope) from the regression of the true response on the predicted response, and the relative mean square error (RMSE) in the test data. The boxplots are across simulations and responses.

###Convert from list to data.frame for plotting
dsc_plots <- convert_dsc_to_dataframe(dsc_out)

###Compute rmse score (relative to mr_mash_consec_em) and add it to the data
rmse_dat <- compute_rmse(dsc_plots)
dsc_plots <- rbind(dsc_plots, rmse_dat)

###Remove mse from scores
dsc_plots <- dsc_plots[which(dsc_plots$score_metric!="mse"), ]

###Create factor version of method
###Create factor version of method
dsc_plots$method_fac <- factor(dsc_plots$method, levels=c("mr_mash_consec_em", "mr_mash_consec_em_init_indep",
                                                        "mr_mash_consec_em_init_shared", "mr_mash_declogBF_em",
                                                        "mr_mash_consec_mixsqp", "mr_mash_consec_mixsqp_init_indep", 
                                                        "mr_mash_consec_mixsqp_init_shared", "mr_mash_declogBF_mixsqp"),
                                                labels=c("consec_em", "consec_em_mrash_indep", "consec_em_mrash_shared",
                                                         "decrease_logBF_em", "consec_mixsqp", "consec_mixsqp_mrash_indep", 
                                                         "consec_mixsqp_mrash_shared", "decrease_logBF_mixsqp"))

###Build data.frame with best accuracy achievable
hlines <- data.frame(score_metric=c("r2", "bias"), max_val=c(unique(dsc_plots$pve), 1))

###Create plots
p <- ggplot(dsc_plots, aes_string(x = "method_fac", y = "score_value", fill = "method_fac")) +
    geom_boxplot(color = "black", outlier.size = 1, width = 0.85) +
    facet_wrap(vars(score_metric), scales="free_y", ncol=2, labeller=labeller(score_metric=facet_labels)) +
    scale_fill_manual(values = colors) +
    labs(x = "", y = "Accuracy", title = "Prediction accuracy", fill="Method") +
    geom_hline(data=hlines, aes(yintercept = max_val), linetype="dashed", size=1) +
    theme_cowplot(font_size = 20) +
    theme(axis.line.x = element_blank(), axis.text.x = element_blank(), axis.ticks.x = element_blank(),
          plot.title = element_text(hjust = 0.5))

shift_legend(p)

Version Author Date
f2fa981 fmorgante 2020-04-28

Let’s now remove outliers from the RMSE plot to make things a little clearer.

p_rmse_nooutliers <- ggplot(dsc_plots[which(dsc_plots$score_metric=="rmse"), ], aes_string(x = "method_fac", y = "score_value", fill = "method_fac")) +
  Ipaper::geom_boxplot2(color = "black", outlier.size = 1, width = 0.85, width.errorbar = 0) +
  scale_fill_manual(values = colors) +
  labs(x = "", y = "Accuracy", title = "RMSE (relative to consec_em)", fill="Method") +
  theme_cowplot(font_size = 20) +
  theme(axis.line.x = element_blank(), axis.text.x = element_blank(), axis.ticks.x = element_blank(),
        plot.title = element_text(hjust = 0.5))

print(p_rmse_nooutliers)

Version Author Date
f2fa981 fmorgante 2020-04-28

Here, we look at the elapsed time (\(log_{10}\) seconds) of mr.mash. Note that this time does not include the run time of mr.ash in the cases where we used it to initialize the posterior means of the regression coefficients.

dsc_plots_time <- dsc_plots[which(dsc_plots$response==1 & dsc_plots$score_metric=="r2"), 
                          -which(colnames(dsc_plots) %in% c("score_metric", "score_value", "response"))]

p_time <- ggplot(dsc_plots_time, aes_string(x = "method_fac", y = "time", fill = "method_fac")) +
  geom_boxplot(color = "black", outlier.size = 1, width = 0.85) +
  scale_fill_manual(values = colors) +
  scale_y_continuous(trans="log10", breaks = trans_breaks("log10", function(x) 10^x),
                      labels = trans_format("log10", math_format(10^.x))) +
  labs(x = "", y = "Elapsed time (seconds) in log10 scale",title = "Run time", fill="Method") +
  theme_cowplot(font_size = 20) +
  theme(axis.line.x = element_blank(), axis.text.x = element_blank(), axis.ticks.x = element_blank(),
        plot.title = element_text(hjust = 0.5))

print(p_time)

Version Author Date
f2fa981 fmorgante 2020-04-28

sessionInfo()
R version 3.5.1 (2018-07-02)
Platform: x86_64-pc-linux-gnu (64-bit)
Running under: Scientific Linux 7.4 (Nitrogen)

Matrix products: default
BLAS/LAPACK: /software/openblas-0.2.19-el7-x86_64/lib/libopenblas_haswellp-r0.2.19.so

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       

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base     

other attached packages:
[1] devtools_2.1.0  usethis_1.5.1   magrittr_1.5    lemon_0.4.3    
[5] gtable_0.3.0    scales_1.1.0    cowplot_1.0.0   ggplot2_3.2.0  
[9] dscrutils_0.4.2

loaded via a namespace (and not attached):
 [1] mcmc_0.9-6           matrixStats_0.55.0   fs_1.3.1            
 [4] lubridate_1.7.4      doParallel_1.0.14    RColorBrewer_1.1-2  
 [7] progress_1.2.2       rprojroot_1.3-2      repr_0.17           
[10] tools_3.5.1          backports_1.1.5      R6_2.4.1            
[13] irlba_2.3.3          lazyeval_0.2.2       colorspace_1.4-1    
[16] sp_1.3-1             withr_2.1.2          tidyselect_0.2.5    
[19] gridExtra_2.3        prettyunits_1.1.1    processx_3.4.0      
[22] compiler_3.5.1       git2r_0.26.1         MBSP_1.0            
[25] cli_1.1.0            quantreg_5.36        SparseM_1.77        
[28] xml2_1.2.0           desc_1.2.0           labeling_0.3        
[31] mvtnorm_1.0-12       callr_3.3.2          mixsqp_0.3-31       
[34] stringr_1.4.0        digest_0.6.25        rmarkdown_1.10      
[37] MCMCpack_1.4-4       base64enc_0.1-3      pkgconfig_2.0.3     
[40] htmltools_0.3.6      sessioninfo_1.1.1    Ipaper_0.1.5        
[43] rlang_0.4.5          readxl_1.1.0         rstudioapi_0.10     
[46] farver_2.0.3         jsonlite_1.6         dplyr_0.8.0.1       
[49] zip_1.0.0            Matrix_1.2-15        Rcpp_1.0.4.6        
[52] munsell_0.5.0        clipr_0.4.1          lifecycle_0.2.0     
[55] stringi_1.4.3        whisker_0.3-2        yaml_2.2.1          
[58] MASS_7.3-51.1        pkgbuild_1.0.3       plyr_1.8.5          
[61] grid_3.5.1           parallel_3.5.1       promises_1.0.1      
[64] crayon_1.3.4         lattice_0.20-38      IRdisplay_0.6.1     
[67] hms_0.5.3            knitr_1.20           ps_1.2.1            
[70] pillar_1.4.1         boot_1.3-20          reshape2_1.4.3      
[73] codetools_0.2-15     pkgload_1.0.2        glue_1.4.0          
[76] evaluate_0.12        mr.mash.alpha_0.1-72 data.table_1.12.8   
[79] remotes_2.1.0        vctrs_0.2.4          GIGrvg_0.5          
[82] httpuv_1.4.5         foreach_1.4.4        testthat_2.1.1      
[85] MatrixModels_0.4-1   cellranger_1.1.0     purrr_0.3.3         
[88] assertthat_0.2.1     openxlsx_4.1.0       coda_0.19-3         
[91] later_0.7.5          tibble_2.1.3         iterators_1.0.10    
[94] memoise_1.1.0        workflowr_1.6.1