#upset
#install.packages("UpSetR")
library(ggsci)
library(UpSetR)
setwd("E:\\colon cancer\\可变剪切\\可变剪切\\1.UpSetR")                                
rt=read.table("asMatrix.txt",sep="\t",header=T,check.names=F,row.names=1)        
gene=sapply(strsplit(rownames(rt),"\\|"),"[",1)
asType=sapply(strsplit(rownames(rt),"\\|"),"[",3)
upsetList=list(AA=unique(gene[asType=="AA"]),
               AD=unique(gene[asType=="AD"]),
               AP=unique(gene[asType=="AP"]),
               AT=unique(gene[asType=="AT"]),
               ES=unique(gene[asType=="ES"]),
               ME=unique(gene[asType=="ME"]),
               RI=unique(gene[asType=="RI"]) )
upsetData=fromList(upsetList)
colors0<-pal_npg("nrc",alpha = 1)(7)
pdf(file="upset0.pdf",onefile = FALSE,width=9,height=6)              
upset(upsetData,
      nsets = 7,                                    
      nintersects = 50,                             
      order.by = "freq",                            
      show.numbers = "yes",                        
      number.angles = 20,                           
      point.size = 1.5,                            
      matrix.color="black",                          
      main.bar.color =colors0,
      sets.bar.color=colors0,
      line.size = 0.8,                               
      mainbar.y.label = "Gene Intersections", 
      sets.x.label = "Set Size")
dev.off()
#unicox
#install.packages('survival')
#install.packages("UpSetR")

pFilter=0.05                                                     

setwd("C:\\Users\\lexb4\\Desktop\\AS\\12.uniCox")               
library(survival)                                                 
library(UpSetR)
rt=read.table("asTime.txt",header=T,sep="\t",check.names=F,row.names=1)     

outTab=data.frame()
for(i in colnames(rt[,3:ncol(rt)])){
  cox <- coxph(Surv(futime, fustat) ~ rt[,i], data = rt)
  coxSummary = summary(cox)
  coxP=coxSummary$coefficients[,"Pr(>|z|)"]
  outTab=rbind(outTab,
               cbind(id=i,
                     z=coxSummary$coefficients[,"z"],
                     HR=coxSummary$conf.int[,"exp(coef)"],
                     HR.95L=coxSummary$conf.int[,"lower .95"],
                     HR.95H=coxSummary$conf.int[,"upper .95"],
                     pvalue=coxSummary$coefficients[,"Pr(>|z|)"])
  )
}
outTab = outTab[is.na(outTab$pvalue)==FALSE,]
outTab=outTab[order(as.numeric(as.vector(outTab$pvalue))),]
write.table(outTab,file="uniCoxResult.txt",sep="\t",row.names=F,quote=F)
sigTab=outTab[as.numeric(as.vector(outTab$pvalue))<pFilter,]
write.table(sigTab,file="uniCoxResult.Sig.txt",sep="\t",row.names=F,quote=F)
sigGenes=c("futime","fustat")
sigGenes=c(sigGenes,as.vector(sigTab[,1]))
uniSigExp=rt[,sigGenes]
uniSigExp=cbind(id=row.names(uniSigExp),uniSigExp)
write.table(uniSigExp,file="uniSigExp.txt",sep="\t",row.names=F,quote=F)
gene=sapply(strsplit(sigGenes,"\\|"),"[",1)
asType=sapply(strsplit(sigGenes,"\\|"),"[",3)
upsetList=list(AA=unique(gene[asType=="AA"]),
               AD=unique(gene[asType=="AD"]),
               AP=unique(gene[asType=="AP"]),
               AT=unique(gene[asType=="AT"]),
               ES=unique(gene[asType=="ES"]),
               ME=unique(gene[asType=="ME"]),
               RI=unique(gene[asType=="RI"]) )
