
#library:------------------------------------------
library(rgrass7)

library(caret)
library(vcd)


#define input variables------------------------------------------

args <- commandArgs(trailingOnly = TRUE)

typevar=args[1]
year=args[2]
clasif=args[3]
valid=args[4]
typemodel=args[5]
workdir=args[6]
seasons = args[7]

#kappa and confusion function-----------------------------------
fun.kappa=function(validate,prediction){
	#confusion
	Kappa_confusion2<-confusionMatrix(prediction,validate ,dnn = c("Predic.", "Reference"))
	#kappa	
	Kappaest<-Kappa(Kappa_confusion2$table)
	Kappaint<-confint(Kappaest)
	#calculate comision, omision
	Kappa_confusion=as.data.frame.matrix(Kappa_confusion2$table)
	Kappa_confusion[,"Total"]<-NA
	Kappa_confusion["Total",]<-NA
	Kappa_confusion[,"ExU"]<-NA
	Kappa_confusion["ExP",]<-NA
	Kappa_confusion[,"CE"]<-NA
	Kappa_confusion["OE",]<-NA
	Kappa_confusion[,"condK"]<-NA
	F_correct<-0
	for (exp in 1:(length(Kappa_confusion[,1])-3)){
		F_correct<-Kappa_confusion[exp,exp]+F_correct
		Kappa_confusion[exp,"Total"]<-sum(Kappa_confusion[exp,1:(length(Kappa_confusion[,1])-3)])
		Kappa_confusion["Total",exp]<-sum(Kappa_confusion[1:(length(Kappa_confusion[,1])-3),exp])
		Kappa_confusion[exp,"ExU"]<-round(Kappa_confusion[exp,exp]/Kappa_confusion[exp,"Total"]*100,digits=3)
		Kappa_confusion["ExP",exp]<-round(Kappa_confusion[exp,exp]/Kappa_confusion["Total",exp]*100,digits=3)
		Kappa_confusion[exp,"CE"]<-round(((Kappa_confusion[exp,"Total"]-Kappa_confusion[exp,exp])/Kappa_confusion[exp,"Total"])*100,digits=3)
		Kappa_confusion["OE",exp]<-round(((Kappa_confusion["Total",exp]-Kappa_confusion[exp,exp])/Kappa_confusion["Total",exp])*100,digits=3)
	}
	Kappa_confusion["Total","Total"]<-sum(Kappa_confusion[1:(length(Kappa_confusion[,1])-3),"Total"])
	#Accuracy:
	F_global<-F_correct/Kappa_confusion["Total","Total"]*100
	#Conditional kappa
	for (exp in 1:(length(Kappa_confusion[,1])-3)){
		Kappa_confusion[exp,"condK"]=round(((Kappa_confusion["Total","Total"]*Kappa_confusion[exp,exp])-(Kappa_confusion[exp,"Total"]*Kappa_confusion["Total",exp])) / ((Kappa_confusion["Total","Total"]*Kappa_confusion[exp,"Total"])-(Kappa_confusion[exp,"Total"]*Kappa_confusion["Total",exp]))*100,digits=3)
	}
	for (exp in 1:(length(Kappa_confusion[1,])-4)){
		Kappa_confusion["condK",exp]=round(((Kappa_confusion["Total","Total"]*Kappa_confusion[exp,exp])-(Kappa_confusion["Total",exp]*Kappa_confusion[exp,"Total"])) / ((Kappa_confusion["Total","Total"]*Kappa_confusion["Total",exp])-(Kappa_confusion["Total",exp,]*Kappa_confusion[exp,"Total"]))*100,digits=3)
	}
	#results
	tablak<-data.frame(t(rep(NA,5)));tablak<-tablak[-1,]
	names(tablak)<-c("Accuracy","Kappa","Int1K","Int2K","ASE");
	tablak["Resum",]<-c(round(F_global,digit=4),round(as.vector(Kappaest$Unweighted[1]),digit=4),round(as.vector(Kappaint[1]),digit=4),round(as.vector(Kappaint[3]),digit=4),round(as.vector(Kappaest$Unweighted[2]),digit=4));

	#export
	return=list(Kappa_confusion,tablak)
	return(return)
}

#input data------------------------------------------

#raster
RASTER <- readRAST(c(valid,clasif))

#
datRASTER <- data.frame(RASTER@data)
datRASTER <- datRASTER[!is.na(datRASTER[,valid]), c(valid,clasif)]

datRASTER[,valid] <- as.factor(datRASTER[,valid])
datRASTER[,clasif] <- as.factor(datRASTER[,clasif])


#folder to save results:
if(dir.exists(paste0(workdir,"/clasifresults"))==F){dir.create(paste0(workdir,"/clasifresults"))}

#summary exists?, if not create
if(file.exists(paste0(workdir,"/summaryVAL.Rdata"))==F){
	tableK <- data.frame(typevar=character(0),clasif=character(0),Accuracy=double(0),Kappa=double(0),Int1k=double(0),Int2k=double(0),ASE=double(0),Optim=integer(0),stringsAsFactors=FALSE)
}else{
	load(paste0(workdir,"/summaryVAL.Rdata"))
}

#validation-----------------------------------------------------------
kappadata=fun.kappa(validate=datRASTER[,valid],prediction=datRASTER[,clasif])
#
tableK[nrow(tableK)+1,]<-c(typevar,typemodel,kappadata[[2]][[1]],kappadata[[2]][[2]],kappadata[[2]][[3]],kappadata[[2]][[4]],kappadata[[2]][[5]],0)

#export confusion table:
write.table(kappadata[[1]],file=paste0(workdir,"/clasifresults/confusion_",typemodel,typevar,year,seasons,".txt"),sep=";")


############################################################
#EXPORT SUMMARY DATA

write.table(tableK,file=paste0(workdir,"/summaryVAL",year,seasons,".txt"),sep=";",row.names=F)
save(tableK,file=paste0(workdir,"/summaryVAL.Rdata"))

