library(FactoMineR) 
if(FALSE) {
  experts=read.csv("data/sensory/perfumes_qda_experts.csv")
head(experts)
temp=subset(experts,Panelist=="CM")[,4:ncol(experts)]
tmp10=temp[1:12,]
tmp1=tmp10[,-1]
rownames(tmp1)=tmp10[,1]

tmp20=temp[13:24,]
tmp2=tmp20[,-1]
rownames(tmp2)=tmp20[,1]
tmp2=tmp2[rownames(tmp1),]
(tmp1+tmp2)/2
}
#5.1
Panelists=read.csv("data/sensory/perfumes_qda_experts.csv")[,"Panelist"]
unique(Panelists)

tmp = read.csv("data/sensory/perfumes_fcp.csv")
FCP=tmp[,-1]
rownames(FCP)=tmp[,1]
colnames(FCP)


id.MLD <- grep(pattern="_MLD",x=colnames(FCP))
out.MLD <- PCA(FCP[,id.MLD],graph=FALSE)
dev.new();plot(out.MLD,axes=c(1,2))
dev.new();plot(out.MLD,axes=c(2,3))


id.CM=grep(pattern="_CM",x=colnames(FCP))
dev.new();out.CM <- PCA(FCP[,id.CM],graph=FALSE)

out.GV <- PCA(FCP[,id.GV],graph=FALSE)
par(mfrow=c(1,2))
plot(out.GV,axes=c(1,2))
plot(out.GV,axes=c(2,3))
par(mfrow=c(1,1))



# 5.2 Using MFA 
library(FactoMineR)
MFA(FCP,
    group=c(6,7,9,10,8,8,3,4,8,6,5,6),
    type=rep("s",12),
    name.group=c("CM","CR","GV","MLD","NMA","PR","RL","SD","SM","SO","SQ","ST"),
    graph = FALSE)




LIST=strsplit(colnames(FCP),"_")
panelist.ID=NULL
for (i in seq(length(LIST))) { 
  panelist.ID=c(panelist.ID, LIST[[i]][2])

}

pattern_ID=paste0("_",unique(panelist.ID))

GROUP.no=NULL
 for (i in pattern_ID) {
GROUP.no=c(GROUP.no,length(grep(pattern=i,x=colnames(FCP))))
}

out.MFA <- MFA(FCP,
               type=rep("s",12), 
               group=GROUP.no,
               name.group=unique(panelist.ID),
               graph = FALSE)

names(out.MFA)
out.MFA$separate.analyses$SM$ind
out.MFA$eig


dev.new();plot(out.MFA,choix="ind",select="contrib 8") #Fig 5.1-2
#dev.new();plot(out.MFA,choix="ind",select="v.test 2")

dev.new();plot(out.MFA,choix="var",select="contrib 10",axes=c(1,3)) #Fig 5.1-3
dev.new();plot(out.MFA,choix="var",select="cos2 0.8")

dimdesc(out.MFA)$Dim.1$quanti
dimdesc(out.MFA)$Dim.2$quanti


PC=out.MFA$global.pca$ind$coord

cor.test(PC[,1],FCP[,"Floral_SO"])
cor.test(PC[,2],FCP[,"Greedy_GV"])

Greedy <- grep(pattern="Greedy",x=colnames(FCP),value=TRUE)
dev.new();plot(out.MFA,choix="var",select=Greedy)

out.HCPC <- HCPC(out.MFA, graph=FALSE)
dev.new();plot(out.HCPC, choice="tree")
dev.new();plot(out.HCPC, choice="bar")
dev.new();plot.HCPC.right(out.HCPC, 
                          choice="map", 
                          legend = list(bty = "y", x = "topright"))
dev.new();plot(out.HCPC, choice="3D.map")

dev.new();plot(out.MFA,
               choix="ind",
               partial="all",
               habillage="group")


dev.new();plot(out.MFA,
               choix="ind",
               partial="all",
               habillage="group",
               select=c("Lolita Lempicka","Pure Poison"))

dev.new();plot(out.MFA,
               choix="ind",
               partial="all",
               habillage="group",
               select=c("J'adore EP","Chanel N5"))

dev.new();plot(out.MFA,
               choix="ind",
               partial="all",
               habillage="group",
               select=c("Angel","Cinema"))




# 5.3

library("FactoMineR")
library("factoextra")
tmp<-read.csv("data/sensory/wines.csv")
wine=tmp[,-1]
rownames(wine)=tmp[,1]
head(wine,3)
colnames(wine)
wine.MFA <- MFA(wine, 
               group = c(2, 5, 3, 10, 9, 2), 
               type = c("n", "s", "s", "s", "s", "s"),
               name.group = c("origin","odor","visual",
                              "odor.after.shaking", "taste","overall"),
               num.group.sup = c(1, 6),
               graph = FALSE)

print(wine.MFA)
head(wine.MFA$eig)
dev.new();fviz_screeplot(wine.MFA) # 5.3-3

#Groups of variables: choice="group"
group <- get_mfa_var(wine.MFA, element  ="group")
group

# Coordinates of groups
group$coord

# Cos2: quality of representation on the factore map
group$cos2

# Contributions to the  dimensions
group$contrib

#To plot the groups of variables
dev.new();fviz_mfa_var(wine.MFA, 
                       choice ="group",
                       col.var = "red",
                       col.var.sup = "blue") # 5.3-4
#col.var = active groups of variables
#col.var.sup = supplementary groups of variables




# Contribution to the first dimension
#dev.new();
fig535A<-fviz_contrib(wine.MFA, choice ="group", axes = 1)+ 
  theme(axis.text.x = element_text(angle=0))+
  coord_flip() # 5.3-5A

