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