rm(list = ls())

library(neuralnet)
library(NeuralNetTools)
library(limma)
setwd("")     
inputFile="Large_test_normalize.txt"       

new_data=read.table(inputFile, header=T, sep="\t", check.names=F, row.names=1)
new_data=t(new_data)
group=gsub("(.*)\\_(.*)", "\\2", row.names(new_data))
diffFile="Newdiff.txt"
test.normalize = read.table('Large_test_normalize.txt',header = T)

set.seed(123456)
sample_num = runif(1000,2,2)
final_auc = rep(NA,length(sample_num))
for(i in 1:length(sample_num)){
  index = sample(test.normalize[,1],sample_num[i])
  require_data = t(new_data[,match(index,colnames(new_data))])
  write.table(require_data, file=paste0("rfGeneExp/rfGeneExp",i,".txt"), sep="\t", quote=F, col.names=T)
  rt = cbind(ID = row.names(require_data),require_data)
  #colnames(rt) = c()
  rt=as.matrix(rt)
  exp=rt[,2:ncol(rt)]
  exp=apply(exp,2,as.numeric)
  dimnames=list(rownames(rt),colnames(rt)[2:ncol(rt)])
  data=matrix(as.numeric(as.matrix(exp)),nrow=nrow(exp),dimnames=dimnames)
  data=avereps(data)
  

  diffRT=read.table(diffFile, header=T, sep="\t", check.names=F, row.names=1)
  diffRT=diffRT[row.names(data),]
  

  dataUp=data[diffRT[,"logFC"]>0, ,drop=FALSE]
  dataDown=data[diffRT[,"logFC"]<0,,drop=FALSE]
  dataUp2=t(apply(dataUp,1,function(x)ifelse(x>median(x),1,0)))
  dataDown2=t(apply(dataDown,1,function(x)ifelse(x>median(x),0,1)))

  if(any(dim(dataUp2)==0,dim(dataDown2)==0)){
    num = which(c(dim(dataUp2)==0,dim(dataDown2)==0))
    if(num<=2){
      outTab = dataDown2
    }else{
      outTab = dataUp2
    }
  }else{
    outTab=rbind(dataUp2, dataDown2)
  }
  
  outTab=rbind(id=colnames(outTab), outTab)
  write.table(outTab, file=paste0("geneScore/geneScore_",i,'.txt'), sep="\t", quote=F, col.names=F)
  

  
  #install.packages("neuralnet")
  #install.packages("NeuralNetTools")
  
  #set.seed(123)
  
  inputFile=paste0("geneScore/geneScore_",i,'.txt')      
  

  data=read.table(inputFile, header=T, sep="\t", check.names=F, row.names=1)
  data=as.data.frame(t(data))
  

  group=gsub("(.*)\\_(.*)", "\\2", row.names(data))
  data$con=ifelse(group=="con", 1, 0)
  data$treat=ifelse(group=="treat", 1, 0)
  
  library(stringr)
  colnames(data) <- str_replace_all(colnames(data),'-','_')

  fit=neuralnet(con+treat~., data, hidden=5)
  fit$result.matrix
  fit$weight
  #plot(fit)
  
  pdf(file=paste0("neuralnet/neuralnet_",i,'.pdf'), width=9, height=7)
  plotnet(fit)
  dev.off()
  

  net.predict=compute(fit, data)$net.result
  net.prediction=c("con", "treat")[apply(net.predict, 1, which.max)]
  predict.table=table(group, net.prediction)
  predict.table
  conAccuracy=predict.table[1,1]/(predict.table[1,1]+predict.table[1,2])
  treatAccuracy=predict.table[2,2]/(predict.table[2,1]+predict.table[2,2])
  paste0("Con accuracy: ", sprintf("%.3f", conAccuracy))
  paste0("Treat accuracy: ", sprintf("%.3f", treatAccuracy))
  

  colnames(net.predict)=c("con", "treat")
  outTab=rbind(id=colnames(net.predict), net.predict)
  write.table(outTab, file=paste0("neural.predict/neural.predict",i,".txt"), sep="\t", quote=F, col.names=F)
  
  
  
  #install.packages("pROC")
  
  
  library(pROC)                 
  inputFile=paste0("neural.predict/neural.predict",i,".txt")     
  

  rt=read.table(inputFile, header=T, sep="\t", check.names=F, row.names=1)
  y=gsub("(.*)\\_(.*)", "\\2", row.names(rt))
  y=ifelse(y=="con", 0, 1)
  

  roc1=roc(y, as.numeric(rt[,2]))
  ci1=ci.auc(roc1, method="bootstrap")
  ciVec=as.numeric(ci1)
  pdf(file="ROC.pdf", width=5, height=5)
  plot(roc1, print.auc=TRUE, col="red", legacy.axes=T, main="Test Large_group")
  text(0.39, 0.43, paste0("95% CI: ",sprintf("%.03f",ciVec[1]),"-",sprintf("%.03f",ciVec[3])), col="red")
  dev.off()
  final_auc[i] = as.numeric(roc1$auc)
}
mean_auc = mean(final_auc)
mean_auc

  
#warnings()


