attempt to fix ugly code...
[valse.git] / pkg / R / selectVariables.R
... / ...
CommitLineData
1#' selectVariables
2#'
3#' It is a function which construct, for a given lambda, the sets of relevant variables.
4#'
5#' @param phiInit an initial estimator for phi (size: p*m*k)
6#' @param rhoInit an initial estimator for rho (size: m*m*k)
7#' @param piInit\tan initial estimator for pi (size : k)
8#' @param gamInit an initial estimator for gamma
9#' @param mini\t\tminimum number of iterations in EM algorithm
10#' @param maxi\t\tmaximum number of iterations in EM algorithm
11#' @param gamma\t power in the penalty
12#' @param glambda grid of regularization parameters
13#' @param X\t\t\t matrix of regressors
14#' @param Y\t\t\t matrix of responses
15#' @param thresh real, threshold to say a variable is relevant, by default = 1e-8
16#' @param eps\t\t threshold to say that EM algorithm has converged
17#' @param ncores Number or cores for parallel execution (1 to disable)
18#'
19#' @return a list of outputs, for each lambda in grid: selected,Rho,Pi
20#'
21#' @examples TODO
22#'
23#' @export
24#'
25selectVariables <- function(phiInit, rhoInit, piInit, gamInit, mini, maxi, gamma,
26 glambda, X, Y, thresh = 1e-08, eps, ncores = 3, fast = TRUE)
27 {
28 if (ncores > 1)
29 {
30 cl <- parallel::makeCluster(ncores, outfile = "")
31 parallel::clusterExport(cl = cl, varlist = c("phiInit", "rhoInit", "gamInit",
32 "mini", "maxi", "glambda", "X", "Y", "thresh", "eps"), envir = environment())
33 }
34
35 # Computation for a fixed lambda
36 computeCoefs <- function(lambda)
37 {
38 params <- EMGLLF(phiInit, rhoInit, piInit, gamInit, mini, maxi, gamma, lambda,
39 X, Y, eps, fast)
40
41 p <- dim(phiInit)[1]
42 m <- dim(phiInit)[2]
43
44 # selectedVariables: list where element j contains vector of selected variables
45 # in [1,m]
46 selectedVariables <- lapply(1:p, function(j)
47 {
48 # from boolean matrix mxk of selected variables obtain the corresponding boolean
49 # m-vector, and finally return the corresponding indices
50 seq_len(m)[apply(abs(params$phi[j, , ]) > thresh, 1, any)]
51 })
52
53 list(selected = selectedVariables, Rho = params$rho, Pi = params$pi)
54 }
55
56 # For each lambda in the grid, we compute the coefficients
57 out <- if (ncores > 1)
58 parLapply(cl, glambda, computeCoefs) else lapply(glambda, computeCoefs)
59 if (ncores > 1)
60 parallel::stopCluster(cl)
61 # Suppress models which are computed twice En fait, ca ca fait la comparaison de
62 # tous les parametres On veut juste supprimer ceux qui ont les memes variables
63 # sélectionnées sha1_array <- lapply(out, digest::sha1) out[
64 # duplicated(sha1_array) ]
65 selec <- lapply(out, function(model) model$selected)
66 ind_dup <- duplicated(selec)
67 ind_uniq <- which(!ind_dup)
68 out2 <- list()
69 for (l in 1:length(ind_uniq))
70 {
71 out2[[l]] <- out[[ind_uniq[l]]]
72 }
73 out2
74}