
#########################################################parametric analysis for gene set enrichment

 setwd ("final")

 
 load ("expr.main.RData")  #the linear regression output matrix
 load ( "expr.perm.RData" )  #permutation 
 s0 <- quantile(expr.perm[[2]], 0.5); rm(expr.perm); gc()
 dScore <- expr.main[,1] / ( expr.main[,2]+ s0)
 names(dScore) <- rownames(expr.main)

 
 go <- c("proc", "func", "comp")
 j <- 1
 load ( paste("../ftp/go.", go[j], ".RData", sep="") )  #the gene ontology 0N1 matrix

 gene.list <- intersect( names(dScore), rownames(go.mat) )
 go.mat <- go.mat[ which(rownames(go.mat) %in% gene.list), ]
 go.mat <- go.mat[, colSums(go.mat) >= 15] #CAN CHANGE THIS  
 go.mat <- go.mat[rowSums(go.mat) >0,]

 gene.list <- intersect(names(dScore), rownames(go.mat) )
 dScore <- dScore[ match(gene.list, names(dScore) ) ]
 go.mat <- go.mat[ match(gene.list, rownames(go.mat) ), ]

 vec <- rep(NA, ncol(go.mat) )
 names(vec)  <- colnames(go.mat)
 z <- p <- vec


 mu <- mean(dScore )
 std <- sqrt( var(dScore) )

 for (i in 1:ncol(go.mat) )
 {
  hit <- rownames(go.mat)[ go.mat[,i]==1 ]

  d <- dScore [ which(names(dScore) %in% hit ) ]
  sm <- mean (d)
  n <- length(hit)

  z[i] <- (sm-mu)/ (std /sqrt(n) )
  ifelse( z[i] <=0, p[i] <- -pnorm(z[i] ), p[i] <- pnorm(z[i], lower.tail=F)  )
 }

 page <- cbind(z, p)
 page <- page[ order( abs(page[,2]) ),]



 hit <- page[ abs(page[,2])< 1e-3,] #CAN CHANGE THIS
 load ("find.RData") #the annotation for gene ontology terms
 anno <- find[ match( rownames(hit), names(find)) ]
 print( data.frame( zscore=hit[,1], pval=hit[,2], anno) )



