Some fixes to re-upload on the CRAN
[morpheus.git] / pkg / R / optimParams.R
CommitLineData
ab35f610
BA
1#' optimParams
2#'
4263503b 3#' Wrapper function for OptimParams class
cbd88fe5 4#'
ab35f610
BA
5#' @name optimParams
6#'
4263503b
BA
7#' @param X Data matrix of covariables
8#' @param Y Output as a binary vector
2b3a6af5
BA
9#' @param K Number of populations.
10#' @param link The link type, 'logit' or 'probit'.
11#' @param M the empirical cross-moments between X and Y (optional)
5af71d43 12#' @param nc Number of cores (default: 0 to use all)
cbd88fe5 13#'
2b3a6af5
BA
14#' @return An object 'op' of class OptimParams, initialized so that
15#' \code{op$run(θ0)} outputs the list of optimized parameters
cbd88fe5
BA
16#' \itemize{
17#' \item p: proportions, size K
18#' \item β: regression matrix, size dxK
19#' \item b: intercepts, size K
20#' }
2b3a6af5
BA
21#' θ0 is a list containing the initial parameters. Only β is required
22#' (p would be set to (1/K,...,1/K) and b to (0,...0)).
cbd88fe5
BA
23#'
24#' @seealso \code{multiRun} to estimate statistics based on β, and
25#' \code{generateSampleIO} for I/O random generation.
26#'
27#' @examples
28#' # Optimize parameters from estimated μ
2b3a6af5
BA
29#' io <- generateSampleIO(100,
30#' 1/2, matrix(c(1,-2,3,1),ncol=2), c(0,0), "logit")
ab35f610 31#' μ <- computeMu(io$X, io$Y, list(K=2))
4263503b 32#' o <- optimParams(io$X, io$Y, 2, "logit")
dfdd811f 33#' \dontrun{
7737c2fa
BA
34#' θ0 <- list(p=1/2, β=μ, b=c(0,0))
35#' par0 <- o$run(θ0)
cbd88fe5 36#' # Compare with another starting point
7737c2fa
BA
37#' θ1 <- list(p=1/2, β=2*μ, b=c(0,0))
38#' par1 <- o$run(θ1)
2b3a6af5 39#' # Look at the function values at par0 and par1:
cbd88fe5 40#' o$f( o$linArgs(par0) )
2b3a6af5
BA
41#' o$f( o$linArgs(par1) )}
42#'
cbd88fe5 43#' @export
5af71d43 44optimParams <- function(X, Y, K, link=c("logit","probit"), M=NULL, nc=0)
cbd88fe5 45{
6dd5c2ac 46 # Check arguments
4263503b
BA
47 if (!is.matrix(X) || any(is.na(X)))
48 stop("X: numeric matrix, no NAs")
0a630686 49 if (!is.numeric(Y) || any(is.na(Y)) || any(Y!=0 & Y!=1))
4263503b 50 stop("Y: binary vector with 0 and 1 only")
6dd5c2ac 51 link <- match.arg(link)
4b2f17bb
BA
52 if (!is.numeric(K) || K!=floor(K) || K < 2 || K > ncol(X))
53 stop("K: integer >= 2, <= d")
cbd88fe5 54
f4e42a2b
BA
55 if (is.null(M))
56 {
57 # Precompute empirical moments
58 Mtmp <- computeMoments(X, Y)
59 M1 <- as.double(Mtmp[[1]])
60 M2 <- as.double(Mtmp[[2]])
61 M3 <- as.double(Mtmp[[3]])
62 M <- c(M1, M2, M3)
63 }
d9edcd6c
BA
64 else
65 M <- c(M[[1]], M[[2]], M[[3]])
f4e42a2b 66
6dd5c2ac
BA
67 # Build and return optimization algorithm object
68 methods::new("OptimParams", "li"=link, "X"=X,
5af71d43 69 "Y"=as.integer(Y), "K"=as.integer(K), "Mhat"=as.double(M), "nc"=as.integer(nc))
cbd88fe5
BA
70}
71
2b3a6af5
BA
72# Encapsulated optimization for p (proportions), β and b (regression parameters)
73#
74# Optimize the parameters of a mixture of logistic regressions model, possibly using
75# \code{mu <- computeMu(...)} as a partial starting point.
76#
77# @field li Link function, 'logit' or 'probit'
78# @field X Data matrix of covariables
79# @field Y Output as a binary vector
80# @field Mhat Vector of empirical moments
81# @field K Number of populations
82# @field n Number of sample points
83# @field d Number of dimensions
5af71d43 84# @field nc Number of cores (OpenMP //)
2b3a6af5
BA
85# @field W Weights matrix (initialized at identity)
86#
cbd88fe5 87setRefClass(
6dd5c2ac 88 Class = "OptimParams",
cbd88fe5 89
6dd5c2ac
BA
90 fields = list(
91 # Inputs
92 li = "character", #link function
93 X = "matrix",
94 Y = "numeric",
7737c2fa 95 Mhat = "numeric", #vector of empirical moments
6dd5c2ac
BA
96 # Dimensions
97 K = "integer",
4263503b 98 n = "integer",
6dd5c2ac 99 d = "integer",
5af71d43 100 nc = "integer",
e92d9d9d
BA
101 # Weights matrix (generalized least square)
102 W = "matrix"
6dd5c2ac 103 ),
cbd88fe5 104
6dd5c2ac
BA
105 methods = list(
106 initialize = function(...)
107 {
108 "Check args and initialize K, d, W"
cbd88fe5 109
4263503b 110 callSuper(...)
f4e42a2b 111 if (!hasArg("X") || !hasArg("Y") || !hasArg("K")
5af71d43 112 || !hasArg("li") || !hasArg("Mhat") || !hasArg("nc"))
f4e42a2b 113 {
6dd5c2ac 114 stop("Missing arguments")
f4e42a2b 115 }
4263503b 116
6dd5c2ac 117 n <<- nrow(X)
f4e42a2b 118 d <<- ncol(X)
86f257f8 119 # W will be initialized when calling run()
6dd5c2ac 120 },
cbd88fe5 121
6dd5c2ac
BA
122 expArgs = function(v)
123 {
124 "Expand individual arguments from vector v into a list"
cbd88fe5 125
6dd5c2ac
BA
126 list(
127 # p: dimension K-1, need to be completed
128 "p" = c(v[1:(K-1)], 1-sum(v[1:(K-1)])),
44559add 129 "β" = t(matrix(v[K:(K+d*K-1)], ncol=d)),
6dd5c2ac
BA
130 "b" = v[(K+d*K):(K+(d+1)*K-1)])
131 },
cbd88fe5 132
6dd5c2ac
BA
133 linArgs = function(L)
134 {
135 "Linearize vectors+matrices from list L into a vector"
cbd88fe5 136
44559add
BA
137 # β linearized row by row, to match derivatives order
138 c(L$p[1:(K-1)], as.double(t(L$β)), L$b)
6dd5c2ac 139 },
cbd88fe5 140
2b3a6af5 141 # TODO: relocate computeW in utils.R
7737c2fa 142 computeW = function(θ)
4263503b 143 {
2b3a6af5
BA
144 "Compute the weights matrix from a parameters list"
145
0f5fbd13 146 require(MASS)
4bf8494d 147 dd <- d + d^2 + d^3
9a6881ed
BA
148 M <- Moments(θ)
149 Omega <- matrix( .C("Compute_Omega",
074c721a 150 X=as.double(X), Y=as.integer(Y), M=as.double(M),
5af71d43 151 pnc=as.integer(nc), pn=as.integer(n), pd=as.integer(d),
9a6881ed 152 W=as.double(W), PACKAGE="morpheus")$W, nrow=dd, ncol=dd )
0f5fbd13 153 MASS::ginv(Omega)
4263503b
BA
154 },
155
b389a46a 156 Moments = function(θ)
4263503b 157 {
2b3a6af5 158 "Compute the vector of theoretical moments (size d+d^2+d^3)"
cbd88fe5 159
7737c2fa 160 p <- θ$p
6dd5c2ac
BA
161 β <- θ$β
162 λ <- sqrt(colSums(β^2))
163 b <- θ$b
164
165 # Tensorial products β^2 = β2 and β^3 = β3 must be computed from current β1
166 β2 <- apply(β, 2, function(col) col %o% col)
167 β3 <- apply(β, 2, function(col) col %o% col %o% col)
168
169 c(
170 β %*% (p * .G(li,1,λ,b)),
171 β2 %*% (p * .G(li,2,λ,b)),
172 β3 %*% (p * .G(li,3,λ,b)))
7737c2fa
BA
173 },
174
175 f = function(θ)
176 {
2b3a6af5 177 "Function to minimize: t(hat_Mi - Mi(θ)) . W . (hat_Mi - Mi(θ))"
7737c2fa 178
0a630686 179 L <- expArgs(θ)
6dd5c2ac 180 A <- as.matrix(Mhat - Moments(L))
4263503b
BA
181 t(A) %*% W %*% A
182 },
cbd88fe5 183
6dd5c2ac
BA
184 grad_f = function(θ)
185 {
2b3a6af5 186 "Gradient of f: vector of size (K-1) + d*K + K = (d+2)*K - 1"
cbd88fe5 187
0a630686 188 L <- expArgs(θ)
0f5fbd13 189 -2 * t(grad_M(L)) %*% W %*% as.matrix(Mhat - Moments(L))
b389a46a 190 },
4263503b 191
7737c2fa 192 grad_M = function(θ)
4263503b 193 {
2b3a6af5 194 "Gradient of the moments vector: matrix of size d+d^2+d^3 x K-1+K+d*K"
4263503b 195
6dd5c2ac
BA
196 p <- θ$p
197 β <- θ$β
198 λ <- sqrt(colSums(β^2))
199 μ <- sweep(β, 2, λ, '/')
200 b <- θ$b
7737c2fa
BA
201
202 res <- matrix(nrow=nrow(W), ncol=0)
cbd88fe5 203
6dd5c2ac
BA
204 # Tensorial products β^2 = β2 and β^3 = β3 must be computed from current β1
205 β2 <- apply(β, 2, function(col) col %o% col)
206 β3 <- apply(β, 2, function(col) col %o% col %o% col)
cbd88fe5 207
6dd5c2ac
BA
208 # Some precomputations
209 G1 = .G(li,1,λ,b)
210 G2 = .G(li,2,λ,b)
211 G3 = .G(li,3,λ,b)
212 G4 = .G(li,4,λ,b)
213 G5 = .G(li,5,λ,b)
cbd88fe5 214
7737c2fa 215 # Gradient on p: K-1 columns, dim rows
6dd5c2ac
BA
216 km1 = 1:(K-1)
217 res <- cbind(res, rbind(
0a630686
BA
218 sweep(as.matrix(β [,km1]), 2, G1[km1], '*') - G1[K] * β [,K],
219 sweep(as.matrix(β2[,km1]), 2, G2[km1], '*') - G2[K] * β2[,K],
220 sweep(as.matrix(β3[,km1]), 2, G3[km1], '*') - G3[K] * β3[,K] ))
cbd88fe5 221
6dd5c2ac
BA
222 for (i in 1:d)
223 {
224 # i determines the derivated matrix dβ[2,3]
225
226 dβ_left <- sweep(β, 2, p * G3 * β[i,], '*')
227 dβ_right <- matrix(0, nrow=d, ncol=K)
228 block <- i
229 dβ_right[block,] <- dβ_right[block,] + 1
230 dβ <- dβ_left + sweep(dβ_right, 2, p * G1, '*')
231
232 dβ2_left <- sweep(β2, 2, p * G4 * β[i,], '*')
233 dβ2_right <- do.call( rbind, lapply(1:d, function(j) {
234 sweep(dβ_right, 2, β[j,], '*')
235 }) )
236 block <- ((i-1)*d+1):(i*d)
237 dβ2_right[block,] <- dβ2_right[block,] + β
238 dβ2 <- dβ2_left + sweep(dβ2_right, 2, p * G2, '*')
239
240 dβ3_left <- sweep(β3, 2, p * G5 * β[i,], '*')
241 dβ3_right <- do.call( rbind, lapply(1:d, function(j) {
242 sweep(dβ2_right, 2, β[j,], '*')
243 }) )
244 block <- ((i-1)*d*d+1):(i*d*d)
245 dβ3_right[block,] <- dβ3_right[block,] + β2
246 dβ3 <- dβ3_left + sweep(dβ3_right, 2, p * G3, '*')
247
248 res <- cbind(res, rbind(dβ, dβ2, dβ3))
249 }
cbd88fe5 250
7737c2fa 251 # Gradient on b
6dd5c2ac
BA
252 res <- cbind(res, rbind(
253 sweep(β, 2, p * G2, '*'),
254 sweep(β2, 2, p * G3, '*'),
255 sweep(β3, 2, p * G4, '*') ))
cbd88fe5 256
6dd5c2ac
BA
257 res
258 },
cbd88fe5 259
35ffd710
BA
260 # userW allows to bypass the W optimization by giving a W matrix
261 run = function(θ0, userW=NULL)
6dd5c2ac
BA
262 {
263 "Run optimization from θ0 with solver..."
7737c2fa 264
6dd5c2ac
BA
265 if (!is.list(θ0))
266 stop("θ0: list")
7737c2fa
BA
267 if (is.null(θ0$β))
268 stop("At least θ0$β must be provided")
0f5fbd13
BA
269 if (!is.matrix(θ0$β) || any(is.na(θ0$β))
270 || nrow(θ0$β) != d || ncol(θ0$β) != K)
271 {
272 stop("θ0$β: matrix, no NA, nrow = d, ncol = K")
273 }
7737c2fa
BA
274 if (is.null(θ0$p))
275 θ0$p = rep(1/K, K-1)
0f5fbd13
BA
276 else if (!is.numeric(θ0$p) || length(θ0$p) != K-1
277 || any(is.na(θ0$p)) || sum(θ0$p) > 1)
278 {
279 stop("θ0$p: length K-1, no NA, positive integers, sum to <= 1")
280 }
ab35f610
BA
281 # NOTE: [["b"]] instead of $b because $b would match $beta (in pkg-cran)
282 if (is.null(θ0[["b"]]))
7737c2fa 283 θ0$b = rep(0, K)
0f5fbd13
BA
284 else if (!is.numeric(θ0$b) || length(θ0$b) != K || any(is.na(θ0$b)))
285 stop("θ0$b: length K, no NA")
86f257f8
BA
286
287 # (Re)Set W to identity, to allow several run from the same object
35ffd710 288 W <<- if (is.null(userW)) diag(d+d^2+d^3) else userW
86f257f8 289
ab35f610 290 # NOTE: loopMax = 3 seems to not improve the final results.
35ffd710 291 loopMax <- ifelse(is.null(userW), 2, 1)
2591fa83 292 x_init <- linArgs(θ0)
ef0d907c 293 for (loop in 1:loopMax)
4bf8494d 294 {
35ffd710 295 op_res <- constrOptim( x_init, .self$f, .self$grad_f,
4bf8494d
BA
296 ui=cbind(
297 rbind( rep(-1,K-1), diag(K-1) ),
298 matrix(0, nrow=K, ncol=(d+1)*K) ),
299 ci=c(-1,rep(0,K-1)) )
ef0d907c
BA
300 if (loop < loopMax) #avoid computing an extra W
301 W <<- computeW(expArgs(op_res$par))
2989133a 302 #x_init <- op_res$par #degrades performances (TODO: why?)
4bf8494d 303 }
4263503b 304
6dd5c2ac
BA
305 expArgs(op_res$par)
306 }
307 )
cbd88fe5
BA
308)
309
310# Compute vectorial E[g^{(order)}(<β,x> + b)] with x~N(0,Id) (integral in R^d)
311# = E[g^{(order)}(z)] with z~N(b,diag(λ))
4263503b 312# by numerically evaluating the integral.
cbd88fe5
BA
313#
314# @param link Link, 'logit' or 'probit'
315# @param order Order of derivative
316# @param λ Norm of columns of β
317# @param b Intercept
318#
319.G <- function(link, order, λ, b)
320{
6dd5c2ac
BA
321 # NOTE: weird "integral divergent" error on inputs:
322 # link="probit"; order=2; λ=c(531.8099,586.8893,523.5816); b=c(-118.512674,-3.488020,2.109969)
323 # Switch to pracma package for that (but it seems slow...)
4263503b
BA
324 sapply( seq_along(λ), function(k) {
325 res <- NULL
326 tryCatch({
327 # Fast code, may fail:
328 res <- stats::integrate(
329 function(z) .deriv[[link]][[order]](λ[k]*z+b[k]) * exp(-z^2/2) / sqrt(2*pi),
330 lower=-Inf, upper=Inf )$value
331 }, error = function(e) {
332 # Robust slow code, no fails observed:
333 sink("/dev/null") #pracma package has some useless printed outputs...
334 res <- pracma::integral(
335 function(z) .deriv[[link]][[order]](λ[k]*z+b[k]) * exp(-z^2/2) / sqrt(2*pi),
336 xmin=-Inf, xmax=Inf, method="Kronrod")
337 sink()
338 })
339 res
340 })
cbd88fe5
BA
341}
342
343# Derivatives list: g^(k)(x) for links 'logit' and 'probit'
344#
345.deriv <- list(
6dd5c2ac
BA
346 "probit"=list(
347 # 'probit' derivatives list;
348 # NOTE: exact values for the integral E[g^(k)(λz+b)] could be computed
349 function(x) exp(-x^2/2)/(sqrt(2*pi)), #g'
350 function(x) exp(-x^2/2)/(sqrt(2*pi)) * -x, #g''
351 function(x) exp(-x^2/2)/(sqrt(2*pi)) * ( x^2 - 1), #g^(3)
352 function(x) exp(-x^2/2)/(sqrt(2*pi)) * (-x^3 + 3*x), #g^(4)
353 function(x) exp(-x^2/2)/(sqrt(2*pi)) * ( x^4 - 6*x^2 + 3) #g^(5)
354 ),
355 "logit"=list(
356 # Sigmoid derivatives list, obtained with http://www.derivative-calculator.net/
357 # @seealso http://www.ece.uc.edu/~aminai/papers/minai_sigmoids_NN93.pdf
358 function(x) {e=exp(x); .zin(e /(e+1)^2)}, #g'
359 function(x) {e=exp(x); .zin(e*(-e + 1) /(e+1)^3)}, #g''
360 function(x) {e=exp(x); .zin(e*( e^2 - 4*e + 1) /(e+1)^4)}, #g^(3)
361 function(x) {e=exp(x); .zin(e*(-e^3 + 11*e^2 - 11*e + 1) /(e+1)^5)}, #g^(4)
362 function(x) {e=exp(x); .zin(e*( e^4 - 26*e^3 + 66*e^2 - 26*e + 1)/(e+1)^6)} #g^(5)
363 )
cbd88fe5
BA
364)
365
366# Utility for integration: "[return] zero if [argument is] NaN" (Inf / Inf divs)
367#
368# @param x Ratio of polynoms of exponentials, as in .S[[i]]
369#
370.zin <- function(x)
371{
6dd5c2ac
BA
372 x[is.nan(x)] <- 0.
373 x
cbd88fe5 374}