#Landslides as drivers for ecosystem evolution and biophysical diversity
#Author: A. Gonzalez-Ollauri
#Date: 19/07/2016
#School of Engineering and Built Environment, Glasgow Caledonian University, Glasgow, G4 0BA, UK
#Contact: alejandro.ollauri@gcu.ac.uk 
############################################
setwd("/Users/Gollauri/Desktop/Landslides/BDV_paper") #insert path!!
library(vegan)
library(rich)
library(reshape2) #for contingency tables
DATA<-read.csv("DATAset_AGO_SBM_2016.csv")
#MATRICES PREPARATION
#seanson 2015
###############
s15<-DATA[DATA$Season=="2015",]
s15df<-data.frame(loc=s15$Location,pos=s15$Position,sp=s15$Species,id=s15$Id,bm=s15$Pooled.biomass_g_m2,A=s15$Species.abundance)
#subsetting data per location
Tp.15<-s15df[s15df$pos=="T",]
M.15<-s15df[s15df$pos=="M",]
B.15<-s15df[s15df$pos=="B",]
#creating matrices (contingency tables)
M.T.15<-xtabs(bm~loc+sp,data=Tp.15)
M.M.15<-xtabs(bm~loc+sp,data=M.15)
M.B.15<-xtabs(bm~loc+sp,data=B.15)
################
#season 2014
###############
s14<-DATA[DATA$Season=="2014",]
s14df<-data.frame(loc=s14$Location,pos=s14$Position,sp=s14$Species,id=s14$Id,bm=s14$Pooled.biomass_g_m2,A=s14$Species.abundance)
#subsetting data per location
Tp.14<-s14df[s14df$pos=="T",]
M.14<-s14df[s14df$pos=="M",]
B.14<-s14df[s14df$pos=="B",]
#creating matrices (contingency tables)
M.T.14<-xtabs(bm~loc+sp,data=Tp.14)
M.M.14<-xtabs(bm~loc+sp,data=M.14)
M.B.14<-xtabs(bm~loc+sp,data=B.14)

############~DIVERISTY~###############################
#SHANNON INDEX
SN.T.15<-diversity(M.T.15,index="shannon")
SN.M.15<-diversity(M.M.15,index="shannon")
SN.B.15<-diversity(M.B.15,index="shannon")
SN.T.14<-diversity(M.T.14,index="shannon")
SN.M.14<-diversity(M.M.14,index="shannon")
SN.B.14<-diversity(M.B.14,index="shannon")
#SIMPSON's INDEX (1-D): ################################
####################################################
SP.T.15<-diversity(M.T.15,index="simpson")
SP.M.15<-diversity(M.M.15,index="simpson")
SP.B.15<-diversity(M.B.15,index="simpson")
SP.T.14<-diversity(M.T.14,index="simpson")
SP.M.14<-diversity(M.M.14,index="simpson")
SP.B.14<-diversity(M.B.14,index="simpson")
###############################################################################
#INTERPRETATION::
#Simpson
SP.T.15t<-SP.T.15[SP.T.15!=1]
SP.M.15t<-SP.M.15[SP.M.15!=1]
SP.B.15t<-SP.B.15[SP.B.15!=1]
SP.T.14t<-SP.T.14[SP.T.14!=1]
SP.M.14t<-SP.M.14[SP.M.14!=1]
SP.B.14t<-SP.B.14[SP.B.14!=1]

boxplot(SP.T.15t,SP.M.15t,SP.B.15t,SP.T.14t,SP.M.14t,SP.B.14t,ylim=c(0,1),col=c("gray84","gray84","gray84","gray48","gray48","gray48"),main="SIMPSON INDEX",names=c("Crest 15","Middle 15","Toe 15","Crest 14","Middle 14","Toe 14"),ylab="Simpson Index")

#Shannon
SN.T.15t<-SN.T.15[SN.T.15!=0]
mean(SN.T.15t)
sd(SN.T.15t)
SN.M.15t<-SN.M.15[SN.M.15!=0]
mean(SN.M.15t)
sd(SN.M.15t)
SN.B.15t<-SN.B.15[SN.B.15!=0]
mean(SN.B.15t)
sd(SN.B.15t)
SN.T.14t<-SN.T.14[SN.T.14!=0]
mean(SN.T.14t)
sd(SN.T.14t)
SN.M.14t<-SN.M.14[SN.M.14!=0]
mean(SN.M.14t)
sd(SN.M.14t)
SN.B.14t<-SN.B.14[SN.B.14!=0]
mean(SN.B.14t)
sd(SN.B.14t)
boxplot(SN.T.15t,SN.M.15t,SN.B.15t,SN.T.14t,SN.M.14t,SN.B.14t,ylim=c(0,3),col=c("gray84","gray84","gray84","gray48","gray48","gray48"),main="SHANNON INDEX",names=c("Crest 15","Middle 15","Toe 15","Crest 14","Middle 14","Toe 14"),ylab="Shannon Index")

#SPECIES EVENNESS
###################
SN.MX<-max(c(SN.T.15t,SN.M.15t,SN.B.15t,SN.T.14t,SN.M.14t,SN.B.14t))

E.SN.T.15t<-SN.T.15[SN.T.15!=0]/SN.MX
mean(E.SN.T.15t)
sd(E.SN.T.15t)
E.SN.M.15t<-SN.M.15[SN.M.15!=0]/SN.MX
mean(E.SN.M.15t)
sd(E.SN.M.15t)
E.SN.B.15t<-SN.B.15[SN.B.15!=0]/SN.MX
mean(E.SN.B.15t)
sd(E.SN.B.15t)
E.SN.T.14t<-SN.T.14[SN.T.14!=0]/SN.MX
mean(E.SN.T.14t)
sd(E.SN.T.14t)
E.SN.M.14t<-SN.M.14[SN.M.14!=0]/SN.MX
mean(E.SN.M.14t)
sd(E.SN.M.14t)
E.SN.B.14t<-SN.B.14[SN.B.14!=0]/SN.MX
mean(E.SN.B.14t)
sd(E.SN.B.14t)
#############################################################
#what if SHANNON is estimated on the basis of ABUNDANCE???:
#there is no difference as it works on the basis of presence/absence species counts
##############################################################
M.T.15b<-xtabs(A~loc+sp,data=Tp.15)
M.M.15b<-xtabs(A~loc+sp,data=M.15)
M.B.15b<-xtabs(A~loc+sp,data=B.15)
M.T.14b<-xtabs(A~loc+sp,data=Tp.14)
M.M.14b<-xtabs(A~loc+sp,data=M.14)
M.B.14b<-xtabs(A~loc+sp,data=B.14)
SN.T.15b<-diversity(M.T.15b,index="shannon")
SN.M.15b<-diversity(M.M.15b,index="shannon")
SN.B.15b<-diversity(M.B.15b,index="shannon")
SN.T.14b<-diversity(M.T.14b,index="shannon")
SN.M.14b<-diversity(M.M.14b,index="shannon")
SN.B.14b<-diversity(M.B.14b,index="shannon")
SN.T.15bt<-SN.T.15b[SN.T.15b!=0]
SN.M.15bt<-SN.M.15b[SN.M.15b!=0]
SN.B.15bt<-SN.B.15b[SN.B.15b!=0]
SN.T.14bt<-SN.T.14b[SN.T.14b!=0]
SN.M.14bt<-SN.M.14b[SN.M.14b!=0]
SN.B.14bt<-SN.B.14b[SN.B.14b!=0]

