### To estimate spatial genetic neighborhoods 

library (memgene)
library (gstudio)
Library (raster)

#In your home directory you should have the genetic distances (GeneticDistance_Slope.rda), a.csv file with the spatial coordinates and the raster of interest

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

#Load genetic distance 
load("GeneticDistance_Slope.rda")


#Load sampling points 
Coords_csv <- read.csv("Coordinates_Slope.csv", header=TRUE, sep = ",")
Coords<- strata_coordinates(Coords_csv, stratum="ID", longitude="x", latitude="y")
Coords<-Coords[,2:3]


# Find Moran’s eigenvectors maps applying a regression framework versus genetic distances 

neighborhood <- mgQuick(GD.mat, Coords)
neighborhood$RsqAdj #genetic variation explained by spatial pattern
neighborhoodProp <- neighborhood$sdev/sum(neighborhood$sdev) #Variation explained by each MEM
format(signif(neighborhoodProp, x)[1:x], scientific=FALSE) # Note: x must be the number of significant Mem detected 

#Plot MEM variables 
Environmental.Var<-raster("Raster.tif") # raster of interest
mgMap(Coords, neighborhood$memgene[, 1:1], add.plot=TRUE,legend=TRUE) #add.plot is positive if you want superimposing MEM plots on an existing surface.

