Last updated: 2020-10-29

Checks: 7 0

Knit directory: mmbr-rss-dsc/

This reproducible R Markdown analysis was created with workflowr (version 1.6.2). 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(20200227) 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 414facb. 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:    .DS_Store
    Ignored:    .Rhistory
    Ignored:    .Rproj.user/
    Ignored:    output/.DS_Store

Untracked files:
    Untracked:  code/mvsusie_missing.R
    Untracked:  data/ENSG00000140265.12.Multi_Tissues.problem.rds
    Untracked:  data/ENSG00000140265.12.Multi_Tissues.rds
    Untracked:  data/FastQTLSumStats.mash.FL_PC3.rds
    Untracked:  output/.mmbr_gtex_res.Rprof.swp
    Untracked:  output/GTExprofile_res.rds
    Untracked:  output/GTExprofile_resL1.rds
    Untracked:  output/GTExprofile_resL3.rds
    Untracked:  output/GTExprofile_resapprox.rds
    Untracked:  output/GTExprofile_resapproxL1.rds
    Untracked:  output/GTExprofile_resapproxL3.rds
    Untracked:  output/GTExprofile_resapproxdiag.rds
    Untracked:  output/GTExprofile_resapproxdiagL1.rds
    Untracked:  output/GTExprofile_resapproxdiagL3.rds
    Untracked:  output/GTExprofile_resdiag.rds
    Untracked:  output/mmbr_gtex_res.Rprof
    Untracked:  output/mmbr_gtex_res_approx.Rprof
    Untracked:  output/mmbr_gtex_res_approx_diag.Rprof
    Untracked:  output/mmbr_gtex_res_diag.Rprof
    Untracked:  output/mnm_missing_output.20200527.rds
    Untracked:  output/test
    Untracked:  output/tiny_data_211_cond2L2.gif
    Untracked:  output/tiny_data_211_cond2L2.pdf
    Untracked:  output/tiny_data_211_cond2L3.gif
    Untracked:  output/tiny_data_211_cond2L3.pdf
    Untracked:  output/tiny_data_211_cond2initL3.gif
    Untracked:  output/tiny_data_211_cond2initL3.pdf

