############### Getting set up ###################

### Set working directory to source file location

###Load geomorph package
library(geomorph) # works with 2.1.5

############################################################
######                MALE BODY SHAPE                #######
############################################################

###### Load tps data 

maleLand <- readland.tps("gen8malebod_dots.tps",specID = c("ID")) # reads a .tps file and calls it Land


############## PROCRUSTES SUPERIMPOSITION ################

### Generalised procrustes alignment of raw tps coordinates
maleLand.gpa <- gpagen(maleLand)


############### MULTIVARIATE ANALYSES #####################

# Import file with treatments (specimens must be in same order)
malegambusiatreatments <-read.csv("malegambusiatreatments.csv", header=T)

# Shorten names
## From generalised procrustes alignment above
Y <- maleLand.gpa$coords
CS <- maleLand.gpa$Csize

## From gambusia treatments file
Sel<- malegambusiatreatments$Selection.regime # selection regime
Line<- malegambusiatreatments$Line    # lines

###### Model to test if selection regime influences multivariate shape

procD.lm(Y ~ Sel/Line*log(CS):Sel/Line,iter=999)

###### Pairwise comparison of selection regimes (included log CS because looking at the effects of selection regime once size related variation has been accounted for)
advanced.procD.lm(Y ~ log(CS),~log(CS)+Sel, 
                  groups = ~ Sel,slope=~log(CS),angle.type="deg", iter=999)


################## VISUALISATION #####################

###### Visualising the relationship between shape and size

## plotAllometry does regression of multivariate shape on log centroid size and gives output for figures to visualise size related shape variation
male.allom <- plotAllometry(maleLand.gpa$coords~maleLand.gpa$Csize,method = "RegScore", verbose=T) 

## verbose=T (in above) saves a lot of useful variables
## these are used for the shape v size plot    
male.allom$allom.score  # A matrix of the allometry shape scores
male.allom$logSize      # A matrix of log centroid size       

## To make the above into a table and write it to a csv file (that I then open in Excel to make plots)
name<-data.frame(logsize=male.allom$logSize,score=male.allom$allom.score)
write.table(name,file="male.allom.output.csv")

## Visualizing size associated shape changes (for warp pics in fig)
ref = mshape(maleLand.gpa$coords)     # save mean shape
GP1<-gridPar(pt.bg = "black",pt.size = 2,grid.lwd = 2)  ###sets up the way the figure looks
# plot biggest fish relative too mean fish
plotRefToTarget(ref,maleLand.gpa$coords[,,which.max(maleLand.gpa$Csize)],gridPars = GP1)     
# plot smallest fish relative too mean fish
plotRefToTarget(ref,maleLand.gpa$coords[,,which.min(maleLand.gpa$Csize)],gridPars = GP1)

# Visualize shape differences between group means
# Create mean shape for each selection regime
Down.mn <- mshape(Y[,,which(Sel == "D")]) 
Con.mn <- mshape(Y[,,which(Sel == "C")])
Up.mn <- mshape(Y[,,which(Sel == "U")])

##import dataset gambusialinks (for putting lines on grids) are the wireframe links to aid visualizations
malegambusialinks <-read.csv("malegambusialinks.csv", header=F)

# Create plots with links
plotRefToTarget(Con.mn,Down.mn,mag=10,method="points",links = malegambusialinks)
plotRefToTarget(Down.mn,Up.mn,mag=10,method="points",links = malegambusialinks)
plotRefToTarget(Con.mn,Up.mn,mag=10,method="points",links = malegambusialinks)