upsetData=fromList(upsetList)
colors0<-pal_npg("nrc",alpha = 1)(7)
pdf(file="upset0.pdf",onefile = FALSE,width=9,height=6)              
upset(upsetData,
      nsets = 7,                                    
      nintersects = 50,                             
      order.by = "freq",                            
      show.numbers = "yes",                        
      number.angles = 20,                           
      point.size = 1.5,                            
      matrix.color="black",                          
      main.bar.color =colors0,
      sets.bar.color=colors0,
      line.size = 0.8,                               
      mainbar.y.label = "Gene Intersections", 
      sets.x.label = "Set Size")
dev.off()
#vol
#install.packages("ggplot2")

library(ggplot2)                                              
setwd("C:\\Users\\lexb4\\Desktop\\AS\\13.vol")                
rt = read.table("uniCoxResult.txt",header=T,sep="\t")        


pdf(file="vol.pdf",width = 5.5,height = 6)             
yMax=8                                     
xMax=5                                    
plot(rt$z,-log10(rt$pvalue), 
     ylab="-log10(pvalue)",xlab="z-score",
     ylim=c(0,yMax),xlim=c(-xMax,xMax),
     bty="l",col="skyblue",
     yaxs="i",pch=20, cex=0.8)
diffSub=subset(rt, pvalue<0.05)
points(diffSub$z,-log10(diffSub$pvalue), pch=20, col="red",cex=1)    
abline(v=0,lty=2,lwd=1.5)
legend("topright", 
       c("Prognosis-related AS", "No significant"),
       bty="n",
       pch=19,
       col=c("red","skyblue"))
dev.off()
#bubble
#install.packages("ggplot2")

library(ggplot2)                                         
setwd("C:\\Users\\lexb4\\Desktop\\AS\\14.bubble")               
rt = read.table("uniCoxResult.Sig.txt",header=T,sep="\t")       
row.names(rt)=rt[,1]
rt[,1]=gsub("\\|","\\-",rt[,1])

for(asType in c("AA","AD","AP","AT","ES","RI","ME")){
  genes=rownames(rt)
  gene=grep(paste0("\\|",asType),genes,value=T)
  geneLength=ifelse(length(gene)>20,20,length(gene))
  data=rt[gene[1:geneLength],]
  
  data=data[order(as.numeric(as.vector(data$pvalue)),decreasing = T),]
  data$id = factor(data$id,levels=as.character(data[,1]))
  
  p = ggplot(data,aes(z,id))		
  pbubble = p + geom_point(aes(color=pvalue,size=-1*log10(pvalue)) )
  pr = pbubble + 
    scale_colour_gradient(low="red",high="skyblue") + 
    labs(color="pvalue",size="-log10(pvalue)",x="z-score",y="")+
    guides(color = guide_colourbar(order = 1), size = guide_legend(order = 2))+
    theme_bw()
  ggsave(paste0(asType,".bubble.pdf"),width=5.5,height=5)                
}
#DEGs
#install.packages("pheatmap")

setwd("C:\\Users\\lexb4\\Desktop\\immuneGene\\09.immuneDiff")                 
fdrFilter=0.05                                                    
logFCfilter=1                                                    
conNum=32                                                        
treatNum=375                                                      

rt=read.table("all.txt",sep="\t",header=T,check.names=F,row.names=1)
diffExp=read.table("diffGeneExp.txt",sep="\t",header=T,check.names=F,row.names=1)
gene=read.table("gene.txt",sep="\t",header=F)
immuneDiffAll=rt[intersect(gene[,1],row.names(rt)),]
immuneDiffGene=intersect(gene[,1],row.names(diffExp))
hmExp=diffExp[immuneDiffGene,]
immuneDiffResult=immuneDiffAll[immuneDiffGene,]

immuneDiffResult=rbind(ID=colnames(immuneDiffResult),immuneDiffResult)
write.table(immuneDiffResult,file="immuneDiff.xls",sep="\t",col.names=F,quote=F)

