R/filteringmenu.R

#set of functions, directly/indirectly involved, in oneChannelGUI filteringMenu
#oneChannelGUI  iqrFilter performs a filtering of gene and/or exon data based on iqr filtering from genefilter
#oneChannelGUI  intensityFilter performs a filtering of gene and/or exon data based intensity data and pOverA function from genefilter
#oneChannelGUI listFilter  performs a filtering of gene and/or exon data based on a list of probesets 
         #contains OpenAFile present in filemenu.R, written immediately after the OpenLargeFile
#oneChannelGUI IPAlistFilter  performs a filtering of gene and/or exon data based on a list of Entez Genes IDs
#oneChannelGUI ExportNormalizedExpressionValues1 present in filemenu.R
#oneChannelGUI intronicBg this function calculate the density distribution for exon (positive) and intron (negative controls) of the controls
               #and allows the user to define a background threshold to be used fgor filtering
#oneChannelGUI plierToZero this function changes very low log2 intesities values to 0, this is expecialy usefull for plier data               
#oneChannelGUI dabgFilter data are filtered on the basis of a p-value defining the probability of expression over background for a probe
#oneChannelGUI recoverUnfiltered data this function allow to recover ffrom an external file the unfiltered data
#oneChannelGUI reviqrFilter reverse IQR filtering for exon analysis. Removes strongly changing gene-level rpobe set that might 
#make more difficult the detection of alternative splcing events.
#oneChannelGUI biomartFilter filtering out all EGs which do not have at least 2 transcripts associated on the basis of ensembl annotation
#oneChannelGUI eSet4meV exporting normalized data in a fromat suitable to be loaded on meV
#oneChannelGUI filteringmiRtargets filtering using miR target information
#oneChannelGUI mRNAmiRCor Filtering by mean of correlation between expression data and miRNA expression changes
#filterBam files
#################################################################################
# x is an ExpressionSet, threshold is the IQR value to be applied
"iqrFilter"<-function(){
          #error if no data are loaded
          Try(whichArrayPlatform <- get("whichArrayPlatform",envir=affylmGUIenvironment))
          if(whichArrayPlatform ==""){
              Try(tkmessageBox(title="Filtering",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())
          }    
          #########################

      #      require(genefilter) || stop("library genefilter could not be found !")
           	##makning the menu for selecting IQR threshold
            Try(ttGetFilterMethod <- tktoplevel(.affylmGUIglobals$ttMain))
	      Try(tkwm.deiconify(ttGetFilterMethod))
            Try(tkgrab.set(ttGetFilterMethod))
            Try(tkfocus(ttGetFilterMethod))
            Try(tkwm.title(ttGetFilterMethod,"IQR Filtering Threshold"))
	
 	      Try(tkgrid(tklabel(ttGetFilterMethod,text="    ")))
	      Try(ttGetFilterMethodTcl <- tclVar("0.25"))
            Try(rbIQR.5 <- tkradiobutton(ttGetFilterMethod,text="IQR 0.5",variable=ttGetFilterMethodTcl,value=0.5,font=.affylmGUIglobals$affylmGUIfont2))
            Try(rbIQR.25<-tkradiobutton(ttGetFilterMethod,text="IQR 0.25",variable=ttGetFilterMethodTcl,value=0.25,font=.affylmGUIglobals$affylmGUIfont2))
            Try(rbIQR.1<-tkradiobutton(ttGetFilterMethod,text="IQR 0.1",variable=ttGetFilterMethodTcl,value=0.1,font=.affylmGUIglobals$affylmGUIfont2))
	      Try(tkgrid(tklabel(ttGetFilterMethod,text="    "),rbIQR.5))
	      Try(tkgrid(tklabel(ttGetFilterMethod,text="    "),rbIQR.25))
	      Try(tkgrid(tklabel(ttGetFilterMethod,text="    "),rbIQR.1))
	      Try(tkgrid.configure(rbIQR.5,rbIQR.25,rbIQR.1,columnspan=2,sticky="w"))
	      Try(tkgrid(tklabel(ttGetFilterMethod,text="    "),tklabel(ttGetFilterMethod,text="    ")))
	      Try(ReturnVal <- "")
	      Try(onCancel <- function() {Try(ReturnVal <<- "");Try(tkgrab.release(ttGetFilterMethod));Try(tkdestroy(ttGetFilterMethod));Try(tkfocus(.affylmGUIglobals$ttMain))})
	      Try(onOK <- function() {Try(ReturnVal <<- tclvalue(ttGetFilterMethodTcl));Try(tkgrab.release(ttGetFilterMethod));Try(tkdestroy(ttGetFilterMethod));Try(tkfocus(.affylmGUIglobals$ttMain))})
        Try(onHelp <- function() tkmessageBox(title="IQR filtering",
                 message="IQR filter remove invariant probe set \non the basis of their distribution in the arrays under analysis.
                           \nIQR=0.1 soft filter, i.e. few invariant probe sets are removed, \nIQR=0.25 intermediate filter, \nIQR=0.5 robust filter, i.e. most of the invariant probe sets are removed.",
                 icon="info"))
        Try(Help.but <- tkbutton(ttGetFilterMethod,text=" Help ",command=function()Try(onHelp()),font=.affylmGUIglobals$affylmGUIfont2))
	      Try(OK.but     <- tkbutton(ttGetFilterMethod,text="OK",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
	      Try(Cancel.but <- tkbutton(ttGetFilterMethod,text="Cancel",command=onCancel,font=.affylmGUIglobals$affylmGUIfont2))

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

	      Try(tkbind(ttGetFilterMethod,"<Destroy>",function() {ReturnVal <- "";Try(tkgrab.release(ttGetFilterMethod));Try(tkfocus(.affylmGUIglobals$ttMain));}))
       Try(tkbind(OK.but, "<Return>",onOK))
       Try(tkbind(Cancel.but, "<Return>",onCancel))      
        Try(tkbind(Help.but, "<Return>",onCancel)) 
	      Try(tkwait.window(ttGetFilterMethod))
	      if(is.na(as.numeric(ReturnVal))){
                              Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
                              return()
        } else{
        ##Filtering routine
        Try(whichArrayPlatform <- get("whichArrayPlatform", env=affylmGUIenvironment))
        Try(    
            if(whichArrayPlatform=="EXON"){
                     Try(FilterMethod <-paste("IQR filter", ReturnVal, sep=" "))
                     Try(threshold <- as.numeric(ReturnVal))
                     Try(NormalizedAffyData.Available     <- get("NormalizedAffyData.Available" , envir=affylmGUIenvironment))
                     if(NormalizedAffyData.Available){
                            Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
                            Try(x <- get("NormalizedAffyData",envir=affylmGUIenvironment))
                            Try(iqr <- function(x){IQR(x)>threshold})
                            Try(ff <- filterfun(iqr))
                            Try(which <- genefilter(x, ff))
                            Try(par(mfrow=c(1,2)))
                            Try(text<-paste("Unfiltered probes= ", dim(exprs(x))[1], sep=""))
                            Try(hist(as.matrix(exprs(x)), breaks=100, main=text))
                            Try(text<-paste("Filtered probes= ", sum(which), " ",FilterMethod,sep=""))
                            Try(hist(as.matrix(exprs(x[which,])), breaks=100, main=text))
                            Try(affylmGUIenvironment$NormalizedAffyData<-x[which,])
                            Try(x.exon <- get("exonAffyData",envir=affylmGUIenvironment))
                            ####temporary saving unfiltered data
                            Try(tempUnfiltered <- tempfile(pattern = "unfiltered", tmpdir = ""))
                            Try(tempUnfiltered <- sub( "\\\\","",tempUnfiltered))
                            Try(tempUnfiltered <- sub( "/","",tempUnfiltered))
                            Try(workingDir <- getwd())
                            Try(workingDir <- sub( "/$","",workingDir))  
                            Try(tempUnfiltered <- paste(workingDir, "/", tempUnfiltered, ".rda", sep=""))
                            Try(assign("unfilteredData.location", tempUnfiltered, envir=affylmGUIenvironment))
                            Try(save(x, x.exon, file=tempUnfiltered))
                            ####temporary saving unfiltered data
                            Try(tkdelete(.affylmGUIglobals$mainTree,"NormalizedAffyData.Status"))
                            Try(tkinsert(.affylmGUIglobals$mainTree,"end","NormalizedAffyData","NormalizedAffyData.Status" ,text=paste("Available (",FilterMethod,")",sep=""),font=.affylmGUIglobals$affylmGUIfontTree))
                            Try(x <- x[which,])#subset of probe set to be used to extract exon data
                            Try(x.lib <- affylmGUIenvironment$exprConsoleLibs$exon.library)
                            Try(x.lib.subset <- x.lib[which(x.lib[,1]%in%as.numeric(featureNames(x))),3])
                            Try(x.lib.subset <- sapply(x.lib.subset ,function(x){strsplit(x, " ")}))
                            Try(x.lib.subset<-as.vector(unlist(x.lib.subset)))
                            Try(affylmGUIenvironment$exonAffyData <- x.exon[which(featureNames(x.exon)%in%x.lib.subset),])
                            Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
                         }
           } else{   
                     Try(FilterMethod <-paste("IQR filter ", ReturnVal, sep=" "))
                     Try(threshold <- as.numeric(ReturnVal))
                     Try(NormalizedAffyData.Available     <- get("NormalizedAffyData.Available" , envir=affylmGUIenvironment))
                     if(NormalizedAffyData.Available){
                            Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
                            Try(x <- get("NormalizedAffyData",envir=affylmGUIenvironment))
                            Try(iqr <- function(x){IQR(x)>threshold})
                            Try(ff <- filterfun(iqr))
                            Try(which <- genefilter(x, ff))
                            Try(par(mfrow=c(1,2)))
                            Try(text<-paste("Unfiltered probes= ", dim(exprs(x))[1], sep="") )
                            Try(hist(as.matrix(exprs(x)), breaks=100, main=text))
                            Try(text<-paste("Filtered probes= ", sum(which), " ",FilterMethod,sep=""))
                            Try(hist(as.matrix(exprs(x[which,])), breaks=100, main=text))
                            Try(affylmGUIenvironment$NormalizedAffyData<-x[which,])
                            ####temporary saving unfiltered data
                            Try(tempUnfiltered <- tempfile(pattern = "unfiltered", tmpdir = ""))
                            Try(tempUnfiltered <- sub( "\\\\","",tempUnfiltered))
                            Try(tempUnfiltered <- sub( "/","",tempUnfiltered) )
                            Try(workingDir <- getwd() )
                            Try(workingDir <- sub( "/$","",workingDir))  
                            Try(tempUnfiltered <- paste(workingDir, "/", tempUnfiltered, ".rda", sep=""))
                            Try(assign("unfilteredData.location", tempUnfiltered, envir=affylmGUIenvironment))
                            Try(save(x, file=tempUnfiltered)) 
                            ####temporary saving unfiltered data

                            Try(tkdelete(.affylmGUIglobals$mainTree,"NormalizedAffyData.Status"))
                            Try(tkinsert(.affylmGUIglobals$mainTree,"end","NormalizedAffyData","NormalizedAffyData.Status" ,text=paste("Available (",FilterMethod,")",sep=""),font=.affylmGUIglobals$affylmGUIfontTree))
                            Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
                         }
            }
     )
  }   
}
################################################################################

# x is an ExpressionSet, threshold is the min intenisty value to be applied, fraction is the % of array with above threshold
"intensityFilter"<-function(){
  #     require(genefilter) || stop("library genefilter could not be found !")
       #error if no data are loaded
       Try(whichArrayPlatform <- get("whichArrayPlatform",envir=affylmGUIenvironment))
       if(whichArrayPlatform ==""){
              Try(tkmessageBox(title="Filtering",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())
      }    
      #########################

       ##Filtering routine
       if(whichArrayPlatform=="EXON"){
         if(affylmGUIenvironment$intronicBg.available){  
           
           Try(intronicBg <- get("intronicBg", env=affylmGUIenvironment))    
           ##making the menu for selecting intensity threshold

           Try(ttIfDialog<-tktoplevel(.affylmGUIglobals$ttMain))
           Try(tkwm.deiconify(ttIfDialog))
           Try(tkgrab.set(ttIfDialog))
           Try(tkfocus(ttIfDialog))
           Try(tkwm.title(ttIfDialog,"Filtering Options"))
           Try(tkgrid(tklabel(ttIfDialog,text="    ")))

           Try(frame1 <- tkframe(ttIfDialog,relief="groove",borderwidth=2))
           Try(HowManyQuestion1 <- tklabel(frame1,text="Intensity threshold\ni.e. the selected intronic BG",font=.affylmGUIglobals$affylmGUIfont2))
           Try(tkgrid(HowManyQuestion1))
           Try(tkgrid.configure(HowManyQuestion1,columnspan=2,sticky="w"))
           Try(thresholdTcl <- tclVar(intronicBg))
           Try(I1.but  <- tkradiobutton(frame1,text=intronicBg, variable=thresholdTcl,value=intronicBg,font=.affylmGUIglobals$affylmGUIfont2))
           Try(tkgrid(I1.but,sticky="w"))
           Try(tkgrid.configure(HowManyQuestion1,I1.but,sticky="w"))

           Try(frame2 <- tkframe(ttIfDialog,relief="groove",borderwidth=2))
           Try(fractionLabel <- tklabel(frame2,text="% of arrays above threshold",font=.affylmGUIglobals$affylmGUIfont2))
           Try(tkgrid(fractionLabel,sticky="w"))
           Try(tkgrid.configure(fractionLabel,sticky="w"))
           Try(fractionTcl <- tclVar("1"))
           Try(F1.but <- tkradiobutton(frame2,text="10%",variable=fractionTcl,value="0.1",font=.affylmGUIglobals$affylmGUIfont2))
           Try(F2.but <- tkradiobutton(frame2,text="25%",variable=fractionTcl,value="0.25",font=.affylmGUIglobals$affylmGUIfont2))
           Try(F3.but <- tkradiobutton(frame2,text="50%",variable=fractionTcl,value="0.5",font=.affylmGUIglobals$affylmGUIfont2))
           Try(F4.but <- tkradiobutton(frame2,text="75%",variable=fractionTcl,value="0.75",font=.affylmGUIglobals$affylmGUIfont2))
           Try(F5.but <- tkradiobutton(frame2,text="100%",variable=fractionTcl,value="1",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(fractionLabel,F1.but,F2.but,F3.but,F4.but,F5.but,sticky="w"))

           Try(onOK <- function()
           {
                ReturnVal1 <- as.numeric(tclvalue(thresholdTcl))
                ReturnVal2 <- as.numeric(tclvalue(fractionTcl))
                Try(ReturnVal <<- paste(ReturnVal1, ReturnVal2, sep=";"))
                Try(tkgrab.release(ttIfDialog))
                Try(tkdestroy(ttIfDialog))
                Try(tkfocus(.affylmGUIglobals$ttMain))
           })

           Try(frame3 <- tkframe(ttIfDialog,borderwidth=2))
           Try(onCancel <- function() {Try(ReturnVal <<- ""); Try(tkgrab.release(ttIfDialog));Try(tkdestroy(ttIfDialog));Try(tkfocus(.affylmGUIglobals$ttMain))})
           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(tkgrid(tklabel(frame3,text="    "),OK.but,Cancel.but,tklabel(frame3,text="    ")))

           Try(tkgrid(tklabel(ttIfDialog,text="    "),frame1,frame2,tklabel(ttIfDialog,text="  ")))
           Try(tkgrid(tklabel(ttIfDialog,text="    ")))
           Try(tkgrid(tklabel(ttIfDialog,text="    "),frame3,tklabel(ttIfDialog,text="  ")))
           Try(tkgrid(tklabel(ttIfDialog,text="    ")))
           Try(tkgrid.configure(frame1,frame3,sticky="w"))

           Try(tkfocus(ttIfDialog))
           Try(tkbind(ttIfDialog, "<Destroy>", function() {Try(tkgrab.release(ttIfDialog));Try(tkfocus(.affylmGUIglobals$ttMain));}))
           Try(tkwait.window(ttIfDialog))
           if(ReturnVal==""){return()}
                       Try(tmp <-strsplit(ReturnVal, ";"))
                       Try(fraction <- as.numeric(tmp[[1]][2]))
                       Try(threshold <- intronicBg)
                       Try(tmp1 <- paste((fraction*100), "%", sep=""))
                       Try(tmp2 <- paste("threshold", intronicBg, sep=" "))
                       Try(tmp3 <- paste(tmp1, tmp2, sep=" "))
                       Try(FilterMethod <- paste("I. filter: ", tmp3, sep=" "))
                       Try(NormalizedAffyData.Available     <- get("NormalizedAffyData.Available" , envir=affylmGUIenvironment))
                       if(NormalizedAffyData.Available) {
                            Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
                            Try(x <- get("NormalizedAffyData",envir=affylmGUIenvironment))
                            Try(f1<-pOverA(fraction, threshold))
                            Try(ff <- filterfun(f1))
                            Try(which <- genefilter(x, ff))
                            Try(par(mfrow=c(1,2)))
                            Try(text<-paste("Unfiltered probes= ", dim(exprs(x))[1], sep=""))
                            Try(hist(as.matrix(exprs(x)), main=text, breaks=100))
                            Try(text<-paste("Filtered probes= ", sum(which), sep=""))
                            Try(hist(as.matrix(exprs(x[which,])), main=text, breaks=100))
                            Try(affylmGUIenvironment$NormalizedAffyData<-x[which,])
                            Try(x.exon <- get("exonAffyData",envir=affylmGUIenvironment))
                            ####temporary saving unfiltered data
                            Try(tempUnfiltered <- tempfile(pattern = "unfiltered", tmpdir = ""))
                            Try(tempUnfiltered <- sub( "\\\\","",tempUnfiltered))
                            Try(tempUnfiltered <- sub( "/","",tempUnfiltered))
                            Try(workingDir <- getwd())
                            Try(workingDir <- sub( "/$","",workingDir))  
                            Try(tempUnfiltered <- paste(workingDir, "/", tempUnfiltered, ".rda", sep=""))
                            Try(assign("unfilteredData.location", tempUnfiltered, envir=affylmGUIenvironment))
                            Try(save(x, x.exon, file=tempUnfiltered)) 
                            ####temporary saving unfiltered data
                            Try(tkdelete(.affylmGUIglobals$mainTree,"NormalizedAffyData.Status"))
                            Try(tkinsert(.affylmGUIglobals$mainTree,"end","NormalizedAffyData","NormalizedAffyData.Status" ,text=paste("Available (",FilterMethod,")",sep=""),font=.affylmGUIglobals$affylmGUIfontTree))
                            Try(x.lib <- affylmGUIenvironment$exprConsoleLibs$exon.library)
                            Try(x.lib.subset <- x.lib[which(x.lib[,1]%in%as.numeric(featureNames(x))),3])
                            Try(x.lib.subset <- sapply(x.lib.subset ,function(x){strsplit(x, " ")}))
                            Try(x.lib.subset<-as.vector(unlist(x.lib.subset)))
                            Try(affylmGUIenvironment$exonAffyData <- x.exon[which(featureNames(x.exon)%in%x.lib.subset),])
                            Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
                       }
              } else{ Try(tkmessageBox(title="Intensity Filter for exon data",message=paste("To apply this filter you need to define an intensity threshold based on intronic data!\n Use the command oneChannelGUI: Set background threshold")))  
}        
           } else if(whichArrayPlatform=="NGS"){
                       Try(ttIfDialog<-tktoplevel(.affylmGUIglobals$ttMain))
                       Try(tkwm.deiconify(ttIfDialog))
                       Try(tkgrab.set(ttIfDialog))
                       Try(tkfocus(ttIfDialog))
                       Try(tkwm.title(ttIfDialog,"Filtering Options"))
                       Try(tkgrid(tklabel(ttIfDialog,text="    ")))

                       Try(frame1 <- tkframe(ttIfDialog,relief="groove",borderwidth=2))
                       Try(HowManyQuestion1 <- tklabel(frame1,text="Counts threshold",font=.affylmGUIglobals$affylmGUIfont2))
                       Try(tkgrid(HowManyQuestion1))
                       Try(tkgrid.configure(HowManyQuestion1,columnspan=2,sticky="w"))
                       Try(thresholdTcl <- tclVar("8"))
                       Try(I0.but  <- tkradiobutton(frame1,text="1",variable=thresholdTcl,value="1",font=.affylmGUIglobals$affylmGUIfont2))
                       Try(I1.but  <- tkradiobutton(frame1,text="4",variable=thresholdTcl,value="4",font=.affylmGUIglobals$affylmGUIfont2))
                       Try(I2.but  <- tkradiobutton(frame1,text="8",variable=thresholdTcl,value="8",font=.affylmGUIglobals$affylmGUIfont2))
                       Try(I3.but  <- tkradiobutton(frame1,text="16",variable=thresholdTcl,value="16",font=.affylmGUIglobals$affylmGUIfont2))
                       Try(I4.but  <- tkradiobutton(frame1,text="32",variable=thresholdTcl,value="32",font=.affylmGUIglobals$affylmGUIfont2))
                       Try(I5.but  <- tkradiobutton(frame1,text="64",variable=thresholdTcl,value="64",font=.affylmGUIglobals$affylmGUIfont2))
                       Try(I6.but  <- tkradiobutton(frame1,text="128",variable=thresholdTcl,value="128",font=.affylmGUIglobals$affylmGUIfont2))
                       Try(I7.but  <- tkradiobutton(frame1,text="254",variable=thresholdTcl,value="254",font=.affylmGUIglobals$affylmGUIfont2))
                       Try(tkgrid(I0.but,sticky="w"))
                       Try(tkgrid(I1.but,sticky="w"))
                       Try(tkgrid(I2.but,sticky="w"))
                       Try(tkgrid(I3.but,sticky="w"))
                       Try(tkgrid(I4.but,sticky="w"))
                       Try(tkgrid(I5.but,sticky="w"))
                       Try(tkgrid(I6.but,sticky="w"))
                       Try(tkgrid(I7.but,sticky="w"))

                       Try(tkgrid.configure(HowManyQuestion1,I0.but,I1.but,I2.but,I3.but,I4.but,I5.but,I6.but,I7.but,sticky="w"))

                       Try(frame2 <- tkframe(ttIfDialog,relief="groove",borderwidth=2))
                       Try(fractionLabel <- tklabel(frame2,text="% of samples above threshold",font=.affylmGUIglobals$affylmGUIfont2))
                       Try(tkgrid(fractionLabel,sticky="w"))
                       Try(tkgrid.configure(fractionLabel,sticky="w"))
                       Try(fractionTcl <- tclVar("0.5"))
                       Try(F1.but <- tkradiobutton(frame2,text="10%",variable=fractionTcl,value="0.1",font=.affylmGUIglobals$affylmGUIfont2))
                       Try(F2.but <- tkradiobutton(frame2,text="25%",variable=fractionTcl,value="0.25",font=.affylmGUIglobals$affylmGUIfont2))
                       Try(F3.but <- tkradiobutton(frame2,text="50%",variable=fractionTcl,value="0.5",font=.affylmGUIglobals$affylmGUIfont2))
                       Try(F4.but <- tkradiobutton(frame2,text="75%",variable=fractionTcl,value="0.75",font=.affylmGUIglobals$affylmGUIfont2))
                       Try(F5.but <- tkradiobutton(frame2,text="100%",variable=fractionTcl,value="1",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(fractionLabel,F1.but,F2.but,F3.but,F4.but,F5.but,sticky="w"))

                       Try(onOK <- function()
                       {
                            ReturnVal1 <- as.numeric(tclvalue(thresholdTcl))
                            ReturnVal2 <- as.numeric(tclvalue(fractionTcl))
                            Try(ReturnVal <<- paste(ReturnVal1, ReturnVal2, sep=";"))
                            Try(tkgrab.release(ttIfDialog))
                            Try(tkdestroy(ttIfDialog))
                            Try(tkfocus(.affylmGUIglobals$ttMain))
                       })

                       Try(frame3 <- tkframe(ttIfDialog,borderwidth=2))
                       Try(onCancel <- function() {Try(ReturnVal <<- ""); Try(tkgrab.release(ttIfDialog));Try(tkdestroy(ttIfDialog));Try(tkfocus(.affylmGUIglobals$ttMain))})
                       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(tkgrid(tklabel(frame3,text="    "),OK.but,Cancel.but,tklabel(frame3,text="    ")))

                       Try(tkgrid(tklabel(ttIfDialog,text="    "),frame1,frame2,tklabel(ttIfDialog,text="  ")))
                       Try(tkgrid(tklabel(ttIfDialog,text="    ")))
                       Try(tkgrid(tklabel(ttIfDialog,text="    "),frame3,tklabel(ttIfDialog,text="  ")))
                       Try(tkgrid(tklabel(ttIfDialog,text="    ")))
                       Try(tkgrid.configure(frame1,frame3,sticky="w"))

                       Try(tkfocus(ttIfDialog))
                       Try(tkbind(ttIfDialog, "<Destroy>", function() {Try(tkgrab.release(ttIfDialog));Try(tkfocus(.affylmGUIglobals$ttMain));}))
                       Try(tkwait.window(ttIfDialog))
                       Try(if(ReturnVal==""){return()})
                       Try(tmp<-strsplit(ReturnVal, ";"))
                       Try(fraction <- as.numeric(tmp[[1]][2]))
                       Try(threshold <- as.numeric(tmp[[1]][1]))
                       Try(tmp1 <- paste((fraction*100), "%", sep=""))
                       Try(tmp2 <- paste("threshold", as.numeric(tmp[[1]][1]), sep=" "))
                       Try(tmp3 <- paste(tmp1, tmp2, sep=" "))
                       Try(NormalizedAffyData.Available     <- get("NormalizedAffyData.Available" , envir=affylmGUIenvironment))
                       if(NormalizedAffyData.Available) {
                            Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
                            Try(x <- get("NormalizedAffyData",envir=affylmGUIenvironment))
                            ####temporary saving unfiltered data
                            Try(tempUnfiltered <- tempfile(pattern = "unfiltered", tmpdir = ""))
                            Try(tempUnfiltered <- sub( "\\\\","",tempUnfiltered))
                            Try(tempUnfiltered <- sub( "/","",tempUnfiltered))
                            Try(workingDir <- getwd())
                            Try(workingDir <- sub( "/$","",workingDir))  
                            Try(tempUnfiltered <- paste(workingDir, "/", tempUnfiltered, ".rda", sep=""))
                            Try(assign("unfilteredData.location", tempUnfiltered, envir=affylmGUIenvironment))
                            Try(save(x, file=tempUnfiltered)) 
                            ####temporary saving unfiltered data

                            Try(f1<-pOverA(fraction, threshold))
                            Try(ff <- filterfun(f1))
                            Try(which <- genefilter(x, ff))
                            Try(par(mfrow=c(1,2)))
                            Try(text<-paste("Unfiltered probes= ", dim(exprs(x))[1], sep=""))
                            Try(hist(log10(as.matrix(exprs(x))), main=text, breaks=100))
                            
                            Try(text<-paste(paste("I. filter: ", tmp3, sep=" ")," Filtered probes= ", sum(which), sep=""))
                            Try(hist(log10(as.matrix(exprs(x[which,]))), main=text, breaks=100))
                            Try(affylmGUIenvironment$NormalizedAffyData<-x[which,])
                            Try(tkdelete(.affylmGUIglobals$mainTree,"NormalizedAffyData.Status") )
                            Try(tkinsert(.affylmGUIglobals$mainTree,"end","NormalizedAffyData","NormalizedAffyData.Status" ,text=paste("Available (",paste("I. filter: ", tmp3, sep=" "),")",sep=""),font=.affylmGUIglobals$affylmGUIfontTree))
                            Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))           
                     }
             } else{
  
                       Try(ttIfDialog<-tktoplevel(.affylmGUIglobals$ttMain))
                       Try(tkwm.deiconify(ttIfDialog))
                       Try(tkgrab.set(ttIfDialog))
                       Try(tkfocus(ttIfDialog))
                       Try(tkwm.title(ttIfDialog,"Filtering Options"))
                       Try(tkgrid(tklabel(ttIfDialog,text="    ")))

                       Try(frame1 <- tkframe(ttIfDialog,relief="groove",borderwidth=2))
                       Try(HowManyQuestion1 <- tklabel(frame1,text="Intensity threshold",font=.affylmGUIglobals$affylmGUIfont2))
                       Try(tkgrid(HowManyQuestion1))
                       Try(tkgrid.configure(HowManyQuestion1,columnspan=2,sticky="w"))
                       Try(thresholdTcl <- tclVar("100"))
                       Try(I0.but  <- tkradiobutton(frame1,text="log2(1)=0",variable=thresholdTcl,value="1",font=.affylmGUIglobals$affylmGUIfont2))
                       Try(I1.but  <- tkradiobutton(frame1,text="log2(50)=5.64",variable=thresholdTcl,value="50",font=.affylmGUIglobals$affylmGUIfont2))
                       Try(I2.but  <- tkradiobutton(frame1,text="log2(100)=6.64",variable=thresholdTcl,value="100",font=.affylmGUIglobals$affylmGUIfont2))
                       Try(I3.but  <- tkradiobutton(frame1,text="log2(150)=7.22",variable=thresholdTcl,value="150",font=.affylmGUIglobals$affylmGUIfont2))
                       Try(I4.but  <- tkradiobutton(frame1,text="log2(200)=7.64",variable=thresholdTcl,value="200",font=.affylmGUIglobals$affylmGUIfont2))
                       Try(tkgrid(I0.but,sticky="w"))
                       Try(tkgrid(I1.but,sticky="w"))
                       Try(tkgrid(I2.but,sticky="w"))
                       Try(tkgrid(I3.but,sticky="w"))
                       Try(tkgrid(I4.but,sticky="w"))
                       Try(tkgrid.configure(HowManyQuestion1,I0.but,I1.but,I2.but,I3.but,I4.but,sticky="w"))

                       Try(frame2 <- tkframe(ttIfDialog,relief="groove",borderwidth=2))
                       Try(fractionLabel <- tklabel(frame2,text="% of arrays above threshold",font=.affylmGUIglobals$affylmGUIfont2))
                       Try(tkgrid(fractionLabel,sticky="w"))
                       Try(tkgrid.configure(fractionLabel,sticky="w"))
                       Try(fractionTcl <- tclVar("1"))
                       Try(F1.but <- tkradiobutton(frame2,text="10%",variable=fractionTcl,value="0.1",font=.affylmGUIglobals$affylmGUIfont2))
                       Try(F2.but <- tkradiobutton(frame2,text="25%",variable=fractionTcl,value="0.25",font=.affylmGUIglobals$affylmGUIfont2))
                       Try(F3.but <- tkradiobutton(frame2,text="50%",variable=fractionTcl,value="0.5",font=.affylmGUIglobals$affylmGUIfont2))
                       Try(F4.but <- tkradiobutton(frame2,text="75%",variable=fractionTcl,value="0.75",font=.affylmGUIglobals$affylmGUIfont2))
                       Try(F5.but <- tkradiobutton(frame2,text="100%",variable=fractionTcl,value="1",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(fractionLabel,F1.but,F2.but,F3.but,F4.but,F5.but,sticky="w"))

                       Try(onOK <- function()
                       {
                            Try(ReturnVal1 <- as.numeric(tclvalue(thresholdTcl)))
                            Try(ReturnVal2 <- as.numeric(tclvalue(fractionTcl)))
                            Try(ReturnVal <<- paste(ReturnVal1, ReturnVal2, sep=";"))
                            Try(tkgrab.release(ttIfDialog))
                            Try(tkdestroy(ttIfDialog))
                            Try(tkfocus(.affylmGUIglobals$ttMain))
                       })

                       Try(frame3 <- tkframe(ttIfDialog,borderwidth=2))
                       Try(onCancel <- function() {Try(ReturnVal <<- ""); Try(tkgrab.release(ttIfDialog));Try(tkdestroy(ttIfDialog));Try(tkfocus(.affylmGUIglobals$ttMain))})
                       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(tkgrid(tklabel(frame3,text="    "),OK.but,Cancel.but,tklabel(frame3,text="    ")))

                       Try(tkgrid(tklabel(ttIfDialog,text="    "),frame1,frame2,tklabel(ttIfDialog,text="  ")))
                       Try(tkgrid(tklabel(ttIfDialog,text="    ")))
                       Try(tkgrid(tklabel(ttIfDialog,text="    "),frame3,tklabel(ttIfDialog,text="  ")))
                       Try(tkgrid(tklabel(ttIfDialog,text="    ")))
                       Try(tkgrid.configure(frame1,frame3,sticky="w"))

                       Try(tkfocus(ttIfDialog))
                       Try(tkbind(ttIfDialog, "<Destroy>", function() {Try(tkgrab.release(ttIfDialog));Try(tkfocus(.affylmGUIglobals$ttMain));}))
                       Try(tkwait.window(ttIfDialog))
                       Try(if(ReturnVal==""){return()})
                       Try(tmp<-strsplit(ReturnVal, ";"))
                       Try(fraction <- as.numeric(tmp[[1]][2]))
                       Try(threshold <- log2(as.numeric(tmp[[1]][1])))
                       Try(tmp1 <- paste((fraction*100), "%", sep=""))
                       Try(tmp2 <- paste("threshold", as.numeric(tmp[[1]][1]), sep=" "))
                       Try(tmp3 <- paste(tmp1, tmp2, sep=" "))
                       Try(FilterMethod <- paste("I. filter: ", tmp3, sep=" "))
                       Try(NormalizedAffyData.Available     <- get("NormalizedAffyData.Available" , envir=affylmGUIenvironment))
                       if(NormalizedAffyData.Available) {
                            Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
                            Try(x <- get("NormalizedAffyData",envir=affylmGUIenvironment))
                            ####temporary saving unfiltered data
                            Try(tempUnfiltered <- tempfile(pattern = "unfiltered", tmpdir = ""))
                            Try(tempUnfiltered <- sub( "\\\\","",tempUnfiltered))
                            Try(tempUnfiltered <- sub( "/","",tempUnfiltered))
                            Try(workingDir <- getwd())
                            Try(workingDir <- sub( "/$","",workingDir))  
                            Try(tempUnfiltered <- paste(workingDir, "/", tempUnfiltered, ".rda", sep=""))
                            Try(assign("unfilteredData.location", tempUnfiltered, envir=affylmGUIenvironment))
                            Try(save(x, file=tempUnfiltered)) 
                            ####temporary saving unfiltered data

                            Try(f1<-pOverA(fraction, threshold))
                            Try(ff <- filterfun(f1))
                            Try(which <- genefilter(x, ff))
                            Try(par(mfrow=c(1,2)) )
                            Try(text<-paste("Unfiltered probes= ", dim(exprs(x))[1], sep=""))
                            Try(hist(as.matrix(exprs(x)), main=text, breaks=100))
                            Try(text<-paste("Filtered probes= ", sum(which), sep=""))
                            Try(hist(as.matrix(exprs(x[which,])), main=text, breaks=100))
                            Try(affylmGUIenvironment$NormalizedAffyData<-x[which,])
                            Try(tkdelete(.affylmGUIglobals$mainTree,"NormalizedAffyData.Status"))
                            Try(tkinsert(.affylmGUIglobals$mainTree,"end","NormalizedAffyData","NormalizedAffyData.Status" ,text=paste("Available (",FilterMethod,")",sep=""),font=.affylmGUIglobals$affylmGUIfontTree))
                            Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))           
                     }
             }
}
################################################################################

# Expression data are filtered on the basis of a list of affy ids
#performs filter also on exon data
"listFilter"<-function(){
          #error if no data are loaded
          Try(whichArrayPlatform <- get("whichArrayPlatform",envir=affylmGUIenvironment))
          if(whichArrayPlatform ==""){
              Try(tkmessageBox(title="Filtering",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())
          }    
          #########################
 
        Try(tkmessageBox(title="Filtering by list",message="Open the file containing the list of probe sets to be used for filtering"))
        Try(whichArrayPlatform <- get("whichArrayPlatform", env=affylmGUIenvironment))
        if(whichArrayPlatform=="AFFY" || whichArrayPlatform=="LARGE" || whichArrayPlatform=="ILLU" || whichArrayPlatform=="NGS" || whichArrayPlatform=="GENE") {
            OpenAFile <- function(FileName)
            {
               Try(tempFileName <- tclvalue(tkgetOpenFile(filetypes="{{Text Files} {.txt}} {{All files} *}")))
               if(!nchar(tempFileName))
               {
                  tkfocus(.affylmGUIglobals$ttMain)
                  return()
               }
               mySel<-read.table(tempFileName, sep="\t", header=F, as.is=TRUE)
               if(dim(mySel)[2]==1){
                    Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
                    Try(x <- get("NormalizedAffyData", envir= affylmGUIenvironment))
                            ####temporary saving unfiltered data
                            tempUnfiltered <- tempfile(pattern = "unfiltered", tmpdir = "")
                            tempUnfiltered <- sub( "\\\\","",tempUnfiltered)
                            tempUnfiltered <- sub( "/","",tempUnfiltered)
                            workingDir <- getwd()
                            workingDir <- sub( "/$","",workingDir)  
                            tempUnfiltered <- paste(workingDir, "/", tempUnfiltered, ".rda", sep="")
                    Try(assign("unfilteredData.location", tempUnfiltered, envir=affylmGUIenvironment))
                    Try(save(x, file=tempUnfiltered)) 
                    ####temporary saving unfiltered data

                    affylmGUIenvironment$NormalizedAffyData<-affylmGUIenvironment$NormalizedAffyData[which(featureNames(affylmGUIenvironment$NormalizedAffyData)%in%as.character(mySel[,1])),]
                    Try(NormalizedAffyData.Available     <- get("NormalizedAffyData.Available" , envir=affylmGUIenvironment))
                    Try(if(NormalizedAffyData.Available){
                                Try(tkdelete(.affylmGUIglobals$mainTree,"NormalizedAffyData.Status"))
                                Try(tkinsert(.affylmGUIglobals$mainTree,"end","NormalizedAffyData","NormalizedAffyData.Status" ,text="Available list filtered",font=.affylmGUIglobals$affylmGUIfontTree))
                         })
               Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
               Try(tkmessageBox(title="Filtering by list",message=paste("Normalized Affy Data data is now made of ", dim(exprs(affylmGUIenvironment$NormalizedAffyData))[1]," probe sets",sep="")))

               } else Try(tkmessageBox(title="Filtering by list",message="Filter file should contain\nonly a column with\nAffymetrix ids", type="ok", icon="error"))  

            }
            OpenAFile()
      }
      if(whichArrayPlatform=="EXON") {
            OpenAFile <- function(FileName)
            {
               Try(tempFileName <- tclvalue(tkgetOpenFile(filetypes="{{Text Files} {.txt}} {{All files} *}")))
               if(!nchar(tempFileName))
               {
                  tkfocus(.affylmGUIglobals$ttMain)
                  return()
               }
               mySel<-read.table(tempFileName, sep="\t", header=F, as.is=TRUE)
               if(dim(mySel)[2]==1){
                    
                    Try(x <- get("NormalizedAffyData", envir= affylmGUIenvironment))
                    Try(x.exon <- get("exonAffyData",envir=affylmGUIenvironment))
                            ####temporary saving unfiltered data
                            tempUnfiltered <- tempfile(pattern = "unfiltered", tmpdir = "")
                            tempUnfiltered <- sub( "\\\\","",tempUnfiltered)
                            tempUnfiltered <- sub( "/","",tempUnfiltered)
                            workingDir <- getwd()
                            workingDir <- sub( "/$","",workingDir)  
                            tempUnfiltered <- paste(workingDir, "/", tempUnfiltered, ".rda", sep="")
                    Try(assign("unfilteredData.location", tempUnfiltered, envir=affylmGUIenvironment))
                    Try(save(x, x.exon, file=tempUnfiltered)) 
                    ####temporary saving unfiltered data

                    affylmGUIenvironment$NormalizedAffyData<-affylmGUIenvironment$NormalizedAffyData[which(featureNames(affylmGUIenvironment$NormalizedAffyData)%in%as.character(mySel[,1])),]
                    Try(NormalizedAffyData.Available     <- get("NormalizedAffyData.Available" , envir=affylmGUIenvironment))

                    Try(x.lib <- affylmGUIenvironment$exprConsoleLibs$exon.library)
                    Try(x.lib.subset <- x.lib[which(x.lib[,1]%in%featureNames(affylmGUIenvironment$NormalizedAffyData)),3]) #in the list obtained from NetAffx there are all the probe set ids and I have to subset only those related to the exon library loaded with the data set
                    Try(x.lib.subset <- sapply(x.lib.subset ,function(x){strsplit(x, " ")}))
                    Try(x.lib.subset<-as.vector(unlist(x.lib.subset)))
                    Try(affylmGUIenvironment$exonAffyData <- x.exon[which(featureNames(x.exon)%in%x.lib.subset),])


                    Try(if(NormalizedAffyData.Available){
                                Try(tkdelete(.affylmGUIglobals$mainTree,"NormalizedAffyData.Status"))
                                Try(tkinsert(.affylmGUIglobals$mainTree,"end","NormalizedAffyData","NormalizedAffyData.Status" ,text="Available list filtered",font=.affylmGUIglobals$affylmGUIfontTree))
                         })
               Try(tkmessageBox(title="Filtering by list",message=paste("Normalized Affy Data data is now made of ", dim(exprs(affylmGUIenvironment$NormalizedAffyData))[1]," probe sets",sep="")))

               } else Try(tkmessageBox(title="Filtering by list",message="Filter file should contain\nonly a column with\nAffymetrix ids", type="ok", icon="error"))  

            }
            OpenAFile()
      }

}
################################################################################

# Expression data are filtered on the basis of a list exported by IPA Ingenuity
"IPAlistFilter"<-function(){
 #     require(annotate) || stop("library annotate could not be found !")
     #error if no data are loaded
     Try(whichArrayPlatform <- get("whichArrayPlatform",envir=affylmGUIenvironment))
     if(whichArrayPlatform ==""){
              Try(tkmessageBox(title="Filtering",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())
    }    
    #########################

    # getDataEnv <- function(name, lib) {
    #    	            get(paste(lib, name, sep = ""), mode = "environment")
    # }
     Try(NormalizedAffyData.Available <- get("NormalizedAffyData.Available", env=affylmGUIenvironment))
     if((whichArrayPlatform=="AFFY" & NormalizedAffyData.Available)|| (whichArrayPlatform=="LARGE" & NormalizedAffyData.Available) || (whichArrayPlatform=="ILLU" & NormalizedAffyData.Available)) {
            Try(x <- get("NormalizedAffyData", env=affylmGUIenvironment))
                            ####temporary saving unfiltered data
                            tempUnfiltered <- tempfile(pattern = "unfiltered", tmpdir = "")
                            tempUnfiltered <- sub( "\\\\","",tempUnfiltered)
                            tempUnfiltered <- sub( "/","",tempUnfiltered)
                            workingDir <- getwd()
                            workingDir <- sub( "/$","",workingDir)  
                            tempUnfiltered <- paste(workingDir, "/", tempUnfiltered, ".rda", sep="")
                    Try(assign("unfilteredData.location", tempUnfiltered, envir=affylmGUIenvironment))
                    Try(save(x, file=tempUnfiltered)) 
                    ####temporary saving unfiltered data
            Try(lib <- .annotation(x))
            if(length(as.character(unlist(strsplit(lib, "\\.")))) < 2 ){
              lib <- paste(lib, ".db", sep="")     
            }   
            require(lib, character.only = TRUE) || {
                             Try(tkmessageBox(title="Filtering by Entrez Gene list",message=paste("need data package: ", lib, sep=" ")))
                             stop("need data package: ", lib)
            }
            Try(tkmessageBox(title="Filtering by EG list",message="Open the file containing a set of Entrez Gene IDs"))
            Try(tempFileName <- tclvalue(tkgetOpenFile(filetypes="{{Text Files} {.txt}} {{All files} *}")))
               if(!nchar(tempFileName))
               {
                  tkfocus(.affylmGUIglobals$ttMain)
                  return()
               }
               mySel<-read.table(tempFileName, sep="\t", header=F, as.is=TRUE, na.string="", quote="")
               if(dim(mySel)[2]==1){
                    Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
                     Try(annlib1 <- as.character(unlist(strsplit(lib, ".db"))))
                     Try(gNsel <- lookUp(featureNames(x), annlib1, "ENTREZID"))
                     Try(sub.gNsel <- gNsel[which(gNsel %in% as.character(mySel[,1]))])
                     x <- x[which(featureNames(x)%in%names(sub.gNsel)),]
                     assign("NormalizedAffyData", x, env=affylmGUIenvironment)
                     Try(tkdelete(.affylmGUIglobals$mainTree,"NormalizedAffyData.Status"))
                     Try(tkinsert(.affylmGUIglobals$mainTree,"end","NormalizedAffyData","NormalizedAffyData.Status" ,text="Available EG list filtered",font=.affylmGUIglobals$affylmGUIfontTree))
                     Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
                     Try(tkmessageBox(title="Filtering by EG list",message=paste("Normalized Affy Data data is now made of ", dim(exprs(affylmGUIenvironment$NormalizedAffyData))[1]," probe sets",sep="")))

               } else Try(tkmessageBox(title="Filtering by EG list",message="Filter file should contain only an column of Entrez genes without header", type="ok", icon="error"))  


    } else if (whichArrayPlatform=="EXON" & NormalizedAffyData.Available){
            Try(tkmessageBox(title="Filtering by EG list",message="Open the file containing a set of Entrez Gene IDs"))
            Try(tempFileName <- tclvalue(tkgetOpenFile(filetypes="{{Text Files} {.txt}} {{All files} *}")))
               if(!nchar(tempFileName))
               {
                  tkfocus(.affylmGUIglobals$ttMain)
                  return()
               }
               mySel<-read.table(tempFileName, sep="\t", header=F, as.is=TRUE, na.string="", quote="")
               if(dim(mySel)[2]==1){
                    Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
                    Try(x <- get("NormalizedAffyData", env=affylmGUIenvironment))
                    Try(x.exon <- get("exonAffyData",envir=affylmGUIenvironment))
                            ####temporary saving unfiltered data
                            tempUnfiltered <- tempfile(pattern = "unfiltered", tmpdir = "")
                            tempUnfiltered <- sub( "\\\\","",tempUnfiltered)
                            tempUnfiltered <- sub( "/","",tempUnfiltered)
                            workingDir <- getwd()
                            workingDir <- sub( "/$","",workingDir)  
                            tempUnfiltered <- paste(workingDir, "/", tempUnfiltered, ".rda", sep="")
                    Try(assign("unfilteredData.location", tempUnfiltered, envir=affylmGUIenvironment))
                    Try(save(x, x.exon, file=tempUnfiltered)) 
                    ####temporary saving unfiltered data
                   
                    Try(whichLib <- get("whichLib",envir=affylmGUIenvironment))
                    #Try(annlibloc <- grep(paste("^",whichLib[[1]][1],sep=""), as.vector(unlist(data(package="oneChannelGUI"))), ignore.case = T))
                    Try(if(whichLib[[1]][1]=="HuEx"){
                            #require(humanLLMappings) || stop("library humanLLMappings could not be found !")
                            #lib <- "humanLLMappings"
                        #    require(org.Hs.eg.db, quietly = TRUE) || stop("\nneed data package: org.Hs.eg.db\n")
                            lib = "org.Hs.eg.db"
                    })
                    Try(if(whichLib[[1]][1]=="MoEx"){
                            #require(mouseLLMappings) || stop("library mouseLLMappings could not be found !")
                            #lib <- "mouseLLMappings"
                      #      require(org.Mm.eg.db, quietly = TRUE) || stop("\nneed data package: org.Mm.eg.db\n")
                            lib = "org.Mm.eg.db"
                   })
                    Try(if(whichLib[[1]][1]=="RaEx"){
                            #require(ratLLMappings) || stop("library ratLLMappings could not be found !")
                            #lib <- "ratLLMappings"
                       #     require(org.Rn.eg.db, quietly = TRUE) || stop("\nneed data package: org.Rn.eg.db\n")
                            lib = "org.Rn.eg.db"
                   })
                    #Try(annlibname <- as.vector(unlist(data(package="oneChannelGUI")))[annlibloc])
                    #Try(data(list=annlibname,package="oneChannelGUI"))
                    #Try(exonannlib <- get(annlibname,envir=.GlobalEnv))
                    if(whichLib[[1]][1] == "HuEx"){
                        Try(libDirLocation <- get("libDirLocation", envir=affylmGUIenvironment))
                        Try(load(paste(libDirLocation, "huex.annotation.rda", sep="/")))
                        Try(exonannlib <- huex.annotation)
                        Try(rm(huex.annotation))
                    }else if(whichLib[[1]][1] == "MoEx"){
                        Try(libDirLocation <- get("libDirLocation", envir=affylmGUIenvironment))
                        Try(load(paste(libDirLocation, "moex.annotation.rda", sep="/")))
                        Try(exonannlib <- moex.annotation)
                        Try(rm(moex.annotation))
                    }else if(whichLib[[1]][1] == "RaEx"){
                        Try(libDirLocation <- get("libDirLocation", envir=affylmGUIenvironment))
                        Try(load(paste(libDirLocation, "raex.annotation.rda", sep="/")))
                        Try(exonannlib <- raex.annotation)
                        Try(rm(raex.annotation))
                    }
   
                    Try(myrefseq <- as.character(exonannlib[which(as.character(exonannlib[,1])%in%featureNames(x)),2]))#selecting the refseq associated to the gene probesetids
                    #Try(gNacc <- as.character(unlist(mget(as.character(mySel[,1]), env=getDataEnv("LL2ACCNUM", lib), ifnotfound=NA))))#select refseq associated to EG            
                    Try(gNacc <- as.character(unlist(lookUp(as.character(mySel[,1]), lib, "ACCNUM"))))
                    Try(sub.gNacc <- intersect(gNacc,myrefseq))
                    Try(sub.gNacc <- sub.gNacc[!is.na(sub.gNacc )])
                    Try(sub.probeset <- as.character(exonannlib[which(as.character(exonannlib[,2])%in%sub.gNacc),1]))
                    Try(x <- x[which(featureNames(x)%in%sub.probeset),])
     
                    Try(x.lib <- affylmGUIenvironment$exprConsoleLibs$exon.library)
                    Try(x.lib.subset <- x.lib[which(x.lib[,1]%in%as.numeric(featureNames(x))),3])
                    Try(x.lib.subset <- sapply(x.lib.subset ,function(x){strsplit(x, " ")}))
                    Try(x.lib.subset<-as.vector(unlist(x.lib.subset)))
                    Try(x.exon <- x.exon[which(featureNames(x.exon)%in%x.lib.subset),])
     
                    Try(assign("NormalizedAffyData", x, envir=affylmGUIenvironment))
                    Try(assign("exonAffyData", x.exon, envir=affylmGUIenvironment))
                    Try(tkdelete(.affylmGUIglobals$mainTree,"NormalizedAffyData.Status"))
                    Try(tkinsert(.affylmGUIglobals$mainTree,"end","NormalizedAffyData","NormalizedAffyData.Status" ,text="Available EG list filtered",font=.affylmGUIglobals$affylmGUIfontTree))
                    Try(tkdelete(.affylmGUIglobals$mainTree,"ExonArrays.Status"))
                    Try(tkinsert(.affylmGUIglobals$mainTree,"end","ExonArrays","ExonArrays.Status" ,text="Available EG list filtered",font=.affylmGUIglobals$affylmGUIfontTree))
                    Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
                    Try(tkmessageBox(title="Filtering by EG list",message=paste("Normalized gene level data is now made of ", dim(exprs(x))[1]," probe sets","\nNormalized exon level data is now made of ", dim(exprs(x.exon))[1]," probe sets",sep="")))

               } else Try(tkmessageBox(title="Filtering by EG list",message="Filter file should contain only an column of Entrez genes without header", type="ok", icon="error"))  
    
    
    } else if(!NormalizedAffyData.Available){
          Try(tkmessageBox(title="Filtering by Probe set list",message="Normalized data are not available!", type="ok", icon="error"))
          Try(tkfocus(.affylmGUIglobals$ttMain))
          return()  
    }

}
################################################################################

#this function calculate the density distribution for exon (positive) and intron (negative controls) of the controls
#and allows the user to define a background threshold to be used fgor filtering
"intronicBg" <- function(){
     #error if no data are loaded
     Try(whichArrayPlatform <- get("whichArrayPlatform",envir=affylmGUIenvironment))
     if(whichArrayPlatform ==""){
              Try(tkmessageBox(title="Filtering",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())
    } else if(whichArrayPlatform!="EXON"){
              Try(tkmessageBox(title="Filtering",message="This filter routine apply only to EXON arrays.",type="ok",icon="error"))
				    	Try(tkfocus(.affylmGUIglobals$ttMain))
              Try(return())
    
    }    
    #########################
      
      Try( ctrl <- affylmGUIenvironment$exprConsoleLibs$controls)#get control info
      Try( exonAffyData <- get("exonAffyData",envir=affylmGUIenvironment) )
      
      #check if ctrl aare still available and not removed by other filters
      Try(test <- intersect(featureNames(exonAffyData),ctrl[,1]))
      if(length(ctrl[,1]) != length(test)){
            Try(tkmessageBox(title="Intronic BG",message="The EXON and INTRON data for Housekeeping genes\nwere removed by some other filtering procedure.\nThis method can be applied only to the unfiltered data set.",type="ok",icon="error"))
	    	    Try(tkfocus(.affylmGUIglobals$ttMain))
             Try(return()) 
      }
      ###################################
      
      
      Try(exonAffyData.neg <- exonAffyData[which(featureNames(exonAffyData)%in%ctrl[which(ctrl[,2]=="neg_control"),1]),])
      Try(exonAffyData.pos <- exonAffyData[which(featureNames(exonAffyData)%in%ctrl[which(ctrl[,2]=="pos_control"),1]),])
      Try(plotDensity(as.matrix(exprs(exonAffyData.neg))))
      Try(legend(min(plotDensity(as.matrix(exprs(exonAffyData.neg)))$all.x),max(plotDensity(as.matrix(exprs(exonAffyData.neg)))$all.y), legend=c("Introns","Exons"), col=c("black","red"), pch=19))
      Try(plotDensity(as.matrix(exprs(exonAffyData.neg)), col="black", add=T))
      Try(plotDensity(as.matrix(exprs(exonAffyData.pos)), col="red", add=T))

      #selecting the BG threshold
                 Try(ttIntronicBg<-tktoplevel(.affylmGUIglobals$ttMain))
                 Try(tkwm.deiconify(ttIntronicBg))
                 Try(tkgrab.set(ttIntronicBg))
                 Try(tkfocus(ttIntronicBg))
                 Try(tkwm.title(ttIntronicBg,"Defining the BG threshold for filtering"))
                 Try(tkgrid(tklabel(ttIntronicBg,text="    ")))
                 Try(IntronicBgnum <- "6.64")
                 Try(Local.IntronicBg <- tclVar(init=IntronicBgnum))
                 Try(entry.IntronicBg <-tkentry(ttIntronicBg,width="4",font=.affylmGUIglobals$affylmGUIfont2,textvariable=Local.IntronicBg,bg="white"))
                 Try(tkgrid(tklabel(ttIntronicBg,text="Please enter a BG threshold.",font=.affylmGUIglobals$affylmGUIfont2)))
                 Try(tkgrid(entry.IntronicBg))
                 onOK <- function()
                 {
                     Try(IntronicBgnum <- as.numeric(tclvalue(Local.IntronicBg)))
                     Try(assign("intronicBg", as.numeric(tclvalue(Local.IntronicBg)),affylmGUIenvironment))
			               Try(assign("intronicBg.available", TRUE,affylmGUIenvironment))
 #                    Try(tclvalue(.affylmGUIglobals$IntronicBgTcl) <- IntronicBgnum)
                     Try(tkgrab.release(ttIntronicBg));Try(tkdestroy(ttIntronicBg));Try(tkfocus(.affylmGUIglobals$ttMain))                        
                 }
                 Try(OK.but <-tkbutton(ttIntronicBg,text="   OK   ",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
                 Try(tkgrid(tklabel(ttIntronicBg,text="    ")))
                 Try(tkgrid(OK.but))
                 Try(tkgrid.configure(OK.but))
                 Try(tkgrid(tklabel(ttIntronicBg,text="       ")))
                 Try(tkfocus(entry.IntronicBg))
                 Try(tkbind(entry.IntronicBg, "<Return>",onOK))
                 Try(tkbind(ttIntronicBg, "<Destroy>", function(){Try(tkgrab.release(ttIntronicBg));Try(tkfocus(.affylmGUIglobals$ttMain));return(0)}))
                 Try(tkwait.window(ttIntronicBg))
                 Try(tkfocus(.affylmGUIglobals$ttMain))
                 Try(IntronicBgnum <- get("intronicBg", env=affylmGUIenvironment))
                 Try(abline(v=as.numeric(IntronicBgnum), lty=2))
                 Try(tkmessageBox(title="BG threshold",message="The selected filtering threshold is shown by a dashed line in the main R window",type="ok",icon="info"))
}
################################################################################

#this function change very low log2 intesities values to 0 this is expecialy usefull for plier data
"plierToZero"<-function(){
           #error if no data are loaded
           Try(whichArrayPlatform <- get("whichArrayPlatform",envir=affylmGUIenvironment))
           if(whichArrayPlatform ==""){
              Try(tkmessageBox(title="Filtering",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())
           }    
           #########################

            Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
            Try(NormalizedAffyData.Available <- get("NormalizedAffyData.Available", env=affylmGUIenvironment))
            Try(exonAffyData.Available <- get("exonAffyData.Available", env=affylmGUIenvironment))
            
            if(NormalizedAffyData.Available & exonAffyData.Available){
               Try(NormalizedAffyData <- get("NormalizedAffyData", env=affylmGUIenvironment))
               Try(tmp <- esApply(NormalizedAffyData, 1, function(x){
                                                              x[which(x < 1)] <- 0
                                                              return(x)}
                         )
               )
               Try(exprs(NormalizedAffyData) <- as.matrix(t(tmp)))
               Try(assign("NormalizedAffyData", NormalizedAffyData, env=affylmGUIenvironment))
               Try(exonAffyData <- get("exonAffyData", env=affylmGUIenvironment))
               Try(tmp <- esApply(exonAffyData, 1, function(x){
                                                              x[which(x < 1)] <- 0
                                                              return(x)}
                         )
               )
               Try(exprs(exonAffyData) <- as.matrix(t(tmp)))
                Try(assign("exonAffyData", exonAffyData, env=affylmGUIenvironment))
                Try(tkmessageBox(title="Plier very low values",message="Log2 intensity values below 1 were converted to 0"))
            } else{
                       Try(tkmessageBox(title="Plier very low values",message="These are not exon array data")) 
            }
            Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))          
}
################################################################################

# Expression data are filtered on the basis of a list exported by IPA Ingenuity
"dabgFilter"<-function(){
  #   require(genefilter) || stop("library genefilter could not be found !")
     #error if no data are loaded
     Try(whichArrayPlatform <- get("whichArrayPlatform",envir=affylmGUIenvironment))
     if(whichArrayPlatform ==""){
              Try(tkmessageBox(title="Filtering",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())
    }    
    #########################

     Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
     Try(dabg.Available <- get("dabg.Available", env=affylmGUIenvironment))
     Try(exonAffyData.Available <- get("exonAffyData.Available", env=affylmGUIenvironment))
     if(dabg.Available & exonAffyData.Available){
                       Try(ttIfDialog<-tktoplevel(.affylmGUIglobals$ttMain))
                       Try(tkwm.deiconify(ttIfDialog))
                       Try(tkgrab.set(ttIfDialog))
                       Try(tkfocus(ttIfDialog))
                       Try(tkwm.title(ttIfDialog,"Filtering Options"))
                       Try(tkgrid(tklabel(ttIfDialog,text="    ")))

                       Try(frame1 <- tkframe(ttIfDialog,relief="groove",borderwidth=2))
                       Try(HowManyQuestion1 <- tklabel(frame1,text="DABG p-value threshold",font=.affylmGUIglobals$affylmGUIfont2))
                       Try(tkgrid(HowManyQuestion1))
                       Try(tkgrid.configure(HowManyQuestion1,columnspan=2,sticky="w"))
                       Try(thresholdTcl <- tclVar("0.05"))
                       Try(I1.but  <- tkradiobutton(frame1,text="0.05",variable=thresholdTcl,value="0.05",font=.affylmGUIglobals$affylmGUIfont2))
                       Try(I2.but  <- tkradiobutton(frame1,text="0.01",variable=thresholdTcl,value="0.01",font=.affylmGUIglobals$affylmGUIfont2))
                       Try(I3.but  <- tkradiobutton(frame1,text="0.005",variable=thresholdTcl,value="0.005",font=.affylmGUIglobals$affylmGUIfont2))
                       Try(I4.but  <- tkradiobutton(frame1,text="0.001",variable=thresholdTcl,value="0.001",font=.affylmGUIglobals$affylmGUIfont2))

                       Try(tkgrid(I1.but,sticky="w"))
                       Try(tkgrid(I2.but,sticky="w"))
                       Try(tkgrid(I3.but,sticky="w"))
                       Try(tkgrid(I4.but,sticky="w"))
                       Try(tkgrid.configure(HowManyQuestion1,I1.but,I2.but,I3.but,I4.but,sticky="w"))

                       Try(frame2 <- tkframe(ttIfDialog,relief="groove",borderwidth=2))
                       Try(fractionLabel <- tklabel(frame2,text="% of arrays below threshold",font=.affylmGUIglobals$affylmGUIfont2))
                       Try(tkgrid(fractionLabel,sticky="w"))
                       Try(tkgrid.configure(fractionLabel,sticky="w"))
                       Try(fractionTcl <- tclVar("0.5"))
                       Try(F1.but <- tkradiobutton(frame2,text="100%",variable=fractionTcl,value="1",font=.affylmGUIglobals$affylmGUIfont2))
                       Try(F2.but <- tkradiobutton(frame2,text="75%",variable=fractionTcl,value="0.75",font=.affylmGUIglobals$affylmGUIfont2))
                       Try(F3.but <- tkradiobutton(frame2,text="50%",variable=fractionTcl,value="0.5",font=.affylmGUIglobals$affylmGUIfont2))
                       Try(F4.but <- tkradiobutton(frame2,text="25%",variable=fractionTcl,value="0.25",font=.affylmGUIglobals$affylmGUIfont2))
                       Try(F5.but <- tkradiobutton(frame2,text="10%",variable=fractionTcl,value="0.1",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(fractionLabel,F1.but,F2.but,F3.but,F4.but,F5.but,sticky="w"))

                       Try(onOK <- function()
                       {
                            ReturnVal1 <- as.numeric(tclvalue(thresholdTcl))
                            ReturnVal2 <- as.numeric(tclvalue(fractionTcl))
                            Try(ReturnVal <<- paste(ReturnVal1, ReturnVal2, sep=";"))
                            Try(tkgrab.release(ttIfDialog))
                            Try(tkdestroy(ttIfDialog))
                            Try(tkfocus(.affylmGUIglobals$ttMain))
                       })

                       Try(frame3 <- tkframe(ttIfDialog,borderwidth=2))
                       Try(onCancel <- function() {Try(ReturnVal <<- ""); Try(tkgrab.release(ttIfDialog));Try(tkdestroy(ttIfDialog));Try(tkfocus(.affylmGUIglobals$ttMain))})
                       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(tkgrid(tklabel(frame3,text="    "),OK.but,Cancel.but,tklabel(frame3,text="    ")))

                       Try(tkgrid(tklabel(ttIfDialog,text="    "),frame1,frame2,tklabel(ttIfDialog,text="  ")))
                       Try(tkgrid(tklabel(ttIfDialog,text="    ")))
                       Try(tkgrid(tklabel(ttIfDialog,text="    "),frame3,tklabel(ttIfDialog,text="  ")))
                       Try(tkgrid(tklabel(ttIfDialog,text="    ")))
                       Try(tkgrid.configure(frame1,frame3,sticky="w"))

                       Try(tkfocus(ttIfDialog))
                       Try(tkbind(ttIfDialog, "<Destroy>", function() {Try(tkgrab.release(ttIfDialog));Try(tkfocus(.affylmGUIglobals$ttMain));}))
                       Try(tkwait.window(ttIfDialog))
                       if(ReturnVal==""){
                            Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
                            Try(return())
                       }
                       Try(tmp<-strsplit(ReturnVal, ";"))
                       Try(fraction <- as.numeric(tmp[[1]][2]))
                       Try(threshold <- as.numeric(tmp[[1]][1]))
                       Try(tmp1 <- paste((fraction*100), "%", sep=""))
                       Try(tmp2 <- paste("threshold", as.numeric(tmp[[1]][1]), sep=" "))
                       Try(tmp3 <- paste(tmp1, tmp2, sep=" "))
                       Try(FilterMethod <- paste("DABG filter: ", tmp3, sep=" "))
                       Try(x <- get("NormalizedAffyData",envir=affylmGUIenvironment))
                       Try(x.exon <- get("exonAffyData", env=affylmGUIenvironment))
                       Try(x.p <- get("dabg.p",envir=affylmGUIenvironment))
                       
                       #f1<-pOverA(fraction, threshold)
                       #ff <- filterfun(f1)
                       #which <- genefilter(x.p, ff)
                       #selected.names <- setdiff(featureNames(x), featureNames(x)[which])
                       #selected.names <- featureNames(x)[which] #these are those data I want to remove
                       myfilter <- function(x, fraction, threshold){
                                tested <- length(which(x <= threshold))
                                ref <- length(x) * fraction
                                if(tested >= ref) return(TRUE) else return(FALSE)    
                       }
                       Try(which <- esApply(x.p, 1, myfilter, fraction=fraction, threshold=threshold))
                       Try(selected.names <- featureNames(x.p)[which])
                       Try(selected.names <- intersect(featureNames(x), selected.names))
                       Try(tkmessageBox(title="DABG filter",message=paste("DABG filtering plots will be displayed in the main R window")))
                       
                       Try(par(mfrow=c(1,2)))
                       Try(text<-paste("Unfiltered probes= ", dim(exprs(x))[1], sep=""))
                       Try(hist(as.matrix(exprs(x)), main=text, breaks=100))
                       ####temporary saving unfiltered data
                       Try(tempUnfiltered <- tempfile(pattern = "unfiltered", tmpdir = ""))
                       Try(tempUnfiltered <- sub( "\\\\","",tempUnfiltered))
                       Try(tempUnfiltered <- sub( "/","",tempUnfiltered))
                       Try(workingDir <- getwd())
                       Try(workingDir <- sub( "/$","",workingDir))  
                       Try(tempUnfiltered <- paste(workingDir, "/", tempUnfiltered, ".rda", sep=""))
                       Try(assign("unfilteredData.location", tempUnfiltered, envir=affylmGUIenvironment))
                       Try(save(x, x.exon, file=tempUnfiltered)) 
                    ####temporary saving unfiltered data

                       Try(x <- x[which(featureNames(x)%in%selected.names),])
                       Try(assign("NormalizedAffyData", x, envir=affylmGUIenvironment))
                       Try(x.lib <- affylmGUIenvironment$exprConsoleLibs$exon.library)
                       Try(x.lib.subset <- x.lib[which(x.lib[,1]%in%featureNames(x)),3]) #in the list obtained from NetAffx there are all the probe set ids and I have to subset only those related to the exon library loaded with the data set
                       Try(x.lib.subset <- sapply(x.lib.subset ,function(x){strsplit(x, " ")}))
                       Try(x.lib.subset<-as.vector(unlist(x.lib.subset)))
                       Try(x.exon <- x.exon[which(featureNames(x.exon)%in%x.lib.subset),])
                       Try(assign("exonAffyData", x.exon, envir=affylmGUIenvironment) )

                       Try(text<-paste("Filtered probes= ", dim(exprs(x))[1], sep=""))
                       Try(hist(as.matrix(exprs(x)), main=text, breaks=100))
                       Try(tkdelete(.affylmGUIglobals$mainTree,"NormalizedAffyData.Status"))
                       Try(tkinsert(.affylmGUIglobals$mainTree,"end","NormalizedAffyData","NormalizedAffyData.Status" ,text=paste("Available (",FilterMethod,")",sep=""),font=.affylmGUIglobals$affylmGUIfontTree))
                       Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
               #######################################################

            
            
            
     } else Try(tkmessageBox(title="Filtering by DABG p-values",message="You have to calculate DABG p-values first!\n Run probesets intensity calculation by APT tools.", type="ok", icon="error"))  

}
################################################################################

"recoverUnfiltered" <- function(){
       Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
       #error if no data are loaded
       Try(whichArrayPlatform <- get("whichArrayPlatform",envir=affylmGUIenvironment))
       if(whichArrayPlatform ==""){
              Try(tkmessageBox(title="Filtering",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())
       }    
       #########################

       Try(unfilteredData.location <- get("unfilteredData.location", envir=affylmGUIenvironment))
       Try(whichArrayPlatform <- get("whichArrayPlatform", envir=affylmGUIenvironment))
       if(unfilteredData.location != "" & whichArrayPlatform=="EXON"){
            Try(load(unfilteredData.location, envir=.GlobalEnv))
            Try(assign("NormalizedAffyData", x, envir=affylmGUIenvironment))
            Try(assign("exonAffyData", x.exon, envir=affylmGUIenvironment))
            Try(tkdelete(.affylmGUIglobals$mainTree,"NormalizedAffyData.Status"))
            Try(tkinsert(.affylmGUIglobals$mainTree,"end","NormalizedAffyData","NormalizedAffyData.Status" ,text="Available",font=.affylmGUIglobals$affylmGUIfontTree))
            Try(tkdelete(.affylmGUIglobals$mainTree,"ExonArrays.Status"))
            Try(tkinsert(.affylmGUIglobals$mainTree,"end","ExonArrays","ExonArrays.Status" ,text="Available",font=.affylmGUIglobals$affylmGUIfontTree))
      #      rm(x)
      #      rm(x.exon)
      #      gc()
      #      gc()
       } else if (unfilteredData.location != ""){
            Try(load(unfilteredData.location, envir=.GlobalEnv))
            Try(assign("NormalizedAffyData", x, envir=affylmGUIenvironment))
            Try(tkdelete(.affylmGUIglobals$mainTree,"NormalizedAffyData.Status"))
            Try(tkinsert(.affylmGUIglobals$mainTree,"end","NormalizedAffyData","NormalizedAffyData.Status" ,text="Available",font=.affylmGUIglobals$affylmGUIfontTree))
       #     rm(x)
       #     gc()
       #     gc()
       } else {Try(tkmessageBox(title="Recovering unfiltered data",message="There is no need to recover unfiltered data since no filtering procedures were applied.", type="ok", icon="info"))}  

       Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
}
################################################################################

# x is an ExpressionSet, threshold is the IQR value to be applied
"reviqrFilter"<-function(){
          #error if no data are loaded
          Try(whichArrayPlatform <- get("whichArrayPlatform",envir=affylmGUIenvironment))
          if(whichArrayPlatform !="EXON"){
              Try(tkmessageBox(title="Filtering",message="No exon array have been loaded.	Please try New or Open from the File menu.",type="ok",icon="error"))
				    	Try(tkfocus(.affylmGUIglobals$ttMain))
              Try(return())
          }    
          #########################

        #    require(genefilter) || stop("library genefilter could not be found !")
           	##makning the menu for selecting IQR threshold
            Try(ttGetFilterMethod <- tktoplevel(.affylmGUIglobals$ttMain))
	      Try(tkwm.deiconify(ttGetFilterMethod))
            Try(tkgrab.set(ttGetFilterMethod))
            Try(tkfocus(ttGetFilterMethod))
            Try(tkwm.title(ttGetFilterMethod,"IQR Filtering Threshold"))
	
 	      Try(tkgrid(tklabel(ttGetFilterMethod,text="    ")))
	      Try(ttGetFilterMethodTcl <- tclVar("0.8"))
            Try(rbIQR1 <- tkradiobutton(ttGetFilterMethod,text="IQR 1",variable=ttGetFilterMethodTcl,value=1,font=.affylmGUIglobals$affylmGUIfont2))
            Try(rbIQR.9<-tkradiobutton(ttGetFilterMethod,text="IQR 0.9",variable=ttGetFilterMethodTcl,value=0.9,font=.affylmGUIglobals$affylmGUIfont2))
            Try(rbIQR.8<-tkradiobutton(ttGetFilterMethod,text="IQR 0.8",variable=ttGetFilterMethodTcl,value=0.8,font=.affylmGUIglobals$affylmGUIfont2))
            Try(rbIQR.7<-tkradiobutton(ttGetFilterMethod,text="IQR 0.7",variable=ttGetFilterMethodTcl,value=0.7,font=.affylmGUIglobals$affylmGUIfont2))
            Try(rbIQR.6<-tkradiobutton(ttGetFilterMethod,text="IQR 0.6",variable=ttGetFilterMethodTcl,value=0.6,font=.affylmGUIglobals$affylmGUIfont2))
            Try(rbIQR.5<-tkradiobutton(ttGetFilterMethod,text="IQR 0.5",variable=ttGetFilterMethodTcl,value=0.5,font=.affylmGUIglobals$affylmGUIfont2))
	      Try(tkgrid(tklabel(ttGetFilterMethod,text="    "),rbIQR1))
	      Try(tkgrid(tklabel(ttGetFilterMethod,text="    "),rbIQR.9))
	      Try(tkgrid(tklabel(ttGetFilterMethod,text="    "),rbIQR.8))
	      Try(tkgrid(tklabel(ttGetFilterMethod,text="    "),rbIQR.7))
	      Try(tkgrid(tklabel(ttGetFilterMethod,text="    "),rbIQR.6))
	      Try(tkgrid(tklabel(ttGetFilterMethod,text="    "),rbIQR.5))
	      Try(tkgrid.configure(rbIQR1,rbIQR.9,rbIQR.8,rbIQR.7,rbIQR.6,rbIQR.5,columnspan=2,sticky="w"))
	      Try(tkgrid(tklabel(ttGetFilterMethod,text="    "),tklabel(ttGetFilterMethod,text="    ")))
	      Try(ReturnVal <- "")
	      Try(onCancel <- function() {Try(ReturnVal <<- "");Try(tkgrab.release(ttGetFilterMethod));Try(tkdestroy(ttGetFilterMethod));Try(tkfocus(.affylmGUIglobals$ttMain))})
	      Try(onOK <- function() {Try(ReturnVal <<- tclvalue(ttGetFilterMethodTcl));Try(tkgrab.release(ttGetFilterMethod));Try(tkdestroy(ttGetFilterMethod));Try(tkfocus(.affylmGUIglobals$ttMain))})
        Try(onHelp <- function() tkmessageBox(title="IQR reverse filtering",
                 message="IQR reverse filter removes probe set characterized by high variability \non the basis of their distribution in the arrays under analysis.\nTo be used for alternative splicing analysis only!",icon="info"))
        Try(Help.but <- tkbutton(ttGetFilterMethod,text=" Help ",command=function()Try(onHelp()),font=.affylmGUIglobals$affylmGUIfont2))
	      Try(OK.but     <- tkbutton(ttGetFilterMethod,text="OK",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
	      Try(Cancel.but <- tkbutton(ttGetFilterMethod,text="Cancel",command=onCancel,font=.affylmGUIglobals$affylmGUIfont2))

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

	      Try(tkbind(ttGetFilterMethod,"<Destroy>",function() {ReturnVal <- "";Try(tkgrab.release(ttGetFilterMethod));Try(tkfocus(.affylmGUIglobals$ttMain));}))
       Try(tkbind(OK.but, "<Return>",onOK))
       Try(tkbind(Cancel.but, "<Return>",onCancel))      
        Try(tkbind(Help.but, "<Return>",onCancel)) 
	      Try(tkwait.window(ttGetFilterMethod))
        if(ReturnVal==""){
            Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
            Try(return())
        }#cancel
        ##Filtering routine
        Try(whichArrayPlatform <- get("whichArrayPlatform", env=affylmGUIenvironment))
        FilterMethod=paste("IQR reverse filter", ReturnVal, sep=" ")
        threshold= as.numeric(ReturnVal)
        NormalizedAffyData.Available     <- get("NormalizedAffyData.Available" , envir=affylmGUIenvironment)
       Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
       x <- get("NormalizedAffyData",envir=affylmGUIenvironment)
       iqr <- function(x){IQR(x)>threshold}
       ff <- filterfun(iqr)
       which <- genefilter(x, ff)
       leftids <- setdiff(featureNames(x),featureNames(x)[which])#remaing probes after reviqrFilter
       par(mfrow=c(1,2))
       text<-paste("Unfiltered probes= ", dim(exprs(x))[1], sep="")
       hist(as.matrix(exprs(x)), breaks=100, main=text)
       text<-paste("Filtered probes= ", length(leftids), " ",FilterMethod,sep="")
       hist(as.matrix(exprs(x[which(featureNames(x)%in%leftids),])), breaks=100, main=text)
       affylmGUIenvironment$NormalizedAffyData<-x[which(featureNames(x)%in%leftids),]
       x.exon <- get("exonAffyData",envir=affylmGUIenvironment)
                            ####temporary saving unfiltered data
                            tempUnfiltered <- tempfile(pattern = "unfiltered", tmpdir = "")
                            tempUnfiltered <- sub( "\\\\","",tempUnfiltered)
                            tempUnfiltered <- sub( "/","",tempUnfiltered)
                            workingDir <- getwd()
                            workingDir <- sub( "/$","",workingDir)  
                            tempUnfiltered <- paste(workingDir, "/", tempUnfiltered, ".rda", sep="")
       assign("unfilteredData.location", tempUnfiltered, envir=affylmGUIenvironment)
       save(x, x.exon, file=tempUnfiltered)
       ####temporary saving unfiltered data
       tkdelete(.affylmGUIglobals$mainTree,"NormalizedAffyData.Status")
       tkinsert(.affylmGUIglobals$mainTree,"end","NormalizedAffyData","NormalizedAffyData.Status" ,text=paste("Available (",FilterMethod,")",sep=""),font=.affylmGUIglobals$affylmGUIfontTree)
       x <- x[which(featureNames(x)%in%leftids),]#subset of probe set to be used to extract exon data
       x.lib <- affylmGUIenvironment$exprConsoleLibs$exon.library
       x.lib.subset <- x.lib[which(x.lib[,1]%in%as.numeric(featureNames(x))),3]
       x.lib.subset <- sapply(x.lib.subset ,function(x){strsplit(x, " ")})
       x.lib.subset<-as.vector(unlist(x.lib.subset))
       affylmGUIenvironment$exonAffyData <- x.exon[which(featureNames(x.exon)%in%x.lib.subset),]
       Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
}
################################################################################
"biomartFilter" <- function(){
           Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))

       #    require(biomaRt) || stop("library biomaRt could not be found !")
           Try(ensembl <- useMart('ensembl'))
          #error if no data are loaded
          Try(whichArrayPlatform <- get("whichArrayPlatform",envir=affylmGUIenvironment))
          if(whichArrayPlatform ==""){
              Try(tkmessageBox(title="Filtering",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(tkmessageBox(title="Filtering",message="No exon array have been loaded.	Please try New or Open from the File menu.",type="ok",icon="error"))
				    	Try(tkfocus(.affylmGUIglobals$ttMain))
              Try(return())
          }
          #########################
 
          Try(eg <- .gettingEG())
          Try(NormalizedAffyData <- get("NormalizedAffyData",envir=affylmGUIenvironment))
          Try(whichLib <- get("whichLib", envir=affylmGUIenvironment))
          if(whichLib[[1]][1]=="HuEx"){
                 ensembl <- useDataset('hsapiens_gene_ensembl', mart=ensembl)
          }
          if(whichLib[[1]][1]=="MoEx"){
                 ensembl <- useDataset('mmusculus_gene_ensembl', mart=ensembl)
          }
	        if(whichLib[[1]][1]=="RaEx"){
                 ensembl <- useDataset('rnorvegicus_gene_ensembl', mart=ensembl)
         }
         Try(emblInfo <- getBM(attributes = c('external_gene_id','entrezgene','ensembl_transcript_id'), filters = 'entrezgene', values = as.character(eg$EG), mart = ensembl)) 
         Try(egWithMultmRNAs <- unique(emblInfo$entrezgene[which(duplicated(emblInfo$entrezgene))]))
         Try(probesetsWithMultmRNAs <- eg$PROBESETID[which(eg$EG%in%egWithMultmRNAs)])
         Try(tkmessageBox(title="multiple mRNAs filter",message=paste("Filtering plots will be displayed in the main R window")))
         par(mfrow=c(1,2))
         text<-paste("Unfiltered probes= ", dim(exprs(NormalizedAffyData))[1], sep="")
         hist(as.matrix(exprs(NormalizedAffyData)), main=text, breaks=100)

         NormalizedAffyData <- NormalizedAffyData[which(featureNames(NormalizedAffyData)%in%probesetsWithMultmRNAs),]
         assign("NormalizedAffyData", NormalizedAffyData, envir=affylmGUIenvironment)

         Try(x.exon <- get("exonAffyData",envir=affylmGUIenvironment))
         Try(x.lib <- affylmGUIenvironment$exprConsoleLibs$exon.library)
         Try(x.lib.subset <- x.lib[which(x.lib[,1]%in%featureNames(NormalizedAffyData)),3]) #in the list obtained from NetAffx there are all the probe set ids and I have to subset only those related to the exon library loaded with the data set
         Try(x.lib.subset <- sapply(x.lib.subset ,function(x){strsplit(x, " ")}))
         Try(x.lib.subset<-as.vector(unlist(x.lib.subset)))
         Try(affylmGUIenvironment$exonAffyData <- x.exon[which(featureNames(x.exon)%in%x.lib.subset),])
         text<-paste("Filtered probes= ", dim(exprs(NormalizedAffyData))[1], sep="")
         hist(as.matrix(exprs(NormalizedAffyData)), main=text, breaks=100)
         tkdelete(.affylmGUIglobals$mainTree,"NormalizedAffyData.Status")
         tkinsert(.affylmGUIglobals$mainTree,"end","NormalizedAffyData","NormalizedAffyData.Status" ,text="Available filtered on multiple mRNAs",font=.affylmGUIglobals$affylmGUIfontTree)
         Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
}
################################################################################
"eSet4meV" <- function(){
  Try(tkmessageBox(title="meV data reformat",message="This routine exports expression data\nin a format suitable for visualization with meV clustering tool."))
  Try(limmaDataSetNameText <- get("limmaDataSetNameText", envir = affylmGUIenvironment))
  Try(NormalizedAffyData.Available <- get("NormalizedAffyData.Available", envir = affylmGUIenvironment))
    Try(if (NormalizedAffyData.Available == FALSE) {tkmessageBox(title = "Export Normalized Expression Values", message = "Normalized expression data are not present in oneChannelGUI.")
        return()
    })
  Try(whichArrayPlatform <- get("whichArrayPlatform", envir = affylmGUIenvironment))
    if(whichArrayPlatform != "EXON"){
       Try(NormalizedAffyData <- get("NormalizedAffyData", envir = affylmGUIenvironment))
       Try(NormalizedAffyData.exprs <- exprs(NormalizedAffyData))
       Try(Targets <- get("Targets",envir=affylmGUIenvironment))
       Try(dimnames(NormalizedAffyData.exprs)[[2]] <- as.character(Targets$Name))
       Try(FileName <- tclvalue(tkgetSaveFile(initialfile = paste(limmaDataSetNameText, "_exprs4meV.txt", sep = ""), filetypes = "{{Tab-Delimited Text Files} {.txt .xls}} {{All files} *}")))
       Try(if (!nchar(FileName)) return())
       Try(write.table(NormalizedAffyData.exprs, file = FileName,  sep = "\t", quote = FALSE, col.names = NA))
       Try(tkmessageBox(title="meV data reformat",message=paste("Expression data are available in",getwd(),"as",paste(limmaDataSetNameText, "_exprs4meV.txt", sep=""),sep="\n")))
 
    } else if(whichArrayPlatform == "EXON"){
       Try(NormalizedAffyData <- get("NormalizedAffyData", envir = affylmGUIenvironment))
       Try(NormalizedAffyData.exprs <- exprs(NormalizedAffyData))
       Try(Targets <- get("Targets",envir=affylmGUIenvironment))
       Try(dimnames(NormalizedAffyData.exprs)[[2]] <- as.character(Targets$Name))
       Try(FileName <- tclvalue(tkgetSaveFile(initialfile = paste(limmaDataSetNameText, "_exprs4meV.txt", sep = ""), filetypes = "{{Tab-Delimited Text Files} {.txt .xls}} {{All files} *}")))
       Try(if (!nchar(FileName)) return())
       Try(write.table(NormalizedAffyData.exprs, file = FileName,  sep = "\t", quote = FALSE, col.names = NA))
       Try(tkmessageBox(title="meV data reformat",message=paste("Gene-level expression data are available in",getwd(),"as",paste(limmaDataSetNameText, "_exprs4meV.txt", sep = ""),sep="\n")))
       Try(exonAffyData <- get("exonAffyData", envir = affylmGUIenvironment))
       Try(exondAffyData.exprs <- exprs(exonAffyData))
       Try(dimnames(exondAffyData.exprs)[[2]] <- as.character(Targets$Name))
       Try(mbVal <- tkmessageBox(title="Exorting exon data", message="Do you wish to export exon intensity data?", icon="question",type="yesnocancel",default="yes"))
       if(tclvalue(mbVal)=="cancel"){Try(return())} else if(tclvalue(mbVal)=="yes"){
             Try(FileName <- tclvalue(tkgetSaveFile(initialfile = paste(limmaDataSetNameText, "_exon_exprs4meV.txt", sep = ""), filetypes = "{{Tab-Delimited Text Files} {.txt .xls}} {{All files} *}")))
             Try(if (!nchar(FileName)) return())
             Try(write.table(exondAffyData.exprs, file = FileName,  sep = "\t", quote = FALSE, col.names = NA))
             Try(tkmessageBox(title="meV data reformat",message=paste("Exon-level expression data are available in",getwd(),"as",paste(limmaDataSetNameText, "_exon_exprs4meV.txt", sep=""),sep="\n")))
       }
   }
}
################################################################################
"filteringmiRtargets"<-function(){
   Try(tkmessageBox(title="Filtering by mean of microRNA human targets",message="This function retrieves predicted miR targets from RmiR.Hs.miRNA package \nand use it to filter microarray data present in oneChannelGUI\nIMPORTANT: Filtering is based on miRNA targets predicted to human miRNAs!."))
   Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
#   Try(require(annotate) || stop("\nMissing annotate library\n"))
#   Try(require(RmiR.Hs.miRNA) || stop("\nMissing RmiR.Hs.miRNA library\n"))
 #  Try(require(org.Hs.eg.db, quietly = TRUE) || stop("\nNeed data package: org.Hs.eg.db\n"))
   Try(lib <- "org.Hs.eg.db")
   ##making the menu for selecting RmiR.Hs.miRNA parameters
   Try(ttSelectDB <- tktoplevel(.affylmGUIglobals$ttMain))
   Try(tkwm.deiconify(ttSelectDB))
   Try(tkgrab.set(ttSelectDB))
   Try(tkfocus(ttSelectDB))
   Try(tkwm.title(ttSelectDB,"Selecting miR target prediction database"))
	
   Try(tkgrid(tklabel(ttSelectDB,text="    ")))
   Try(ttSelectDBTcl <- tclVar("miranda"))
   Try(rbIQR.a <- tkradiobutton(ttSelectDB,text="miranda",variable=ttSelectDBTcl,value="miranda",font=.affylmGUIglobals$affylmGUIfont2))
   Try(rbIQR.b<-tkradiobutton(ttSelectDB,text="mirbase",variable=ttSelectDBTcl,value="mirbase",font=.affylmGUIglobals$affylmGUIfont2))
   Try(rbIQR.c<-tkradiobutton(ttSelectDB,text="mirtarget2",variable=ttSelectDBTcl,value="mirtarget2",font=.affylmGUIglobals$affylmGUIfont2))
   Try(rbIQR.d <- tkradiobutton(ttSelectDB,text="pictar",variable=ttSelectDBTcl,value="pictar",font=.affylmGUIglobals$affylmGUIfont2))
   Try(rbIQR.e<-tkradiobutton(ttSelectDB,text="tarbase",variable=ttSelectDBTcl,value="tarbase",font=.affylmGUIglobals$affylmGUIfont2))
   Try(rbIQR.f<-tkradiobutton(ttSelectDB,text="targetscan",variable=ttSelectDBTcl,value="targetscan",font=.affylmGUIglobals$affylmGUIfont2))

   Try(tkgrid(tklabel(ttSelectDB,text="    "),rbIQR.a))
   Try(tkgrid(tklabel(ttSelectDB,text="    "),rbIQR.b))
   Try(tkgrid(tklabel(ttSelectDB,text="    "),rbIQR.c))
   Try(tkgrid(tklabel(ttSelectDB,text="    "),rbIQR.d))
   Try(tkgrid(tklabel(ttSelectDB,text="    "),rbIQR.e))
   Try(tkgrid(tklabel(ttSelectDB,text="    "),rbIQR.f))

   Try(tkgrid.configure(rbIQR.a,rbIQR.b,rbIQR.c,rbIQR.d,rbIQR.e,rbIQR.f,columnspan=2,sticky="w"))
   Try(tkgrid(tklabel(ttSelectDB,text="    "),tklabel(ttSelectDB,text="    ")))
   Try(ReturnDB <- "")
   Try(onCancel <- function() {Try(ReturnDB <<- "");Try(tkgrab.release(ttSelectDB));Try(tkdestroy(ttSelectDB));Try(tkfocus(.affylmGUIglobals$ttMain))})
   Try(onOK <- function() {Try(ReturnDB <<- tclvalue(ttSelectDBTcl));Try(tkgrab.release(ttSelectDB));Try(tkdestroy(ttSelectDB));Try(tkfocus(.affylmGUIglobals$ttMain))})
   Try(OK.but     <- tkbutton(ttSelectDB,text="OK",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
   Try(Cancel.but <- tkbutton(ttSelectDB,text="Cancel",command=onCancel,font=.affylmGUIglobals$affylmGUIfont2))

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

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

   Try(mydb <- ReturnDB)
   
   ###detecting the miR
   Try(ttmiR<-tktoplevel(.affylmGUIglobals$ttMain))
   Try(tkwm.deiconify(ttmiR))
   Try(tkgrab.set(ttmiR))
   Try(tkfocus(ttmiR))
   Try(tkwm.title(ttmiR,"miR Input"))
   Try(tkgrid(tklabel(ttmiR,text="    ")))
   Try(miRname <- "")
   Try(Local.miR <- tclVar(init=miRname))
   Try(entry.miR <-tkentry(ttmiR,width="10",font=.affylmGUIglobals$affylmGUIfont2,textvariable=Local.miR,bg="white"))
   Try(tkgrid(tklabel(ttmiR,text="Please enter the miR to be use to retrieve putative targets.\nThe input format is like: miR-125b",font=.affylmGUIglobals$affylmGUIfont2)))
   Try(tkgrid(entry.miR))
   onOK <- function()
   {
      Try(miRname <- tclvalue(Local.miR))
      Try(assign("miRname", tclvalue(Local.miR),affylmGUIenvironment))
      Try(assign("miRname.available", TRUE,affylmGUIenvironment))
      Try(tkgrab.release(ttmiR));Try(tkdestroy(ttmiR));Try(tkfocus(.affylmGUIglobals$ttMain))                        
   }
   Try(OK.but <-tkbutton(ttmiR,text="   OK   ",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
   Try(tkgrid(tklabel(ttmiR,text="    ")))
   Try(tkgrid(OK.but))
   Try(tkgrid.configure(OK.but))
   Try(tkgrid(tklabel(ttmiR,text="       ")))
   Try(tkfocus(entry.miR))
   Try(tkbind(entry.miR, "<Return>",onOK))
   Try(tkbind(ttmiR, "<Destroy>", function(){Try(tkgrab.release(ttmiR));Try(tkfocus(.affylmGUIglobals$ttMain));return(0)}))
   Try(tkwait.window(ttmiR))

   Try(miRname <- get("miRname", env=affylmGUIenvironment))
   Try(mymirset <- dbGetQuery(RmiR.Hs.miRNA_dbconn(), paste("SELECT * FROM ",mydb," WHERE mature_miRNA='hsa-",miRname,"'", sep="")))
   Try(symbol <- toupper(as.character(unlist(lookUp(as.character(mymirset$gene_id), lib, "SYMBOL")))))
   Try(mymirset <- cbind(mymirset, symbol))
   Try(names(mymirset) <- c("EG", "mature_miRNA", "SYMBOL"))
   
   if(dim(mymirset)[1]==0){
        Try(tkmessageBox(title="miR putative targets",message=paste("No genes are associated to ", miRname ,"\nAre you sure that you have correctly typed in the miR name?",sep="")))
        Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
        tkfocus(.affylmGUIglobals$ttMain)
        return()
   } else{
        Try(whichArrayPlatform <- get("whichArrayPlatform",envir=affylmGUIenvironment))
        if(whichArrayPlatform ==""){
              Try(tkmessageBox(title="Filtering",message="No arrays have been loaded.	Please try New or Open from the File menu.",type="ok",icon="error"))
				    	Try(tkfocus(.affylmGUIglobals$ttMain))
	    	      Try(assign("miRname", "" ,affylmGUIenvironment))
              Try(assign("miRname.available", FALSE,affylmGUIenvironment))
              Try(return())
        }
   }    
          #########################
        Try(whichArrayPlatform <- get("whichArrayPlatform", env=affylmGUIenvironment))
#        if(whichArrayPlatform=="AFFY" || whichArrayPlatform=="ILLU" || whichArrayPlatform=="LARGE") {
        if(whichArrayPlatform=="LARGE"){
           Try(x <- get("NormalizedAffyData", envir= affylmGUIenvironment))
           ####temporary saving unfiltered data
           tempUnfiltered <- tempfile(pattern = "unfiltered", tmpdir = "")
           tempUnfiltered <- sub( "\\\\","",tempUnfiltered)
           tempUnfiltered <- sub( "/","",tempUnfiltered)
           workingDir <- getwd()
           workingDir <- sub( "/$","",workingDir)  
           tempUnfiltered <- paste(workingDir, "/", tempUnfiltered, ".rda", sep="")
           Try(assign("unfilteredData.location", tempUnfiltered, envir=affylmGUIenvironment))
           Try(save(x, file=tempUnfiltered)) 
           ####temporary saving unfiltered data
           x.ann <- .annotation(x)
           if(x.ann ==""){
                Try(tkmessageBox(title="Filtering",message="No annotation is available for the loaded data set.",type="ok",icon="error"))
				    	  Try(tkfocus(.affylmGUIglobals$ttMain))
                Try(return())
           }else if(x.ann =="HuEx" || x.ann =="MoEx" || x.ann =="HuEx"){
                 myann <- .gettingEG()
           }else{
                Try(tkmessageBox(title="Filtering",message="This annotation library is not supported for this filtering procedure.",type="ok",icon="error"))
				    	  Try(tkfocus(.affylmGUIglobals$ttMain))
	    	        Try(assign("miRname", "" ,affylmGUIenvironment))
                Try(assign("miRname.available", FALSE,affylmGUIenvironment))
                Try(return())
           }
           sub.myann <- myann[which(myann$SYMBOL%in%intersect(as.character(mymirset$SYMBOL), as.character(myann$SYMBOL))),]
           affylmGUIenvironment$NormalizedAffyData<-affylmGUIenvironment$NormalizedAffyData[which(featureNames(affylmGUIenvironment$NormalizedAffyData)%in%as.character(sub.myann$PROBESETID)),]
                    Try(NormalizedAffyData.Available     <- get("NormalizedAffyData.Available" , envir=affylmGUIenvironment))
                    Try(if(NormalizedAffyData.Available){
                                Try(tkdelete(.affylmGUIglobals$mainTree,"NormalizedAffyData.Status"))
                                Try(tkinsert(.affylmGUIglobals$mainTree,"end","NormalizedAffyData","NormalizedAffyData.Status" ,text=paste("Available list filtered by miRNA targets for", miRname,sep=" "),font=.affylmGUIglobals$affylmGUIfontTree))
                         })
               Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
               Try(tkmessageBox(title="Filtering by miR targets",message=paste("Normalized Affy Data data is now made of ", dim(exprs(affylmGUIenvironment$NormalizedAffyData))[1]," probe sets",sep="")))
       }else{
                Try(tkmessageBox(title="Filtering",message="This microarray platform is notsupported for this filtering procedure.",type="ok",icon="error"))
				    	  Try(tkfocus(.affylmGUIglobals$ttMain))
				    	  Try(assign("miRname", "" ,affylmGUIenvironment))
                Try(assign("miRname.available", FALSE,affylmGUIenvironment))
                Try(return())
       }
   
   Try(assign("miRname", "" ,affylmGUIenvironment))
   Try(assign("miRname.available", FALSE,affylmGUIenvironment))
   Try(tkfocus(.affylmGUIglobals$ttMain))
   Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))

}
################################################################################
"mRNAmiRCor"  <- function(){
   Try(tkmessageBox(title="Filtering by mean of correlation between expression data and miRNA expression changes",message="This function filters data on the basis of the correlation between mRNA expression and miRNA expression changes."))
   Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
   
#   require(genefilter) || stop("library genefilter could not be found !")
   #error if no data are loaded
   Try(whichArrayPlatform <- get("whichArrayPlatform",envir=affylmGUIenvironment))
   if(whichArrayPlatform ==""){
              Try(tkmessageBox(title="Filtering",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())
   }    
   ##making the menu for selecting correlation threshold
   Try(ttIfDialog<-tktoplevel(.affylmGUIglobals$ttMain))
   Try(tkwm.deiconify(ttIfDialog))
   Try(tkgrab.set(ttIfDialog))
   Try(tkfocus(ttIfDialog))
   Try(tkwm.title(ttIfDialog,"Correlation Options"))
   Try(tkgrid(tklabel(ttIfDialog,text="    ")))

   Try(frame1 <- tkframe(ttIfDialog,relief="groove",borderwidth=2))
   Try(HowManyQuestion1 <- tklabel(frame1,text="Correlation Method",font=.affylmGUIglobals$affylmGUIfont2))
   Try(tkgrid(HowManyQuestion1))
   Try(tkgrid.configure(HowManyQuestion1,columnspan=2,sticky="w"))
   Try(thresholdTcl <- tclVar("pearson"))
   Try(I0.but  <- tkradiobutton(frame1,text="pearson",variable=thresholdTcl,value="pearson",font=.affylmGUIglobals$affylmGUIfont2))
   Try(I1.but  <- tkradiobutton(frame1,text="kendall",variable=thresholdTcl,value="kendall",font=.affylmGUIglobals$affylmGUIfont2))
   Try(I2.but  <- tkradiobutton(frame1,text="spearman",variable=thresholdTcl,value="spearman",font=.affylmGUIglobals$affylmGUIfont2))
   Try(tkgrid(I0.but,sticky="w"))
   Try(tkgrid(I1.but,sticky="w"))
   Try(tkgrid(I2.but,sticky="w"))

   Try(tkgrid.configure(HowManyQuestion1,I0.but,I1.but,I2.but,sticky="w"))

   Try(frame2 <- tkframe(ttIfDialog,relief="groove",borderwidth=2))
   Try(fractionLabel <- tklabel(frame2,text="miRNA modulators",font=.affylmGUIglobals$affylmGUIfont2))
   Try(tkgrid(fractionLabel,sticky="w"))
   Try(tkgrid.configure(fractionLabel,sticky="w"))
   Try(fractionTcl <- tclVar("antagomir"))
   Try(F1.but <- tkradiobutton(frame2,text="antagomir",variable=fractionTcl,value="antagomir",font=.affylmGUIglobals$affylmGUIfont2))
   Try(F2.but <- tkradiobutton(frame2,text="mimic",variable=fractionTcl,value="mimic",font=.affylmGUIglobals$affylmGUIfont2))

   Try(tkgrid(F1.but,sticky="w"))
   Try(tkgrid(F2.but,sticky="w"))

   Try(tkgrid.configure(fractionLabel,F1.but,F2.but,sticky="w"))

    Try(onOK <- function()
    {
        ReturnVal1 <- tclvalue(thresholdTcl)
        ReturnVal2 <- tclvalue(fractionTcl)
        Try(ReturnVal <<- paste(ReturnVal1, ReturnVal2, sep=";"))
        Try(tkgrab.release(ttIfDialog))
        Try(tkdestroy(ttIfDialog))
        Try(tkfocus(.affylmGUIglobals$ttMain))
    })

    Try(frame3 <- tkframe(ttIfDialog,borderwidth=2))
    Try(onCancel <- function() {Try(ReturnVal <<- ""); Try(tkgrab.release(ttIfDialog));Try(tkdestroy(ttIfDialog));Try(tkfocus(.affylmGUIglobals$ttMain))})
    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(tkgrid(tklabel(frame3,text="    "),OK.but,Cancel.but,tklabel(frame3,text="    ")))

    Try(tkgrid(tklabel(ttIfDialog,text="    "),frame1,frame2,tklabel(ttIfDialog,text="  ")))
    Try(tkgrid(tklabel(ttIfDialog,text="    ")))
    Try(tkgrid(tklabel(ttIfDialog,text="    "),frame3,tklabel(ttIfDialog,text="  ")))
    Try(tkgrid(tklabel(ttIfDialog,text="    ")))
    Try(tkgrid.configure(frame1,frame3,sticky="w"))

    Try(tkfocus(ttIfDialog))
    Try(tkbind(ttIfDialog, "<Destroy>", function() {Try(tkgrab.release(ttIfDialog));Try(tkfocus(.affylmGUIglobals$ttMain));}))
    Try(tkwait.window(ttIfDialog))
    if(ReturnVal==""){return()}
    tmp<-strsplit(ReturnVal, ";")
    method <- tmp[[1]][1]
    modulator <- tmp[[1]][2]
    
    mRNAdata <- get("NormalizedAffyData",envir=affylmGUIenvironment)
    mRNAexprs <- exprs(mRNAdata)
    Targets <- get("Targets",envir=affylmGUIenvironment)
    #loading miR expression data
    Try(tkmessageBox(title="Loading miRNA expression data",message="Open the file containing the expression data for miRNA for the same set of samples loaded in oneChannelGUI.\nThe miR expression file has two columns: Name, Value\nIMPORTANT Name column in target file loaded in oneChannelGUI, need to be the same for Name column in miR expression file."))                   
    .OpenAmiRFile <- function(FileName){
      Try(tempFileName <- tclvalue(tkgetOpenFile(filetypes="{{Text Files} {.txt}} {{All files} *}")))
      if(!nchar(tempFileName))
      {
         tkfocus(.affylmGUIglobals$ttMain)
         Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
         return()
      }
      mymiRdata <-read.table(tempFileName, sep="\t", header=T, as.is=TRUE)
      return(mymiRdata)
    }
    mymirData <- .OpenAmiRFile()
    ###check congruence between mRNA and miR samples
    c.lenght <- length(intersect(Targets$Name, mymirData$Name))
    if(c.lenght == dim(Targets)[1] &&  c.lenght == dim(mymirData)[1]){
           if(identical(Targets$Name, mymirData$Name)){
                .recursiveCor <- function(x,y, method) {cor(x = x, y = y, method = method)}
                mycor <- apply(mRNAexprs, 1, .recursiveCor, y=as.numeric(mymirData$Value), method= method)
                myres <- data.frame(featureNames(mRNAdata), mycor)
                Try(tkmessageBox(title="Reorganizing Target file as for maSigPro time course analysis",message="This function require a Target file organized as the one needed to run time course analysis via maSigPro."))
                        
                Try(masigpro.edesign())
                Try(mydesign <- get("edesign", affylmGUIenvironment))
                if(dim(mydesign)[2] != 4){
                      Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
                      Try(tkmessageBox(title="Filtering by direct correlation",message="The Target file does not seems to have a maSigPro structure with the following columns: Time Replicate Control cond1\nPlease check the help file for the correct definition of a Target file with maSigPro structure."))
                      Try(return())
                }
                ctrl <- which(mydesign$Control == 1)
                trt <-  which(mydesign$Control == 0)
                time.u <- sort(unique(mydesign$Time))
                my.x <- NULL
                my.y <- NULL
                for(i in time.u){
                   my.x  <- c(my.x, ctrl[which(mydesign$Time[ctrl] == i)])
                   my.y  <- c(my.y, trt[which(mydesign$Time[trt] == i)])
                }
                .recursiveCorRNA <- function(x,myx, myy, method) {xa = x[myx]; ya = x[myy]; cor(x = xa, y = ya, method = method)}
                mycorRNA <- apply(mRNAexprs, 1, .recursiveCorRNA, myx=my.x, myy=my.y , method= method)
                myres <- data.frame(myres, mycorRNA)
                names(myres) <- c("ids","miRcor","mRNAcor")
                par(mfrow=c(1,2))
                hist(mycor, main="Correlation between mRNA \nand miRNA expression", xlab="")
                hist(mycorRNA, main="Correlation between mRNA \nw/wo microRNA expression perturbation", xlab="")
                
                if(modulator == "antagomir"){
                        Try(myres <- myres[which(myres$miRcor <0),])
                        Try(myres <- myres[which(myres$mRNAcor <0),])
                        Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
                        Try(tkmessageBox(title="Filtering by inverse correlation",message=paste("Genes IDs characterized by inverse correlation between mRNA expression w/wo Antagomir based perturbation are saved ", dim(myres)[1], " out of ", dim(exprs(affylmGUIenvironment$NormalizedAffyData))[1]," probe sets",sep="")))
                        Try(FileName <- tclvalue(tkgetSaveFile(initialfile=paste("Antagomir_",method,".xls",sep=""),filetypes="{{Tab-Delimited Text Files} {.txt .xls}} {{All files} *}")))
                        Try(if(!nchar(FileName))
                            return())
                        Try(write.table(myres,file=FileName,quote=FALSE, sep="\t", row.names=F, col.names=T))
                        Try(pdf.filename <- paste(FileName, ".pdf", sep=""))
                        Try(pdf(pdf.filename))
                        for(i in  myres$ids) {
                                  mygene <- as.vector(mRNAexprs[which(rownames(mRNAexprs)==i),])
                                  PlotGroups(mygene, edesign = mydesign, main=i)
                        }
                        Try(dev.off())
                        Try(tkmessageBox(title="maSigPro PlotGroups",message=paste("Plots are saved in your working directory in file", pdf.filename, sep=" ") , type="ok", icon="info"))
                       
                 }else{
                        Try(myres <- myres[which(myres$miRcor <0),])
                        Try(myres <- myres[which(myres$mRNAcor >0),])
                        Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
                        Try(tkmessageBox(title="Filtering by direct correlation",message=paste("Genes IDs characterized by direct correlation between mRNA expression w/wo Mimic based perturbation are saved ", dim(myres)[1], " out of ", dim(exprs(affylmGUIenvironment$NormalizedAffyData))[1]," probe sets",sep="")))
                        Try(FileName <- tclvalue(tkgetSaveFile(initialfile=paste("Mimic_",method,".xls",sep=""),filetypes="{{Tab-Delimited Text Files} {.txt .xls}} {{All files} *}")))
                        Try(if(!nchar(FileName))
                           return())
                        Try(write.table(myres,file=FileName,quote=FALSE, sep="\t", row.names=F, col.names=T))
                        Try(pdf.filename <- paste(FileName, ".pdf", sep=""))
                        Try(pdf(pdf.filename))
                        for(i in  myres$ids) {
                                  mygene <- as.vector(mRNAexprs[which(rownames(mRNAexprs)==i),])
                                  PlotGroups(mygene, edesign = mydesign, main=i)
                        }
                        Try(dev.off())
                        Try(tkmessageBox(title="maSigPro PlotGroups",message=paste("Plots are saved in your working directory in file", pdf.filename, sep=" ") , type="ok", icon="info"))
                 }
           }else{
                  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
                  Try(tkmessageBox(title="Filtering by correlation",message="The data set in oneChannelGUI and the miR data have the samples organized in different way!\nPlease modify the miRdata file to have the same samples organization as in the Target name of the dataset load in oneChannelGUI."), type="error")
                  return()
           }
    }else{
           Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
           Try(tkmessageBox(title="Filtering by correlation",message="The data set in oneChannelGUI and the miR data do not contain the same number of samples!"), type="error")
           return()
    }
 }

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

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.