R/qcmenu.R

Defines functions delta.plot1 PlotOptionsv1 affyPlotMA

Documented in affyPlotMA PlotOptionsv1

#set of functions, directly/indirectly involved, in oneChannelGUI qcMenu
#oneChannelGUI normBoxplot this function produces a boxplot for NormalizedAffyData
#oneChannelGUI ocPlotPCA this function produces a PCA plot using the normalized expression data works both with affy and exon arrays
#oneChannelGUI ocPlotHist this function produces an affy hist plot for exon and gene level data after probeset intenisty calculation
#oneChannelGUI sample.size.evaluation allows sample size and statistical power estimation using the ssize package
#oneChannelGUI sample.size.evaluation1 allows sample size and statistical power estimation using the sizepower package
#oneChannelGUI PlotOptionsv1 plotting optino selections
#affyPlotMA modified to use the expr(NormalizedAffyData)
#oneChannelGUI rawBoxplotPN plot the raw log2 intensity values for positive and negative ctrls extracted from CEL files
#oneChannelGUI qcMDS evaluating the presence eof outliers using plotMDS.dge of NGS data
#oneChannelGUI EDAplotQuality bam qc associated to EDASeq
#              EDAreadNumber
#              EDANtFreq 
#              EDAboxplot
#              EDAbiasPlot
# oneChannelGUI fastQC java tool to evaluate fastq quality
################################################################################
"normBoxplot" <- function(){
        #error if no data are loaded
         Try(whichArrayPlatform <- get("whichArrayPlatform",envir=affylmGUIenvironment))
         if(whichArrayPlatform ==""){
              Try(tkmessageBox(title="QC",message="No arrays have been loaded.	Please try New or Open from the File menu.",type="ok",icon="error"))
				    	Try(tkfocus(.affylmGUIglobals$ttMain))
              Try(return())
         }    
         #########################
         if(whichArrayPlatform=="LARGE" || whichArrayPlatform=="GENE" || whichArrayPlatform=="ILLU"){
               if(affylmGUIenvironment$NormalizedAffyData.Available){
                      Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
                      Try(NormalizedAffyData <- get("NormalizedAffyData",envir=affylmGUIenvironment))
                      Try( boxplot(as.data.frame(exprs(NormalizedAffyData)), las=2, names=pData(NormalizedAffyData)$Name,ylab="Normalized log2(intensities)"))
                      Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
               }
         } else if (whichArrayPlatform=="AFFY"){
               if(affylmGUIenvironment$NormalizedAffyData.Available){
                      Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
                      Try(NormalizedAffyData <- get("NormalizedAffyData",envir=affylmGUIenvironment))
                      Try( boxplot(as.data.frame(exprs(NormalizedAffyData)), las=2, names=pData(NormalizedAffyData)$Name,ylab="Normalized log2(intensities)"))
                      Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
               }
         } else if (whichArrayPlatform=="NGS"){
               if(affylmGUIenvironment$NormalizedAffyData.Available){
                      Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
                      Try(NormalizedAffyData <- get("NormalizedAffyData",envir=affylmGUIenvironment))
                      Try( boxplot(as.data.frame(log10(exprs(NormalizedAffyData))), las=2, names=pData(NormalizedAffyData)$Name,ylab="log10 peaks counts"))
                      Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
               }
         } else{
             Try(tkmessageBox(title="Box plot normalized data",message="Probe set summary is not available!\nNext menu will give options for probe set summarization", type="ok", icon="info"))
             Try(NormalizeNow())
             Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
             Try(NormalizedAffyData <- get("NormalizedAffyData",envir=affylmGUIenvironment))
             Try( boxplot(as.data.frame(exprs(NormalizedAffyData)), las=2, names=pData(NormalizedAffyData)$Name,ylab="Normalized log2(intensities)"))               
             Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
         }      
}