immuneGeneExp=rbind(ID=colnames(hmExp),hmExp)
write.table(immuneGeneExp,file="immuneGeneExp.txt",sep="\t",col.names=F,quote=F)

pdf(file="vol.pdf",height=5,width=5)
xMax=max(abs(as.numeric(as.vector(immuneDiffAll$logFC))))
yMax=max(-log10(immuneDiffAll$fdr))+1
plot(as.numeric(as.vector(immuneDiffAll$logFC)), -log10(immuneDiffAll$fdr), xlab="logFC",ylab="-log10(fdr)",
     main="Volcano", ylim=c(0,yMax),xlim=c(-xMax,xMax),yaxs="i",pch=20, cex=0.8)
diffSub=subset(immuneDiffAll, fdr<fdrFilter & as.numeric(as.vector(logFC))>logFCfilter)
points(as.numeric(as.vector(diffSub$logFC)), -log10(diffSub$fdr), pch=20, col="red",cex=0.8)
diffSub=subset(immuneDiffAll, fdr<fdrFilter & as.numeric(as.vector(logFC))<(-logFCfilter))
points(as.numeric(as.vector(diffSub$logFC)), -log10(diffSub$fdr), pch=20, col="green",cex=0.8)
abline(v=0,lty=2,lwd=3)
dev.off()

library(pheatmap)
hmExp=log2(hmExp+0.001)
Type=c(rep("N",conNum),rep("T",treatNum))
names(Type)=colnames(diffExp)
Type=as.data.frame(Type)
pdf(file="heatmap.pdf",height=12,width=15)
pheatmap(hmExp, 
         annotation=Type, 
         color = colorRampPalette(c("green", "black", "red"))(50),
         cluster_cols =F,
         show_colnames = F,
         show_rownames = F,
         fontsize = 12,
         fontsize_row=3,
         fontsize_col=10)
dev.off()
#muticox
#install.packages('survival')

library(survival)                                        
setwd("C:\\Users\\lexb4\\Desktop\\AS\\16.multiCox")      
rt=read.table("lassoSigExp.txt",header=T,sep="\t",check.names=F,row.names=1)    

multiCox=coxph(Surv(futime, fustat) ~ ., data = rt)
multiCox=step(multiCox,direction = "both")
multiCoxSum=summary(multiCox)

outTab=data.frame()
outTab=cbind(
  coef=multiCoxSum$coefficients[,"coef"],
  HR=multiCoxSum$conf.int[,"exp(coef)"],
  HR.95L=multiCoxSum$conf.int[,"lower .95"],
  HR.95H=multiCoxSum$conf.int[,"upper .95"],
  pvalue=multiCoxSum$coefficients[,"Pr(>|z|)"])
outTab=cbind(id=row.names(outTab),outTab)
outTab=gsub("`","",outTab)
write.table(outTab,file="multiCox.xls",sep="\t",row.names=F,quote=F)

riskScore=predict(multiCox,type="risk",newdata=rt)
coxGene=rownames(multiCoxSum$coefficients)
coxGene=gsub("`","",coxGene)
outCol=c("futime","fustat",coxGene)
risk=as.vector(ifelse(riskScore>median(riskScore),"high","low"))
write.table(cbind(id=rownames(cbind(rt[,outCol],riskScore,risk)),cbind(rt[,outCol],riskScore,risk)),
            file="risk.txt",
            sep="\t",
            quote=F,
            row.names=F)
#riskplot
#install.packages("pheatmap")

library(pheatmap)
setwd("C:\\Users\\lexb4\\Desktop\\AS\\19.riskPlot")            
rt=read.table("risk.txt",sep="\t",header=T,row.names=1,check.names=F)       
rt=rt[order(rt$riskScore),]                                    