par(mfrow=c(2,2))
boxplot(SN.T.15t,SN.M.15t,SN.B.15t,SN.T.14t,SN.M.14t,SN.B.14t,ylim=c(0,3),col=c("gray84","gray84","gray84","gray48","gray48","gray48"),main="SHANNON INDEX",names=c("Crest 15","Middle 15","Toe 15","Crest 14","Middle 14","Toe 14"),ylab="Shannon Index")
boxplot(SN.T.15bt,SN.M.15bt,SN.B.15bt,SN.T.14bt,SN.M.14bt,SN.B.14bt,ylim=c(0,3),col=c("gray84","gray84","gray84","gray48","gray48","gray48"),main="SHANNON INDEX",names=c("Crest 15","Middle 15","Toe 15","Crest 14","Middle 14","Toe 14"),ylab="Shannon Index")
boxplot(E.SN.T.15t,E.SN.M.15t,E.SN.B.15t,E.SN.T.14t,E.SN.M.14t,E.SN.B.14t,ylim=c(0,1),col=c("gray84","gray84","gray84","gray48","gray48","gray48"),main="EQUITATIVE SHANNON INDEX",names=c("Crest 15","Middle 15","Toe 15","Crest 14","Middle 14","Toe 14"),ylab="Shannon Index")
boxplot(SP.T.15t,SP.M.15t,SP.B.15t,SP.T.14t,SP.M.14t,SP.B.14t,ylim=c(0,1),col=c("gray84","gray84","gray84","gray48","gray48","gray48"),main="SIMPSON INDEX",names=c("Crest 15","Middle 15","Toe 15","Crest 14","Middle 14","Toe 14"),ylab="Simpson Index")

#############################
#STATISTICS
SHANNON<-data.frame(season=c(rep("2015",34),rep("2014",25)),loc=c(rep("T",12),rep("M",9),rep("B",13),rep("T",8),rep("M",8),rep("B",9)),SNi=c(SN.T.15t,SN.M.15t,SN.B.15t,SN.T.14t,SN.M.14t,SN.B.14t)) 
plot(density(SHANNON$SNi))#not entirely normal, so Kruskal
kruskal.test(SHANNON$SNi~SHANNON$loc) #nO DIFFERENT
#Kruskal-Wallis rank sum test

#data:  SHANNON$SNi by SHANNON$loc
#Kruskal-Wallis chi-squared = 0.90482, df = 2, p-value = 0.6361
kruskal.test(SHANNON$SNi~SHANNON$season) #DIFFERENT

#data:  SHANNON$SNi by SHANNON$season
#Kruskal-Wallis chi-squared = 6.3529, df = 1, p-value = 0.01172

kruskal.test(SHANNON$SNi[SHANNON$season=="2015"]~SHANNON$loc[SHANNON$season=="2015"]) #NO DIFF
#data:  SHANNON$SNi[SHANNON$season == "2015"] by SHANNON$loc[SHANNON$season == "2015"]
#Kruskal-Wallis chi-squared = 2.0442, df = 2, p-value = 0.3598
kruskal.test(SHANNON$SNi[SHANNON$season=="2014"]~SHANNON$loc[SHANNON$season=="2014"])  #NO DIFF
#############################
Eq.SHANNON<-data.frame(season=c(rep("2015",34),rep("2014",25)),loc=c(rep("T",12),rep("M",9),rep("B",13),rep("T",8),rep("M",8),rep("B",9)),SNi=c(E.SN.T.15t,E.SN.M.15t,E.SN.B.15t,E.SN.T.14t,E.SN.M.14t,E.SN.B.14t))
plot(density(Eq.SHANNON$SNi))
kruskal.test(Eq.SHANNON$SNi~Eq.SHANNON$loc)
summary(aov(Eq.SHANNON$SNi~Eq.SHANNON$loc)) #same
############################
SIMPSON<-data.frame(season=c(rep("2015",34),rep("2014",25)),loc=c(rep("T",12),rep("M",9),rep("B",13),rep("T",8),rep("M",9),rep("B",8)),SPi=c(SP.T.15t,SP.M.15t,SP.B.15t,SP.T.14t,SP.M.14t,SP.B.14t)) 
plot(density(SIMPSON$SPi))
kruskal.test(SIMPSON$SPi~SIMPSON$loc) #no diff
kruskal.test(SIMPSON$SPi[SIMPSON$season=="2015"]~SIMPSON$loc[SIMPSON$season=="2015"]) #no diff
kruskal.test(SIMPSON$SPi[SIMPSON$season=="2014"]~SIMPSON$loc[SIMPSON$season=="2014"]) #no diff (by little)
kruskal.test(SIMPSON$SPi~SIMPSON$season)#no didd
#data:  SIMPSON$SPi by SIMPSON$season
#Kruskal-Wallis chi-squared = 8.3841, df = 1, p-value = 0.003785 
###################################################
############ ~ SPECIES RICHNESS ~ #################
###################################################
#rich(): Computes the cumulative and average species richness over a set of samples, the associated bootstrap statistics and other useful indices; when verbose is FALSE a simplified outcome is provided:
#cr=cumulative richness over sampling units (i.e. total number of sp present)
#me=mean richness over sampling units
#mrsd=standard deviation of the mean richness
R.T.15<-rich(M.T.15,verbose=TRUE,nrandom=499) #with bootstrap
R.M.15<-rich(M.M.15,verbose=TRUE,nrandom=499)
R.B.15<-rich(M.B.15,verbose=TRUE,nrandom=499)
R.T.14<-rich(M.T.14,verbose=TRUE,nrandom=499)
R.M.14<-rich(M.M.14,verbose=TRUE,nrandom=499)
R.B.14<-rich(M.B.14,verbose=TRUE,nrandom=499)
###
rich(M.T.15,verbose=F,nrandom=499)
rich(M.M.15,verbose=F,nrandom=499)
rich(M.B.15,verbose=F,nrandom=499)
rich(M.T.14,verbose=F,nrandom=499)
rich(M.M.14,verbose=F,nrandom=499)
rich(M.B.14,verbose=F,nrandom=499)

