correction emgrank.R
[valse.git] / src / test / generate_test_data / helpers / EMGrank.R
CommitLineData
c3b2c1ab
BG
1source("/home/goehry/Documents/valse/valse/R/vec_bin.R")
2require(MASS)
3EMGrank = function(Pi, Rho, mini, maxi, X, Y, tau, rank){
c2028869
BG
4 #matrix dimensions
5 n = dim(X)[1]
6 p = dim(X)[2]
7 m = dim(Rho)[2]
8 k = dim(Rho)[3]
9
10 #init outputs
11 phi = array(0, dim=c(p,m,k))
12 Z = rep(1, n)
13 Pi = piInit
14 LLF = 0
15
16 #local variables
17 Phi = array(0, dim=c(p,m,k))
18 deltaPhi = c(0)
19 sumDeltaPhi = 0
20 deltaPhiBufferSize = 20
21
22 #main loop
23 ite = 1
24 while(ite<=mini || (ite<=maxi && sumDeltaPhi>tau)){
25 #M step: Mise à jour de Beta (et donc phi)
26 for(r in 1:k){
27 Z_bin = vec_bin(Z,r)
28 Z_vec = Z_bin$vec #vecteur 0 et 1 aux endroits o? Z==r
29 Z_indice = Z_bin$indice
30 if(sum(Z_indice) == 0){
31 next
32 }
33 #U,S,V = SVD of (t(Xr)Xr)^{-1} * t(Xr) * Yr
c3b2c1ab
BG
34 sv = svd(ginv( crossprod(X[Z_indice,]) ) %*% crossprod(X[Z_indice,], Y[Z_indice,]) )
35 S = diag(sv$d)
36 U = sv$u
37 V = sv$v
c2028869
BG
38 #Set m-rank(r) singular values to zero, and recompose
39 #best rank(r) approximation of the initial product
c3b2c1ab
BG
40 if(r==k){
41 j_r_1 = length(S)
42 }
43 else{
44 j_r_1 = c(rank[r]+1:length(S))
45 }
46 S[j_r_1] = 0
47 S = diag(S, nrow = ncol(U))
48 phi[,,r] = U %*% S %*% t(V) %*% Rho[,,r]
c2028869
BG
49 }
50
51 #Etape E et calcul de LLF
52 sumLogLLF2 = 0
53 for(i in 1:n){
54 sumLLF1 = 0
55 maxLogGamIR = -Inf
56 for(r in 1:k){
57 dotProduct = tcrossprod(Y[i,]%*%Rho[,,r]-X[i,]%*%phi[,,r])
58 logGamIR = log(Pi[r]) + log(det(Rho[,,r])) - 0.5*dotProduct
59 #Z[i] = index of max (gam[i,])
60 if(logGamIR > maxLogGamIR){
61 Z[i] = r
62 maxLogGamIR = logGamIR
63 }
64 sumLLF1 = sumLLF1 + exp(logGamIR) / (2*pi)^(m/2)
65 }
66 sumLogLLF2 = sumLogLLF2 + log(sumLLF1)
67 }
68
69 LLF = -1/n * sumLogLLF2
70
71 #update distance parameter to check algorithm convergence (delta(phi, Phi))
72 deltaPhi = c(deltaPhi, max(max(max((abs(phi-Phi))/(1+abs(phi))))) )
73 if(length(deltaPhi) > deltaPhiBufferSize){
c3b2c1ab
BG
74 l_1 = c(2:length(deltaPhi))
75 deltaPhi = deltaPhi[l_1]
c2028869
BG
76 }
77 sumDeltaPhi = sum(abs(deltaPhi))
78
79 #update other local variables
80 Phi = phi
81 ite = ite+1
82
83 }
84 return(list(phi=phi, LLF=LLF))
85}