1 EMGLLF_R = function(phiInit,rhoInit,piInit,gamInit,mini,maxi,gamma,lambda,X,Y,tau)
14 S = array(0, dim=c(p,m,k))
18 Gram2 = array(0, dim=c(p,p,k))
19 ps2 = array(0, dim=c(p,m,k))
20 X2 = array(0, dim=c(n,p,k))
21 Y2 = array(0, dim=c(n,m,k))
26 # Remember last pi,rho,phi values for exit condition in the end of loop
31 # Calcul associé à Y et X
35 Y2[,mm,r] = sqrt(gam[,r]) * Y[,mm]
37 X2[i,,r] = sqrt(gam[i,r]) * X[i,]
39 ps2[,mm,r] = crossprod(X2[,,r],Y2[,mm,r])
43 Gram2[j,s,r] = crossprod(X2[,j,r], X2[,s,r])
52 b = sapply( 1:k, function(r) sum(abs(phi[,,r])) )
54 a = sum(gam %*% log(pi))
56 # Tant que les props sont negatives
58 pi2AllPositive = FALSE
59 while (!pi2AllPositive)
61 pi2 = pi + 0.1^kk * ((1/n)*gam2 - pi)
62 pi2AllPositive = all(pi2 >= 0)
66 # t(m) la plus grande valeur dans la grille O.1^k tel que ce soit décroissante ou constante
67 while( kk < 1000 && -a/n + lambda * sum(pi^gamma * b) <
68 -sum(gam2 * log(pi2))/n + lambda * sum(pi2^gamma * b) )
70 pi2 = pi + 0.1^kk * (1/n*gam2 - pi)
74 pi = (pi + t*(pi2-pi)) / sum(pi + t*(pi2-pi))
83 ps = ps + Y2[i,mm,r] * sum(X2[i,,r] * phi[,mm,r])
84 nY2 = sum(Y2[,mm,r]^2)
85 rho[mm,mm,r] = (ps+sqrt(ps^2+4*nY2*gam2[r])) / (2*nY2)
95 S[j,mm,r] = -rho[mm,mm,r]*ps2[j,mm,r] + sum(phi[-j,mm,r] * Gram2[j,-j,r])
96 if (abs(S[j,mm,r]) <= n*lambda*(pi[r]^gamma))
98 else if(S[j,mm,r] > n*lambda*(pi[r]^gamma))
99 phi[j,mm,r] = (n*lambda*(pi[r]^gamma)-S[j,mm,r]) / Gram2[j,j,r]
101 phi[j,mm,r] = -(n*lambda*(pi[r]^gamma)+S[j,mm,r]) / Gram2[j,j,r]
110 # Precompute det(rho[,,r]) for r in 1...k
111 detRho = sapply(1:k, function(r) det(rho[,,r]))
120 gam[i,r] = pi[r]*exp(-0.5*sum((Y[i,]%*%rho[,,r]-X[i,]%*%phi[,,r])^2))*detRho[r]
121 sumGamI = sumGamI + gam[i,r]
123 sumLogLLH = sumLogLLH + log(sumGamI) - log((2*base::pi)^(m/2))
124 if (sumGamI > EPS) #else: gam[i,] is already ~=0
125 gam[i,] = gam[i,] / sumGamI
128 sumPen = sum(pi^gamma * b)
130 llh = -sumLogLLH/n + lambda*sumPen
131 dist = ifelse( ite == 1, llh, (llh-last_llh) / (1+abs(llh)) )
132 Dist1 = max( (abs(phi-Phi)) / (1+abs(phi)) )
133 Dist2 = max( (abs(rho-Rho)) / (1+abs(rho)) )
134 Dist3 = max( (abs(pi-Pi)) / (1+abs(Pi)) )
135 dist2 = max(Dist1,Dist2,Dist3)
137 if (ite >= mini && (dist >= tau || dist2 >= sqrt(tau)))
141 affec = apply(gam, 1, which.max)
142 list( "phi"=phi, "rho"=rho, "pi"=pi, "llh"=llh, "S"=S, "affec"=affec )