#############################################
#SP RICHNESS COMPARISONS between locations
#############################################
##Species richnesses are computed as the cumulative value over all samples. Richnesses are compared by mean of a randomization test without controlling for differences of sampling regime of communities density; given that this was similar for the three considered habitats
#######################################################
c2cv(M.T.15,M.B.15,nrandom=99,pr1=0.025,pr2=0.975,verbose=TRUE)
#no significantly different; but there is a difference of 8 species, being higher for the TOE (i.e. bottom)
c2cv(M.T.15,M.M.15,nrandom=99,pr1=0.025,pr2=0.975,verbose=TRUE)
#no differences, but the middle habitat is 3 species richer, indicating a GRADIENT as we progress down the slope
c2cv(M.B.15,M.M.15,nrandom=99,pr1=0.025,pr2=0.975,verbose=TRUE)
#where the bottom one is 5 species richer....
#DO THIS PATTERN HOLD OVER SEASONS?
c2cv(M.T.14,M.B.14,nrandom=99,pr1=0.025,pr2=0.975,verbose=TRUE)
#top in this case seems to be richer :P
c2cv(M.T.14,M.M.14,nrandom=99,pr1=0.025,pr2=0.975,verbose=TRUE)
#and also respect to the middle
c2cv(M.M.14,M.B.14,nrandom=99,pr1=0.025,pr2=0.975,verbose=TRUE)
#the middle seems to be 1 point richer, showing the oposite pattern as seen for 2015....could this be indicating landscape evolution. There is one year away from the landslide episodes and as the diversity decreases on the top part it increases in the lower and middle...???? (POTENTIAL DISCUSSION POINT)
#SO: DOES RICHNESS increase OR DECREASE over time?
c2cv(M.T.15,M.T.14,nrandom=99,pr1=0.025,pr2=0.975,verbose=TRUE)
#richness at the top HAS DECREASED considerably
c2cv(M.M.15,M.M.14,nrandom=99,pr1=0.025,pr2=0.975,verbose=TRUE)
#IT has increased considerably in the middle
c2cv(M.B.15,M.B.14,nrandom=99,pr1=0.025,pr2=0.975,verbose=TRUE)
#AN ALSO DOES IN for the bottom::

##########
#RAREFACTION CURVES
####################
#without BOOTSTRAP
rc.t.15<-rarc(M.T.15,samplesize=NULL, nrandom=99)
#this porduces the whole series for being able to plot the rarefaction curve
rc.t.15b<-rarc(M.T.15,samplesize=15, nrandom=99)
#this just gives me the richness up to a given sample
rc.m.15<-rarc(M.M.15,samplesize=NULL, nrandom=99)
rc.b.15<-rarc(M.B.15,samplesize=NULL, nrandom=99)
rc.t.14<-rarc(M.T.14,samplesize=NULL, nrandom=99)
rc.m.14<-rarc(M.M.14,samplesize=NULL, nrandom=99)
rc.b.14<-rarc(M.B.14,samplesize=NULL, nrandom=99)

plot(richness~samples,type="l",lwd=2,lty=1,data=rc.b.15,cex.lab=1.5,main="Species Richness")
lines(richness~samples,type="l",lwd=2,lty=2,data=rc.m.15)
lines(richness~samples,type="l",lwd=2,lty=3,data=rc.t.15)
lines(richness~samples,type="l",lwd=2,lty=1,data=rc.b.14,col="gray84")
lines(richness~samples,type="l",lwd=2,lty=2,data=rc.m.14,col="gray84")
lines(richness~samples,type="l",lwd=2,lty=3,data=rc.t.14,col="gray84")
legend("bottomright",c("Toe 14","Mid 14","Crest 14","Toe 15","Mid 15","Crest 15"),lty=c(1,2,3,1,2,3),lwd=c(2,2,2,2,2,2),col=c("gray84","gray84","gray84","black","black","black"),cex=1.5)
########################################################
########################################################
#FURTHER COMPARISONS: distance and similarity between habitats, seasons and then between quadrants!!
########################################################
#1) BRAY-KURTIS similarity: compares species counts between two sites in terms of presence and absence; for which we make use of the function 'share()', which computes the number of shared species as well as the total number of species
##################################
SI<-function(c,sp1,sp2){ #B-K similarity index
SI<-1-(2*c/(sp1+sp2))
} 
#the higher the number the more different they are
##HABITATS
TvsM.15<-list(M.T.15,M.M.15)
sh.t.m.15<-shared(TvsM.15)
SI.t.m.15<-SI(c=sh.t.m.15[1,2],sp1=sh.t.m.15[1,1],sp2=sh.t.m.15[2,2])
####
TvsB.15<-list(M.T.15,M.B.15)
sh.t.b.15<-shared(TvsB.15)
SI.t.b.15<-SI(c=sh.t.b.15[1,2],sp1=sh.t.b.15[1,1],sp2=sh.t.b.15[2,2])
####
BvsM.15<-list(M.B.15,M.M.15)
sh.b.m.15<-shared(BvsM.15)
SI.b.m.15<-SI(c=sh.t.b.15[1,2],sp1=sh.b.m.15[1,1],sp2=sh.b.m.15[2,2])
#the highest difference was found between the middle and bottom followed by bottom and top, so the bottom is the most different
####
TvsM.14<-list(M.T.14,M.M.14)
sh.t.m.14<-shared(TvsM.14)
SI.t.m.14<-SI(c=sh.t.m.14[1,2],sp1=sh.t.m.14[1,1],sp2=sh.t.m.14[2,2])
####
TvsB.14<-list(M.T.14,M.B.14)
sh.t.b.14<-shared(TvsB.14)
SI.t.b.14<-SI(c=sh.t.b.14[1,2],sp1=sh.t.b.14[1,1],sp2=sh.t.b.14[2,2])
####
BvsM.14<-list(M.B.14,M.M.14)
sh.b.m.14<-shared(BvsM.14)
SI.b.m.14<-SI(c=sh.t.b.14[1,2],sp1=sh.b.m.14[1,1],sp2=sh.b.m.14[2,2])
#it seems that for the 14 seasons the similarities are higher, and as it evolves they increase. This can be discussed in the lines of lanscape evolution. 
#for the 14 season the most dissimilar turned to be the top!!
#######################################################
#SEASONS per HABITAT
####################
TvsT<-list(M.T.15,M.T.14)
sh.t.t<-shared(TvsT)
SI.t.t<-SI(c=sh.t.t[1,2],sp1=sh.t.t[1,1],sp2=sh.t.t[2,2])
#HIGHLY different
MvsM<-list(M.M.15,M.M.14)
sh.m.m<-shared(MvsM)
SI.m.m<-SI(c=sh.m.m[1,2],sp1=sh.m.m[1,1],sp2=sh.m.m[2,2])
#highly different too, but less than top and top
BvsB<-list(M.B.15,M.B.14)
sh.b.b<-shared(BvsB)
SI.b.b<-SI(c=sh.b.b[1,2],sp1=sh.b.b[1,1],sp2=sh.b.b[2,2])
#very different and just a bit below the differences at the top :P
######################################################
##################################################################################
####################### ~ ENVIRONMENTAL COVARIATES ~ ############################
#################################################################################
#1) HABITAT GRADIENTS: are there any gradients in terms of OM, TKN or penetration ?
####################
s15<-DATA[DATA$Season=="2015",]
s15df<-data.frame(loc=s15$Location,pos=s15$Position,sp=s15$Species,id=s15$Id,bm=s15$Pooled.biomass_g_m2,bm2=s15$Mass_per_m2,cone=s15$cone_kPa,OC=s15$OC_per,TKN=s15$TKN_per)
#subsetting data per location
Tp.15<-s15df[s15df$pos=="T",]
M.15<-s15df[s15df$pos=="M",]
B.15<-s15df[s15df$pos=="B",]

