Package as sent to CRAN
[valse.git] / pkg / R / main.R
1 #' runValse
2 #'
3 #' Main function
4 #'
5 #' @param X matrix of covariates (of size n*p)
6 #' @param Y matrix of responses (of size n*m)
7 #' @param procedure among 'LassoMLE' or 'LassoRank'
8 #' @param selecMod method to select a model among 'DDSE', 'DJump', 'BIC' or 'AIC'
9 #' @param gamma integer for the power in the penaly, by default = 1
10 #' @param mini integer, minimum number of iterations in the EM algorithm, by default = 10
11 #' @param maxi integer, maximum number of iterations in the EM algorithm, by default = 100
12 #' @param eps real, threshold to say the EM algorithm converges, by default = 1e-4
13 #' @param kmin integer, minimum number of clusters, by default = 2
14 #' @param kmax integer, maximum number of clusters, by default = 10
15 #' @param rank.min integer, minimum rank in the low rank procedure, by default = 1
16 #' @param rank.max integer, maximum rank in the low rank procedure, by default = 5
17 #' @param ncores_outer Number of cores for the outer loop on k
18 #' @param ncores_inner Number of cores for the inner loop on lambda
19 #' @param thresh real, threshold to say a variable is relevant, by default = 1e-8
20 #' @param grid_lambda, a vector with regularization parameters if known, by default numeric(0)
21 #' @param size_coll_mod (Maximum) size of a collection of models, by default 50
22 #' @param fast TRUE to use compiled C code, FALSE for R code only
23 #' @param verbose TRUE to show some execution traces
24 #' @param plot TRUE to plot the selected models after run
25 #'
26 #' @return
27 #' The selected model (except if the collection of models
28 #' has less than 11 models, the function returns the collection as it can not select one using Capushe)
29 #'
30 #' @examples
31 #' n = 50; m = 10; p = 5
32 #' beta = array(0, dim=c(p,m,2))
33 #' beta[,,1] = 1
34 #' beta[,,2] = 2
35 #' data = generateXY(n, c(0.4,0.6), rep(0,p), beta, diag(0.5, p), diag(0.5, m))
36 #' X = data$X
37 #' Y = data$Y
38 #' res = runValse(X, Y, kmax = 5, plot=FALSE)
39 #' X <- matrix(runif(100), nrow=50)
40 #' Y <- matrix(runif(100), nrow=50)
41 #' res = runValse(X, Y, plot=FALSE)
42 #'
43 #' @export
44 runValse <- function(X, Y, procedure = "LassoMLE", selecMod = "DDSE", gamma = 1, mini = 10,
45 maxi = 50, eps = 1e-04, kmin = 2, kmax = 3, rank.min = 1, rank.max = 5, ncores_outer = 1,
46 ncores_inner = 1, thresh = 1e-08, grid_lambda = numeric(0), size_coll_mod = 50,
47 fast = TRUE, verbose = FALSE, plot = TRUE)
48 {
49 n <- nrow(X)
50 p <- ncol(X)
51 m <- ncol(Y)
52
53 if (verbose) print("main loop: over all k and all lambda")
54
55 if (ncores_outer > 1) {
56 cl <- parallel::makeCluster(ncores_outer, outfile = "")
57 parallel::clusterExport(cl = cl, envir = environment(), varlist = c("X",
58 "Y", "procedure", "selecMod", "gamma", "mini", "maxi", "eps", "kmin",
59 "kmax", "rank.min", "rank.max", "ncores_outer", "ncores_inner", "thresh",
60 "size_coll_mod", "verbose", "p", "m"))
61 }
62
63 # Compute models with k components
64 computeModels <- function(k) {
65 if (ncores_outer > 1)
66 require("valse") #nodes start with an empty environment
67
68 if (verbose)
69 print(paste("Parameters initialization for k =", k))
70 # smallEM initializes parameters by k-means and regression model in each
71 # component, doing this 20 times, and keeping the values maximizing the
72 # likelihood after 10 iterations of the EM algorithm.
73 P <- initSmallEM(k, X, Y, fast)
74 if (length(grid_lambda) == 0) {
75 grid_lambda <- computeGridLambda(P$phiInit, P$rhoInit, P$piInit, P$gamInit,
76 X, Y, gamma, mini, maxi, eps, fast)
77 }
78 if (length(grid_lambda) > size_coll_mod)
79 grid_lambda <- grid_lambda[seq(1, length(grid_lambda), length.out = size_coll_mod)]
80
81 if (verbose)
82 print("Compute relevant parameters")
83 # select variables according to each regularization parameter from the grid:
84 # S$selected corresponding to selected variables
85 S <- selectVariables(P$phiInit, P$rhoInit, P$piInit, P$gamInit, mini, maxi,
86 gamma, grid_lambda, X, Y, thresh, eps, ncores_inner, fast)
87
88 if (procedure == "LassoMLE") {
89 if (verbose)
90 print("run the procedure Lasso-MLE")
91 # compute parameter estimations, with the Maximum Likelihood Estimator,
92 # restricted on selected variables.
93 models <- constructionModelesLassoMLE(P$phiInit, P$rhoInit, P$piInit,
94 P$gamInit, mini, maxi, gamma, X, Y, eps, S, ncores_inner, fast, verbose)
95 } else {
96 if (verbose)
97 print("run the procedure Lasso-Rank")
98 # compute parameter estimations, with the Low Rank Estimator, restricted on
99 # selected variables.
100 models <- constructionModelesLassoRank(S, k, mini, maxi, X, Y, eps, rank.min,
101 rank.max, ncores_inner, fast, verbose)
102 }
103 # warning! Some models are NULL after running selectVariables
104 models <- models[sapply(models, function(cell) !is.null(cell))]
105 models
106 }
107
108 # List (index k) of lists (index lambda) of models
109 models_list <-
110 if (ncores_outer > 1) {
111 parallel::parLapply(cl, kmin:kmax, computeModels)
112 } else {
113 lapply(kmin:kmax, computeModels)
114 }
115 if (ncores_outer > 1) parallel::stopCluster(cl)
116
117 if (!requireNamespace("capushe", quietly = TRUE)) {
118 warning("'capushe' not available: returning all models")
119 return(models_list)
120 }
121
122 # Get summary 'tableauRecap' from models
123 tableauRecap <- do.call(rbind, lapply(seq_along(models_list), function(i) {
124 models <- models_list[[i]]
125 # For a collection of models (same k, several lambda):
126 LLH <- sapply(models, function(model) model$llh[1])
127 k <- length(models[[1]]$pi)
128 sumPen <- sapply(models, function(model) k * (dim(model$rho)[1] + sum(model$phi[,,1] != 0) + 1) - 1)
129 data.frame(model = paste(i, ".", seq_along(models), sep = ""), pen = sumPen/n, complexity = sumPen, contrast = -LLH)
130 }))
131 tableauRecap <- tableauRecap[which(tableauRecap[, 4] != Inf), ]
132 if (verbose) print(tableauRecap)
133
134 if (nrow(tableauRecap) > 10) {
135 modSel <- capushe::capushe(tableauRecap, n)
136 indModSel <- if (selecMod == "DDSE") {
137 as.numeric(modSel@DDSE@model)
138 } else if (selecMod == "Djump") {
139 as.numeric(modSel@Djump@model)
140 } else if (selecMod == "BIC") {
141 modSel@BIC_capushe$model
142 } else if (selecMod == "AIC") {
143 modSel@AIC_capushe$model
144 }
145 listMod <- as.integer(unlist(strsplit(as.character(indModSel), "[.]")))
146 modelSel <- models_list[[listMod[1]]][[listMod[2]]]
147 modelSel$models <- tableauRecap
148
149 if (plot) plot_valse(X, Y, modelSel)
150 return(modelSel)
151 }
152 tableauRecap
153 }