remove also NY21 as in R code
[valse.git] / test / generate_test_data / EMGrank.R
CommitLineData
c3bc4705 1#helper to always have matrices as arg (TODO: put this elsewhere? improve?)
f7244815 2# --> Yes, we should use by-columns storage everywhere... [later!]
c3bc4705
BA
3matricize <- function(X)
4{
5 if (!is.matrix(X))
6 return (t(as.matrix(X)))
7 return (X)
8}
9
c3b2c1ab 10require(MASS)
f7244815 11EMGrank_R = function(Pi, Rho, mini, maxi, X, Y, tau, rank)
ef67d338 12{
c2028869
BG
13 #matrix dimensions
14 n = dim(X)[1]
15 p = dim(X)[2]
16 m = dim(Rho)[2]
17 k = dim(Rho)[3]
18
19 #init outputs
20 phi = array(0, dim=c(p,m,k))
21 Z = rep(1, n)
c2028869
BG
22 LLF = 0
23
24 #local variables
25 Phi = array(0, dim=c(p,m,k))
ef67d338
BA
26 deltaPhi = c()
27 sumDeltaPhi = 0.
c2028869
BG
28 deltaPhiBufferSize = 20
29
30 #main loop
31 ite = 1
ef67d338 32 while (ite<=mini || (ite<=maxi && sumDeltaPhi>tau))
c3bc4705 33 {
c2028869 34 #M step: Mise à jour de Beta (et donc phi)
c3bc4705
BA
35 for(r in 1:k)
36 {
37 Z_indice = seq_len(n)[Z==r] #indices où Z == r
38 if (length(Z_indice) == 0)
c2028869 39 next
c2028869 40 #U,S,V = SVD of (t(Xr)Xr)^{-1} * t(Xr) * Yr
c3bc4705
BA
41 s = svd( ginv(crossprod(matricize(X[Z_indice,]))) %*%
42 crossprod(matricize(X[Z_indice,]),matricize(Y[Z_indice,])) )
43 S = s$d
c2028869
BG
44 #Set m-rank(r) singular values to zero, and recompose
45 #best rank(r) approximation of the initial product
c3bc4705
BA
46 if(rank[r] < length(S))
47 S[(rank[r]+1):length(S)] = 0
ef67d338 48 phi[,,r] = s$u %*% diag(S) %*% t(s$v) %*% Rho[,,r]
c2028869 49 }
ef67d338 50
c3bc4705
BA
51 #Etape E et calcul de LLF
52 sumLogLLF2 = 0
ef67d338
BA
53 for(i in seq_len(n))
54 {
c3bc4705
BA
55 sumLLF1 = 0
56 maxLogGamIR = -Inf
ef67d338
BA
57 for (r in seq_len(k))
58 {
c3bc4705
BA
59 dotProduct = tcrossprod(Y[i,]%*%Rho[,,r]-X[i,]%*%phi[,,r])
60 logGamIR = log(Pi[r]) + log(det(Rho[,,r])) - 0.5*dotProduct
61 #Z[i] = index of max (gam[i,])
ef67d338
BA
62 if(logGamIR > maxLogGamIR)
63 {
c3bc4705
BA
64 Z[i] = r
65 maxLogGamIR = logGamIR
66 }
ef67d338 67 sumLLF1 = sumLLF1 + exp(logGamIR) / (2*pi)^(m/2)
c3bc4705
BA
68 }
69 sumLogLLF2 = sumLogLLF2 + log(sumLLF1)
70 }
c2028869 71
c3bc4705 72 LLF = -1/n * sumLogLLF2
ef67d338 73
c3bc4705 74 #update distance parameter to check algorithm convergence (delta(phi, Phi))
ef67d338
BA
75 deltaPhi = c( deltaPhi, max( (abs(phi-Phi)) / (1+abs(phi)) ) ) #TODO: explain?
76 if (length(deltaPhi) > deltaPhiBufferSize)
77 deltaPhi = deltaPhi[2:length(deltaPhi)]
c3bc4705 78 sumDeltaPhi = sum(abs(deltaPhi))
ef67d338 79
c3bc4705
BA
80 #update other local variables
81 Phi = phi
82 ite = ite+1
c2028869 83 }
ef67d338 84 return(list("phi"=phi, "LLF"=LLF))
9ade3f1b 85}