s14<-DATA[DATA$Season=="2014",]
s14df<-data.frame(loc=s14$Location,pos=s14$Position,sp=s14$Species,id=s14$Id,bm=s14$Pooled.biomass_g_m2,bm2=s14$Mass_per_m2,cone=s14$cone_kPa,OC=s14$OC_per,TKN=s14$TKN_per)
#subsetting data per location
Tp.14<-s14df[s14df$pos=="T",]
M.14<-s14df[s14df$pos=="M",]
B.14<-s14df[s14df$pos=="B",]

#cone penetration (kPa):: just season 2015
##########################
T.cone.15<-as.numeric(na.omit(Tp.15$cone))
mean(T.cone.15)
sd(T.cone.15)
M.cone.15<-as.numeric(na.omit(M.15$cone))
mean(M.cone.15)
sd(M.cone.15)
B.cone.15<-as.numeric(na.omit(B.15$cone))
mean(B.cone.15)
sd(B.cone.15)
#there is a gradient, penetrability is higher at the bottom; now i need to find what variable can explain this (i.e. biomass, diversity..)
par(mfrow=c(2,2))
boxplot(T.cone.15,M.cone.15,B.cone.15,names=c("Crest","Mid","Toe"),ylab="Cone Penetration (kPa)",main="Cone Penetration per Habitat") 
plot(density(T.cone.15)) #not normal
plot(density(M.cone.15)) #not normal
plot(density(B.cone.15)) #normal
CONE<-c(T.cone.15,M.cone.15,B.cone.15)
plot(density(CONE)) #not far from normal, though
kruskal.test(list(T.cone.15,M.cone.15,B.cone.15)) #DIFFERENT
#Kruskal-Wallis rank sum test
#data:  list(T.cone.15, M.cone.15, B.cone.15)
#Kruskal-Wallis chi-squared = 9.5864, df = 2, p-value = 0.008286
###################################################################

#organic carbon
####################
T.OC.15<-as.numeric(na.omit(Tp.15$OC))
mean(T.OC.15)
sd(T.OC.15)
M.OC.15<-as.numeric(na.omit(M.15$OC))
mean(M.OC.15)
sd(M.OC.15)
B.OC.15<-as.numeric(na.omit(B.15$OC))
mean(B.OC.15)
sd(B.OC.15)
T.OC.14<-as.numeric(na.omit(Tp.14$OC))
mean(T.OC.14)
sd(T.OC.14)
M.OC.14<-as.numeric(na.omit(M.14$OC))
mean(M.OC.14)
sd(M.OC.14)
B.OC.14<-as.numeric(na.omit(B.14$OC))
mean(B.OC.14)
sd(B.OC.14)
boxplot(T.OC.14,M.OC.14,B.OC.14,T.OC.15,M.OC.15,B.OC.15,names=c("Crest","Mid","Toe","Crest","Mid","Toe"),col=c("gray48","gray48","gray48","gray84","gray84","gray84"),ylab="OM (%)",main="OM per Habitat",ylim=c(0,10))
legend("topleft",pch=c(15,15),col=c("gray48","gray84"),c("season 2014","season 2015"),cex=1.5)
#there seem o be no differences, albeit the variability at the crest seems to be the highest
plot(density(c(T.OC.14,M.OC.14,B.OC.14,T.OC.15,M.OC.15,B.OC.15))) #not normal
#and there is a peak that may suggest data inconsistency :P
plot(density(c(T.OC.14,M.OC.14,B.OC.14)))
plot(density(c(T.OC.15,M.OC.15,B.OC.15)))
kruskal.test(list(T.OC.14,M.OC.14,B.OC.14,T.OC.15,M.OC.15,B.OC.15)) #NO DIFFERENT
#Kruskal-Wallis rank sum test
#data:  list(T.OC.14, M.OC.14, B.OC.14, T.OC.15, M.OC.15, B.OC.15)
#Kruskal-Wallis chi-squared = 2.05, df = 5, p-value = 0.8422
kruskal.test(list(T.OC.14,M.OC.14,B.OC.14))
kruskal.test(list(T.OC.15,M.OC.15,B.OC.15))
OM.14<-c(T.OC.14,M.OC.14,B.OC.14)
OM.15<-c(T.OC.15,M.OC.15,B.OC.15)
kruskal.test(list(OM.14,OM.15))
#######################################################################

#TKN
##########
T.TKN.15<-as.numeric(na.omit(Tp.15$TKN))
mean(T.TKN.15)
sd(T.TKN.15)
M.TKN.15<-as.numeric(na.omit(M.15$TKN))
mean(M.TKN.15)
sd(M.TKN.15)
B.TKN.15<-as.numeric(na.omit(B.15$TKN))
mean(B.TKN.15)
sd(B.TKN.15)
T.TKN.14<-as.numeric(na.omit(Tp.14$TKN))
mean(T.TKN.14)
sd(T.TKN.14)
M.TKN.14<-as.numeric(na.omit(M.14$TKN))
mean(M.TKN.14)
sd(M.TKN.14)
B.TKN.14<-as.numeric(na.omit(B.14$TKN))
mean(B.TKN.14)
sd(B.TKN.14)
boxplot(T.TKN.14,M.TKN.14,B.TKN.14,T.TKN.15,M.TKN.15,B.TKN.15,names=c("Crest","Mid","Toe","Crest","Mid","Toe"),col=c("gray48","gray48","gray48","gray84","gray84","gray84"),ylab="TKN (%)",main="TKN per Habitat",ylim=c(0,0.2))
legend("topleft",pch=c(15,15),col=c("gray48","gray84"),c("season 2014","season 2015"),cex=1.5)

