'update'
[valse.git] / R / initSmallEM.R
1 vec_bin = function(X,r)
2 {
3 Z = c()
4 indice = c()
5 j = 1
6 for (i in 1:length(X))
7 {
8 if(X[i] == r)
9 {
10 Z[i] = 1
11 indice[j] = i
12 j=j+1
13 } else
14 Z[i] = 0
15 }
16 return (list(Z=Z,indice=indice))
17 }
18
19 initSmallEM = function(k,X,Y,tau)
20 {
21 n = nrow(Y)
22 m = ncol(Y)
23 p = ncol(X)
24
25 betaInit1 = array(0, dim=c(p,m,k,20))
26 sigmaInit1 = array(0, dim = c(m,m,k,20))
27 phiInit1 = array(0, dim = c(p,m,k,20))
28 rhoInit1 = array(0, dim = c(m,m,k,20))
29 piInit1 = matrix(0,20,k)
30 gamInit1 = array(0, dim=c(n,k,20))
31 LLFinit1 = list()
32
33 require(MASS) #Moore-Penrose generalized inverse of matrix
34 for(repet in 1:20)
35 {
36 clusters = hclust(dist(y)) #default distance : euclidean
37 #cutree retourne les indices (à quel cluster indiv_i appartient) d'un clustering hierarchique
38 clusterCut = cutree(clusters,k)
39 Zinit1[,repet] = clusterCut
40
41 for(r in 1:k)
42 {
43 Z = Zinit1[,repet]
44 Z_bin = vec_bin(Z,r)
45 Z_vec = Z_bin$Z #vecteur 0 et 1 aux endroits où Z==r
46 Z_indice = Z_bin$indice #renvoit les indices où Z==r
47
48 betaInit1[,,r,repet] =
49 ginv(t(x[Z_indice,])%*%x[Z_indice,])%*%t(x[Z_indice,])%*%y[Z_indice,]
50 sigmaInit1[,,r,repet] = diag(m)
51 phiInit1[,,r,repet] = betaInit1[,,r,repet]/sigmaInit1[,,r,repet]
52 rhoInit1[,,r,repet] = solve(sigmaInit1[,,r,repet])
53 piInit1[repet,r] = sum(Z_vec)/n
54 }
55
56 for(i in 1:n)
57 {
58 for(r in 1:k)
59 {
60 dotProduct = (y[i,]%*%rhoInit1[,,r,repet]-x[i,]%*%phiInit1[,,r,repet]) %*%
61 (y[i,]%*%rhoInit1[,,r,repet]-x[i,]%*%phiInit1[,,r,repet])
62 Gam[i,r] = piInit1[repet,r]*det(rhoInit1[,,r,repet])*exp(-0.5*dotProduct)
63 }
64 sumGamI = sum(gam[i,])
65 gamInit1[i,,repet]= Gam[i,] / sumGamI
66 }
67
68 miniInit = 10
69 maxiInit = 11
70
71 new_EMG = .Call("EMGLLF",phiInit1[,,,repet],rhoInit1[,,,repet],piInit1[repet,],
72 gamInit1[,,repet],miniInit,maxiInit,1,0,x,y,tau)
73 LLFEessai = new_EMG$LLF
74 LLFinit1[repet] = LLFEessai[length(LLFEessai)]
75 }
76
77 b = which.max(LLFinit1)
78 phiInit = phiInit1[,,,b]
79 rhoInit = rhoInit1[,,,b]
80 piInit = piInit1[b,]
81 gamInit = gamInit1[,,b]
82
83 return (list(phiInit=phiInit, rhoInit=rhoInit, piInit=piInit, gamInit=gamInit))
84 }