riskClass=rt[,"risk"]
lowLength=length(riskClass[riskClass=="low"])
highLength=length(riskClass[riskClass=="high"])
line=rt[,"riskScore"]
line[line>10]=10
pdf(file="riskScore.pdf",width = 12,height = 5)
plot(line,
     type="p",
     pch=20,
     xlab="Patients (increasing risk socre)",
     ylab="Risk score",
     col=c(rep("green",lowLength),
           rep("red",highLength)))
abline(h=median(rt$riskScore),v=lowLength,lty=2)
dev.off()

color=as.vector(rt$fustat)
color[color==1]="red"
color[color==0]="green"
pdf(file="survStat.pdf",width = 12,height = 5)
plot(rt$futime,
     pch=19,
     xlab="Patients (increasing risk socre)",
     ylab="Survival time (years)",
     col=color)
abline(v=lowLength,lty=2)
dev.off()

rt1=rt[c(3:(ncol(rt)-2))]
rt1=t(rt1)
annotation=data.frame(type=rt[,ncol(rt)])
rownames(annotation)=rownames(rt)
pdf(file="heatmap.pdf",width = 12,height = 5)
pheatmap(rt1, 
         annotation=annotation, 
         cluster_cols = FALSE,
         fontsize_row=11,
         fontsize_col=3,
         color = colorRampPalette(c("green", "black", "red"))(50) )
dev.off()
#multiroc
#install.packages("survivalROC")

library(survivalROC)
setwd("C:\\Users\\lexb4\\Desktop\\Autophagy\\22.multiROC")     
rt=read.table("indepInput.txt",header=T,sep="\t",check.names=F,row.names=1)    
rt$futime=rt$futime/365
rocCol=rainbow(ncol(rt)-2)
aucText=c()

#绘制risk score的ROC曲线
pdf(file="multiROC.pdf",width=6,height=6)
par(oma=c(0.5,1,0,1),font.lab=1.5,font.axis=1.5)
roc=survivalROC(Stime=rt$futime, status=rt$fustat, marker = rt$riskScore, predict.time =1, method="KM")
plot(roc$FP, roc$TP, type="l", xlim=c(0,1), ylim=c(0,1),col=rocCol[1], 
     xlab="False positive rate", ylab="True positive rate",
     lwd = 2, cex.main=1.3, cex.lab=1.2, cex.axis=1.2, font=1.2)
aucText=c(aucText,paste0("risk score"," (AUC=",sprintf("%.3f",roc$AUC),")"))
abline(0,1)

j=1
for(i in colnames(rt[,3:(ncol(rt)-1)])){
  roc=survivalROC(Stime=rt$futime, status=rt$fustat, marker = rt[,i], predict.time =1, method="KM")
  j=j+1
  aucText=c(aucText,paste0(i," (AUC=",sprintf("%.3f",roc$AUC),")"))
  lines(roc$FP, roc$TP, type="l", xlim=c(0,1), ylim=c(0,1),col=rocCol[j],lwd = 2)
}
legend("bottomright", aucText,lwd=2,bty="n",col=rocCol)
dev.off()
#unilndep
#install.packages('survival')
#install.packages('forestplot')

library(survival)
library(forestplot)
setwd("C:\\Users\\lexb4\\Desktop\\AS\\21.uniIndep")                          

clrs <- fpColors(box="green",line="darkblue", summary="royalblue")           
rt=read.table("indepInput.txt",header=T,sep="\t",check.names=F,row.names=1)

outTab=data.frame()
for(i in colnames(rt[,3:ncol(rt)])){
  cox <- coxph(Surv(futime, fustat) ~ rt[,i], data = rt)
  coxSummary = summary(cox)
  coxP=coxSummary$coefficients[,"Pr(>|z|)"]
  outTab=rbind(outTab,
               cbind(id=i,
                     HR=coxSummary$conf.int[,"exp(coef)"],
                     HR.95L=coxSummary$conf.int[,"lower .95"],
                     HR.95H=coxSummary$conf.int[,"upper .95"],
                     pvalue=coxSummary$coefficients[,"Pr(>|z|)"])
  )
}
write.table(outTab,file="uniCox.xls",sep="\t",row.names=F,quote=F)