#There seems to be a gradient too, that it is even more marked as the time evolves. Nitrogen gets reduced at top and middel (above all) and it seems to enrich the toe...Interesting
plot(density(c(T.TKN.14,M.TKN.14,B.TKN.14))) #not normal
plot(density(c(T.TKN.15,M.TKN.15,B.TKN.15))) #not normal
kruskal.test(list(T.TKN.14,M.TKN.14,B.TKN.14)) #no different but by little
kruskal.test(list(T.TKN.15,M.TKN.15,B.TKN.15)) #DIFFERENT !!!!!!!
kruskal.test(list(T.TKN.14,M.TKN.14,B.TKN.14,T.TKN.15,M.TKN.15,B.TKN.15))
TKN.15<-c(T.TKN.15,M.TKN.15,B.TKN.15)
TKN.14<-c(T.TKN.14,M.TKN.14,B.TKN.14)
kruskal.test(list(TKN.14,TKN.15))
############################################################################

#TOTAL BIOMASS (i.e. total biomass per habitat and season)
###############
T.TBM.15<-as.numeric(na.omit(Tp.15$bm2))
mean(T.TBM.15)
sd(T.TBM.15)
M.TBM.15<-as.numeric(na.omit(M.15$bm2))
mean(M.TBM.15)
sd(M.TBM.15)
B.TBM.15<-as.numeric(na.omit(B.15$bm2))
mean(B.TBM.15)
sd(B.TBM.15)
T.TBM.14<-as.numeric(na.omit(Tp.14$bm2))
mean(T.TBM.14)
sd(T.TBM.14)
M.TBM.14<-as.numeric(na.omit(M.14$bm2))
mean(M.TBM.14)
sd(M.TBM.14)
B.TBM.14<-as.numeric(na.omit(B.14$bm2))
mean(B.TBM.14)
sd(B.TBM.14)
boxplot(T.TBM.14,M.TBM.14,B.TBM.14,T.TBM.15,M.TBM.15,B.TBM.15,names=c("Crest","Mid","Toe","Crest","Mid","Toe"),col=c("gray48","gray48","gray48","gray84","gray84","gray84"),ylab="TBN (g)",main="TBM per Habitat",ylim=c(0,2000))
legend("topleft",pch=c(15,15),col=c("gray48","gray84"),c("season 2014","season 2015"),cex=1.5)
#the second season (2015) showed the expeced trend in which a endency towards a reduction in biomass shoud be expected. For the first season it was not detected, though. There seems to be more biomass in the first season and that can be attributed to the climate (i.e. need to show mean values of T and P for support). 
#there seems not to be a direct relation with TKN (although we'll check later), but the effect may be delayed and would produce mope plant gwoeth in the subsequent seasons. The sampling site may deserve discussion too..
plot(density(c(T.TBM.14,M.TBM.14,B.TBM.14,T.TBM.15,M.TBM.15,B.TBM.15))) #not normal
kruskal.test(list(T.TBM.14,M.TBM.14,B.TBM.14)) #NO DIFFERENT
#Kruskal-Wallis chi-squared = 2.3492, df = 2, p-value = 0.3089
kruskal.test(list(T.TBM.15,M.TBM.15,B.TBM.15)) #DIFFERENT !!!!
#Kruskal-Wallis chi-squared = 11.196, df = 2, p-value = 0.003705
#differences between the seasons:
A<-c(T.TBM.14,M.TBM.14,B.TBM.14)
B<-c(T.TBM.15,M.TBM.15,B.TBM.15)
kruskal.test(list(A,B)) #not really!!
#Kruskal-Wallis chi-squared = 2.0791, df = 1, p-value = 0.1493

par(mfrow=c(2,3))
boxplot(T.cone.15,M.cone.15,B.cone.15,names=c("Crest","Mid","Toe"),ylab="Cone Penetration (kPa)",main="Cone Penetration per Habitat") 
boxplot(T.OC.14,M.OC.14,B.OC.14,T.OC.15,M.OC.15,B.OC.15,names=c("Crest","Mid","Toe","Crest","Mid","Toe"),col=c("gray48","gray48","gray48","gray84","gray84","gray84"),ylab="OM (%)",main="OM per Habitat",ylim=c(0,10))
legend("topleft",pch=c(15,15),col=c("gray48","gray84"),c("season 2014","season 2015"))
boxplot(T.TKN.14,M.TKN.14,B.TKN.14,T.TKN.15,M.TKN.15,B.TKN.15,names=c("Crest","Mid","Toe","Crest","Mid","Toe"),col=c("gray48","gray48","gray48","gray84","gray84","gray84"),ylab="TKN (%)",main="TKN per Habitat",ylim=c(0,0.2))
legend("topleft",pch=c(15,15),col=c("gray48","gray84"),c("season 2014","season 2015"))
boxplot(T.TBM.14,M.TBM.14,B.TBM.14,T.TBM.15,M.TBM.15,B.TBM.15,names=c("Crest","Mid","Toe","Crest","Mid","Toe"),col=c("gray48","gray48","gray48","gray84","gray84","gray84"),ylab="TBN (g)",main="TBM per Habitat",ylim=c(0,2000))
legend("topleft",pch=c(15,15),col=c("gray48","gray84"),c("season 2014","season 2015"))
boxplot(SN.T.14t,SN.M.14t,SN.B.14t,SN.T.15t,SN.M.15t,SN.B.15t,ylim=c(0,3),col=c("gray48","gray48","gray48","gray84","gray84","gray84"),main="SHANNON INDEX",names=c("Crest 15","Middle 15","Toe 15","Crest 14","Middle 14","Toe 14"),ylab="Shannon Index")
#the levels of N could have a relationship with the diveristy in terms of shannon.
plot(richness~samples,type="l",lwd=2,lty=1,data=rc.b.15,cex.lab=1.5,main="Species Richness")
lines(richness~samples,type="l",lwd=2,lty=2,data=rc.m.15)
lines(richness~samples,type="l",lwd=2,lty=3,data=rc.t.15)
lines(richness~samples,type="l",lwd=2,lty=1,data=rc.b.14,col="gray84")
lines(richness~samples,type="l",lwd=2,lty=2,data=rc.m.14,col="gray84")
lines(richness~samples,type="l",lwd=2,lty=3,data=rc.t.14,col="gray84")
legend("bottomright",c("Toe 14","Mid 14","Crest 14","Toe 15","Mid 15","Crest 15"),lty=c(1,2,3,1,2,3),lwd=c(2,2,2,2,2,2),col=c("gray84","gray84","gray84","black","black","black"),cex=1)
####################################################################
############################################################################
################### ~ CORRELATION MATRIX ~ #################################
############################################################################
#for species richness...(species counts per quadrant)
RR<-data.frame(loc=DATA$Location,pos=DATA$Position,season=DATA$Season,richness=DATA$Species.Richness)
RR.2<-na.omit(RR)
RR.15<-RR.2[RR.2$season=="2015",]
RR.14<-RR.2[RR.2$season=="2014",]
RR.t.15<-RR.15[RR.15$pos=="T",]
RR.m.15<-RR.15[RR.15$pos=="M",]
RR.b.15<-RR.15[RR.15$pos=="B",]
RR.t.14<-RR.14[RR.14$pos=="T",]
RR.m.14<-RR.14[RR.14$pos=="M",]
RR.b.14<-RR.14[RR.14$pos=="B",]

