fix some errors
[valse.git] / pkg / R / constructionModelesLassoMLE.R
1 #' constructionModelesLassoMLE
2 #'
3 #' TODO: description
4 #'
5 #' @param ...
6 #'
7 #' @return ...
8 #'
9 #' export
10 constructionModelesLassoMLE = function(phiInit, rhoInit, piInit, gamInit, mini, maxi,
11 gamma, X, Y, thresh, tau, S, ncores=3, artefact = 1e3, verbose=FALSE)
12 {
13 if (ncores > 1)
14 {
15 cl = parallel::makeCluster(ncores)
16 parallel::clusterExport( cl, envir=environment(),
17 varlist=c("phiInit","rhoInit","gamInit","mini","maxi","gamma","X","Y","thresh",
18 "tau","S","ncores","verbose") )
19 }
20
21 # Individual model computation
22 computeAtLambda <- function(lambda)
23 {
24 if (ncores > 1)
25 require("valse") #// nodes start with an empty environment
26
27 if (verbose)
28 print(paste("Computations for lambda=",lambda))
29
30 n = dim(X)[1]
31 p = dim(phiInit)[1]
32 m = dim(phiInit)[2]
33 k = dim(phiInit)[3]
34
35 sel.lambda = S[[lambda]]$selected
36 # col.sel = which(colSums(sel.lambda)!=0) #if boolean matrix
37 col.sel <- which( sapply(sel.lambda,length) > 0 ) #if list of selected vars
38
39 if (length(col.sel) == 0)
40 {return (NULL)} else {
41
42 # lambda == 0 because we compute the EMV: no penalization here
43 res_EM = EMGLLF(phiInit[col.sel,,],rhoInit,piInit,gamInit,mini,maxi,gamma,0,
44 X[,col.sel],Y,tau)
45
46 # Eval dimension from the result + selected
47 phiLambda2 = res_EM$phi
48 rhoLambda = res_EM$rho
49 piLambda = res_EM$pi
50 phiLambda = array(0, dim = c(p,m,k))
51 for (j in seq_along(col.sel))
52 phiLambda[col.sel[j],,] = phiLambda2[j,,]
53
54 dimension = 0
55 for (j in 1:p)
56 {
57 b = setdiff(1:m, sel.lambda[[j]])## je confonds un peu ligne et colonne : est-ce dans le bon sens ?
58 ## moi pour la dimension, j'aurai juste mis length(unlist(sel.lambda)) mais je sais pas si c'est rapide
59 if (length(b) > 0)
60 phiLambda[j,b,] = 0.0
61 dimension = dimension + sum(sel.lambda[[j]]!=0)
62 }
63
64 # Computation of the loglikelihood
65 densite = vector("double",n)
66 for (r in 1:k)
67 {
68 delta = (Y%*%rhoLambda[,,r] - (X[, col.sel]%*%phiLambda[col.sel,,r]))/artefact
69 print(max(delta))
70 densite = densite + piLambda[r] *
71 det(rhoLambda[,,r])/(sqrt(2*base::pi))^m * exp(-tcrossprod(delta)/2.0)
72 }
73 llhLambda = c( sum(artefact^2 * log(densite)), (dimension+m+1)*k-1 )
74 list("phi"= phiLambda, "rho"= rhoLambda, "pi"= piLambda, "llh" = llhLambda)
75 }
76 }
77
78 # For each lambda, computation of the parameters
79 out =
80 if (ncores > 1)
81 parLapply(cl, 1:length(S), computeAtLambda)
82 else
83 lapply(1:length(S), computeAtLambda)
84
85 if (ncores > 1)
86 parallel::stopCluster(cl)
87
88 out
89 }