rt=read.table("uniCox.xls",header=T,sep="\t",row.names=1,check.names=F)
data=as.matrix(rt)
HR=data[,1:3]
hr=sprintf("%.3f",HR[,"HR"])
hrLow=sprintf("%.3f",HR[,"HR.95L"])
hrHigh=sprintf("%.3f",HR[,"HR.95H"])
pVal=data[,"pvalue"]
pVal=ifelse(pVal<0.001, "<0.001", sprintf("%.3f", pVal))
tabletext <- 
  list(c(NA, rownames(HR)),
       append("pvalue", pVal),
       append("Hazard ratio",paste0(hr,"(",hrLow,"-",hrHigh,")")) )          
pdf(file="forest.pdf",onefile = FALSE,
    width = 6,             
    height = 4,           
)
forestplot(tabletext, 
           rbind(rep(NA, 3), HR),
           col=clrs,
           graphwidth=unit(50, "mm"),
           xlog=T,
           lwd.ci=2,
           boxsize=0.3,
           xlab="Hazard ratio"
)
dev.off()
#multiIndep
#install.packages('survival')
#install.packages('forestplot')

library(survival)
library(forestplot)
setwd("C:\\Users\\lexb4\\Desktop\\AS\\22.multiIndep")                        #设置工作目录

clrs <- fpColors(box="red",line="darkblue", summary="royalblue")             #定义森林图颜色
rt=read.table("indepInput.txt",header=T,sep="\t",check.names=F,row.names=1)

multiCox=coxph(Surv(futime, fustat) ~ ., data = rt)
multiCoxSum=summary(multiCox)

outTab=data.frame()
outTab=cbind(
  HR=multiCoxSum$conf.int[,"exp(coef)"],
  HR.95L=multiCoxSum$conf.int[,"lower .95"],
  HR.95H=multiCoxSum$conf.int[,"upper .95"],
  pvalue=multiCoxSum$coefficients[,"Pr(>|z|)"])
outTab=cbind(id=row.names(outTab),outTab)
write.table(outTab,file="multiCox.xls",sep="\t",row.names=F,quote=F)

rt=read.table("multiCox.xls",header=T,sep="\t",row.names=1,check.names=F)
data=as.matrix(rt)
HR=data[,1:3]
hr=sprintf("%.3f",HR[,"HR"])
hrLow=sprintf("%.3f",HR[,"HR.95L"])
hrHigh=sprintf("%.3f",HR[,"HR.95H"])
pVal=data[,"pvalue"]
pVal=ifelse(pVal<0.001, "<0.001", sprintf("%.3f", pVal))
tabletext <- 
  list(c(NA, rownames(HR)),
       append("pvalue", pVal),
       append("Hazard ratio",paste0(hr,"(",hrLow,"-",hrHigh,")")) )         
pdf(file="forest.pdf",onefile = FALSE,
    width = 6,             
    height = 4,           
)
forestplot(tabletext, 
           rbind(rep(NA, 3), HR),
           col=clrs,
           graphwidth=unit(50, "mm"),
           xlog=T,
           lwd.ci=2,
           boxsize=0.3,
           xlab="Hazard ratio"
)
dev.off()
#PCA
setwd("E:\\STAD\\PCA")
risk=read.table("risk.txt",sep="\t",header=T,row.names=1)
data=risk[,3:(ncol(risk)-2)]
group=as.vector(risk[,"risk"])
data.class <- rownames(data)
data.pca <- prcomp(data, scale. = TRUE)
write.table(predict(data.pca),file="newTab.xls",quote=F,sep="\t")      
dt=predict(data.pca)
rk=risk$risk
wt=data.frame(dt)
rt=cbind(wt,rk)