#topographical variables
names(DATA)

#gonna remove T6T from season 2015 :( as I've lost the coordinates...
#matrix preparation (27/6/16: including species richness)
ts.15<-c("T4T","T14T","T10T","T5T","T11T","T12T","T9T","T15T","T13T","T7T","T8T")
ms.15<-c("T13M","T15M","T14M","T8M","T7M","T9M","T6M","T10M","T5M")
bs.15<-c("T4B","T9B","T3B","T11B","T7B","T12B","T5B","T8B","T13B","T15B","T14B","T10B","T6B")
ts.14<-c("T5T","T9T","T3T","T8T","T7T","T11T","T10T","T6T")
ms.14<-c("T3M","T8M","T7M","T4M","T6M","T10M","T9M","T5M")
bs.14<-c("T8B","T2B","T4B","T6B","T10B","T5B","T7B","T3B","T9B")
pos<-c(rep("c",11),rep("m",9),rep("t",13),rep("c",8),rep("m",8),rep("t",9))
season<-c(rep("2015",33),rep("2014",25))
cone<-c(T.cone.15[-10],M.cone.15,B.cone.15,rep("NA",25))
OC<-c(T.OC.15,M.OC.15,B.OC.15,T.OC.14,M.OC.14,B.OC.14)
TKN<-c(T.TKN.15,M.TKN.15,B.TKN.15,T.TKN.14,M.TKN.14,B.TKN.14)
BM<-c(T.TBM.15[-10],M.TBM.15,B.TBM.15,T.TBM.14,M.TBM.14,B.TBM.14)
slope<-as.numeric(na.omit(DATA$Slope))
shade<-as.numeric(na.omit(DATA$shade))
aspect<-as.numeric(na.omit(DATA$aspect))
curvature<-as.numeric(na.omit(DATA$curvature))
shannon<-c(SN.T.15t[7],SN.T.15t[5],SN.T.15t[1],SN.T.15t[8],SN.T.15t[2],SN.T.15t[3],SN.T.15t[12],SN.T.15t[6],SN.T.15t[4],SN.T.15t[10],SN.T.15t[11],SN.M.15t[2],SN.M.15t[4],SN.M.15t[3],SN.M.15t[8],SN.M.15t[7],SN.M.15t[9],SN.M.15t[6],SN.M.15t[1],SN.M.15t[5],SN.B.15t[8],SN.B.15t[13],SN.B.15t[7],SN.B.15t[2],SN.B.15t[11],SN.B.15t[3],SN.B.15t[9],SN.B.15t[12],SN.B.15t[4],SN.B.15t[6],SN.B.15t[5],SN.B.15t[1],SN.B.15t[10],SN.T.14t[4],SN.T.14t[8],SN.T.14t[3],SN.T.14t[7],SN.T.14t[6],SN.T.14t[2],SN.T.14t[1],SN.T.14t[5],SN.M.14t[2],SN.M.14t[7],SN.M.14t[6],SN.M.14t[3],SN.M.14t[5],SN.M.14t[1],SN.M.14t[8],SN.M.14t[4],SN.B.14t[8],SN.B.14t[2],SN.B.14t[4],SN.B.14t[6],SN.B.14t[1],SN.B.14t[5],SN.B.14t[7],SN.B.14t[3],SN.B.14t[9])
richness<-c(RR.t.15$richness[-10],RR.m.15$richness,RR.b.15$richness,RR.t.14$richness,RR.m.14$richness,RR.b.14$richness)
MM.dt<-data.frame(loc=c(ts.15,ms.15,bs.15,ts.14,ms.14,bs.14),habitat=pos,season=season,penetrability=as.numeric(cone),OM=as.numeric(OC),TKN=as.numeric(TKN),Biomass=as.numeric(BM),slope_gradient=as.numeric(slope[-7]),hillshade=as.numeric(shade),aspect=as.numeric(aspect),curvature=as.numeric(curvature),shannon=as.numeric(shannon),richness=as.numeric(richness))

#correlations: let's look first at 2015 with cone...
MM.dt.15<-MM.dt[MM.dt$season=="2015",]
library(corrplot)
corrplot(cor(MM.dt.15[,c("penetrability","OM","TKN","slope_gradient","hillshade","aspect","curvature","shannon","richness","Biomass")]),diag=TRUE,method=c("color"),type=c("upper"),addCoef.col="black",tl.col="black",tl.srt=45)
########now whole correlation without cone..
corrplot(cor(MM.dt[,c("OM","TKN","slope_gradient","hillshade","aspect","curvature","shannon","richness","Biomass")]),diag=TRUE,method=c("color"),type=c("upper"),addCoef.col="black",tl.col="black",tl.srt=45)
#season 2014
MM.dt.14<-MM.dt[MM.dt$season=="2014",]
corrplot(cor(MM.dt.14[,c("OM","TKN","slope_gradient","hillshade","aspect","curvature","shannon","richness","Biomass")]),diag=TRUE,method=c("color"),type=c("upper"),addCoef.col="black",tl.col="black",tl.srt=45)
################################################################################
################################################################################
# ~ INDICATOR SPECIES ANALYSIS ~
################################################################################
library(indicspecies)
#to do this analysis we will first exluce from the original data all those records pertaining to mixed biomass and so on...
toRemove1<-which(DATA$Species=="Mixed Biomass")
toRemove2<-which(DATA$Species=="Mixed Biomass_Grass")
toRemove3<-which(DATA$Species=="Mixed Grass")
toRemove4<-which(DATA$Species=="Mixed biomass")
toRemove5<-which(DATA$Species=="Mixed grass")
DT<-DATA[-c(toRemove1,toRemove2,toRemove3,toRemove4,toRemove5),]
DT<-DT[-346,]
#now I need the contingency tables in terms of Species Abundance
head(DT)
MM<-xtabs(Species.abundance~Site+Species,data=DT)
write.csv(MM,"MM.csv")
#process MM.csv removing the two first columns as an appropiate matrix is needed starting at 0,0

