T1 <- read.table("presCM.txt", header=T, sep="\t");
T2 <- read.table("presCM2.txt", header=T, sep="\t");
T1$NonExprime <- T1$Inscrits - T1$Exprimes
T2$NonExprime <- T2$Inscrits - T2$Exprimes



candidatsT1 <- c("NonExprime", "BESANCENOT", "BUFFET", "SCHIVARDI", "BAYROU", "BOVE", "VOYNET", "DE.VILLIERS", "ROYAL", "NIHOUS", "LE.PEN", "LAGUILLER", "SARKOZY")
candidatsT2 <- c("NonExprime", "SARKOZY", "ROYAL")
n <- length(candidatsT1);
nbBureaux <- dim(T1)[1];

T2$t1 <- as.matrix(T1[,candidatsT1])


modROYAL <- lm(ROYAL ~ 0+t1, data=T2).html
summary(modROYAL)

modDiff <- lm(ROYAL-SARKOZY ~ t1, data=T2).html
summary(modDiff)

Tab <- data.frame(Finaliste=c(rep("SARKOZY", nbBureaux), rep("ROYAL", nbBureaux), rep("Exprimes", nbBureaux)), Votes = c(T2$SARKOZY, T2$ROYAL, T2$ROYAL+T2$SARKOZY), Bureau=rep(T2$Bureau, 3))
M1 <- matrix(0, ncol=2*n, nrow=3*nbBureaux);
M1[1:nbBureaux,1:n] = as.matrix(T1[,candidatsT1])
M1[(nbBureaux+1):(2*nbBureaux),(n+1):(2*n)] = as.matrix(T1[,candidatsT1])
M1[(2*nbBureaux+1):(3*nbBureaux),1:n] = as.matrix(T1[,candidatsT1])
M1[(2*nbBureaux+1):(3*nbBureaux),(n+1):(2*n)] = as.matrix(T1[,candidatsT1])
Tab$t1 <- M1;
modComplet <- lm(Votes~0+t1, data=Tab).html
theta <- modComplet$coefficients;
tauxTransferts <- data.frame()
for (j in 1:n){
  tauxTransferts["T2_SARKOZY", candidatsT1[j]] <- theta[j];
  tauxTransferts["T2_ROYAL", candidatsT1[j]] <- theta[n+j];
  tauxTransferts["Non exprime", candidatsT1[j]] <- 1-theta[j]-theta[n+j];
}
tauxTransferts


erreur <- function(b){
  sum((Tab$t1 %*% b - Tab$Votes)^2)
}
UI <- matrix(0, ncol = 2*n, nrow = 5*n);
CI <- rep(0, 5*n)
for (j in 1:n){
  UI[j, j] = 1; UI[n+j, n+j] = 1;
  CI[j] = 0; CI[n+j] = 0;

  UI[2*n+j, j] = -1; UI[3*n+j, n+j] = -1;
  CI[2*n+j] = -1; CI[3*n+j] = -1;
  
  UI[4*n+j, j] = -1; UI[4*n+j, n+j] = -1;
  CI[4*n+j] = -1;
}
UI <- UI * (1-10^(-11));

initialGuess <- rep(1/3, 2*n)
erreur(initialGuess)
res <- constrOptim(initialGuess, grad=NULL, erreur, ui=UI, ci=CI)
theta <- res$par
tauxTransferts <- data.frame()
for (j in 1:n){
  tauxTransferts["T2_SARKOZY", candidatsT1[j]] <- theta[j];
  tauxTransferts["T2_ROYAL", candidatsT1[j]] <- theta[n+j];
  tauxTransferts["Non exprime", candidatsT1[j]] <- 1-theta[j]-theta[n+j];
}
round(100*tauxTransferts)
