celestialgod

fast lm f statistics

Apr 23rd, 2016
199
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
R 3.90 KB | None | 0 0
  1. requirePackages <- c("foreach", "doSNOW", "data.table", "purrr",
  2.                      "pipeR", "parallel", "Rcpp", "RcppArmadillo", "RcppParallel")
  3. if (!all(requirePackages %in% rownames(installed.packages())))
  4.   install.packages(requirePackages[!requirePackages %in% rownames(installed.packages())])
  5.  
  6. library(foreach)
  7. library(doSNOW)
  8. library(plyr)
  9. library(data.table)
  10. library(purrr)
  11. library(pipeR)
  12. library(Rcpp)
  13. library(RcppArmadillo)
  14.  
  15. sourceCpp(code = '
  16. // [[Rcpp::depends(RcppArmadillo)]]
  17. #include <RcppArmadillo.h>
  18. using namespace Rcpp;
  19. using namespace arma;
  20.  
  21. // [[Rcpp::export]]
  22. double fast_lm_f_stat(const vec& y, const mat& X)
  23. {
  24.  if (y.n_elem != X.n_rows)
  25.    Rcpp::stop("The size of y must be equal to the number of rows of X." );
  26.  vec beta = solve(X, y);
  27.  vec yhat = X * beta;
  28.  double MSR = sum(square(yhat - mean(y))) / ((double) X.n_cols - 1.0),
  29.         MSE = sum(square(y - yhat)) /
  30.           ((double) y.n_elem - (double) X.n_cols);
  31.  return(MSR / MSE);
  32. }')
  33.  
  34. gene <- fread('GE_QNbyPopu_qc_CHB.txt') %>>%
  35.   '['(j = TargetID := NULL) %>>% as.matrix
  36. # gene is a matrix with dimensio c(12028, 45)
  37. R <- 999
  38. x <- as.factor(rep(c("AA","AB","BB"), c(19, 15, 11)))
  39. xMat <- model.matrix(~ ., data.frame(x))
  40.  
  41. lm_f_stat <- function(y, X){
  42.   solve(crossprod(X), crossprod(X, y)) %>>%
  43.     (b ~ X %*% b) %>>%
  44.     (yhat ~ sum((yhat - mean(y))^2) / sum((y - yhat)^2) /
  45.        (ncol(X) - 1) * (length(y) - ncol(X)))
  46. }
  47.  
  48. # check the result is corerect
  49. summary(lm(gene[1, ]~ xMat))$fstatistic[1] %>>%
  50.   {
  51.     stopifnot(abs(. - lm_f_stat(gene[1, ], xMat)) < 1e-6)
  52.     stopifnot(abs(. - fast_lm_f_stat(gene[1, ], xMat)) < 1e-6)
  53.   }
  54.  
  55. st <- proc.time()
  56. p.value <- map_dbl(1:nrow(gene), function(i){
  57.   mean(map_dbl(1:R, ~fast_lm_f_stat(sample(gene[i, ]), xMat)) >
  58.          fast_lm_f_stat(gene[i, ], xMat))
  59. })
  60. proc.time() - st
  61. #  user  system elapsed
  62. # 10.05    0.72  277.50
  63.  
  64. cl <- makeCluster(parallel::detectCores(), type = "SOCK")
  65. registerDoSNOW(cl)
  66.  
  67. clusterEnv <- clusterEvalQ(cl, {
  68.   library(purrr)
  69.   library(pipeR)
  70. })
  71. clusterExport(cl, c("lm_f_stat", "xMat", "R"))
  72.  
  73. st <- proc.time()
  74. p.value <- aaply(gene, 1, function(y){
  75.   mean(map_dbl(1:R, ~lm_f_stat(sample(y), xMat)) >
  76.          lm_f_stat(y, xMat))
  77. }, .parallel = TRUE)
  78. proc.time() - st
  79. #   user  system elapsed
  80. # 296.68    0.11  298.29
  81.  
  82. stopCluster(cl)
  83.  
  84. library(RcppParallel)
  85. sourceCpp(code = '
  86. // [[Rcpp::depends(RcppArmadillo)]]
  87. #include <RcppArmadillo.h>
  88. using namespace Rcpp;
  89. using namespace arma;
  90. // [[Rcpp::depends(RcppParallel)]]
  91. #include <RcppParallel.h>
  92. using namespace RcppParallel;
  93.  
  94. inline double fast_lm_f_stat(const vec& y, const mat& X)
  95. {
  96.  vec beta = solve(X, y);
  97.  vec yhat = X * beta;
  98.  double MSR = sum(square(yhat - mean(y))) / ((double) X.n_cols - 1.0),
  99.         MSE = sum(square(y - yhat)) /
  100.           ((double) y.n_elem - (double) X.n_cols);
  101.  return(MSR / MSE);
  102. }
  103.  
  104. struct pvalueWorker: public Worker {
  105.  const double& rep;
  106.  const mat& Y;
  107.  const mat& X;
  108.  vec& pvalues;
  109.  pvalueWorker(const double& rep, const mat& Y, const mat& X, vec& pvalues):
  110.    rep(rep), Y(Y), X(X), pvalues(pvalues) {}
  111.  void operator()(std::size_t begin, std::size_t end)
  112.  {
  113.    for (uword i = begin; i < end; i++)
  114.    {
  115.      vec tmp_y = Y.row(i).t(), tmp_y2 = tmp_y;
  116.      double f0 = fast_lm_f_stat(tmp_y, X);
  117.      vec f_rep(rep);
  118.      for (uword j = 0; j < (uword) rep; j++)
  119.      {
  120.        tmp_y2 = shuffle(tmp_y);
  121.        f_rep(j) = fast_lm_f_stat(tmp_y2, X);
  122.      }
  123.      pvalues(i) = (double) sum(f_rep > f0) / rep;
  124.    }
  125.  }
  126. };
  127.  
  128. // [[Rcpp::export]]
  129. vec pvalue_f(const double& rep, const mat& Y, const mat& X)
  130. {
  131.  vec pvalues(Y.n_rows);
  132.  pvalueWorker pvalue_worker(rep, Y, X, pvalues);
  133.  parallelFor(0, Y.n_rows, pvalue_worker);
  134.  return(pvalues);
  135. }')
  136.  
  137. st <- proc.time()
  138. p.value <- pvalue_f(R, gene, xMat)
  139. proc.time() - st
  140. #   user  system elapsed
  141. # 207.96    0.00   26.82
Advertisement
Add Comment
Please, Sign In to add comment