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