#now I need the classification of sites vector
###########################################
#1=TOP (crest); 2=MIDDLE; 3=BOTTOM (Toe)
###########################################
groups<-c(1,2,1,3,1,2,3,2,1,1,3,3,1,3,3,3,3,3,2,3,3,1,2,1,1,1,2,1,1,2,3,3,2,2,2,1,3,3,1,2,1,1,1,3,2,3,3,2,1,3,2,3,1,2,2,2,3,3,1)
MMx<-read.csv("MM.csv")
#########################
#now we porceed with the INDICATOR SPECIES ANALYSIS
indval<-multipatt(MMx,groups,func="r.g",control=how(nperm=999))
summary(indval,indvalcomp=TRUE)

round(indval$str,3) #
#An advantage of the phi and point biserial coefficients is that they can take negative values. When this happens, the value of the index is expressing the fact that a species tends to ’avoid’ particular environmental conditions.

indval$sign
indval.2<-multipatt(MMx,groups,func="IndVal.g",control=how(nperm=999))
summary(indval.2,indvalcomp=TRUE)
#from this outcome we can extraxt the so-called A: specifity and B:fidelity. 
indval.2$sign
write.csv(indval.2$sign,"SPECIES INDEX.csv")

# HOW ALL THIS CHANGES WHEN ANALYSED ON A SEASONAL BASIS (i.e 2015 or 2015)?
############################################################################
DT.15<-DT[DT$Season=="2015",]
DT.14<-DT[DT$Season=="2014",]
MM.15<-xtabs(Species.abundance~Site+Species,data=DT.15)
MM.14<-xtabs(Species.abundance~Site+Species,data=DT.14)
write.csv(MM.15,"MM.15.csv")
write.csv(MM.14,"MM.14.csv")
#process the csv and load them again
MM15x<-read.csv("MM.15.csv")
MM14x<-read.csv("MM.14.csv")

groups.15<-c(1,2,1,3,1,2,3,2,1,1,3,3,1,3,3,3,3,3,2,3,3,1,2,1,1,1,2,1,1,2,3,3,2,2)
groups.14<-c(2,1,3,3,1,2,1,1,1,3,2,3,3,2,1,3,2,3,1,2,2,2,3,3,1)

#SEASON 2015
indval.15<-multipatt(MM15x,groups.15,func="r.g",control=how(nperm=999))
summary(indval.15,indvalcomp=TRUE) #it matches in certain species
indval.14<-multipatt(MM14x,groups.14,func="r.g",control=how(nperm=999))
summary(indval.14,indvalcomp=TRUE) #not very consistent
#I believe the 2015 season provides more consistency to the analysis and therefore I should present the results from both seasons together....

#COVERAGE
coverage(MMx,indval.2)
coverage(MMx,indval) 
#we can plot the coverage
plotcoverage(MMx,indval,group=1,lty=1)
plotcoverage(MMx,indval,group="2",lty=2,col="blue",add=TRUE)
plotcoverage(MMx,indval,group="3",lty=2,col="red",add=TRUE)

#SPECIES COMBINATIONS (VERY INTERESTING)
#Ecological indicators can be of many kinds. De Ca ́ceres et al. [2012] re- cently explored the indicator value of combinations of species instead of just considering individual species. The rationale behind this approach is that two or three species, when found together, bear more ecological information than a single one.
COMBsp<-combinespecies(MMx,max.order=3)$XC
dim(MMx)
dim(COMBsp)
#The resulting data frame has the same number of sites (i.e. 41) but as many columns as species combinations (in this case 561 columns). Each element of the data frame contains an abundance value, which is the min- imum abundance value among all the species forming the combination, for the corresponding site. In our example, we used max.order = 2 to limit the order of combinations. Therefore, only pairs of species were considered.
ind.COMBsp<-multipatt(COMBsp,groups,duleg=TRUE,control=how(nperm=999))
summary(ind.COMBsp,invalcomp=TRUE)
#NONETHELESS, the best indicators seem to be individual species..when considering pairs
#when considering trios (i.e. max.order=3), still the individual species work better

###############################################################################
################################################################################
#################### ~ ENVIRONMENTAL COVARIATES ~ on SHANNON INDEX
####################################################################
##################################################################
#################################################################
###########################

#1) TREE 1::SHANNON~covarites
set.seed(2)
library(rpart)
library(rattle)
#RANDOM HOLD-BACK VALIDATION
train.15<-sample(nrow(MM.dt.15),0.7*nrow(MM.dt.15))
SN.rt.15a<-rpart(shannon~habitat+penetrability+OM+TKN+slope_gradient+hillshade+aspect+curvature,data=MM.dt.15[train.15,],method="anova",control=rpart.control(minsplit=3))
summary(SN.rt.15a) #variable importance
plot(SN.rt.15a)#like this because I can show the tree and might be illustrative
text(SN.rt.15a)
names(SN.rt.15a)

rsq.rpart(SN.rt.15a)
SN.rt.15a.pr<-predict(SN.rt.15a,newdata=MM.dt.15[train.15,])
R2.SN.rt.15a<-lm(SN.rt.15a.pr~MM.dt.15$shannon[train.15])
as.matrix(summary(R2.SN.rt.15a)$adj.r.squared) #extremely high!!!
RMSE.SN.rt.15a<-sqrt(mean((MM.dt.15$shannon[train.15]-SN.rt.15a.pr)^2))


#PRUNING 
SN.rt.15.P<-prune(SN.rt.15a,cp=0.06)
summary(SN.rt.15.P)
rsq.rpart(SN.rt.15.P)
SN.rt.15.pr<-predict(SN.rt.15.P,newdata=MM.dt.15[train.15,])
R2.SN.rt.15<-lm(SN.rt.15.pr~MM.dt.15$shannon[train.15])
as.matrix(summary(R2.SN.rt.15)$adj.r.squared) #extremely high!!!
RMSE.SN.rt<-sqrt(mean((MM.dt$shannon[train.15]-SN.rt.15.pr)^2))
fancyRpartPlot(SN.rt.15.P,uniform=TRUE,main="",sub="",palettes="Greys")

