### edgeR for detection of DEGs from the normalized data by other normalization methods (Tc, Med, UQ, FQ, Med-pgQ2 and UQ-pgQ2)
edgeR_noTMM<-function(data, conds, pair){
  data_new<-data
  colnames(data_new)
  #class<-conds<-c(rep("uhr",2),rep("hbr", 2))
  # conds<-factor(conds)
  ### using TMM normalization#####################
  edgeR.dgelist<-DGEList(counts=as.matrix(data_new), group=conds)
  head(edgeR.dgelist$counts) # original count matrix
  edgeR.dgelist<-calcNormFactors(edgeR.dgelist, method="none") # 
  
  edgeR.dgelist<-estimateCommonDisp(edgeR.dgelist)
  edgeR.dgelist<-estimateTagwiseDisp(edgeR.dgelist,trend="movingave")
  head(edgeR.dgelist$samples)
  norm<-edgeR.dgelist$pseudo.counts # without change the size of factor and pseudo.count is 
  # different from normalized counts
  edgeR.test.tgw<-exactTest(edgeR.dgelist, dispersion="tagwise", pair=pair) # B vs A, HBR vs. UHR
  (n<-nrow(edgeR.test.tgw$table)) 
  res1<-topTags(edgeR.test.tgw,n,sort.by="none")$table 
  return(res1)
}

# per gene normalization by Median: pgQ2
# X: a matrix of data with the multiplication of factor (f) as:
# f=50, 100, 200, 500 or 1000

pgene1<-function(X, f ){
  m<-apply(X,1, median)
  si<-m/f # multiply f=100 per gene per sample
  X1<-scale(t(X),center=FALSE,scale=si)
  res<-t(X1)
  rownames(res)<-rownames(X)
  return(res)  
}


library("edgeR")

## Med normalization

norm.med<-med(data1) # median normalization per sample
head(norm.med)[1:2,]
norm.MedpgQ2<-pgene1(norm.med, f=100)  # per gene normalization across samples with scaling factor 100
head(norm.MedpgQ2)[1:2,]
res3.DEGs<-edgeR_noTMM(norm.MedpgQ2, conds, pair) # DEGs using exact test from edgeR 
head(res3.DEGs)[1:2, ]
