#setwd('/pub1/data/mg_projects/projects/web_script/R/')
library(optparse)
option_list <- list(
  make_option(c("-i", "--infile"), type = "character", default = '/pub1/data/mg_projects/projects/web_script/tool_runing/420f10668a5d1ee388078d128f6778b8/input.json',
              action = "store", help = "Input a exp file path!"
  ),
  make_option(c("-o", "--outfile"), type = "character", default = '/pub1/data/mg_projects/projects/web_script/tool_runing/dae42f7681eca28355c6ba9105a3b5ff',
              action = "store", help = "Input a outfolder path!"
  )
)
logs=c()
#stx=rbind()
tryCatch({
  Args <- commandArgs()
  opt = parse_args(OptionParser(option_list = option_list, usage = "GEO Data press"))
  #logs=c(logs,paste0('geting data:',paste0(paste0(names(opt),'=',opt),collapse = ',')))
  logs=c(logs,paste0('run muti_cox.R-',basename(opt$outfile)))
  #library("rjson")
  library(jsonlite)
  data<-jsonlite::stream_in(file(opt$infile),pagesize = 1000)
  values=unlist(data$values)
  times=unlist(data$times)
  events=unlist(data$events)
  isStep=as.numeric(unlist(data$step))
  colNames=unlist(data$colNames)
  #isStep=1
  #isRow=1
  #web_script/tool_runing/test_data/TCGA_Test_exp.txt
  #head(dat)
  
  set.seed(123456789)
  library('survival')
  
    dat1=matrix(as.numeric(values),ncol = length(colNames),byrow = T)  
    times=as.numeric(times)
    events=as.numeric(events)
    logs=c(logs,paste0('clean data,row=',nrow(dat1),',col=',ncol(dat1)))
    
    colnames(dat1)=paste0('C',1:ncol(dat1))
    
    cxDat=cbind(time=times,status=events,dat1)
    
    fmla <- as.formula(paste0("Surv(time, status) ~",paste0(colnames(dat1),collapse = '+')))
    logs=c(logs,paste0('start cox'))
    cox <- survival::coxph(fmla, data = as.data.frame(cxDat))
    #cox$coefficients
    #cox$wald.test
    res1=cbind(summary(cox)[[7]][,c(2,5)],summary(cox)[[8]][,c(3,4)],summary(cox)[[7]][,1])
    row.names(res1)=colNames[match(row.names(res1),colnames(dat1))]
    colnames(res1)[5]='coef'
    logs=c(logs,paste0('output cox result'))
    write.table(cbind(Tag=row.names(res1),res1),file = paste0(opt$outfile,'/mutiCox.txt')
                ,row.names = F,col.names = T,quote = F,sep = '\t')  
    
    if(isStep==1){
      logs=c(logs,paste0('step cox'))
      cox2=step(cox)
      #cox2$anova
      logs=c(logs,paste0('steped cox,output'))
      res2=cbind(summary(cox2)[[7]][,c(2,5)],summary(cox2)[[8]][,c(3,4)])
      row.names(res2)=colNames[match(row.names(res2),colnames(dat1))]
      write.table(cbind(Tag=row.names(res2),res2),file = paste0(opt$outfile,'/mutiCoxStep.txt')
                  ,row.names = F,col.names = T,quote = F,sep = '\t')  
      riskcore=dat1[,match(names(cox2$coefficients),colnames(dat1))]%*%cox2$coefficients
      lst.exp=dat1[,match(names(cox2$coefficients),colnames(dat1))]
      cxs=summary(cox2)
      logs=c(logs,paste0('logtest=',cxs$logtest[3]))
      logs=c(logs,paste0('sctest=',cxs$sctest[3]))
      logs=c(logs,paste0('waldtest=',cxs$waldtest[3]))
      logs=c(logs,paste0('concordance=',cxs$concordance[1]))
    }else{
      riskcore=dat1[,match(names(cox$coefficients),colnames(dat1))]%*%cox$coefficients
      lst.exp=dat1[,match(names(cox$coefficients),colnames(dat1))]
      cxs=summary(cox)
      logs=c(logs,paste0('logtest=',cxs$logtest[3]))
      logs=c(logs,paste0('sctest=',cxs$sctest[3]))
      logs=c(logs,paste0('waldtest=',cxs$waldtest[3]))
      logs=c(logs,paste0('concordance=',cxs$concordance[1]))
    }
    risk_OS=cbind(Time=times,Status=events,RiskScore=riskcore[,1])
    logs=c(logs,paste0('output riskcore'))
    write.table(cbind(Tag=paste0('R',1:length(times)),risk_OS),file = paste0(opt$outfile,'/riskscore.txt')
                ,row.names = F,col.names = T,quote = F,sep = '\t') 
    colnames(lst.exp)=colNames[match(colnames(lst.exp),colnames(dat1))]
    logs=c(logs,paste0('output lst gene exp'))
    write.table(cbind(Tag=paste0('R',1:length(times)),lst.exp),file = paste0(opt$outfile,'/filterGeneExp.txt')
                ,row.names = F,col.names = T,quote = F,sep = '\t') 
    logs=c(logs,paste0('runed all'))
  
},error = function(e) {
  print(conditionMessage(e))
  logs=c(logs,paste0('error:',conditionMessage(e)))
}, finally = {
  write.table(logs,file = paste0(opt$outfile,'/run.log'),quote = F,row.names = T,col.names = T,sep = '\t')
})


