setwd()
library(Morpho)
library(geomorph)
library(rgl)
library(ggplot2)
library(ggConvexHull)
library(ggfortify)
library(cluster)
library(ggrepel)
library(class)
library(stats)
library(mclust)
library(diptest)
library(nortest)

load(file=SLIDED_FILE_HERE) # Working for complete and distal femur + complete tibia

#GPA
gpa<-procSym(slided$dataslide)

#PCA
plot(gpa$PCscores[,1],gpa$PCscores[,2],cex=1,pch=16,col="black", xlab=gpa$Variance[1,2], ylab=gpa$Variance[2,2])
text(gpa$PCscores[,1],gpa$PCscores[,2],as.vector(lab),col=1, pos=1, cex=0.5, font=3)

#Allometry
size<-gpa$size
pcs<-gpa$PCscores[,1]
lgs<-log(size)
cor.test(pcs,lgs)

#Mixture Modelling PC1
Gmix<-Mclust(gpa$PCscores[,1])
summary(Gmix, parameters = TRUE)

#PC1 Min and Max theoretical shapes###########
gpag<-gpagen(slided$dataslide)
gpa<-gm.prcomp(gpag$coords)
summary(gpa)
plot(gpa)
#Meanshape
meanshape<-gpag$consensus
meanshape<-mirror(as.matrix(meanshape))
write.pts(meanshape, filename="./Landmark/Femur/Complet/Slide/Meanshape/RFem_meanshape")
meshape<-tps3d(template,as.matrix(ptstemp), as.matrix(meanshape))
#meshape<-warpRefMesh(template,as.matrix(ptstemp), as.matrix(meanshape), centered = FALSE)
#meshape<-mirror(meshape, icpiter = 1)
plot3d(meshape, col="cornsilk", specular=1,add=T)
mesh2ply(meshape, filename = "./Landmark/Femur/Complet/Slide/Meanshape/RFem_meanshape")
meshape<-ply2mesh(filename="./Landmark/Femur/Complet/Slide/Meanshape/RFem_meanshape")
#MIN et MAX shapes
PC1<-gpa$x[,1]
PC2<-gpa$x[,2]
PC3<-gpa$x[,3]

pPC1<-shape.predictor(gpag$coords, x=PC1, intercept=FALSE, min=min(PC1), max=max(PC1))
pPC2<-shape.predictor(gpag$coords, x=PC2, intercept=FALSE, min=min(PC2), max=max(PC2))
pPC3<-shape.predictor(gpag$coords, x=PC3, intercept=FALSE, min=min(PC3), max=max(PC3))

########## mean shape / group (Morph A and B) along PC1

### mean
mnA<-as.numeric("-0.0173959196666667") # mean of every specimen from Morph A was calculated based on their coordinates from the GPA/PC1
mnB<-as.numeric("0.0257217905") ## mean of every specimen from Morph B was calculated based on their coordinates from the GPA/PC1

mPC1<-shape.predictor(gpag$coords, x= PC1, intercept=FALSE, min=mnA , max=mnB)

##PC1
PC1minshape<-mPC1$min
PC1maxshape<-mPC1$max
PC1minshape<-mirror(PC1minshape, icpiter = 1)
PC1maxshape<-mirror(PC1maxshape, icpiter = 1)
write.pts(PC1minshape, filename="./Landmark/Femur/Complet/Slide/Meanshape/RFem_minshape")
write.pts(PC1maxshape, filename="./Landmark/Femur/Complet/Slide/Meanshape/RFem_maxshape")
minshape<-tps3d(meshape, as.matrix(meanshape), as.matrix(PC1minshape))
maxshape<-tps3d(meshape, as.matrix(meanshape), as.matrix(PC1maxshape))

deformGrid3d(PC1minshape,PC1maxshape, col1="goldenrod1", col2="forestgreen", type="s", size=0.0005, align=T, createMesh=T, add=T)

#SAVE
mesh2ply(minshape, filename = "./Landmark/Femur/Complet/Slide/Meanshape/RFem_minshapePC1")
mesh2ply(maxshape, filename = "./Landmark/Femur/Complet/Slide/Meanshape/RFem_maxshapePC1")