Unstaged changes:
    Modified:   analysis/mmbr_missing_rss_problem1.Rmd

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/GTExprofileProblem.Rmd) and HTML (docs/GTExprofileProblem.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
Rmd 414facb zouyuxin 2020-10-29 wflow_publish("analysis/GTExprofileProblem.Rmd")
html 88f7737 zouyuxin 2020-10-29 Build site.
Rmd 6cd6fac zouyuxin 2020-10-29 wflow_publish("analysis/GTExprofileProblem.Rmd")

We investigate the BF problem observed here in more details. We fit model with L = 1 and a simpler prior. We don't estimate prior scalar.

knitr::read_chunk("code/mvsusie_missing.R")

R code for mvSuSiE with missing data in Y:

## this is a simplified implementation for mvSuSiE with missing data in Y
## prior_variance is a matrix
## prior_variance and residual_variance are fixed in the algorithm.
library(abind)
library(susieR)
mvsusie_missing = function(X, Y, L=10, prior_variance, residual_variance, approximate=FALSE, intercept = TRUE,
                           max_iter = 100, prior_weights=NULL, tol=1e-3, min_abs_corr=0.5, prior_tol=1E-9){
  if (is.null(dim(Y))) Y <- matrix(Y,length(Y),1)
  R <- ncol(Y)
  N <- nrow(Y)
  J <- ncol(X)
  Y_missing <- is.na(Y)
  Y_non_missing <- !Y_missing
  # store missing pattern, TRUE for observe, FALSE for missing
  missing_pattern <- unique(Y_non_missing)
  Y_missing_pattern_assign <- numeric(N)
  for(k in 1:nrow(missing_pattern)){
    idx = which(apply(Y_non_missing, 1, function(x) identical(x, missing_pattern[k,])))
    Y_missing_pattern_assign[idx] <- k
  }
  Y[Y_missing] <- 0
  if(approximate){
    X_for_Y_missing <- array(X, dim = c(N, J, R))
    for(r in 1:R) {
      X_for_Y_missing[Y_missing[,r],,r] <- NA
    }
  }else{
    X_for_Y_missing <- outer(X,  diag(R)) # N by J by R by R
  }

  ## compute inverse of residual variance for each missing pattern
  residual_variance_inv <- list()
  for(k in 1:nrow(missing_pattern)){
    if(R == 1){
      residual_variance_inv[[k]] <- missing_pattern[k,] / residual_variance
    }else{
      Vk = residual_variance[which(missing_pattern[k,]), which(missing_pattern[k,])]
      eigenVk = eigen(Vk, symmetric = TRUE)
      dinv = 1/(eigenVk$values)
      residual_variance_inv[[k]] <- matrix(0, R, R)
      residual_variance_inv[[k]][which(missing_pattern[k,]), which(missing_pattern[k,])] = eigenVk$vectors %*% (dinv * t(eigenVk$vectors))
    }
  }

  ## centering
  if(intercept){
    if(approximate){
      cm_x <- colMeans(X_for_Y_missing, na.rm=T) # J by R
      Xbar = cm_x
      for(r in 1:R){
        X_for_Y_missing[,,r] <- t(t(X_for_Y_missing[,,r]) - cm_x[,r])
        X_for_Y_missing[,,r][is.na(X_for_Y_missing[,,r])] <- 0
      }
      if (R == 1) Y_mean <- mean(Y[Y_non_missing])
      else Y_mean <- sapply(1:R, function(r) mean(Y[Y_non_missing[,r],r]))
      Y <- t(t(Y) - Y_mean)
      Y[!Y_non_missing] <- 0
    }else{
      # sum_i V_i^{-1} R by R matrix
      Vinvsum = Reduce('+', lapply(1:nrow(missing_pattern), function(i)
        residual_variance_inv[[i]] * sum(Y_missing_pattern_assign == i)))
      Vinvsuminv <- invert_via_chol(Vinvsum)

      # sum_i V_i^{-1} y_i R by 1 matrix
      Ysum = Reduce('+', lapply(1:N, function(i)
        residual_variance_inv[[Y_missing_pattern_assign[i]]] %*% Y[i,] ))

      # center Y
      Y_mean <- as.numeric(Vinvsuminv %*% Ysum)
      Y <- t(t(Y) - Y_mean)
      Y[!Y_non_missing] <- 0

      # center X
      Xbar <- array(0, dim=c(J, R, R))
      for(j in 1:J){
        # For variant j, Vinvsuminv sum_i V_i^{-1} X_{i,j} R by R matrix
        Xbar[j,,] <- Vinvsuminv %*% Reduce('+', lapply(1:N, function(i) residual_variance_inv[[Y_missing_pattern_assign[i]]] * X[i,j]) )
        X_for_Y_missing[,j,,] <- sweep(X_for_Y_missing[,j,,,drop=F], 3:4, Xbar[j,,])
      }
    }
  }

  svs_inv <- list()
  for(j in 1:J){
    # For variant j, sum_i X_for_Y_missing[i,j,,]^T V_i^{-1} X_for_Y_missing[i,j,,], R by R matrix
    # when there is no missing, it is sum(x_j^2) * V^{-1}
    if(approximate){
      svs_inv[[j]] <- Reduce('+', lapply(1:N, function(i) t(residual_variance_inv[[Y_missing_pattern_assign[i]]] *
                                                                 X_for_Y_missing[i,j,]) * X_for_Y_missing[i,j,]))
    }else{
      svs_inv[[j]] <- Reduce('+', lapply(1:N, function(i) crossprod(X_for_Y_missing[i,j,,],
                                             residual_variance_inv[[Y_missing_pattern_assign[i]]] %*%
                                             X_for_Y_missing[i,j,,])))
    }
  }
  s = init(N, J, R, L, prior_variance, prior_weights)
  pip_history = list()
  for(i in 1:max_iter){
    s = update_each_effect(X, Xbar, X_for_Y_missing, Y, s, Y_missing_pattern_assign, residual_variance_inv, svs_inv)
    pip_history[[i]] = s$alpha
    if(i > 1){
      delta = max(abs(apply(1 - pip_history[[i]], 2, prod) - apply(1 - pip_history[[i-1]], 2, prod)))
      if(delta < tol){
        s$niter = i
        s$delta = delta
        break
      }
    }
  }
  s$null_index = -9
  s$V = 1
  s$sets = susie_get_cs(s, X=X, min_abs_corr=min_abs_corr)
  s$pip = susie_get_pip(s, prior_tol=prior_tol)
  return(s)
}

update_each_effect = function(X, Xbar, X_for_Y_missing, Y, s, Y_missing_pattern_assign, residual_variance_inv, svs_inv) {
  # Repeat for each effect to update.
  L = nrow(s$alpha)
  if (L > 0)
    for (l in 1:L) {

      # Remove lth effect from fitted values.
      s$Xr = s$Xr - compute_Xb(Xbar, X, X_for_Y_missing, s$alpha[l,] * s$mu[l,,])

      # Compute residuals.
      R = Y - s$Xr

      res = SER(X_for_Y_missing,R,Y_missing_pattern_assign,residual_variance_inv,svs_inv, s$prior, s$prior_weights)

      # Update the variational estimate of the posterior mean.
      s$alpha[l,]  = res$alpha
      s$mu[l,,]    = res$mu1
      s$mu2[l,,]   = res$mu2
      s$lbf[l]     = res$lbf_model

      s$Xr = s$Xr + compute_Xb(Xbar, X, X_for_Y_missing, s$alpha[l,] * s$mu[l,,])
    }
  return(s)
}

SER = function(X_for_Y_missing, Y, Y_missing_pattern_assign, residual_variance_inv, svs_inv, prior, prior_weights = NULL){
  J = dim(X_for_Y_missing)[2]
  if (is.null(prior_weights))
    prior_weights = rep(1/J,J)
  XtY = compute_XtY(X_for_Y_missing,Y,Y_missing_pattern_assign, residual_variance_inv)
  post = multivariate_regression(XtY, svs_inv, prior)
  posterior_b1 = post$b1 # J by R
  if (length(dim(post$b2)) == 3) posterior_b2 = t(apply(post$b2, 3, diag)) # J by R
  else posterior_b2 = post$b2
  lbf = post$lbf
  maxlbf = max(lbf)
  # w is proportional to BF, but subtract max for numerical stability.
  w = exp(lbf - maxlbf)
  # Posterior prob for each SNP.
  w_weighted = w * prior_weights
  weighted_sum_w = sum(w_weighted)
  alpha = w_weighted / weighted_sum_w
  lbf_model = maxlbf + log(weighted_sum_w)
  return(list(alpha = alpha,mu1 = posterior_b1,mu2 = posterior_b2,lbf = lbf,
              lbf_model = lbf_model))
}

multivariate_regression = function(XtY, svs_inv, U) {
  post_cov = lapply(1:length(svs_inv), function(j) U %*% solve(diag(nrow(U)) + svs_inv[[j]] %*% U))
  lbf = sapply(1:length(svs_inv), function(j) -0.5 * log(det(diag(nrow(U)) + svs_inv[[j]] %*% U)) + 0.5*t(XtY[j,])%*%(post_cov[[j]]%*%XtY[j,]))
  lbf[which(is.nan(lbf))] = 0
  post_b1 = t(do.call(cbind, lapply(1:length(svs_inv), function(j) post_cov[[j]] %*% XtY[j,]))) # J by R
  post_b2 = lapply(1:length(post_cov), function(j) tcrossprod(post_b1[j,]) + post_cov[[j]]) # length J list with R by R matrix
  # deal with degerated case with 1 condition
  if (ncol(post_b1) == 1) {
    post_b2 = matrix(unlist(post_b2), length(post_b2), 1)
  } else {
    post_b2 = aperm(abind(post_b2, along = 3), c(2,1,3)) # R by R by J
  }
  return(list(b1 = post_b1, b2 = post_b2, lbf = lbf, cov = post_cov))
}

## utils
invert_via_chol = function(x) {
  if (all(x==0)) return(x)
  return(chol2inv(muffled_chol(x)))
}

muffled_chol = function(x, ...){
  withCallingHandlers(chol(x, ...),
                      warning = function(w) {
                        if (grepl("the matrix is either rank-deficient or indefinite", w$message))
                          invokeRestart("muffleWarning")
                      })
}

compute_XtY = function(X_for_Y_missing,Y,Y_missing_pattern_assign,residual_variance_inv){ # J by R
  N = dim(X_for_Y_missing)[1]
  J = dim(X_for_Y_missing)[2]
  if(length(dim(X_for_Y_missing)) == 3){ ## approximate
    XtY <- t(sapply(1:J, function(j) Reduce('+', lapply(1:N, function(i) (residual_variance_inv[[Y_missing_pattern_assign[i]]] %*%Y[i,]) * X_for_Y_missing[i,j,]) )))
  }else{
    XtY <- t(sapply(1:J, function(j) Reduce('+', lapply(1:N, function(i) crossprod(X_for_Y_missing[i,j,,],
                                                                                   residual_variance_inv[[Y_missing_pattern_assign[i]]] %*%Y[i,]) ))))
  }
  if (nrow(XtY) != J) XtY <- t(XtY)
  return(XtY)
}

init = function(N, J, R, L, U, prior_weights){
  if(is.null(prior_weights))
    prior_weights = rep(1/J,J)
  else
    prior_weights = prior_weights / sum(prior_weights)

  s = list(alpha  = matrix(1/J, L, J),
           mu     = array(0,dim = c(L, J, R)),
           mu2    = array(0,dim = c(L, J, R)),
           Xr     = matrix(0,N, R),
           prior      = U,
           prior_weights = prior_weights)
  class(s) = 'susie'
  return(s)
}

compute_Xb = function(Xbar, X, X_for_Y_missing, b){
  if(is.vector(b)){
    b = matrix(b, length(b),1)
  }
  if(length(dim(X_for_Y_missing)) == 3){
    Xb = sapply(1:ncol(b), function(r) X_for_Y_missing[,,r] %*% b[,r])
  }else{
    Xbarb = Reduce('+', lapply(1:ncol(X), function(j) Xbar[j,,] %*% b[j,]))
    Xb = X %*% b - matrix(Xbarb, nrow(X), ncol(b), byrow = TRUE)
  }
  return(Xb)
}

Load data

dat = readRDS('data/ENSG00000140265.12.Multi_Tissues.problem.rds')

Model with dense residual varaince

m = mvsusie_missing(dat$X, dat$Y, prior_variance = dat$prior$FLASH_1, residual_variance = dat$residual_var, L = 1, approximate=FALSE)
susie_plot(m, y='PIP')

Version Author Date
88f7737 zouyuxin 2020-10-29

Check CS details:

m$sets
$cs
$cs$L1
 [1] 243 244 249 253 260 263 264 265 268 270


$purity
   min.abs.corr mean.abs.corr median.abs.corr
L1    0.9458794     0.9856198       0.9887131

$cs_index
[1] 1

$coverage
[1] 0.95

Model with diagonal residual variance

m_diag = mvsusie_missing(dat$X, dat$Y, prior_variance = dat$prior$FLASH_1, residual_variance = diag(diag(dat$residual_var)), L = 1, approximate=TRUE)
susie_plot(m_diag, y='PIP')

Version Author Date
88f7737 zouyuxin 2020-10-29

Check CS details:

m_diag$sets
$cs
$cs$L1
[1] 253


$purity
   min.abs.corr mean.abs.corr median.abs.corr
L1            1             1               1

$cs_index
[1] 1

$coverage
[1] 0.95

Sanity check using Identity matrix as prior variance

Model with dense residual varaince

mi = mvsusie_missing(dat$X, dat$Y, prior_variance = diag(49), residual_variance = dat$residual_var, L = 1, approximate=FALSE)
susie_plot(mi, y='PIP')

Version Author Date
88f7737 zouyuxin 2020-10-29

Model with diagonal residual variance

mi_diag = mvsusie_missing(dat$X, dat$Y, prior_variance = diag(49), residual_variance = diag(diag(dat$residual_var)), L = 1, approximate=TRUE)
susie_plot(mi_diag, y='PIP')

Version Author Date
88f7737 zouyuxin 2020-10-29

As a sanity check for the implemented method, we fit model for each tissue separately. The product of fitted BFs over all tissues should equal to the BFs from model with diagonal residual variance and Identity prior matrix.

malpha_r = matrix(NA, 49, 501)
for(r in 1:49){
  mr = mvsusie_missing(dat$X, dat$Y[,r], prior_variance = matrix(1,1,1), residual_variance = diag(dat$residual_var)[r], L = 1, approximate=TRUE)
  malpha_r[r, ] = mr$alpha
}
{plot(apply(malpha_r, 2, prod)/sum(apply(malpha_r, 2, prod)), mi_diag$alpha, xlab='product of BF', ylab='BF from mvsusie')
abline(0,1)}

Version Author Date
88f7737 zouyuxin 2020-10-29

sessionInfo()
R version 3.6.3 (2020-02-29)
Platform: x86_64-apple-darwin15.6.0 (64-bit)
Running under: macOS Catalina 10.15.7

Matrix products: default
BLAS:   /Library/Frameworks/R.framework/Versions/3.6/Resources/lib/libRblas.0.dylib
LAPACK: /Library/Frameworks/R.framework/Versions/3.6/Resources/lib/libRlapack.dylib

locale:
[1] en_US.UTF-8/en_US.UTF-8/en_US.UTF-8/C/en_US.UTF-8/en_US.UTF-8

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

other attached packages:
[1] susieR_0.9.26   abind_1.4-5     workflowr_1.6.2

loaded via a namespace (and not attached):
 [1] Rcpp_1.0.5       plyr_1.8.6       pillar_1.4.6     compiler_3.6.3  
 [5] later_1.1.0.1    git2r_0.27.1     tools_3.6.3      digest_0.6.27   
 [9] evaluate_0.14    lifecycle_0.2.0  tibble_3.0.4     gtable_0.3.0    
[13] lattice_0.20-41  pkgconfig_2.0.3  rlang_0.4.8      Matrix_1.2-18   
[17] rstudioapi_0.11  yaml_2.2.1       xfun_0.18        dplyr_1.0.2     
[21] stringr_1.4.0    knitr_1.30       generics_0.0.2   fs_1.5.0        
[25] vctrs_0.3.4      tidyselect_1.1.0 rprojroot_1.3-2  grid_3.6.3      
[29] reshape_0.8.8    glue_1.4.2       R6_2.4.1.9001    rmarkdown_2.5   
[33] purrr_0.3.4      ggplot2_3.3.2    magrittr_1.5     whisker_0.4     
[37] backports_1.1.10 scales_1.1.1     promises_1.1.1   ellipsis_0.3.1  
[41] htmltools_0.5.0  colorspace_1.4-1 httpuv_1.5.4     stringi_1.5.3   
[45] munsell_0.5.0    crayon_1.3.4