################################################################################
#run the affycoretool plotPCA
"ocPlotPCA" <- function(){
         #error if no data are loaded
         Try(whichArrayPlatform <- get("whichArrayPlatform",envir=affylmGUIenvironment))
         if(whichArrayPlatform ==""){
              Try(tkmessageBox(title="QC",message="No arrays have been loaded.	Please try New or Open from the File menu.",type="ok",icon="error"))
				    	Try(tkfocus(.affylmGUIglobals$ttMain))
              Try(return())
         }    
         #########################

    #plotPCA was derived by affycoretools they desapeared in relase 2.0
    "plotPCA" <- function (eset, groups = NULL, groupnames = NULL, addtext = NULL, 
    x.coord = NULL, y.coord = NULL, screeplot = FALSE, squarepca = FALSE, 
    pch = NULL, col = NULL, title=NULL,...) {

        if (is.null(groupnames))  groupnames <- sampleNames(eset)
        if (is.factor(groupnames)) groupnames <- as.character(groupnames)
        pca <- prcomp(t(exprs(eset)))        
        x <- exprs(eset)
        dimnames(x)[[2]] <-  groupnames
        hc <- hclust(dist(t(x)), "ave")
    
        if (screeplot) {
            plot(pca, main = title)
        } else {
            if (squarepca) {
                ylim <- max(abs(range(pca$x[, 1])))
                ylim <- c(-ylim, ylim)
            } else ylim <- NULL
            if (!is.null(groups)) {
                if (is.null(pch)) pch <- groups
                if (is.null(col)) col <- groups
                plot(pca$x[, 1:2], pch = pch, col = col, ylab = "PC2", xlab = "PC1", main = title, ylim = ylim, ...)
            }  else {
                if (is.null(pch)) pch <- ""
                if (is.null(col)) col <- 1:length(groupnames)
                par(mfrow=c(1,3))
                plot(pca, main="PCs information content")
                plot(pca$x[, 1:2], pch = pch, ylab = "PC2", xlab = "PC1", main = title, ylim = ylim, ...)
                text(pca$x[, 1:2], groupnames, col= col <- 1:length(groupnames) , cex=0.7) 
                plot(hc, main="Samples HCL", xlab="")
           }
      }
   }          
   Try(whichArrayPlatform <- get("whichArrayPlatform",envir=affylmGUIenvironment))
   if(whichArrayPlatform=="EXON"){
      Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
      if(affylmGUIenvironment$exonAffyData.Available){
           	##makning the menu for selecting gene or exon level density plot
            Try(ttGeneExonMethod <- tktoplevel(.affylmGUIglobals$ttMain))
	          Try(tkwm.deiconify(ttGeneExonMethod))
            Try(tkgrab.set(ttGeneExonMethod))
            Try(tkfocus(ttGeneExonMethod))
            Try(tkwm.title(ttGeneExonMethod,"Gene/Exon level plots"))
	
 	          Try(tkgrid(tklabel(ttGeneExonMethod,text="    ")))
	          Try(ttGeneExonMethodTcl <- tclVar("gene"))
            Try(rbGene <- tkradiobutton(ttGeneExonMethod,text="Gene levels",variable=ttGeneExonMethodTcl,value="gene",font=.affylmGUIglobals$affylmGUIfont2))
            Try(rbExon<-tkradiobutton(ttGeneExonMethod,text="Exon levels",variable=ttGeneExonMethodTcl,value="exon",font=.affylmGUIglobals$affylmGUIfont2))
	          Try(tkgrid(tklabel(ttGeneExonMethod,text="    "),rbGene))
	          Try(tkgrid(tklabel(ttGeneExonMethod,text="    "),rbExon))
	          Try(tkgrid.configure(rbGene,rbExon,columnspan=2,sticky="w"))
	          Try(tkgrid(tklabel(ttGeneExonMethod,text="    "),tklabel(ttGeneExonMethod,text="    ")))
	          Try(ReturnVal <- "")
	          Try(onCancel <- function() {Try(ReturnVal <<- "");Try(tkgrab.release(ttGeneExonMethod));Try(tkdestroy(ttGeneExonMethod));Try(tkfocus(.affylmGUIglobals$ttMain))})
	          Try(onOK <- function() {Try(ReturnVal <<- tclvalue(ttGeneExonMethodTcl));Try(tkgrab.release(ttGeneExonMethod));Try(tkdestroy(ttGeneExonMethod));Try(tkfocus(.affylmGUIglobals$ttMain))})

	          Try(OK.but     <- tkbutton(ttGeneExonMethod,text="OK",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
	          Try(Cancel.but <- tkbutton(ttGeneExonMethod,text="Cancel",command=onCancel,font=.affylmGUIglobals$affylmGUIfont2))

	          Try(tkgrid(tklabel(ttGeneExonMethod,text="    "),OK.but,Cancel.but,tklabel(ttGeneExonMethod,text="    ")))
	          Try(tkgrid.configure(OK.but,sticky="e"))
	          Try(tkgrid.configure(Cancel.but,sticky="w"))
	          Try(tkgrid(tklabel(ttGeneExonMethod,text="    ")))

	          Try(tkbind(ttGeneExonMethod,"<Destroy>",function() {ReturnVal <- "";Try(tkgrab.release(ttGeneExonMethod));Try(tkfocus(.affylmGUIglobals$ttMain));}))
                Try(tkbind(OK.but, "<Return>",onOK))
                Try(tkbind(Cancel.but, "<Return>",onCancel))      

	          Try(tkwait.window(ttGeneExonMethod))
            if(ReturnVal=="gene"){
                Try(NormalizedAffyData <- get("NormalizedAffyData",envir=affylmGUIenvironment))
                Try(plotPCA(NormalizedAffyData, groupnames= affylmGUIenvironment$Targets$Name, title="Gene level PCA"))               
            } else if (ReturnVal=="exon"){
                Try(exonAffyData <- get("exonAffyData",envir=affylmGUIenvironment))
                Try(plotPCA(exonAffyData, groupnames= affylmGUIenvironment$Targets$Name, title="Exon level PCA"))               
            } else {
                     Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
                     Try(return())
            }
       } else{
               Try(tkmessageBox(title="Gene level PCA/HCL",message="No exon data are available! These data seem not to be exon arrays data",type="ok",icon="error"))
       }
       Try(tkmessageBox(title="Exon level PCA/HCL",message=paste("Plots will be displayed in the main R window")))
       Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
   }
      
   if(whichArrayPlatform=="AFFY"){
         if(affylmGUIenvironment$NormalizedAffyData.Available){
            Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
            Try(NormalizedAffyData <- get("NormalizedAffyData",envir=affylmGUIenvironment))
            Try(plotPCA(NormalizedAffyData, groupnames= affylmGUIenvironment$Targets$Name, title="Samples PCA plot"))               
            Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
         } else{
             Try(tkmessageBox(title="plotPCA",message="Probe set summary is not available!\nNext menu will give options for probe set summarization", type="ok", icon="info"))
             Try(NormalizeNow())
             Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
             Try(NormalizedAffyData <- get("NormalizedAffyData",envir=affylmGUIenvironment))
             Try(plotPCA(NormalizedAffyData, groupnames= affylmGUIenvironment$Targets$Name, title="Samples PCA plot"))               
             Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
         }             
   }
   if(whichArrayPlatform=="LARGE" || whichArrayPlatform=="GENE" || whichArrayPlatform=="ILLU" || whichArrayPlatform=="NGS"){
         if(affylmGUIenvironment$NormalizedAffyData.Available){
            Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
            Try(NormalizedAffyData <- get("NormalizedAffyData",envir=affylmGUIenvironment))
            Try(plotPCA(NormalizedAffyData, groupnames= affylmGUIenvironment$Targets$Name, title="Samples PCA plot"))               
            Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
         } else{
             Try(tkmessageBox(title="plotPCA",message="Probe set summary is not available!", type="ok", icon="error"))
         }             
   }
}
################################################################################

#this function will plot density plot for the gene and exon expression loaded in oneChannelGUI
#modify plotHist function from affycoretools
"ocPlotHist" <- function(){
         #error if no data are loaded
         Try(whichArrayPlatform <- get("whichArrayPlatform",envir=affylmGUIenvironment))
         if(whichArrayPlatform ==""){
              Try(tkmessageBox(title="QC",message="No arrays have been loaded.	Please try New or Open from the File menu.",type="ok",icon="error"))
				    	Try(tkfocus(.affylmGUIglobals$ttMain))
              Try(return())
         }    
         #########################

  plotHist<- function (dat, filenames = NULL, title=NULL) 
  {
     if (is.null(filenames)) 
         filenames <- sampleNames(dat)
     cl <- make.cl(filenames)
     if (length(filenames) <= 8) {
         if (is(dat, "ExpressionSet"))
             plotDensity(as.matrix(exprs(dat)), lty = cl, lwd = 2, col = 1:length(filenames), main=title)
         x.ax <- legend(1, 1, legend = filenames, lty = 1, lwd = 2, 
             col = cl, plot = FALSE)$rect$w
         legend(par("usr")[2] - (par("usr")[2] - par("usr")[1])/100 - 
             x.ax, par("usr")[4] - (par("usr")[4] - par("usr")[3])/100, 
             legend = filenames, lty = 1, lwd = 2, col = cl)
     }
     else {
         if (is(dat, "ExpressionSet")) 
             plotDensity(as.matrix(exprs(dat)), lty = cl, lwd = 2, col = 1:length(filenames), main=title)
         x.ax <- legend(1, 1, legend = filenames, lty = 1, lwd = 2, 
             col = cl, plot = FALSE)$rect$w
         y.ax <- legend(1, 1, legend = filenames, lty = 1, lwd = 2, 
             col = cl, plot = FALSE)$rect$h
         ydiff <- par("usr")[4] - par("usr")[3]
         if (y.ax < ydiff) {
             legend(par("usr")[2] - (par("usr")[2] - par("usr")[1])/100 - 
                 x.ax, par("usr")[4] - (par("usr")[4] - par("usr")[3])/100, 
                 legend = filenames, lty = cl, lwd = 2, col = 1:length(filenames))
         }
         else {
             cexval <- 1
             while (y.ax > ydiff) {
                 cexval <- cexval - 0.05
                 y.ax <- legend(1, 1, legend = filenames, lty = 1, 
                   lwd = 2, col = cl, plot = FALSE, cex = cexval)$rect$h
                 x.ax <- legend(1, 1, legend = filenames, lty = 1, 
                   lwd = 2, col = cl, plot = FALSE, cex = cexval)$rect$w
             }
             legend(par("usr")[2] - (par("usr")[2] - par("usr")[1])/100 - 
                 x.ax, par("usr")[4] - (par("usr")[4] - par("usr")[3])/100, 
                 legend = filenames, lty = cl, lwd = 2, col = 1:length(filenames), 
                 cex = cexval)
         }
     }
 }
 make.cl <- function(filenames){
   ## A function to make a classlabel for plotting
   ## Check for number of files
   if(length(filenames) <= 8)
     cl <- 1 : length(filenames)
   if(length(filenames) > 8){
     mod <- floor(length(filenames)/8)
     cl <- NULL
     for(i in 1 : mod){
       cl <- c(cl, rep(i, 8))
     }
     rem <- length(filenames) - mod*8
     cl <- c(cl, rep(mod + 1, rem))
   }
   cl
 }

 if(affylmGUIenvironment$exonAffyData.Available){

           	##makning the menu for selecting gene or exon level density plot
            Try(ttGeneExonMethod <- tktoplevel(.affylmGUIglobals$ttMain))
	          Try(tkwm.deiconify(ttGeneExonMethod))
            Try(tkgrab.set(ttGeneExonMethod))
            Try(tkfocus(ttGeneExonMethod))
            Try(tkwm.title(ttGeneExonMethod,"Gene/Exon level plots"))
	
 	          Try(tkgrid(tklabel(ttGeneExonMethod,text="    ")))
	          Try(ttGeneExonMethodTcl <- tclVar("gene"))
            Try(rbGene <- tkradiobutton(ttGeneExonMethod,text="Gene levels",variable=ttGeneExonMethodTcl,value="gene",font=.affylmGUIglobals$affylmGUIfont2))
            Try(rbExon<-tkradiobutton(ttGeneExonMethod,text="Exon levels",variable=ttGeneExonMethodTcl,value="exon",font=.affylmGUIglobals$affylmGUIfont2))
	      Try(tkgrid(tklabel(ttGeneExonMethod,text="    "),rbGene))
	      Try(tkgrid(tklabel(ttGeneExonMethod,text="    "),rbExon))
	      Try(tkgrid.configure(rbGene,rbExon,columnspan=2,sticky="w"))
	      Try(tkgrid(tklabel(ttGeneExonMethod,text="    "),tklabel(ttGeneExonMethod,text="    ")))
	      Try(ReturnVal <- "")
	      Try(onCancel <- function() {Try(ReturnVal <<- "");Try(tkgrab.release(ttGeneExonMethod));Try(tkdestroy(ttGeneExonMethod));Try(tkfocus(.affylmGUIglobals$ttMain))})
	      Try(onOK <- function() {Try(ReturnVal <<- tclvalue(ttGeneExonMethodTcl));Try(tkgrab.release(ttGeneExonMethod));Try(tkdestroy(ttGeneExonMethod));Try(tkfocus(.affylmGUIglobals$ttMain))})

	      Try(OK.but     <- tkbutton(ttGeneExonMethod,text="OK",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
	      Try(Cancel.but <- tkbutton(ttGeneExonMethod,text="Cancel",command=onCancel,font=.affylmGUIglobals$affylmGUIfont2))

	      Try(tkgrid(tklabel(ttGeneExonMethod,text="    "),OK.but,Cancel.but,tklabel(ttGeneExonMethod,text="    ")))
	      Try(tkgrid.configure(OK.but,sticky="e"))
	      Try(tkgrid.configure(Cancel.but,sticky="w"))
	      Try(tkgrid(tklabel(ttGeneExonMethod,text="    ")))

	      Try(tkbind(ttGeneExonMethod,"<Destroy>",function() {ReturnVal <- "";Try(tkgrab.release(ttGeneExonMethod));Try(tkfocus(.affylmGUIglobals$ttMain));}))
            Try(tkbind(OK.but, "<Return>",onOK))
            Try(tkbind(Cancel.but, "<Return>",onCancel))      

	      Try(tkwait.window(ttGeneExonMethod))
        if(ReturnVal=="gene"){
            Try(NormalizedAffyData <- get("NormalizedAffyData",envir=affylmGUIenvironment))
            plotHist(NormalizedAffyData, title="Gene level density plot")
        } else if (ReturnVal=="exon") {
            Try(exonAffyData <- get("exonAffyData",envir=affylmGUIenvironment))
            plotHist(exonAffyData, title="Exon level density plot")
        } else {
                Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
                Try(return())
        }
 }
 else{
     Try(tkmessageBox(title="Gene/Exon level Histograms",message="No exon data are available! These data seem not to be exon arrays data",type="ok",icon="error"))
 }

 Try(tkmessageBox(title="Gene/Exon level Histograms",message=paste("Plots will be displayed in the main R window")))
}
################################################################################
#part of the functions used to evaluate sample size and statistical power estimation
# sd distribution
"sample.size.evaluation" <- function(){
#  require(multtest) || stop("library multtest could not be found !")
#  require(ssize) || stop("library ssize could not be found !")
           #error if no data are loaded
         Try(whichArrayPlatform <- get("whichArrayPlatform",envir=affylmGUIenvironment))
         if(whichArrayPlatform ==""){
              Try(tkmessageBox(title="Study design",message="No arrays have been loaded.	Please try New or Open from the File menu.",type="ok",icon="error"))
				    	Try(tkfocus(.affylmGUIglobals$ttMain))
              Try(return())
         }    
         #########################

    if(whichArrayPlatform =="EXON"){
               Try(NormalizedAffyData <- get("NormalizedAffyData", env=affylmGUIenvironment))
    }else{
              if(affylmGUIenvironment$NormalizedAffyData.Available){
                     Try(NormalizedAffyData <- get("NormalizedAffyData", env=affylmGUIenvironment))
               } else {
                     Try(tkmessageBox(title="Sample size & Power plots",message="Normalized data are not available.\n Please calculate the probe set expression summaries ", type="ok", icon="error"))
                     Try(return())
               }     
         }
               Try(expression.values <- exprs(NormalizedAffyData))
               #assigning fold.change graphical menu
                 Try(ttGetFC<-tktoplevel(.affylmGUIglobals$ttMain))
                 Try(tkwm.deiconify(ttGetFC))
                 Try(tkgrab.set(ttGetFC))
                 Try(tkfocus(ttGetFC))
                 Try(tkwm.title(ttGetFC,"Assigning Fold Change"))
                 Try(tkgrid(tklabel(ttGetFC,text="    ")))
                 Try(FCnum <- "")
                 Try(Local.FC <- tclVar(init=FCnum))
                 Try(entry.FC <-tkentry(ttGetFC,width="3",font=.affylmGUIglobals$affylmGUIfont2,textvariable=Local.FC,bg="white"))
                 Try(tkgrid(tklabel(ttGetFC,text="Please Fold Change value.",font=.affylmGUIglobals$affylmGUIfont2)))
                 Try(tkgrid(entry.FC))
                 onOK <- function()
                 {
                     Try(FCnum <- as.numeric(tclvalue(Local.FC)))
                     if(nchar(FCnum)==0)
                       FCnum <- "Unselected"
                     Try(assign("FCnum",FCnum,affylmGUIenvironment))
                     Try(tclvalue(.affylmGUIglobals$FCTcl) <- FCnum)
                     Try(tkgrab.release(ttGetFC));Try(tkdestroy(ttGetFC));Try(tkfocus(.affylmGUIglobals$ttMain))
                 }
                 Try(OK.but <-tkbutton(ttGetFC,text="   OK   ",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
                 Try(tkgrid(tklabel(ttGetFC,text="    ")))
                 Try(tkgrid(OK.but))
                 Try(tkgrid.configure(OK.but))
                 Try(tkgrid(tklabel(ttGetFC,text="       ")))
                 Try(tkfocus(entry.FC))
                 Try(tkbind(entry.FC, "<Return>",onOK))
                 Try(tkbind(ttGetFC, "<Destroy>", function(){Try(tkgrab.release(ttGetFC));Try(tkfocus(.affylmGUIglobals$ttMain));return(0)}))
                 Try(tkwait.window(ttGetFC))
                 Try(tkfocus(.affylmGUIglobals$ttMain))
                 if(FCnum == "Unselected"){
                             Try(tkmessageBox(title="Sample size & Power plots",message="Fold change threshold was not selected.\nAborting analysis.", type="ok", icon="error"))
                             Try(return())
                 }
               #######################################################àà
               #assigning power and sig.level grphical menu
                 Try(ttGetPower<-tktoplevel(.affylmGUIglobals$ttMain))
                 Try(tkwm.deiconify(ttGetPower))
                 Try(tkgrab.set(ttGetPower))
                 Try(tkfocus(ttGetPower))
                 Try(tkwm.title(ttGetPower,"Assigning the Statistical Power"))
                 Try(tkgrid(tklabel(ttGetPower,text="    ")))
                 Try(Powernum <- "")
                 Try(Local.Power <- tclVar(init=Powernum))
                 Try(entry.Power <-tkentry(ttGetPower,width="3",font=.affylmGUIglobals$affylmGUIfont2,textvariable=Local.Power,bg="white"))
                 Try(tkgrid(tklabel(ttGetPower,text="Please assign a Power value, \ni.e. any value between 0 and 1",font=.affylmGUIglobals$affylmGUIfont2)))
                 Try(tkgrid(entry.Power))
                 onOK <- function()
                 {
                     Try(Powernum <- as.numeric(tclvalue(Local.Power)))
                     if(nchar(Powernum)==0)
                       Powernum <- "Unselected"
                     Try(assign("Powernum",Powernum,affylmGUIenvironment))
                     Try(tclvalue(.affylmGUIglobals$PowerTcl) <- Powernum)
                     Try(tkgrab.release(ttGetPower));Try(tkdestroy(ttGetPower));Try(tkfocus(.affylmGUIglobals$ttMain))
                 }
                 Try(OK.but <-tkbutton(ttGetPower,text="   OK   ",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
                 Try(tkgrid(tklabel(ttGetPower,text="    ")))
                 Try(tkgrid(OK.but))
                 Try(tkgrid.configure(OK.but))
                 Try(tkgrid(tklabel(ttGetPower,text="       ")))
                 Try(tkfocus(entry.Power))
                 Try(tkbind(entry.Power, "<Return>",onOK))
                 Try(tkbind(ttGetPower, "<Destroy>", function(){Try(tkgrab.release(ttGetPower));Try(tkfocus(.affylmGUIglobals$ttMain));return(0)}))
                 Try(tkwait.window(ttGetPower))
                 Try(tkfocus(.affylmGUIglobals$ttMain))
                 if(Powernum == "Unselected"){
                             Try(tkmessageBox(title="Sample size & Power plots",message="Power threshold was not selected.\nAborting analysis.", type="ok", icon="error"))
                             Try(return())
                 }
               #######################################################àà
               #######################################################àà
               #assigning power and sig.level grphical menu
                 Try(ttGetSL<-tktoplevel(.affylmGUIglobals$ttMain))
                 Try(tkwm.deiconify(ttGetSL))
                 Try(tkgrab.set(ttGetSL))
                 Try(tkfocus(ttGetSL))
                 Try(tkwm.title(ttGetSL,"Assigning the significance level"))
                 Try(tkgrid(tklabel(ttGetSL,text="    ")))
                 Try(SLnum <- "")
                 Try(Local.SL <- tclVar(init=SLnum))
                 Try(entry.SL <-tkentry(ttGetSL,width="4",font=.affylmGUIglobals$affylmGUIfont2,textvariable=Local.SL,bg="white"))
                 Try(tkgrid(tklabel(ttGetSL,text="Please assign the significance level, \n, i.e. 0.05 or lower",font=.affylmGUIglobals$affylmGUIfont2)))
                 Try(tkgrid(entry.SL))
                 onOK <- function()
                 {
                     Try(SLnum <- as.numeric(tclvalue(Local.SL)))
                     if(nchar(SLnum)==0)
                       SLnum <- "Unselected"
                     Try(assign("SLnum",SLnum,affylmGUIenvironment))
                     Try(tclvalue(.affylmGUIglobals$SLTcl) <- SLnum)
                     Try(tkgrab.release(ttGetSL));Try(tkdestroy(ttGetSL));Try(tkfocus(.affylmGUIglobals$ttMain))
                 }
                 Try(OK.but <-tkbutton(ttGetSL,text="   OK   ",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
                 Try(tkgrid(tklabel(ttGetSL,text="    ")))
                 Try(tkgrid(OK.but))
                 Try(tkgrid.configure(OK.but))
                 Try(tkgrid(tklabel(ttGetSL,text="       ")))
                 Try(tkfocus(entry.SL))
                 Try(tkbind(entry.SL, "<Return>",onOK))
                 Try(tkbind(ttGetSL, "<Destroy>", function(){Try(tkgrab.release(ttGetSL));Try(tkfocus(.affylmGUIglobals$ttMain));return(0)}))
                 Try(tkwait.window(ttGetSL))
                 Try(tkfocus(.affylmGUIglobals$ttMain))
                 if(SLnum == "Unselected"){
                             Try(tkmessageBox(title="Sample size & Power plots",message="Significance threshold was not selected.\nAborting analysis.", type="ok", icon="error"))
                             Try(return())
                 }
               #######################################################àà
               Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
               Try(common.sd<-function(x){
                       covariate.data <<- affylmGUIenvironment$Targets$Target
                       target.unique <- unique(covariate.data)
                       common.sd1<- sqrt((sd(x[which(covariate.data==target.unique[1])])^2*(length(which(covariate.data==target.unique[1]))-1))
                                   +(sd(x[which(covariate.data==target.unique[2])])^2*(length(which(covariate.data==target.unique[2]))-1))/
                                   (length(which(covariate.data==target.unique[1]))+length(which(covariate.data==target.unique[2]))-2))
               })#Wei et al. BMC Genomics. 2004, 5:87
               Try(exp.sd <- apply(expression.values, 1, common.sd))
               Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))

               ########################################################
               #defining if ssize or delta function to be used
                          	##makning the menu for selecting IQR threshold
            Try(ttGetPlotMethod <- tktoplevel(.affylmGUIglobals$ttMain))
	      Try(tkwm.deiconify(ttGetPlotMethod))
            Try(tkgrab.set(ttGetPlotMethod))
            Try(tkfocus(ttGetPlotMethod))
            Try(tkwm.title(ttGetPlotMethod,"Sample size or Power plot"))
	
 	      Try(tkgrid(tklabel(ttGetPlotMethod,text="    ")))
	      Try(ttGetPlotMethodTcl <- tclVar("delta"))
            Try(rbSsize <- tkradiobutton(ttGetPlotMethod,text="Sample size plot",variable=ttGetPlotMethodTcl,value="ssize",font=.affylmGUIglobals$affylmGUIfont2))
            Try(rbDelta<-tkradiobutton(ttGetPlotMethod,text="Power plot",variable=ttGetPlotMethodTcl,value="delta",font=.affylmGUIglobals$affylmGUIfont2))
	      Try(tkgrid(tklabel(ttGetPlotMethod,text="    "),rbSsize))
	      Try(tkgrid(tklabel(ttGetPlotMethod,text="    "),rbDelta))
	      Try(tkgrid.configure(rbSsize,rbDelta,columnspan=2,sticky="w"))
	      Try(tkgrid(tklabel(ttGetPlotMethod,text="    "),tklabel(ttGetPlotMethod,text="    ")))
	      Try(ReturnVal <- "")
	      Try(onCancel <- function() {Try(ReturnVal <<- "");Try(tkgrab.release(ttGetPlotMethod));Try(tkdestroy(ttGetPlotMethod));Try(tkfocus(.affylmGUIglobals$ttMain))})
	      Try(onOK <- function() {Try(ReturnVal <<- tclvalue(ttGetPlotMethodTcl));Try(tkgrab.release(ttGetPlotMethod));Try(tkdestroy(ttGetPlotMethod));Try(tkfocus(.affylmGUIglobals$ttMain))})

	      Try(OK.but     <- tkbutton(ttGetPlotMethod,text="OK",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
	      Try(Cancel.but <- tkbutton(ttGetPlotMethod,text="Cancel",command=onCancel,font=.affylmGUIglobals$affylmGUIfont2))

	      Try(tkgrid(tklabel(ttGetPlotMethod,text="    "),OK.but,Cancel.but,tklabel(ttGetPlotMethod,text="    ")))
	      Try(tkgrid.configure(OK.but,sticky="e"))
	      Try(tkgrid.configure(Cancel.but,sticky="w"))
	      Try(tkgrid(tklabel(ttGetPlotMethod,text="    ")))

	      Try(tkbind(ttGetPlotMethod,"<Destroy>",function() {ReturnVal <- "";Try(tkgrab.release(ttGetPlotMethod));Try(tkfocus(.affylmGUIglobals$ttMain));}))
            Try(tkbind(OK.but, "<Return>",onOK))
            Try(tkbind(Cancel.but, "<Return>",onCancel))      

	      Try(tkwait.window(ttGetPlotMethod))
        if(ReturnVal <- ""){
                             Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
                             Try(return())
        }


               #################################################################################
               Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
               Try(fold.change <- get("FCnum", env=affylmGUIenvironment))
               Try(power <- get("Powernum", env=affylmGUIenvironment))
               Try(sig.level <- get("SLnum", env=affylmGUIenvironment))

               
               #defining the significance threshold using BH correction
               Try(covariate.data <- affylmGUIenvironment$Targets$Target)
               Try(target.unique <- unique(covariate.data))
 if((length(which(covariate.data==target.unique[1])) + length(which(covariate.data==target.unique[2]))) == length(covariate.data)){
               Try(covariate.data[which(covariate.data==target.unique[1])]  <- 0)
               Try(covariate.data[which(covariate.data==target.unique[2])]<- 1)
               Try(covariate.data <- as.numeric(covariate.data))
               Try(teststat <- mt.teststat(expression.values, covariate.data))
               Try(rawp0 <- 2 * (1 - pnorm(abs(teststat))))
               Try(res <- mt.rawp2adjp(rawp0, "BH"))
               Try(adjp <- res$adjp)
               Try(sig.level.BH <- max(adjp[which(adjp[,2] <= sig.level),1]))
               ####################################################################################

               #pow, power.plot compute and display a cumulative plot of the fraction of
               #genes achieving a specified power for a fixed sample size (n), effect size
               #(delta), and significance level (sig.level).
               #Try(all.power <- pow(sd = exp.sd, n = length(covariate.data), delta = log2(fold.change), sig.level = sig.level))
               
               #Try( power.plot(all.power, lwd = 2, col = "blue")
               #     xmax <- par("usr")[2] - 0.05
               #     ymax <- par("usr")[4] - 0.05
               #     legend(x = xmax, y = ymax, legend = strsplit(paste("n=", n, ",","fold change=", fold.change, ",", "alpha=", sig.level, ",", "# genes=", nobs(exp.sd), sep = ""), ",")[[1]], xjust = 1, yjust = 1, cex = 1)
               #)
               
               #ssize,ssize.plot compute and display a cumulative plot of the fraction of
               #genes for which a specified sample size is sufficient to achieve a specified
               #power (power), effect size (delta), and significance level (sig.level).
      if(ReturnVal == "ssize"){
               Try(all.size <- ssize(sd = exp.sd, delta = log2(fold.change), sig.level = sig.level.BH, power = power, alpha.correct="") )
               
               Try( ssize.plot(all.size, lwd = 2, col = "magenta", xlim = c(1, 20)))
               Try( xmax <- par("usr")[2] - 1)
               Try( ymin <- par("usr")[3] + 0.05 )
               Try( legend(x = xmax, y = ymin, legend = strsplit(paste("fold change=", fold.change, ",", "alpha=", sig.level, ",", "power=", power, ",", "# genes=", nobs(exp.sd), sep = ""), ",")[[1]], xjust = 1, yjust = 0, cex = 1) )
               Try( title(paste("Sample Size to Detect ", fold.change,"-Fold Change", collapse="")))
               Try(tkmessageBox(title="Sample size plot",message="Plot is shown in the main R window", type="ok", icon="info"))
       } else{
               #delta,delta.plot compute and display a cumulative plot of the fraction of
               #genes which can achieve a specified power (power), for a specified sample
               #size (n), and significance level (sig.level) for a range of effect
               #sizes.
               Try(all.delta <- delta(sd = exp.sd, power = power, n = length(covariate.data)/2, sig.level = sig.level.BH, alpha.correct=""))

               Try( .delta.plot1(all.delta, lwd = 2, col = "magenta", xlim = c(1, 10)) )
               Try( xmax <- par("usr")[2] - 1 )
               Try( ymin <- par("usr")[3] + 0.05)
               Try( legend(x = xmax, y = ymin, legend = strsplit(paste("n=", length(covariate.data)/2, ",", "alpha=", sig.level, ",", "power=", power, ",", "# genes=", nobs(exp.sd), sep = ""), ",")[[1]], xjust = 1, yjust = 0, cex = 1))
               Try( title(paste("Fold Change to Achieve", power * 100, "% Power", collapse=" ")))
               Try(tkmessageBox(title="Power plot",message="Plot is shown in the main R window", type="ok", icon="info"))
      }
  } else Try(tkmessageBox(title="Sample size & Power plots",message="This analysis can be applied only to 2 group experiment\nReorganize your data to fullfil these requirements", type="ok", icon="error"))
  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
}
#internal because siggenes overlay this function 
.delta.plot1 <- function(x,
                       xlab="Fold Change",
                       ylab="Proportion of Genes",
                       marks=c(1.5, 2.0, 2.5, 3.0, 4.0, 6.0,10),
                       ...)
  {
    n <- nobs(x)
    inv <- list()
    inv$x <- sort(x)
    inv$y <- ecdf(x)(inv$x)
    plot(inv, type="s",
         xlab=xlab, ylab=ylab, yaxt="n",
         ..., )
    vals <- pretty(inv$y * n)
    labels <- paste( format(vals/n*100,digits=2), "%=", vals, sep='')
    axis(side=2, at=vals/n, labels=labels, srt=90, adj=0.5)
    if(!is.null(marks) && length(marks)>0 )
      {
        xmin <- par("usr")[1]
        ymin <- par("usr")[3]
        
        for(mark in marks)
          {
            y <- inv$y[ which(inv$x>mark)[1]-1 ]
            lines( x=rbind( c(mark, ymin),
                            c(mark, y) ),
                   lty=2, col='red' )
            text( x=mark, y=ymin, label=format(mark,2), col="red", adj=c(0,0))
            lines( x=rbind( c(xmin, y),
                            c(mark, y) ),
                   lty=2, col='red' )
            text( x=xmin, y=y,
                 label=paste(format(y*100,digits=2),"%=",
                             format(y*n,digits=2), sep=''),
                 col="red", adj=c(0,0), xpd=TRUE)
          }
      }
  }
################################################################################

#part of the functions used to evaluate sample size and statistical power estimation sizepower package
# sd distribution
"sample.size.evaluation1" <- function(){
# require(sizepower) || stop("library sizepower could not be found !")
          #error if no data are loaded
         Try(whichArrayPlatform <- get("whichArrayPlatform",envir=affylmGUIenvironment))
         if(whichArrayPlatform ==""){
              Try(tkmessageBox(title="Study design",message="No arrays have been loaded.	Please try New or Open from the File menu.",type="ok",icon="error"))
				    	Try(tkfocus(.affylmGUIglobals$ttMain))
              Try(return())
         }    
         #########################


    if(whichArrayPlatform =="EXON"){
               Try(NormalizedAffyData <- get("NormalizedAffyData", env=affylmGUIenvironment))
    }else{
              if(affylmGUIenvironment$NormalizedAffyData.Available){
                     Try(NormalizedAffyData <- get("NormalizedAffyData", env=affylmGUIenvironment))
               } else {
                     Try(tkmessageBox(title="Sample size & Power Experiment Estimation",message="Normalized data are not available.\n Please calculate the probe set expression summaries ", type="ok", icon="error"))
                     Try(return())
               }
    }
               Try(expression.values <- exprs(NormalizedAffyData))
               covariate.data <- affylmGUIenvironment$Targets$Target
               target.unique <- unique(covariate.data)
               if(length(target.unique)>2){
                   Try(tkmessageBox(title="Sample size & Power Experiment Estimation",message="This function apply only two class experiment.", type="ok", icon="error"))
                   return()
               } else{
                       ##Selecting the function to be used
                       Try(ttsizepowerMethod <- tktoplevel(.affylmGUIglobals$ttMain))
	                     Try(tkwm.deiconify(ttsizepowerMethod))
                       Try(tkgrab.set(ttsizepowerMethod))
                       Try(tkfocus(ttsizepowerMethod))
                       Try(tkwm.title(ttsizepowerMethod,"Sample size & Power Experiment Estimation"))
	
 	                     Try(tkgrid(tklabel(ttsizepowerMethod,text="    ")))
	                     Try(ttsizepowerMethodTcl <- tclVar("size"))
                       Try(rbSsize <- tkradiobutton(ttsizepowerMethod,text="Sample size estimation",variable=ttsizepowerMethodTcl,value="size",font=.affylmGUIglobals$affylmGUIfont2))
                       Try(rbPower<-tkradiobutton(ttsizepowerMethod,text="Power estimation",variable=ttsizepowerMethodTcl,value="power",font=.affylmGUIglobals$affylmGUIfont2))
	                     Try(tkgrid(tklabel(ttsizepowerMethod,text="    "),rbSsize))
	                     Try(tkgrid(tklabel(ttsizepowerMethod,text="    "),rbPower))
	                     Try(tkgrid.configure(rbSsize,rbPower,columnspan=2,sticky="w"))
	                     Try(tkgrid(tklabel(ttsizepowerMethod,text="    "),tklabel(ttsizepowerMethod,text="    ")))
	                     Try(ReturnVal <- "")
	                     Try(onCancel <- function() {Try(ReturnVal <<- "");Try(tkgrab.release(ttsizepowerMethod));Try(tkdestroy(ttsizepowerMethod));Try(tkfocus(.affylmGUIglobals$ttMain))})
	                     Try(onOK <- function() {Try(ReturnVal <<- tclvalue(ttsizepowerMethodTcl));Try(tkgrab.release(ttsizepowerMethod));Try(tkdestroy(ttsizepowerMethod));Try(tkfocus(.affylmGUIglobals$ttMain))})

       	               Try(OK.but     <- tkbutton(ttsizepowerMethod,text="OK",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
	                     Try(Cancel.but <- tkbutton(ttsizepowerMethod,text="Cancel",command=onCancel,font=.affylmGUIglobals$affylmGUIfont2))

	                     Try(tkgrid(tklabel(ttsizepowerMethod,text="    "),OK.but,Cancel.but,tklabel(ttsizepowerMethod,text="    ")))
	                     Try(tkgrid.configure(OK.but,sticky="e"))
	                     Try(tkgrid.configure(Cancel.but,sticky="w"))
	                     Try(tkgrid(tklabel(ttsizepowerMethod,text="    ")))

	                     Try(tkbind(ttsizepowerMethod,"<Destroy>",function() {ReturnVal <- "";Try(tkgrab.release(ttsizepowerMethod));Try(tkfocus(.affylmGUIglobals$ttMain));}))
                       Try(tkbind(OK.but, "<Return>",onOK))
                       Try(tkbind(Cancel.but, "<Return>",onCancel))      

	                     Try(tkwait.window(ttsizepowerMethod))
	             
                      #######################################################àà
                      if(ReturnVal == ""){
                                  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
                                  Try(return())
                      }
                      Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
                       Try(common.sd<-function(x){
                               covariate.data <<- affylmGUIenvironment$Targets$Target
                               target.unique <- unique(covariate.data)
                               common.sd1<- sqrt((sd(x[which(covariate.data==target.unique[1])])^2*(length(which(covariate.data==target.unique[1]))-1))
                                           +(sd(x[which(covariate.data==target.unique[2])])^2*(length(which(covariate.data==target.unique[2]))-1))/
                                            (length(which(covariate.data==target.unique[1]))+length(which(covariate.data==target.unique[2]))-2))
                          
                       })#Wei et al. BMC Genomics. 2004, 5:87
                       Try(exp.sd <- apply(expression.values, 1, common.sd))
                       Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
                       ########################################################

	             
                       Try(if(ReturnVal=="size"){
                              # Try(tkmessageBox(title="Sample sixe evaluation",message="This routine computes the required sample size.",type="ok",icon="info"))
   
                                ##making the menu for selecting sample sixe parameters
                                Try(ttsizepowerDialog<-tktoplevel(.affylmGUIglobals$ttMain))
                                Try(tkwm.deiconify(ttsizepowerDialog))
                                Try(tkgrab.set(ttsizepowerDialog))
                                Try(tkfocus(ttsizepowerDialog))
                                Try(tkwm.title(ttsizepowerDialog,"Sample size parameters"))
                                Try(tkgrid(tklabel(ttsizepowerDialog,text="    ")))

                                #Try(frame1 <- tkframe(ttsizepowerDialog,relief="groove",borderwidth=2))
                                #Try(HowManyQuestion1 <- tklabel(frame1,text="Mean number of false positives",font=.affylmGUIglobals$affylmGUIfont2))
                                #Try(tkgrid(HowManyQuestion1))
                                #Try(tkgrid.configure(HowManyQuestion1,columnspan=2,sticky="w"))

                                Try(fTcl <- tclVar("1"))
	                              #Try(f1.but			<- tkradiobutton(frame1,text="1",variable=fTcl,value=1,font=.affylmGUIglobals$affylmGUIfont2))
	                              #Try(f2.but	 <- tkradiobutton(frame1,text="5",variable=fTcl,value=5,font=.affylmGUIglobals$affylmGUIfont2))
	                              #Try(f3.but		<- tkradiobutton(frame1,text="10",variable=fTcl,value=10,font=.affylmGUIglobals$affylmGUIfont2))
	                              #Try(f4.but	<- tkradiobutton(frame1,text="20",variable=fTcl,value=20,font=.affylmGUIglobals$affylmGUIfont2))
	                              #Try(f5.but <- tkradiobutton(frame1,text="40",variable=fTcl,value=40,font=.affylmGUIglobals$affylmGUIfont2))

	                              #Try(tkgrid(f1.but,sticky="w"))
	                              #Try(tkgrid(f2.but,sticky="w"))
	                              #Try(tkgrid(f3.but,sticky="w"))
	                              #Try(tkgrid(f4.but,sticky="w"))
	                              #Try(tkgrid(f5.but,sticky="w"))
	                              #Try(tkgrid.configure(HowManyQuestion1,f1.but,f2.but,f3.but,f4.but,f5.but,sticky="w"))

	                              Try(frame2 <- tkframe(ttsizepowerDialog,relief="groove",borderwidth=2))
	                              Try(powerLabel <- tklabel(frame2,text="Power level for an individual gene",font=.affylmGUIglobals$affylmGUIfont2))
	                              Try(tkgrid(powerLabel,sticky="w"))
	                              Try(tkgrid.configure(powerLabel,sticky="w"))

                                Try(powerTcl <- tclVar("0.9"))

	                              Try(p1.but <- tkradiobutton(frame2,text="0.99",variable=powerTcl,value=0.99,font=.affylmGUIglobals$affylmGUIfont2))
	                              Try(p2.but <- tkradiobutton(frame2,text="0.95",variable=powerTcl,value=0.95,font=.affylmGUIglobals$affylmGUIfont2))
	                              Try(p3.but <- tkradiobutton(frame2,text="0.9",variable=powerTcl,value=0.9,font=.affylmGUIglobals$affylmGUIfont2))
	                              Try(p4.but <- tkradiobutton(frame2,text="0.85",variable=powerTcl,value=0.85,font=.affylmGUIglobals$affylmGUIfont2))
	                              Try(p5.but <- tkradiobutton(frame2,text="0.8",variable=powerTcl,value=0.8,font=.affylmGUIglobals$affylmGUIfont2))

	                              Try(tkgrid(p1.but,sticky="w"))
	                              Try(tkgrid(p2.but,sticky="w"))
	                              Try(tkgrid(p3.but,sticky="w"))
	                              Try(tkgrid(p4.but,sticky="w"))
	                              Try(tkgrid(p5.but,sticky="w"))

                                Try(frame3 <- tkframe(ttsizepowerDialog,relief="groove",borderwidth=2))
	                              Try(fcLabel <- tklabel(frame3,text="Absolute log2(Fold Change)",font=.affylmGUIglobals$affylmGUIfont2))
	                              Try(tkgrid(fcLabel,sticky="w"))
	                              Try(tkgrid.configure(fcLabel,sticky="w"))

                                Try(fcTcl <- tclVar("1"))
	                              Try(fc1.but <- tkradiobutton(frame3,text="1",variable=fcTcl,value=1,font=.affylmGUIglobals$affylmGUIfont2))
	                              Try(fc2.but	 <- tkradiobutton(frame3,text="1.5"  ,variable=fcTcl,value=1.5  ,font=.affylmGUIglobals$affylmGUIfont2))
	                              Try(fc3.but	 <- tkradiobutton(frame3,text="2"  ,variable=fcTcl,value=2  ,font=.affylmGUIglobals$affylmGUIfont2))
	                              Try(fc4.but <- tkradiobutton(frame3,text="2.5",variable=fcTcl,value=2.5,font=.affylmGUIglobals$affylmGUIfont2))
	
	                              Try(tkgrid(fc1.but,sticky="w"))
	                              Try(tkgrid(fc2.but	,sticky="w"))
	                              Try(tkgrid(fc3.but	,sticky="w"))
	                              Try(tkgrid(fc4.but,sticky="w"))

	                              Try(Abort <- 1)
                                sizepower.param <- list()
   
	                              Try(onOK <- function()
	                              {
			                              Try(sizepower.param[[1]] <<- tclvalue(fTcl))
			                              Try(tkgrab.release(ttsizepowerDialog))
			                              Try(tkdestroy(ttsizepowerDialog))
			                              Try(tkfocus(.affylmGUIglobals$ttMain))
			                              Try(sizepower.param[[2]]	<<- tclvalue(powerTcl))
			                              Try(sizepower.param[[3]]	<<- tclvalue(fcTcl))
			                              Try(Abort					<<- 0)
	                              })
	                              
	                             #Try(onHelp <- function() Try(help("topTable",htmlhelp=TRUE)))

	                             Try(frame4 <- tkframe(ttsizepowerDialog,borderwidth=2))
	                             Try(onCancel <- function() {Try(tkgrab.release(ttsizepowerDialog));Try(tkdestroy(ttsizepowerDialog));Try(tkfocus(.affylmGUIglobals$ttMain));Abort <<- 1})
	                             Try(OK.but <-tkbutton(frame4,text="   OK   ",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
	                             Try(Cancel.but <-tkbutton(frame4,text=" Cancel ",command=onCancel,font=.affylmGUIglobals$affylmGUIfont2))
	                             #Try(Help.but <-tkbutton(frame4,text=" Help ",command=onHelp,font=.affylmGUIglobals$affylmGUIfont2))

	                             Try(tkgrid(tklabel(frame4,text="    "),OK.but,Cancel.but,tklabel(frame4,text="    ")))

	                             Try(tkgrid(tklabel(ttsizepowerDialog,text="    "),frame2,tklabel(ttsizepowerDialog,text="  ")))
	                             #Try(tkgrid(tklabel(ttsizepowerDialog,text="    ")))
	                             Try(tkgrid(tklabel(ttsizepowerDialog,text="    "),frame3,frame4,tklabel(ttsizepowerDialog,text="  ")))
	                             #Try(tkgrid(tklabel(ttsizepowerProDialog,text="    ")))
	                             Try(tkgrid.configure(frame2, frame3,sticky="w"))
	                             #Try(tkgrid.configure(frame1,frame3,sticky="w"))
                             #	Try(tkgrid.configure(frame4,sticky="s"))

	                             Try(tkfocus(ttsizepowerDialog))
	                             Try(tkbind(ttsizepowerDialog, "<Destroy>", function() {Try(tkgrab.release(ttsizepowerDialog));Try(tkfocus(.affylmGUIglobals$ttMain));}))
	                             Try(tkwait.window(ttsizepowerDialog))

	                             Try(if(Abort==1) return())
	                              
                               Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
	                              #In this case the sample size is based on the mean of the common variance
                                Try(mysample <- sampleSize.randomized(ER0 = as.numeric(sizepower.param[[1]]), 
                                                              G0 = dim(expression.values)[1], 
                                                              power = as.numeric(sizepower.param[[2]]), 
                                                              absMu1 = as.numeric(sizepower.param[[3]]), 
                                                              sigmad = sqrt(2)*mean(exp.sd))
                                    )
                                Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))    
                                Try(tkmessageBox(title="Sample size evaluation",message=paste("Given a",sizepower.param[[1]],"mean number of false positives\n",sizepower.param[[2]],"power\n",sizepower.param[[3]],"absolute mean difference in log-expression between treatment and control\n","The sample size (per group) is",mysample$n, sep=" "),type="ok",icon="info"))
                                Try(cat(paste("Sample size evaluation:\n","Given a",sizepower.param[[1]],"mean number of false positives\n",sizepower.param[[2]],"power\n",sizepower.param[[3]],"absolute mean difference in log-expression between treatment and control\n","The sample size (per group) is",mysample$n,"\n", sep=" ")))

                       } else {
               
                             #   Try(tkmessageBox(title="Power evaluation",message="This routine computes the individual \npower value for a completely randomized design.\n This power value is the expected fraction of truly differentially expressed genes that \nwill be correctly declared as differentially expressed by the tests.",type="ok",icon="info"))
               
                                ##making the menu for selecting the power parameters
                                Try(ttsizepowerDialog<-tktoplevel(.affylmGUIglobals$ttMain))
                                Try(tkwm.deiconify(ttsizepowerDialog))
                                Try(tkgrab.set(ttsizepowerDialog))
                                Try(tkfocus(ttsizepowerDialog))
                                Try(tkwm.title(ttsizepowerDialog,"Sample size parameters"))
                                Try(tkgrid(tklabel(ttsizepowerDialog,text="    ")))

                                #Try(frame1 <- tkframe(ttsizepowerDialog,relief="groove",borderwidth=2))
                                #Try(HowManyQuestion1 <- tklabel(frame1,text=
                                #   "Mean number of false positives",font=.affylmGUIglobals$affylmGUIfont2))
                                #Try(tkgrid(HowManyQuestion1))
                                #Try(tkgrid.configure(HowManyQuestion1,columnspan=2,sticky="w"))

                                Try(fTcl <- tclVar("1"))
	                              #Try(f1.but			<- tkradiobutton(frame1,text="1",variable=fTcl,value=1,font=.affylmGUIglobals$affylmGUIfont2))
	                              #Try(f2.but	 <- tkradiobutton(frame1,text="5",variable=fTcl,value=5,font=.affylmGUIglobals$affylmGUIfont2))
	                              #Try(f3.but		<- tkradiobutton(frame1,text="10",variable=fTcl,value=10,font=.affylmGUIglobals$affylmGUIfont2))
	                              #Try(f4.but	<- tkradiobutton(frame1,text="20",variable=fTcl,value=20,font=.affylmGUIglobals$affylmGUIfont2))
	                              #Try(f5.but <- tkradiobutton(frame1,text="40",variable=fTcl,value=40,font=.affylmGUIglobals$affylmGUIfont2))

	                              #Try(tkgrid(f1.but,sticky="w"))
	                              #Try(tkgrid(f2.but,sticky="w"))
	                              #Try(tkgrid(f3.but,sticky="w"))
	                              #Try(tkgrid(f4.but,sticky="w"))
	                              #Try(tkgrid(f5.but,sticky="w"))
	                              #Try(tkgrid.configure(HowManyQuestion1,f1.but,f2.but,f3.but,f4.but,f5.but,sticky="w"))

                                Try(frame2 <- tkframe(ttsizepowerDialog,relief="groove",borderwidth=2))
	                              Try(fcLabel <- tklabel(frame2,text="Absolute log2(Fold Change)",font=.affylmGUIglobals$affylmGUIfont2))
	                              Try(tkgrid(fcLabel,sticky="w"))
	                              Try(tkgrid.configure(fcLabel,sticky="w"))

                                Try(fcTcl <- tclVar("1"))
	                              Try(fc1.but <- tkradiobutton(frame2,text="1",variable=fcTcl,value=1,font=.affylmGUIglobals$affylmGUIfont2))
	                              Try(fc2.but	 <- tkradiobutton(frame2,text="1.5"  ,variable=fcTcl,value=1.5  ,font=.affylmGUIglobals$affylmGUIfont2))
	                              Try(fc3.but	 <- tkradiobutton(frame2,text="2"  ,variable=fcTcl,value=2  ,font=.affylmGUIglobals$affylmGUIfont2))
	                              Try(fc4.but <- tkradiobutton(frame2,text="2.5",variable=fcTcl,value=2.5,font=.affylmGUIglobals$affylmGUIfont2))
	
	                              Try(tkgrid(fc1.but,sticky="w"))
	                              Try(tkgrid(fc2.but	,sticky="w"))
	                              Try(tkgrid(fc3.but	,sticky="w"))
	                              Try(tkgrid(fc4.but,sticky="w"))

	                              Try(Abort <- 1)
                                sizepower.param <- list()
   
	                              Try(onOK <- function()
	                              {
			                              Try(sizepower.param[[1]] <<- tclvalue(fTcl))
			                              Try(tkgrab.release(ttsizepowerDialog))
			                              Try(tkdestroy(ttsizepowerDialog))
			                              Try(tkfocus(.affylmGUIglobals$ttMain))
			                              Try(sizepower.param[[2]]	<<- tclvalue(fcTcl))
			                              Try(Abort					<<- 0)
	                              })
	                              
	                                
	                             #Try(onHelp <- function() Try(help("topTable",htmlhelp=TRUE)))

	                             Try(frame3 <- tkframe(ttsizepowerDialog,borderwidth=2))
	                             Try(onCancel <- function() {Try(tkgrab.release(ttsizepowerDialog));Try(tkdestroy(ttsizepowerDialog));Try(tkfocus(.affylmGUIglobals$ttMain));Abort <<- 1})
	                             Try(OK.but <-tkbutton(frame3,text="   OK   ",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
	                             Try(Cancel.but <-tkbutton(frame3,text=" Cancel ",command=onCancel,font=.affylmGUIglobals$affylmGUIfont2))
	                             #Try(Help.but <-tkbutton(frame4,text=" Help ",command=onHelp,font=.affylmGUIglobals$affylmGUIfont2))

	                             Try(tkgrid(tklabel(frame3,text="    "),OK.but,Cancel.but,tklabel(frame3,text="    ")))

	                             Try(tkgrid(tklabel(ttsizepowerDialog,text="    "),frame2,tklabel(ttsizepowerDialog,text="  ")))
	                             #Try(tkgrid(tklabel(ttsizepowerDialog,text="    ")))
	                             Try(tkgrid(tklabel(ttsizepowerDialog,text="    "),frame3,tklabel(ttsizepowerDialog,text="  ")))
	                             #Try(tkgrid(tklabel(ttsizepowerProDialog,text="    ")))
	                             Try(tkgrid.configure(frame2,frame3,sticky="w"))
                             #	Try(tkgrid.configure(frame4,sticky="s"))

	                             Try(tkfocus(ttsizepowerDialog))
	                             Try(tkbind(ttsizepowerDialog, "<Destroy>", function() {Try(tkgrab.release(ttsizepowerDialog));Try(tkfocus(.affylmGUIglobals$ttMain));}))
	                             Try(tkwait.window(ttsizepowerDialog))

	                             Try(if(Abort==1) return())
	                             
	                              
	                              Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
	                              #In this case the sample size is based on the mean of the common variance
                                Try(mysample <- power.randomized(ER0 = as.numeric(sizepower.param[[1]]), 
                                                              G0 = dim(expression.values)[1],  
                                                              absMu1 = as.numeric(sizepower.param[[2]]), 
                                                              sigmad = sqrt(2)*mean(exp.sd),
                                                              n=ceiling(dim(expression.values)[2]/2))
                                    )
                                Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
                                Try(tkmessageBox(title="Power evaluation",message=paste("Given a",sizepower.param[[1]],"mean number of false positives\n",(dim(expression.values)[2]/2),"replicates for each condition\n",sizepower.param[[2]]," absolute mean difference in log-expression between treatment and control\n","the power is",signif(mysample$power,2), sep=" "),type="ok",icon="info"))
                                Try(cat(paste("Power evaluation","Given a",sizepower.param[[1]],"mean number of false positives\n",(dim(expression.values)[2]/2),"replicates for each condition\n",sizepower.param[[2]]," absolute mean difference in log-expression between treatment and control\n","the power is",signif(mysample$power,2),"\n", sep=" ")))
                                
               
                       })
         }
}
################################################################################

PlotOptionsv1 <- function()
{
  Try(ttGetPlotOptions<-tktoplevel(.affylmGUIglobals$ttMain))
  Try(tkwm.title(ttGetPlotOptions,"Plot Options"))
  Try(tkwm.deiconify(ttGetPlotOptions))
  Try(tkgrab.set(ttGetPlotOptions))
  Try(tkframe1 <- tkframe(ttGetPlotOptions,borderwidth=2))
  Try(tkframe2 <- tkframe(tkframe1,relief="groove",borderwidth=2))
  Try(tkframe4<-tkframe(tkframe1,borderwidth=2))

  Try(tkgrid(tklabel(tkframe1,text="    ")))

  Try(tkgrid(tklabel(tkframe2,text="Choose a graphics device for plotting.",font=.affylmGUIglobals$affylmGUIfont2),column=2,rowspan=1,columnspan=2,sticky="w"))

  Try(affylmGUIglobals <- get(".affylmGUIglobals",envir=.GlobalEnv))
  Try(if (!("graphicsDevice" %in% names(affylmGUIglobals)))
  {
    Try(affylmGUIglobals$graphicsDevice <- "R")
    Try(assign(".affylmGUIglobals",affylmGUIglobals,.GlobalEnv))
  })
  #Try(graphicsDevice <- .affylmGUIglobals$graphicsDevice)
  Try(graphicsDevice <- "R")
  
  Try(graphicsDeviceTcl <- tclVar(graphicsDevice))

  Try(tkrplot.but <- tkradiobutton(tkframe2,text="Tk R Plot",variable=graphicsDeviceTcl,value="tkrplot",font=.affylmGUIglobals$affylmGUIfont2))  
  Try(R.but       <- tkradiobutton(tkframe2,text="R",variable=graphicsDeviceTcl,value="R",font=.affylmGUIglobals$affylmGUIfont2))  
    
  Try(tkgrid(tkrplot.but,column=2))
  Try(tkgrid(R.but,column=2))

  Try(tkgrid.configure(tkrplot.but,R.but,sticky="w"))
  Try(tkgrid(tkframe2))
  Try(newGraphicsDevice <- "")
  onOK <- function()
  {
    Try(newGraphicsDevice<<-tclvalue(graphicsDeviceTcl))
    Try(tkgrab.release(ttGetPlotOptions))
    Try(tkdestroy(ttGetPlotOptions))
    Try(if (newGraphicsDevice==graphicsDevice)
      return())    
    Try(graphicsDevice <- newGraphicsDevice)
    
    Try(if (graphicsDevice=="R" && .Platform$OS.type=="windows")
      Try(tkmessageBox(title="R graphics device",
      message="It is strongly recommended that you run R in SDI (Single Document Interface) mode when using the R graphics device",icon="warning")))
    
    Try(affylmGUIglobals <- get(".affylmGUIglobals",envir=.GlobalEnv))
    Try(affylmGUIglobals$graphicsDevice <- graphicsDevice)
    Try(assign(".affylmGUIglobals",affylmGUIglobals,.GlobalEnv))
    Try(tkfocus(.affylmGUIglobals$ttMain))  
  }
  Try(OK.but <-tkbutton(tkframe4,text="   OK   ",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
  Try(Cancel.but <-tkbutton(tkframe4,text=" Cancel ",command=function(){Try(tkgrab.release(ttGetPlotOptions));Try(tkdestroy(ttGetPlotOptions));newGraphicsDevice<-"";Try(tkfocus(.affylmGUIglobals$ttMain))},font=.affylmGUIglobals$affylmGUIfont2))
  Try(onHelp <- function() tkmessageBox(title="Plotting Device",
    message="The R graphics is device can be resized more easily, but it may be inconvenient for Windows users running R in MDI mode.",
    icon="info"))
  Try(Help.but <- tkbutton(tkframe4,text=" Help ",command=function()Try(onHelp()),font=.affylmGUIglobals$affylmGUIfont2))
  Try(tkgrid(tklabel(tkframe4,text="                    ")))
  Try(tkgrid(OK.but,Cancel.but,Help.but))
  Try(tkgrid.configure(OK.but,sticky="e"))
  Try(tkgrid.configure(Cancel.but,sticky="e"))
  Try(tkgrid.configure(Help.but,sticky="e"))  
  Try(tkgrid(tklabel(tkframe4,text="       ")))
  Try(tkgrid(tkframe4))
  Try(tkgrid(tkframe1))
  Try(tkfocus(OK.but))
  Try(tkbind(ttGetPlotOptions, "<Return>",onOK))
  Try(tkbind(ttGetPlotOptions, "<Destroy>", function() {Try(tkgrab.release(ttGetPlotOptions));Try(tkfocus(.affylmGUIglobals$ttMain))}))
  Try(tkwait.window(ttGetPlotOptions))

  Try(tkdestroy(ttGetPlotOptions))  

# This return value below is not used.  The function above is used for its effect
# on PlotOptions in affylmGUIenvironment
  return(newGraphicsDevice)
}
################################################################################
affyPlotMA <- function(){
	Try(ArraysLoaded  <- get("ArraysLoaded", envir=affylmGUIenvironment))
	Try(SlideNamesVec  <- get("SlideNamesVec", envir=affylmGUIenvironment))
	Try(RawAffyData <- get("RawAffyData",envir=affylmGUIenvironment))
	Try(
		if (ArraysLoaded==FALSE){
			Try(tkmessageBox(title="M A Plot",message="Error: No arrays have been loaded.", icon="error",default="ok"))
			return()
		}
	)
	Try(LocalHScale <- .affylmGUIglobals$Myhscale)
	Try(LocalVScale <- .affylmGUIglobals$Myvscale)
	#
	Try(SlideNums <- GetSlideNums())
	Try(if (length(SlideNums)==0) return())
	Try(slide1 <- SlideNums$slide1)
	Try(slide2 <- SlideNums$slide2)
	#
	Try(WhetherToNormalize <- tclvalue(tkmessageBox(title="M A Plot",message="Use normalized data?",type="yesnocancel",icon="question")))
	Try(if (WhetherToNormalize=="cancel") return())
	#
	Try(
		if (WhetherToNormalize=="yes"){
			Try(NormalizedAffyData.Available <- get("NormalizedAffyData.Available",envir=affylmGUIenvironment))
			Try(
				if (NormalizedAffyData.Available==FALSE){
					NormalizeNow()
				}
			)
			Try(NormalizedAffyData.Available <- get("NormalizedAffyData.Available",envir=affylmGUIenvironment))
			Try(
				if (NormalizedAffyData.Available==FALSE){
					tkmessageBox(title="M A Plot",message="An error occured while trying to normalize the data.")
					return()
				}
			)
			Try(NormalizedAffyData <- get("NormalizedAffyData", envir=affylmGUIenvironment))
      Try(NormalizedAffyData.exprs <- exprs(NormalizedAffyData))

			Try(R <- NormalizedAffyData.exprs[,slide1])  # Using cDNA notation (R for one channel/array, G for the other)
			Try(G <- NormalizedAffyData.exprs[,slide2])  # Using cDNA notation (R for one channel/array, G for the other)
			pch <- 16
			cex <- 0.2
		}else{
			Try(R <- log2(exprs(RawAffyData)[,slide1]))  # Using cDNA notation (R for one channel/array, G for the other)
			Try(G <- log2(exprs(RawAffyData)[,slide2]))  # Using cDNA notation (R for one channel/array, G for the other)
			pch <- "."
			cex <- 1
		}
	)
	# R and G are already log2ed.
	M <- R - G
	A <- 0.5*(R+G)
	Try(
		plotFunction <- function(){
			Try(opar<-par(bg="white"))
			Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
			Try(plot(A,M,pch=pch,cex=cex,xlab=xLabel,ylab=yLabel))
			Try(title(plotTitle))
			Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
			Try(tmp<-par(opar))
		}#end of plotFunction <- function()
	)
	Try(
		if (WhetherToNormalize=="yes"){
			Try(plotTitle<-paste("Normalized M A Plot (",SlideNamesVec[slide1]," vs ",SlideNamesVec[slide2],")",sep=""))
		}else{
			Try(plotTitle<-paste("Raw M A Plot (",SlideNamesVec[slide1]," vs ",SlideNamesVec[slide2],")",sep=""))
		}
	)
	Try(plotLabels <- GetPlotLabels(plotTitle,"A","M"))
	Try(if (length(plotLabels)==0) return())
	Try(plotTitle <- plotLabels$plotTitle)
	Try(xLabel    <- plotLabels$xLabel)
	Try(yLabel    <- plotLabels$yLabel)
	#
	Try(
		if(.affylmGUIglobals$graphicsDevice=="tkrplot"){
		#	require("tkrplot")
			CopyToClip <- function() Try(tkrreplot(imgaffylmGUI))
			Try(ttGraph<-tktoplevel(.affylmGUIglobals$ttMain))
			Try(tkwm.withdraw(ttGraph))
			Try(tkwm.title(ttGraph,plotTitle))
			Try(imgaffylmGUI<-tkrplot(ttGraph,plotFunction,hscale=LocalHScale,vscale=LocalVScale))
			Try(tkwm.title(ttGraph,plotTitle))
			SetupPlotKeyBindings(tt=ttGraph,img=imgaffylmGUI)
			SetupPlotMenus(tt=ttGraph,initialfile="",plotFunction,img=imgaffylmGUI)
			Try(tkgrid(imgaffylmGUI))
			Try(
				if(as.numeric(tclvalue(tkwinfo("reqheight",imgaffylmGUI)))<10){  # Nothing plotted.
					Try(tkdestroy(ttGraph))
				}else{
					Try(tkwm.deiconify(ttGraph))
					Try(tkfocus(imgaffylmGUI))
				}
			)
		}else{
			Try(plot.new())
			Try(plotFunction())
		}
	)
}#end of affyPlotMA <- function()


################################################################################

"rawBoxplotPN" <- function(){
    #error if no data are loaded
    Try(whichArrayPlatform <- get("whichArrayPlatform",envir=affylmGUIenvironment))
    if(whichArrayPlatform ==""){
              Try(tkmessageBox(title="QC",message="No arrays have been loaded.	Please try New or Open from the File menu.",type="ok",icon="error"))
				    	Try(tkfocus(.affylmGUIglobals$ttMain))
              Try(return())
    }
   if(whichArrayPlatform!="EXON"){return()} #only on exons 
    Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
    Try(localDir <- getwd())
    Try(whichLib <- get("whichLib", affylmGUIenvironment))
    Try(affylibs <- dir(system.file("affylibs",package="oneChannelGUI")))
    Try(ctrl <- affylibs[intersect(grep(whichLib[[1]][1],  affylibs), grep("controls",  affylibs))])
    #check if the affylibs are available else it install it
    Try(if(length(ctrl) == 0){
          tkmessageBox(title="QC",message="It seems that the Affymetrix/Apt libraries are not available.\nNext messages will help you to install/set them.",type="ok",icon="error")		    	
          aptFolder()
          geneExonLibs()
    })
    Try(ctrl.table <- read.table(paste(system.file("affylibs",package="oneChannelGUI"),"/",ctrl, sep=""), sep="\t", as.is=T, header=T))

    Try(pgf <- paste(system.file("affylibs",package="oneChannelGUI"),"/",affylibs[intersect(grep(whichLib[[1]][1],  affylibs), grep("pgf",  affylibs))],sep=""))
    Try(clf <- paste(system.file("affylibs",package="oneChannelGUI"),"/",affylibs[intersect(grep(whichLib[[1]][1],  affylibs), grep("clf",  affylibs))],sep=""))
    setwd(localDir)
    Try(p.ctrl <- ctrl.table[which(ctrl.table[,2]=="pos_control"),])
    Try(n.ctrl <- ctrl.table[which(ctrl.table[,2]=="neg_control"),])
    Try(pn.ctrl <- rbind(p.ctrl, n.ctrl))
    Try(write.table(pn.ctrl, "ctrlpn.txt", sep="\t", row.names=F))

   #defining the temp file containing target info for apt extract
   Try(Targets <- get("Targets",envir=affylmGUIenvironment))
   Try(tempTarget <- tempfile(pattern = "target", tmpdir = getwd()))
   Try(tempTarget <- sub( "\\\\","/",tempTarget)) #changing double backslach with slash
   Try(write.table(Targets[,2:3], tempTarget, sep="\t", row.names =F, col.names = c("cel_files", "group_id"))) 
   Try(tempOut <- tempfile(pattern = "out", tmpdir = getwd()))#creating a temp outfile
   Try(tempOut <- sub( "\\\\","/",tempOut)) #changing double backslach with slash
   
   #running apt-cel-extract
   Try(extractCel <- paste(get("aptDir",   affylmGUIenvironment),"/bin/apt-cel-extract", sep=""))
   Try(extractCel <- paste(extractCel, " -o rawPN.txt ", "-p ", pgf ," -c ",clf," --probeset-ids ctrlpn.txt ", "--cel-files " , tempTarget, sep="")) 
   Try(cat("Be patient...... starting probe signal extraction ...."))
   Try(system(extractCel))
   Try(cat("Be patient...... ending probe signal extraction ...."))
   
   #creating the box plot fro P and N
   Try(tmp <- read.table("rawPN.txt", sep="\t", header=T))
   Try(tmp.p <- tmp[which(tmp$probeset_id%in%p.ctrl$probeset_id), 8:dim(tmp)[2]])
   Try(names(tmp.p) <- Targets$Name)
   Try(tmp.p <- log2(tmp.p))
   Try(tmp.n <- tmp[which(tmp$probeset_id%in%n.ctrl$probeset_id), 8:dim(tmp)[2]])
   Try(names(tmp.n) <- Targets$Name)
   Try(tmp.n <- log2(tmp.n))
   Try(par(mfrow=c(1,2)))
   Try(boxplot(tmp.p, main="Positive Ctrls", ylab="raw log2(intensity)", las=2))
   Try(boxplot(tmp.n, main="Negative Ctrls", ylab="raw log2(intensity)", las=2))
   Try(tkmessageBox(title="Raw probes intensities from CELs",message="Box plot of raw controls intensity data is available in main R window",icon="info"))
   Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
   
}
################################################################################
"qcMDS" <- function(){
#   Try(require(edgeR) || stop("Missing edgeR library"))
   Try(Targets <- get("Targets",envir=affylmGUIenvironment))
   Try(whichArrayPlatform <- get("whichArrayPlatform",envir=affylmGUIenvironment))
   if(whichArrayPlatform ==""){
              Try(tkmessageBox(title="QC",message="No arrays have been loaded.	Please try New or Open from the File menu.",type="ok",icon="error"))
				    	Try(tkfocus(.affylmGUIglobals$ttMain))
              Try(return())
   }
   if(affylmGUIenvironment$NormalizedAffyData.Available & affylmGUIenvironment$NGS.Available){
         Try(NormalizedAffyData <- get("NormalizedAffyData", env=affylmGUIenvironment))
         Try(mappedReads <- get("mappedReads", env=affylmGUIenvironment))
         Try(targets <- get("Targets", env=affylmGUIenvironment))
    } else Try(tkmessageBox(title="NGS data set",message="Normalized data are not available.", type="ok", icon="error"))
    Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
    cat("\ncreating the DGEList")
   Try(NGSscaling.Available <- get("NGSscaling.Available", env=affylmGUIenvironment))
   if(NGSscaling.Available){
           Try(scaledReads <- get("NGSscaling", env=affylmGUIenvironment))
           Try(mylist <- DGEList(counts= exprs(NormalizedAffyData), group=as.factor(targets$Target), lib.size=scaledReads))
   } else {Try(mylist <- DGEList(counts= exprs(NormalizedAffyData), group=as.factor(targets$Target)))} 
    Try(mylist <- estimateCommonDisp(mylist))
    Try(plotMDS.DGEList(mylist, labels=Targets$Name, main=paste("Multidimensional scaling plot\nCommon disp. after normalization",signif(mylist$common.dispersion,2),sep=" ")))
    Try(tkmessageBox(title="Multdimensional scaling plot",message="Multidimensional scaling plot is available in main R window",icon="info"))
    Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
}
################################################################################
"EDAplotQuality" <- function(){
 #  require(EDASeq) || stop("Missing EDASeq library")
   Try(whichArrayPlatform <- get("whichArrayPlatform",envir=affylmGUIenvironment))
   if(whichArrayPlatform ==""){
              Try(tkmessageBox(title="QC",message="No arrays have been loaded.	Please try New or Open from the File menu.",type="ok",icon="error"))
				    	Try(tkfocus(.affylmGUIglobals$ttMain))
              Try(return())
   }
   if(affylmGUIenvironment$NormalizedAffyData.Available & affylmGUIenvironment$NGS.Available){
         Try(NormalizedAffyData <- get("NormalizedAffyData", env=affylmGUIenvironment))
         Try(targets <- get("Targets", env=affylmGUIenvironment))
    } else Try(tkmessageBox(title="NGS data set",message="Normalized data are not available.", type="ok", icon="error"))
    Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
    Try(bfs <- BamFileList(targets$FileName))
    Try(pd <- DataFrame("name"=targets$Name, "Target"= targets$Target, row.names=paste(targets$Name, targets$Target, sep=".")))
    Try(elementMetadata(bfs) <- pd)
    Try(plotQuality(bfs))
    Try(legend("topright",unique(elementMetadata(bfs)[,1]),fill=rainbow(length(unique(elementMetadata(bfs)[,1])))))
    Try(tkmessageBox(title="EDASeq Quality plot",message="EDASeq Quality plot is available in main R window",icon="info"))
    Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
}
################################################################################
"EDAreadNumber" <- function(){
#   require(EDASeq) || stop("Missing EDASeq library")
   Try(whichArrayPlatform <- get("whichArrayPlatform",envir=affylmGUIenvironment))
   if(whichArrayPlatform ==""){
              Try(tkmessageBox(title="QC",message="No arrays have been loaded.	Please try New or Open from the File menu.",type="ok",icon="error"))
				    	Try(tkfocus(.affylmGUIglobals$ttMain))
              Try(return())
   }
   if(affylmGUIenvironment$NormalizedAffyData.Available & affylmGUIenvironment$NGS.Available){
         Try(NormalizedAffyData <- get("NormalizedAffyData", env=affylmGUIenvironment))
         Try(targets <- get("Targets", env=affylmGUIenvironment))
    } else Try(tkmessageBox(title="NGS data set",message="Normalized data are not available.", type="ok", icon="error"))
    Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
    Try(bfs <- BamFileList(targets$FileName))
    Try(pd <- DataFrame("name"=targets$Name, "Target"= targets$Target, row.names=paste(targets$Name, targets$Target, sep=".")))
    Try(elementMetadata(bfs) <- pd)
    Try(barplot(bfs, names.arg=unique(elementMetadata(bfs)[,1]),col=rainbow(length(unique(elementMetadata(bfs)[,1])))))
    Try(tkmessageBox(title="EDASeq Read Number",message="EDASeq read number plot is available in main R window",icon="info"))
    Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
}
################################################################################
"EDANtFreq" <- function(){
 #  require(EDASeq) || stop("Missing EDASeq library")
   Try(whichArrayPlatform <- get("whichArrayPlatform",envir=affylmGUIenvironment))
   if(whichArrayPlatform ==""){
              Try(tkmessageBox(title="QC",message="No arrays have been loaded.	Please try New or Open from the File menu.",type="ok",icon="error"))
				    	Try(tkfocus(.affylmGUIglobals$ttMain))
              Try(return())
   }
   if(affylmGUIenvironment$NormalizedAffyData.Available & affylmGUIenvironment$NGS.Available){
         Try(NormalizedAffyData <- get("NormalizedAffyData", env=affylmGUIenvironment))
         Try(targets <- get("Targets", env=affylmGUIenvironment))
    } else {
	    Try(tkmessageBox(title="NGS data set",message="Normalized data are not available.", type="ok", icon="error"))
        Try(return())
   }
    Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
    Try(bfs <- BamFileList(targets$FileName))
    Try(pd <- DataFrame("name"=targets$Name, "Target"= targets$Target, row.names=paste(targets$Name, targets$Target, sep=".")))
    Try(elementMetadata(bfs) <- pd)
    Try(plot.names <- paste(unique(elementMetadata(bfs)[,1]), seq(1, length(unique(elementMetadata(bfs)[,1]))), sep=" = ", collapse=", "))
    ##selecting the bam to be plotted for mapping  I.E. selecting the chromosome for the mapping
      Try(ttcolExtract<-tktoplevel(.affylmGUIglobals$ttMain))
      Try(tkwm.deiconify(ttcolExtract))
      Try(tkgrab.set(ttcolExtract))
      Try(tkfocus(ttcolExtract))
      Try(tkwm.title(ttcolExtract,"Selecting the BAM file to be plotted"))
      Try(tkgrid(tklabel(ttcolExtract,text="    ")))
      Try(plotNtBam <- "")
      Try(Local.colExtract <- tclVar(init=plotNtBam))
      Try(entry.colExtract <-tkentry(ttcolExtract,width="4",font=.affylmGUIglobals$affylmGUIfont2,textvariable=Local.colExtract,bg="white"))
      Try(tkgrid(tklabel(ttcolExtract,text=paste("Please enter the number associated to the sample of of interest\n", plot.names),font=.affylmGUIglobals$affylmGUIfont2)))
      Try(tkgrid(entry.colExtract))
      onOK <- function()
      {
                     Try(assign("plotNtBam", as.numeric(tclvalue(Local.colExtract)),affylmGUIenvironment))
                     Try(tkgrab.release(ttcolExtract));Try(tkdestroy(ttcolExtract));Try(tkfocus(.affylmGUIglobals$ttMain))                        
      }
      Try(OK.but <-tkbutton(ttcolExtract,text="   OK   ",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
      Try(tkgrid(tklabel(ttcolExtract,text="    ")))
      Try(tkgrid(OK.but))
      Try(tkgrid.configure(OK.but))
      Try(tkgrid(tklabel(ttcolExtract,text="       ")))
      Try(tkfocus(entry.colExtract))
      Try(tkbind(entry.colExtract, "<Return>",onOK))
      Try(tkbind(ttcolExtract, "<Destroy>", function(){Try(tkgrab.release(ttcolExtract));Try(tkfocus(.affylmGUIglobals$ttMain));return(0)}))
      Try(tkwait.window(ttcolExtract))
      Try(tkfocus(.affylmGUIglobals$ttMain))
      Try(plotNtBam <- get("plotNtBam", affylmGUIenvironment))
      Try(plotNtFrequency(bfs[[plotNtBam]], main=unique(elementMetadata(bfs)[plotNtBam,1])))
      Try(tkmessageBox(title="EDASeq Nt frequency",message=paste("EDASeq Nt frequency plot for sample", unique(elementMetadata(bfs)[plotNtBam,1]),"is available in main R window",icon="info")))
      Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
}
################################################################################
"EDAboxplot" <- function(){
 #  Try(require(EDASeq) || stop("Missing EDASeq library"))
   Try(whichArrayPlatform <- get("whichArrayPlatform",envir=affylmGUIenvironment))
   if(whichArrayPlatform ==""){
              Try(tkmessageBox(title="QC",message="No arrays have been loaded.	Please try New or Open from the File menu.",type="ok",icon="error"))
			  Try(tkfocus(.affylmGUIglobals$ttMain))
			  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
              Try(return())
   }
   if(affylmGUIenvironment$NormalizedAffyData.Available & affylmGUIenvironment$NGS.Available){
         Try(NormalizedAffyData <- get("NormalizedAffyData", env=affylmGUIenvironment))
         Try(Targets <- get("Targets", env=affylmGUIenvironment))
    } else {
	    Try(tkmessageBox(title="NGS data set",message="Normalized data are not available.", type="ok", icon="error"))
        Try(return())
   }

    Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))

    Try(bowtieDirAvailable <- get("whichArrayPlatform",envir=affylmGUIenvironment))
    Try(bowtieDirLocation.Available <- get("bowtieDirLocation.Available",envir=affylmGUIenvironment))
    if(bowtieDirLocation.Available){
	      Try(bowtieDirLocation <- get("bowtieDirLocation",envir=affylmGUIenvironment))      
    } else{
	      Try(tkmessageBox(title="Bowtie data",message="It seems that Bowtie dir is missing!\nPlease install Bowtie using the function in General Tools menu",icon="error"))
	      Try(return())
    }
    #adding gc content to eset
    Try(whichGenome <- annotation(NormalizedAffyData))
    if(whichGenome == ""){
	       Try(tkmessageBox(title="Genome selection",message="No genome is indicated in the annotation slot of ExpressionSet",type="ok", icon="error"))
	       Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
	       Try(return())
	  } else if (whichGenome == "hs19"){
	     Try(annlibname <- system.file("bowtie/hg19_gene-level.scaffold.Rda",package="oneChannelGUI"))
	     Try(load(annlibname))
	  } else if (whichGenome == "mm9"){
	     Try(annlibname <- system.file("bowtie/mm9_gene-level.scaffold.Rda",package="oneChannelGUI"))
	     Try(load(annlibname))
	  } else if (whichGenome == "rn4"){
	     Try(annlibname <- system.file("bowtie/rn4_gene-level.scaffold.Rda",package="oneChannelGUI"))
	     Try(load(annlibname))
	  }	 else{
	       Try(tkmessageBox(title="Genome selection",message="In the annotation slot of ExpressionSet is present a genome not annotated in oneChannelGUI!\nContact the maintainer for Genome implementation",type="ok", icon="error"))
	       Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
	       Try(return())
	  }
	  #detecting the chr under analysis
	  Try(chr <- strsplit(Targets$FileName[1], "_")) #getting the chr
	  Try(chr <- as.vector(unlist(chr)))
	  Try(chr <- chr[length(chr)])
	  Try(chr <- sub(".bam", "", chr))  #needed to extract the right subset of gene-level annotation from  makeGeneScaffold generated GRanges list
	  Try(chr <- sub("chr0", "chr", chr))
	  #selecting the chromosome genomic reanges on which assigning BAM data
	  Try(chr.gr <- chr.gr[which(names(chr.gr) == chr)])
	  Try(genes.lenght <- width(ranges(chr.gr[[1]])))
	  Try(names(genes.lenght) <- elementMetadata(chr.gr[[1]])$names)
	  Try(gc.freq <- gc.freq[which(names(gc.freq) == chr)])
	  Try(gc.freq <- unlist(gc.freq))
	  Try(tmp.names <- names(gc.freq))
	  Try(tmp.names <- sapply(tmp.names,function(x,chr){tmp<-sub(chr,'',x);return(tmp)},chr=paste(chr,'.', sep="")))
	  Try(tmp.names <- as.character(tmp.names))
	  Try(names(gc.freq) <- tmp.names)
	  if(identical(names(genes.lenght), names(gc.freq))){
		  Try(feature <- data.frame(gc=gc.freq,length=genes.lenght))
	  }else{
		  Try(gc.freq <- gc.freq[order(names(gc.freq))])
		  Try(genes.lenght <- genes.lenght[order(names(genes.lenght))])
		  Try(feature <- data.frame(gc=gc.freq,length=genes.lenght))
	  }
	  Try(var.tmp.pd<-data.frame(names(feature)))
	  Try(names(var.tmp.pd)<-"labelDescription" )
	  Try(rownames(var.tmp.pd)<-names(feature))
	  Try(tmp1.pd<-new("AnnotatedDataFrame", data=feature, varMetadata=var.tmp.pd))
	
	
	  #making eset featureNames identical to names gc.freq and genes.length 
	  .myFeature <- function(eset){
	      tmp.names <- featureNames(NormalizedAffyData)
          tmp.names <- sapply(tmp.names, function(x){sub('\\-_','#',x)})
          tmp.names <- as.character(tmp.names)
          tmp.names <- sapply(tmp.names, function(x){sub('\\+_','#',x)})
          tmp.names <- as.character(tmp.names)
          tmp.names <- sapply(tmp.names, function(x){tmp <- strsplit(x, '#');return(tmp[[1]][2])})
          tmp.names <- as.character(tmp.names)
          return(tmp.names)
      }
	  Try(counts <- NormalizedAffyData)
	  Try(featureNames(counts) <- .myFeature(NormalizedAffyData))
	  Try(tmp1.pd <- tmp1.pd[which(featureNames(tmp1.pd)%in%featureNames(counts)),])
	  Try(counts <- counts[which(featureNames(counts)%in%featureNames(tmp1.pd)),])
	  Try(counts <- counts[order(featureNames(counts)),])
	  Try(tmp1.pd <- tmp1.pd[order(featureNames(tmp1.pd)),])     
      Try(eseq <- newSeqExpressionSet(exprs(counts), phenoData=pData(counts), featureData=tmp1.pd))
      Try(names(pData(eseq))[1] <- "conditions")
      Try(tkmessageBox(title="EDASeq Boxplot",message="Sample boxplot is available in main R window",icon="info"))
      Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
      Try(boxplot(eseq, ylab="log10 counts"))
}
################################################################################
"EDAbiasPlot" <- function(){
 #  Try(require(EDASeq) || stop("Missing EDASeq library"))
   Try(whichArrayPlatform <- get("whichArrayPlatform",envir=affylmGUIenvironment))
   if(whichArrayPlatform ==""){
              Try(tkmessageBox(title="QC",message="No arrays have been loaded.	Please try New or Open from the File menu.",type="ok",icon="error"))
			  Try(tkfocus(.affylmGUIglobals$ttMain))
			  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
              Try(return())
   }
   if(affylmGUIenvironment$NormalizedAffyData.Available & affylmGUIenvironment$NGS.Available){
         Try(NormalizedAffyData <- get("NormalizedAffyData", env=affylmGUIenvironment))
         Try(Targets <- get("Targets", env=affylmGUIenvironment))
    } else {
	    Try(tkmessageBox(title="NGS data set",message="Normalized data are not available.", type="ok", icon="error"))
        Try(return())
   }

    Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))

    Try(bowtieDirAvailable <- get("whichArrayPlatform",envir=affylmGUIenvironment))
    Try(bowtieDirLocation.Available <- get("bowtieDirLocation.Available",envir=affylmGUIenvironment))
    if(bowtieDirLocation.Available){
	      Try(bowtieDirLocation <- get("bowtieDirLocation",envir=affylmGUIenvironment))      
    } else{
	      Try(tkmessageBox(title="Bowtie data",message="It seems that Bowtie dir is missing!\nPlease install Bowtie using the function in General Tools menu",icon="error"))
	      Try(return())
    }
    #adding gc content to eset
    Try(whichGenome <- annotation(NormalizedAffyData))
    if(whichGenome == ""){
	       Try(tkmessageBox(title="Genome selection",message="No genome is indicated in the annotation slot of ExpressionSet",type="ok", icon="error"))
	       Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
	       Try(return())
	  } else if (whichGenome == "hs19"){
	     Try(annlibname <- system.file("bowtie/hg19_gene-level.scaffold.Rda",package="oneChannelGUI"))
	     Try(load(annlibname))
	  } else if (whichGenome == "mm9"){
	     Try(annlibname <- system.file("bowtie/mm9_gene-level.scaffold.Rda",package="oneChannelGUI"))
	     Try(load(annlibname))
	  } else if (whichGenome == "rn4"){
	     Try(annlibname <- system.file("bowtie/rn4_gene-level.scaffold.Rda",package="oneChannelGUI"))
	     Try(load(annlibname))
	  }	 else{
	       Try(tkmessageBox(title="Genome selection",message="In the annotation slot of ExpressionSet is present a genome not annotated in oneChannelGUI!\nContact the maintainer for Genome implementation",type="ok", icon="error"))
	       Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
	       Try(return())
	  }
	  #detecting the chr under analysis
	  Try(chr <- strsplit(Targets$FileName[1], "_")) #getting the chr
	  Try(chr <- as.vector(unlist(chr)))
	  Try(chr <- chr[length(chr)])
	  Try(chr <- sub(".bam", "", chr))  #needed to extract the right subset of gene-level annotation from  makeGeneScaffold generated GRanges list
	  Try(chr <- sub("chr0", "chr", chr))
	  #selecting the chromosome genomic reanges on which assigning BAM data
	  Try(chr.gr <- chr.gr[which(names(chr.gr) == chr)])
	  Try(genes.lenght <- width(ranges(chr.gr[[1]])))
	  Try(names(genes.lenght) <- elementMetadata(chr.gr[[1]])$names)
	  Try(gc.freq <- gc.freq[which(names(gc.freq) == chr)])
	  Try(gc.freq <- unlist(gc.freq))
	  Try(tmp.names <- names(gc.freq))
	  Try(tmp.names <- sapply(tmp.names,function(x,chr){tmp<-sub(chr,'',x);return(tmp)},chr=paste(chr,'.', sep="")))
	  Try(tmp.names <- as.character(tmp.names))
	  Try(names(gc.freq) <- tmp.names)
	  if(identical(names(genes.lenght), names(gc.freq))){
		  Try(feature <- data.frame(gc=gc.freq,length=genes.lenght))
	  }else{
		  Try(gc.freq <- gc.freq[order(names(gc.freq))])
		  Try(genes.lenght <- genes.lenght[order(names(genes.lenght))])
		  Try(feature <- data.frame(gc=gc.freq,length=genes.lenght))
	  }
	  Try(var.tmp.pd<-data.frame(names(feature)))
	  Try(names(var.tmp.pd)<-"labelDescription" )
	  Try(rownames(var.tmp.pd)<-names(feature))
	  Try(tmp1.pd<-new("AnnotatedDataFrame", data=feature, varMetadata=var.tmp.pd))


	  #making eset featureNames identical to names gc.freq and genes.length 
	  .myFeature <- function(eset){
	      tmp.names <- featureNames(NormalizedAffyData)
          tmp.names <- sapply(tmp.names, function(x){sub('\\-_','#',x)})
          tmp.names <- as.character(tmp.names)
          tmp.names <- sapply(tmp.names, function(x){sub('\\+_','#',x)})
          tmp.names <- as.character(tmp.names)
          tmp.names <- sapply(tmp.names, function(x){tmp <- strsplit(x, '#');return(tmp[[1]][2])})
          tmp.names <- as.character(tmp.names)
          return(tmp.names)
      }
	  Try(counts <- NormalizedAffyData)
	  Try(featureNames(counts) <- .myFeature(NormalizedAffyData))
	  Try(tmp1.pd <- tmp1.pd[which(featureNames(tmp1.pd)%in%featureNames(counts)),])
	  Try(counts <- counts[which(featureNames(counts)%in%featureNames(tmp1.pd)),])
	  Try(counts <- counts[order(featureNames(counts)),])
	  Try(tmp1.pd <- tmp1.pd[order(featureNames(tmp1.pd)),])
      Try(eseq <- newSeqExpressionSet(exprs(counts), phenoData=pData(counts), featureData=tmp1.pd))
      Try(names(pData(eseq))[1] <- "conditions")
      Try(tkmessageBox(title="EDASeq Bias Plot",message="Sample bias plot is available in main R window",icon="info"))
      Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
      Try(par(mfrow=c(2,2)))
      #low resolution plot
      Try(biasPlot(eseq, "gc", log=T, ylim=c(0,5)))
      Try(biasPlot(eseq, "length", log=T, ylim=c(0,5)))
      #high resolution plot
      Try(biasPlot(eseq, "gc", log=T))
      Try(biasPlot(eseq, "length", log=T))      
}
###########################################################################################################
"fastQC" <-function(){
	Try(binDir <- get("binDir",envir=affylmGUIenvironment))
	Try(system(paste(binDir,"/fastqc",sep="")))
}
###########################################################################################################

Try the oneChannelGUI package in your browser

Any scripts or data that you put into this service are public.

oneChannelGUI documentation built on Nov. 17, 2017, 11:02 a.m.