### PCA to estimate genetic distances based in PCA 

library(ecodist)
library(SNPRelate)


#In your home directory you should have the vcf file 

#Set your home directory
setwd("~/Path")


vcf_f <- "./SNPS.recode.vcf"

#Convert vcf file to Genomic Data Structure format
gds_f<-snpgdsVCF2GDS(vcf_f, "Ad3", method="biallelic.only", verbose = TRUE) 
genofile <- snpgdsOpen("gds_f")  
snpgdsSummary("gds_f")

#Principal Component Analysis 
pca<-snpgdsPCA(genofile,autosome.only = FALSE, num.thread=2, eigen.cnt=100)
pc.percent <- pca$varprop*100


#genetic distances based on dissimilarity of individual genotypes by calculating the Euclidean distance-based on PCA
pca.dist<-distance(pca$eigenvect[,y:x], method = "euclidean") # Note: [,y:x] = specify the range of eigenvectors to consider: CVM ([,1:33]), ECLM ([,1:57]), PNLM ([,1:87]) 
GD.dist<-as.dist(pca_dist)
GD.mat<-as.matrix(GD.dist)

save(GD.mat, file="./GeneticDistance_Slope.rda") #Slope represents our regional scales (CVM, ECLM) or our global scale (PNLM)