######################
#########################
#2) TREE 2:: SHANNON~covariates without cone (two seasons)
#NOW I NEED TO CONSIDER THE SAME but for the two seasons and excluding CONE
##############################################################################
set.seed(2)
train<-sample(nrow(MM.dt),0.7*nrow(MM.dt))
SN.rt<-rpart(shannon~habitat+OM+TKN+slope_gradient+hillshade+aspect+curvature,data=MM.dt[train,],method="anova",control=rpart.control(minsplit=3))
plot(SN.rt)
text(SN.rt) 
summary(SN.rt)
SN.rt$variable.importance
SN.rt.15a$variable.importance

#goodness of fit
rsq.rpart(SN.rt.15a)
SN.rt.pr<-predict(SN.rt,newdata=MM.dt[train,])
R2.SN.rt<-lm(SN.rt.pr~MM.dt$shannon[train])
as.matrix(summary(R2.SN.rt)$adj.r.squared) #extremely high!!!
RMSE.SN.rt<-sqrt(mean((MM.dt$shannon[train]-SN.rt.pr)^2)) #very good

#PRUNING
SN.rt.P<-prune(SN.rt,cp=0.06)
summary(SN.rt.P)
rsq.rpart(SN.rt.P)
SN.rt.P.pr<-predict(SN.rt.P,newdata=MM.dt[train,])
R2.SN.rt.P<-lm(SN.rt.P.pr~MM.dt$shannon[train])
as.matrix(summary(R2.SN.rt.P)$adj.r.squared) #extremely high!!!
RMSE.SN.rt.P<-sqrt(mean((MM.dt$shannon[train]-SN.rt.P.pr)^2))
fancyRpartPlot(SN.rt.P,uniform=TRUE,main="",sub="",palettes="Greys")
plot(SN.rt.P.pr~MM.dt$shannon[train])
abline(R2.SN.rt.P)
##########################################################################
#3) TREE 3:: RICHNESS ~ covariates 
#####################################
set.seed(2)
train.15<-sample(nrow(MM.dt.15),0.7*nrow(MM.dt.15))
RR.rt.15<-rpart(richness~habitat+penetrability+OM+TKN+slope_gradient+hillshade+aspect+curvature,data=MM.dt.15[train.15,],method="anova",control=rpart.control(minsplit=3))
summary(RR.rt.15)
#prunning
RR.rt.15.P<-prune(RR.rt.15,cp=0.06)
summary(RR.rt.15.P)
rsq.rpart(RR.rt.15.P)
#goodness of fit
RR.rt.15.pr<-predict(RR.rt.15.P,newdata=MM.dt.15[train.15,])
R2.RR.rt.15<-lm(RR.rt.15.pr~MM.dt.15$richness[train.15])
as.matrix(summary(R2.RR.rt.15)$adj.r.squared) #extremely high!!!
RMSE.RR.rt.15<-sqrt(mean((MM.dt.15$richness[train.15]-RR.rt.15.pr)^2))
fancyRpartPlot(RR.rt.15.P,uniform=TRUE,main="",sub="",palettes="Greys")

#######################################
#4) TREE 4:: RICHNESS ~ covariates without cone (two seasons)
##############################################################
set.seed(2)
train<-sample(nrow(MM.dt),0.7*nrow(MM.dt))
RR.rt<-rpart(richness~habitat+OM+TKN+slope_gradient+hillshade+aspect+curvature,data=MM.dt[train,],method="anova",control=rpart.control(minsplit=3))
summary(RR.rt)
#prunning
RR.rt.P<-prune(RR.rt,cp=0.06)
summary(RR.rt.P)
rsq.rpart(RR.rt.P)
#goodness of fit
RR.rt.pr<-predict(RR.rt.P,newdata=MM.dt[train,])
R2.RR.rt<-lm(RR.rt.pr~MM.dt$richness[train])
as.matrix(summary(R2.RR.rt)$adj.r.squared) #extremely high!!!
RMSE.RR.rt<-sqrt(mean((MM.dt$richness[train]-RR.rt.pr)^2))
fancyRpartPlot(RR.rt.P,uniform=TRUE,main="",sub="",palettes="Greys")


#################################################################
#5) TREE 5:: PLANT BIOMASS ~ covariates
#Last but not least, is it possible to predict plant biomass?
###################################################################
set.seed(2)
BM.rt.15<-rpart(Biomass~penetrability+habitat+OM+TKN+slope_gradient+hillshade+aspect+curvature,data=MM.dt.15[train.15,],method="anova",control=rpart.control(minsplit=3))
summary(BM.rt.15) #cone is the most important related to biomass?


#prunning
BM.rt.15.P<-prune(BM.rt.15,cp=0.06)
summary(BM.rt.15.P)
rsq.rpart(BM.rt.15.P)
#goodness of fit
BM.rt.15.pr<-predict(BM.rt.15.P,newdata=MM.dt.15[train.15,])
R2.BM.rt.15<-lm(BM.rt.15.pr~MM.dt.15$Biomass[train.15])
as.matrix(summary(R2.BM.rt.15)$adj.r.squared) #extremely high!!!
RMSE.BM.rt.15<-sqrt(mean((MM.dt.15$Biomass[train.15]-BM.rt.15.pr)^2))
fancyRpartPlot(BM.rt.15.P,uniform=TRUE,main="",sub="",palettes="Greys")


##################################################
#6) TREE 6:: PLANT BIOMASS ~ covariates without cone
###################################################################
set.seed(2)
BM.rt<-rpart(Biomass~habitat+OM+TKN+slope_gradient+hillshade+aspect+curvature,data=MM.dt[train,],method="anova",control=rpart.control(minsplit=3))
summary(BM.rt) 
plot(BM.rt)
text(BM.rt)
BM.rt.pr<-predict(BM.rt,newdata=MM.dt[train,])
R2.BM.rt<-lm(BM.rt.pr~MM.dt$Biomass[train])
as.matrix(summary(R2.BM.rt)$adj.r.squared) #extremely high!!!
RMSE.BM.rt<-sqrt(mean((MM.dt$Biomass[train]-BM.rt.pr)^2))
plot(BM.rt.pr~MM.dt$Biomass[train]) #I could provide these plots...
fancyRpartPlot(BM.rt,uniform=TRUE,main="",sub="",palettes="Greys")

#let's prune

BM.rt.P<-prune(BM.rt,cp=0.06)
summary(BM.rt.P)
rsq.rpart(BM.rt.P)
BM.rt.P.pr<-predict(BM.rt.P,newdata=MM.dt[train,])
R2.BM.rt.P<-lm(BM.rt.P.pr~MM.dt$Biomass[train])
as.matrix(summary(R2.BM.rt.P)$adj.r.squared) #extremely high!!!
RMSE.BM.rt.P<-sqrt(mean((MM.dt$Biomass[train]-BM.rt.P.pr)^2))
fancyRpartPlot(BM.rt.P,uniform=TRUE,main="",sub="",palettes="Greys")

####################################################################