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