# Contribution to the second dimension
#dev.new();
fig535B<-fviz_contrib(wine.MFA, choice ="group", axes = 2)+ 
  theme(axis.text.x = element_text(angle=0))+
  coord_flip()  # 5.3-5B

dev.new();gridExtra::grid.arrange(fig535A, fig535B, ncol = 2)


# Quantitative variables
# The function get_mfa_var() [in factoextra] is used to 
# extract the results for quantitative variables. 
# This function returns a list containing the coordinates, 
# the cos2 and the contribution of variables:
  
quanti.var <- get_mfa_var(wine.MFA, choice ="quanti.var")
quanti.var 
# Coordinates
quanti.var$coord
# Cos2: quality on the factore map
quanti.var$cos2
# Contributions to the dimensions
quanti.var$contrib

dev.new();fviz_mfa_var(wine.MFA, choice ="quanti.var", palette = "jco", 
             col.var.sup = "violet", repel = TRUE)# 5.3-6

dev.new();fviz_mfa_var(wine.MFA, choice ="quanti.var", palette = "jco", 
             col.var.sup = "violet", repel = TRUE,
             geom = c("point", "text"), legend = "bottom") # 5.3-7


# Contributions to dimension 1
#dev.new()
fig539A<-fviz_contrib(wine.MFA, choice = "quanti.var",
             axes = 1,
             top = 20,
             palette = "jco") + 
  theme(axis.text.x = element_text(angle=0))+
  coord_flip() # 5.3-8A
  
# Contributions to dimension 2
#dev.new()
fig539B<-
  fviz_contrib(wine.MFA, choice = "quanti.var",
                       axes = 2,
                       top = 20,
                       palette = "jco")+ 
  theme(axis.text.x = element_text(angle=0))  + 
  coord_flip()# 5.3-8B

#library("gridExtra")
dev.new();gridExtra::grid.arrange(fig538A, fig538B, ncol = 2)

# Contributions to dimension 1+2
dev.new();fviz_contrib(wine.MFA, choice = "quanti.var",
                       axes = 1:2,
                       top = 20,
                       palette = "jco")  + 
  coord_flip()# 5.3-9



dev.new();fviz_mfa_var(wine.MFA, choice ="quanti.var", col.var = "contrib", 
             gradient.cols = c("#00AFBB", "#E7B800", "#FC4E07"), 
             col.var.sup = "violet", repel = TRUE,
             geom = c("point", "text"))# 5.3-10

# Color by cos2 values: quality on the factor map
dev.new();fviz_mfa_var(wine.MFA, choice ="quanti.var",col.var = "cos2",
             gradient.cols = c("#00AFBB", "#E7B800", "#FC4E07"), 
             col.var.sup = "violet", repel = TRUE)# 5.3-11

# To create a bar plot of variables cos2, type this:
dev.new();fviz_cos2(wine.MFA, choice = "quanti.var", axes = 1)  +
  theme(axis.text.x = element_text(angle=0))  +
  coord_flip() # 5.3-12




#Graph of individuals
#To get the results for individuals, type this:
  
ind <- get_mfa_ind(wine.MFA)
ind
# To plot individuals, use fviz_mfa_ind(). 
# By default, individuals are colored in blue. However, like variables, 
# it’s also possible to color individuals by their cos2 values
dev.new();fviz_mfa_ind(wine.MFA, col.ind = "cos2", 
             gradient.cols = c("#00AFBB", "#E7B800", "#FC4E07"),
             repel = TRUE)# 5.3-13

#If you want to color the wines according to the supplementary qualitative variable “Label”
dev.new();fviz_mfa_ind(wine.MFA, 
             habillage = "Label", # color by groups 
             palette = c("#00AFBB", "#E7B800", "#FC4E07"),
             addEllipses = TRUE, ellipse.type = "confidence", 
             repel = TRUE # Avoid text overlapping
             ) # 5.3-14

#Color individuals using multiple categorical variables at the same time
dev.new();fviz_ellipses(wine.MFA, c("Label", "Soil"), 
                        repel = TRUE) # 5.3-15

# Alternatively, you can specify categorical variable indices:
  
dev.new();fviz_ellipses(wine.MFA, 1:2, geom = "point") # 5.3-16


## Graph of partial individuals

#The graph of partial individuals represents each wine viewed by each group
# and its barycenter. To plot the partial points of all individuals, type this:
  
dev.new();fviz_mfa_ind(wine.MFA, partial = "all") # 5.3-17
# If you want to visualize partial points for wines of interest, 
# let say c(“1DAM”, “1VAU”, “2ING”), use this:
  
dev.new();fviz_mfa_ind(wine.MFA, 
                       partial = c("1DAM", "1VAU", "2ING")) # 5.3-18

## Graph of partial axes
# The graph of partial axes shows the relationship between 
# the principal axes of the MFA and the ones obtained from analyzing
# each group using either a PCA (for groups of continuous variables) or a MCA (for qualitative variables).

dev.new();fviz_mfa_axes(wine.MFA) # 5.3-19


## Using PCA instead of MFA
names(wine)
winePCA <- PCA(wine,quali.sup=1:2,quanti.sup=30:31,graph=FALSE)
dev.new();plot(winePCA,col.quali="gray48", 
                   repel = TRUE)
dev.new();plot(winePCA,col.quali="gray48",
                   habillage=2,
                   col.hab=c("gray","azure4", "black","gainsboro"), 
                   repel = TRUE)

dev.new();plot(winePCA,
               choix="var",
               col.var="gray",
               col.quanti="black", 
               repel = TRUE)




