R/dataminingmenu.R

Defines functions plotGO templA metaArrayMerge metaArrayIC annotateNGSeset maligReads SaveNGSGO

Documented in annotateNGSeset metaArrayIC metaArrayMerge plotGO templA

#set of functions, directly/indirectly involved, in oneChannelGUI dataminingMenu
#oneChannelGUI GOenrichment searching for enrichment of gO terms
        #contains oneChannelGUI SaveTopTable called inside the function
        #         oneChannelGUI OpenAFile called inside the function
#oneChannelGUI plotGO plotting GO relations
#oneChannelGUI extractAffyids This function starts for a topTable and extracts the subset of probe ids associated to a GO class
#                             found differentially expressed using the Goenrichment function
        #contains oneChannelGUI OpenAFile called inside the function
        #         oneChannelGUI SaveHtmlTable called inside the function
#oneChannelGUI templA making a template A from a top table
         #         calling SaveTopTable present inside the function
#oneChanneGUI metaArrayMerge  create a merge object to be used for IC analysis using metaArrayIC
#oneChannelGUI metaArrayIC run metaArray implementation of Parmigiani Integrative Correlation
#oneChannelGUI annotateNGSeset uses ChIPpeakAnno to retrieve various type of annotation to be added to my data set
#oneChannelGUI getNGSannotation create an ENSEMBL based annotation for NGS data
#oneChannelGUI Reads2logis run .reads2logos loads reads quality alignment generated from shrimp and gives as output the barplot of the raw
#              counts for a specific sample or experimental group and save the count matrix of the alignment to the reference sequence
#              actual implementation works with the non-coding RNA subset saved in oneChannelGUI
#oneChannelGUI startmeV starting meV clustering
#oneChannelGUI RmiRInterface interface to RmiR
#oneChannelGUI retrieveMirTargets interface to RmiR.Hs.miRNA to retrieve targets given a specific miR
#oneChannelGUI extractmirTargets  This routine extracst a subset of putative targets having anti-correlated expression with respect to user defined microRNA
#oneChannelGUI ctrtrtHeatmap function that reorganize data on the basis of a maSigPro target. ONly if one condition is used
#oneChannelGUI goseqInterface
#################################################################################
#updated 13.02.06
#my.go= "BP", "MF", "CC" class of GO to be investigated
#mylib="mgu74av2" microarray anntation library
#pValue=0.01 significant p-value to be detetcted
#topTable=topTable from affylmGUI

"GOenrichment"<-function(){
   #        require(GOstats) || stop("library GOstats could not be found !")
          Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
           #error if no data are loaded
          Try(whichArrayPlatform <- get("whichArrayPlatform",envir=affylmGUIenvironment))
          if(whichArrayPlatform ==""){
              Try(tkmessageBox(title="GO analysis",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 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="P-value threshold",font=.affylmGUIglobals$affylmGUIfont2))
           Try(tkgrid(HowManyQuestion1))
           Try(tkgrid.configure(HowManyQuestion1,columnspan=2,sticky="w"))
           Try(thresholdTcl <- tclVar("0.01"))
           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.001",variable=thresholdTcl,value="0.001",font=.affylmGUIglobals$affylmGUIfont2))
           Try(I4.but  <- tkradiobutton(frame1,text="0.0001",variable=thresholdTcl,value="0.0001",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="GO class",font=.affylmGUIglobals$affylmGUIfont2))
           Try(tkgrid(fractionLabel,sticky="w"))
           Try(tkgrid.configure(fractionLabel,sticky="w"))
           Try(fractionTcl <- tclVar("BP"))
           Try(F1.but <- tkradiobutton(frame2,text="BP",variable=fractionTcl,value="BP",font=.affylmGUIglobals$affylmGUIfont2))
           Try(F2.but <- tkradiobutton(frame2,text="MF",variable=fractionTcl,value="MF",font=.affylmGUIglobals$affylmGUIfont2))
           Try(F3.but <- tkradiobutton(frame2,text="CC",variable=fractionTcl,value="CC",font=.affylmGUIglobals$affylmGUIfont2))
           
           Try(tkgrid(F1.but,sticky="w"))
           Try(tkgrid(F2.but,sticky="w"))
           Try(tkgrid(F3.but,sticky="w"))
           Try(tkgrid.configure(fractionLabel,F1.but,F2.but,F3.but,sticky="w"))

           Try(onOK <- function()
           {
                ReturnVal1 <- as.numeric(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(tkgrab.release(ttIfDialog));
                                Try(tkdestroy(ttIfDialog));
                                Try(tkfocus(.affylmGUIglobals$ttMain));
                                Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
                                Try(return())
           })
           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,frame2,sticky="w"))

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

	#if exon arrays are used till a specifi exon array data base is available as data base we use the LLMapping libraries
      Try(whichArrayPlatform <- get("whichArrayPlatform", envir=affylmGUIenvironment))
	    if(whichArrayPlatform=="EXON"){
	    #     require(annotate, quietly = TRUE) || stop("\nneed data package: annotate\n")
           tmp<-strsplit(ReturnVal, ";")
           p.value= as.numeric(tmp[[1]][1])
           Try(x <- get("NormalizedAffyData",envir=affylmGUIenvironment))
           my.go= tmp[[1]][2]
           whichLib <- get("whichLib", envir=affylmGUIenvironment)
                    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"
                   })
      }else{
           tmp<-strsplit(ReturnVal, ";")
           p.value= as.numeric(tmp[[1]][1])
           Try(x <- get("NormalizedAffyData",envir=affylmGUIenvironment))
           lib= .annotation(x)
           if(length(as.character(unlist(strsplit(lib, "\\.")))) == 1){
                   Try(lib <- paste(lib, ".db", sep=""))
           }
           my.go= tmp[[1]][2]
           Try(require(lib, character.only = TRUE) || stop("need data package: ", lib))
     #      Try(require("annotate", character.only = TRUE) || stop("need data package: annotate"))
    
     }
      ###################carica la lista di affyids
####################################################################################
#      getDataEnv <- function(name, lib) {
#        	get(paste(lib, name, sep = ""), mode = "environment")
#    	}
#    	require(lib, character.only = TRUE) || stop("need data package: ", 
#        lib)
####################################################################################

       Try(startFun <- tclvalue(tkmessageBox(title="GO class enrichment",message="Open the file with the list of differentially expressed probe sets.",type="yesno",icon="question")))
       if (startFun=="no"){
                       Try(tkmessageBox(title="GO class enrichment",message="The file with the list of differentially expressed probe sets\nwas not given!\nAborting analysis."))  
                       Try(return())
       }

      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=T, as.is=TRUE)
         return(mySel)
      }
      tmp.x <- OpenAFile()
      if(dim(tmp.x)[2]>1){
            Try(tkmessageBox(title="GO class enrichment",message=paste("Input file should contain\nonly a column with\nAffymetrix ids")))
            Try(return())  
      }
      
      if(whichArrayPlatform=="EXON"){
        #Try(annlibloc <- grep(paste("^",whichLib[[1]][1],sep=""), as.vector(unlist(data(package="oneChannelGUI"))), ignore.case = T))
        #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(genelist <- featureNames(x))#normalizeAffyData in x
        Try(acc <- as.character(exonannlib$ACC[which(as.character(exonannlib$PROBESETID)%in%genelist)])) #defining the universe of ll
        Try(acc <- acc[!is.na(acc)]) #remove NA
#        Try(lltoacc <- mget(acc, env=getDataEnv("ACCNUM2LL", lib), ifnotfound=""))#LL ids
        Try(lltoacc <- as.character(unlist(lookUp(as.character(acc), lib, "ACCNUM2EG"))))
        Try(gNuniverse <- unique(as.character(unlist(lltoacc))))#ll universe

        Try(gNsel<-as.character(tmp.x[,1]))
        Try(myacc <- as.character(exonannlib$ACC[which(as.character(exonannlib$PROBESETID)%in%gNsel)])) #defining the acc of diff exprs
        Try(myacc <- myacc[!is.na(myacc)])
        #Try(mylltoacc <- mget(myacc,env=getDataEnv("ACCNUM2LL", lib), ifnotfound=""))#LL ids
        Try(mylltoacc <- as.character(unlist(lookUp(myacc, lib, "ACCNUM2EG"))))
        Try(gNll <- unique(as.character(unlist(mylltoacc))))#ll of diff exprs data
      }else{
        gNsel<-as.character(tmp.x[,1])
        Try(annlib1 <- as.character(unlist(strsplit(lib, ".db"))))
        Try(gNll <- lookUp(gNsel, annlib1, "ENTREZID"))
        Try(gNll <- unique(as.character(unlist(gNll))))
        Try(gNuniverse <- lookUp(featureNames(x), annlib1, "ENTREZID"))
        Try(gNuniverse <- unique(as.character(unlist(gNuniverse))))
        
        #gNll <- unique(as.character(unlist(mget(gNsel, env=getDataEnv("ENTREZID", lib), ifnotfound=NA))))#ll of diff exprs data
        #gNuniverse <- unique(as.character(unlist(mget(featureNames(x), env=getDataEnv("ENTREZID", lib), ifnotfound=NA))))#ll universe
     }
      
      ##########################nuova parte
      
      Try(params <- new("GOHyperGParams", geneIds = gNll, universeGeneIds = gNuniverse,
      annotation = lib, ontology = my.go, pvalueCutoff = p.value, conditional = FALSE,testDirection = "over"))
      Try(hgOver <- hyperGTest(params))
      Try(hgOver.info <- paste(description(hgOver),
            paste(length(universeCounts(hgOver)),"GO BP ids tested","(",length(which(pvalues(hgOver) < p.value)),"have p<",p.value,")", sep=" "),
            paste("Selected gene set size:",length(geneIds(hgOver)), sep=" "),
            paste("Gene universe size:", universeMappedCount(hgOver), sep=" "),
            paste("Annotation package:", hgOver@annotation, sep=" "), 
            sep="\n"))
      Try(tkmessageBox(title="GO class enrichment",message=paste(hgOver.info),icon="info",type="ok"))
      Try(conditional(params) <- TRUE)
      #Try(hgCondOver <- hyperGTest(params))
      Try(ggMat <- summary(hgOver))
          ggMat[,2:4] <- signif(ggMat[,2:4] ,2)
          #ggMat.term <- sapply(as.vector(ggMat[,7]), function(x){x.1 <- strsplit(x,">"); return(x.1[[2]])})
          #ggMat.term <- strsplit(ggMat[,7], ">")
          #ggMat.term <- sapply(ggMat.term, function(x){x[[2]]})
          #ggMat.term <- strsplit(ggMat.term, "<")
          #ggMat.term <- sapply(ggMat.term, function(x){x[[1]]})
          #ggMat[,7] <-  ggMat.term

        SaveTopTable <- function()
        {
               Try(FileName <- tclvalue(tkgetSaveFile(initialfile=paste("GO.enrichment.",my.go,"p-value",p.value,".xls",sep=""),filetypes="{{Tab-Delimited Text Files} {.txt .xls}} {{All files} *}")))
               Try(if(!nchar(FileName))
               return())
               Try(write.table(ggMat,file=FileName,quote=FALSE,sep="\t", row.names = F))
        }
 #Try(tkmessageBox(title="GO class enrichment",message="Enriched classes will be displayed in a text window.  You can save it as a tab-delimited text file and then import it into a spreadsheet program.",icon="info",type="ok"))
       Try(tempfile1 <- tempfile())
       write.table(ggMat,file=tempfile1,quote=FALSE,col.names=NA,sep="\t")
       ttToptableTable <- tktoplevel(.affylmGUIglobals$ttMain)
       tkwm.title(ttToptableTable,paste("GO enriched classes using p-value= ",p.value," annotation lib= ",lib," GO class= ",my.go,sep=" "))
       xscr <-tkscrollbar(ttToptableTable, repeatinterval=5,orient="horizontal", command=function(...)tkxview(txt,...))
       scr <- tkscrollbar(ttToptableTable, repeatinterval=5, command=function(...)tkyview(txt,...))
       txt <- tktext(ttToptableTable, bg="white", font="courier",xscrollcommand=function(...)tkset(xscr,...), yscrollcommand=function(...)tkset(scr,...),wrap="none",width=100)
       tkpack(scr, side="right", fill="y")
       tkpack(xscr, side="bottom", fill="x")
       tkpack(txt, side="left", fill="both", expand="yes")
       chn <- tclvalue(tclopen( tempfile1))
       tkinsert(txt, "end", tclvalue(tclread( chn)))
       tclclose( chn)
       tkconfigure(txt, state="disabled")
       tkmark.set(txt,"insert","0.0")
       tkfocus(txt)
       tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow")
       topMenu2 <- tkmenu(ttToptableTable)
       tkconfigure(ttToptableTable, menu=topMenu2)
       fileMenu2 <- tkmenu(topMenu2, tearoff=FALSE)
       tkadd(fileMenu2, "command", label="Save As", command=SaveTopTable) # ) # ,font=affylmGUIfontMenu)
       tkadd(fileMenu2, "command", label="Close", command=function() tkdestroy(ttToptableTable)) # ) # ,font=affylmGUIfontMenu)
       tkadd(topMenu2, "cascade", label="File", menu=fileMenu2) # ,font=affylmGUIfontMenu)
 
      
      #Try(tkmessageBox(title="GO class enrichment",message="Results will be saved as html file in your working directory",icon="info",type="ok"))
      #Try(FileName <- tclvalue(tkgetSaveFile(initialfile="GO.enriched.terms.html",filetypes="{{HTML files} {.html}} {{All files} *}")))
      #htmlReport(hgCondOver, file = FileName)
      #####################################
     #plotitng graphs
     Try(startGraph <- tclvalue(tkmessageBox(title="Plotting Graph",message="Do you wish to plot the graph of the enriched GO terms?\nIf you answer yes, graphviz software and Rgraphviz package should be already installed.",type="yesno",icon="question")))
     if (startGraph=="yes"){
           #      require(Rgraphviz) || stop("library Rgraphviz could not be found !")
     } else {
                 Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
                 Try(return())
     }
     if(my.go == "BP"){
            tfG <- GOGraph(ggMat[,1], GOBPPARENTS)
      } else if (my.go == "MF"){
            tfG <- GOGraph(ggMat[,1], GOMFPARENTS)
      } else if (my.go == "CC"){
            tfG <- GOGraph(ggMat[,1], GOCCPARENTS)
      }
     gCol <- rep("lightblue", length(nodes(tfG)))
     gCol[which(nodes(tfG)%in%ggMat[,1])] <- "tomato"
     
     tGfnA <- makeNodeAttrs(tfG,label=nodes(tfG),shape="ellipse",fillcolor=gCol,fixedsize=FALSE)
     Try(tkmessageBox(title="Plotting GO parents",message="Plot of GO term parents will be displayed on the main R window",icon="info",type="ok"))
     plot(tfG, nodeAttrs=tGfnA)
     Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))

}

#GOenrichment()
################################################################################

plotGO<-function(){
#  require(GOstats) || stop("library GOstats could not be found !")
#  require(Rgraphviz) || stop("library Rgraphviz could not be found !")
  #error if no data are loaded
  Try(whichArrayPlatform <- get("whichArrayPlatform",envir=affylmGUIenvironment))
  if(whichArrayPlatform ==""){
              Try(tkmessageBox(title="GO analysis",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(ttGetGOName<-tktoplevel(.affylmGUIglobals$ttMain))
  Try(tkwm.deiconify(ttGetGOName))
  Try(tkgrab.set(ttGetGOName))
  Try(tkfocus(ttGetGOName))
  Try(tkwm.title(ttGetGOName,"GO class identifier"))
  Try(tkgrid(tklabel(ttGetGOName,text="    ")))
  Try(GONameText <- "")
  Try(Local.GOName <- tclVar(init=GONameText))
  Try(entry.GOName <-tkentry(ttGetGOName,width="10",font=.affylmGUIglobals$affylmGUIfont2,textvariable=Local.GOName,bg="white"))
  Try(tkgrid(tklabel(ttGetGOName,text="Please enter the GO term.",font=.affylmGUIglobals$affylmGUIfont2)))
  Try(tkgrid(entry.GOName))
  onOK <- function()
  {
      Try(GONameText <- tclvalue(Local.GOName))
      if(nchar(GONameText)==0)
        GONameText <- "Unselected"
      Try(assign("GONameText",GONameText,affylmGUIenvironment))
      Try(tclvalue(.affylmGUIglobals$GONameTcl) <- GONameText)
      Try(tkgrab.release(ttGetGOName));Try(tkdestroy(ttGetGOName));Try(tkfocus(.affylmGUIglobals$ttMain))
  }
  Try(OK.but <-tkbutton(ttGetGOName,text="   OK   ",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
  Try(tkgrid(tklabel(ttGetGOName,text="    ")))
  Try(tkgrid(OK.but))
  Try(tkgrid.configure(OK.but))
  Try(tkgrid(tklabel(ttGetGOName,text="       ")))
  Try(tkfocus(entry.GOName))
  Try(tkbind(entry.GOName, "<Return>",onOK))
  Try(tkbind(ttGetGOName, "<Destroy>", function(){Try(tkgrab.release(ttGetGOName));Try(tkfocus(.affylmGUIglobals$ttMain));return(0)}))
  Try(tkwait.window(ttGetGOName))
  Try(tkfocus(.affylmGUIglobals$ttMain))
 #plotting parents of a specific GO term
 
  Try(i <- get("GONameText",envir=affylmGUIenvironment))

#defining the GO class
            Try(ttGetFilterMethod <- tktoplevel(.affylmGUIglobals$ttMain))
	      Try(tkwm.deiconify(ttGetFilterMethod))
            Try(tkgrab.set(ttGetFilterMethod))
            Try(tkfocus(ttGetFilterMethod))
            Try(tkwm.title(ttGetFilterMethod,"Which GO class?"))
	
 	      Try(tkgrid(tklabel(ttGetFilterMethod,text="    ")))
	      Try(ttGetFilterMethodTcl <- tclVar("BP"))
            Try(rbIQR.5 <- tkradiobutton(ttGetFilterMethod,text="BP",variable=ttGetFilterMethodTcl,value="BP",font=.affylmGUIglobals$affylmGUIfont2))
            Try(rbIQR.25<-tkradiobutton(ttGetFilterMethod,text="MF",variable=ttGetFilterMethodTcl,value="MF",font=.affylmGUIglobals$affylmGUIfont2))
            Try(rbIQR.1<-tkradiobutton(ttGetFilterMethod,text="CC",variable=ttGetFilterMethodTcl,value="CC",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(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,tklabel(ttGetFilterMethod,text="    ")))
	      Try(tkgrid.configure(OK.but,sticky="e"))
	      Try(tkgrid.configure(Cancel.but,sticky="w"))
	      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(tkwait.window(ttGetFilterMethod))
  if(ReturnVal=="BP"){
     tfG <- GOGraph(i, GOBPPARENTS)
     rootNames <- c("all", "top")
     root <- rootNames[rootNames %in% nodes(tfG)]
     if (length(root) > 0)  tfG <- removeNode(root, tfG)
     nL <- nodes(tfG)
     nLterm = unlist(getGOTerm(nL), use.names=FALSE)
     names(nLterm) = nL
     nLterm = gsub("_", " ", nLterm)
     tGfnA <- list()
     tmp <- rep("ellipse", length(nL))
     names(tmp) <- nL
     tGfnA$shape = tmp;
     tmp <- rep(FALSE, length(nL))
     names(tmp) = nL
     tGfnA$fixedsize = tmp
     names(nLterm) <- nL
     tGfnA$label = nLterm
     Try(tkmessageBox(title="Plotting GO parents",message="Plot of GO term parents will be displayed on the main R window",icon="info",type="ok"))
     plot(tfG, nodeAttrs=tGfnA)
  } else if(ReturnVal=="MF"){
     tfG <- GOGraph(i, GOMFPARENTS)
     rootNames <- c("all", "top")
     root <- rootNames[rootNames %in% nodes(tfG)]
     if (length(root) > 0)  tfG <- removeNode(root, tfG)
     nL <- nodes(tfG)
     nLterm = unlist(getGOTerm(nL), use.names=FALSE)
     names(nLterm) = nL
     nLterm = gsub("_", " ", nLterm)
     tGfnA <- list()
     tmp <- rep("ellipse", length(nL))
     names(tmp) <- nL
     tGfnA$shape = tmp;
     tmp <- rep(FALSE, length(nL))
     names(tmp) = nL
     tGfnA$fixedsize = tmp
     names(nLterm) <- nL
     tGfnA$label = nLterm
     Try(tkmessageBox(title="Plotting GO parents",message="Plot of GO term parents will be displayed on the main R window",icon="info",type="ok"))
     plot(tfG, nodeAttrs=tGfnA)
  } else if(ReturnVal=="CC"){

     tfG <- GOGraph(i, GOCCPARENTS)
     rootNames <- c("all", "top")
     root <- rootNames[rootNames %in% nodes(tfG)]
     if (length(root) > 0)  tfG <- removeNode(root, tfG)
     nL <- nodes(tfG)
     nLterm = unlist(getGOTerm(nL), use.names=FALSE)
     names(nLterm) = nL
     nLterm = gsub("_", " ", nLterm)
     tGfnA <- list()
     tmp <- rep("ellipse", length(nL))
     names(tmp) <- nL
     tGfnA$shape = tmp;
     tmp <- rep(FALSE, length(nL))
     names(tmp) = nL
     tGfnA$fixedsize = tmp
     names(nLterm) <- nL
     tGfnA$label = nLterm
     Try(tkmessageBox(title="Plotting GO parents",message="Plot of GO term parents will be displayed on the main R window",icon="info",type="ok"))
     plot(tfG, nodeAttrs=tGfnA)
  } else{
      Try(return())
  } 
}
################################################################################

#This function starts for a topTable and extracts the subset of probe ids associated to a GO class
#found differentially expressed using the Goenrichment function
"extractAffyids" <- function(){
  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
#  require(annotate, quietly = TRUE) || stop("\nneed data package: annotate\n")
#  require(annaffy, quietly = TRUE) || stop("\nneed data package: annaffy\n")
  #error if no data are loaded
  Try(whichArrayPlatform <- get("whichArrayPlatform",envir=affylmGUIenvironment))
  if(whichArrayPlatform ==""){
            Try(tkmessageBox(title="GO analysis",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(ttGetGOName<-tktoplevel(.affylmGUIglobals$ttMain))
  Try(tkwm.deiconify(ttGetGOName))
  Try(tkgrab.set(ttGetGOName))
  Try(tkfocus(ttGetGOName))
  Try(tkwm.title(ttGetGOName,"GO class identifier"))
  Try(tkgrid(tklabel(ttGetGOName,text="    ")))
  Try(GONameText <- "")
  Try(Local.GOName <- tclVar(init=GONameText))
  Try(entry.GOName <-tkentry(ttGetGOName,width="10",font=.affylmGUIglobals$affylmGUIfont2,textvariable=Local.GOName,bg="white"))
  Try(tkgrid(tklabel(ttGetGOName,text="Please enter the GO term.",font=.affylmGUIglobals$affylmGUIfont2)))
  Try(tkgrid(entry.GOName))
  onOK <- function()
  {
      Try(GONameText <- tclvalue(Local.GOName))
      if(nchar(GONameText)==0)
        GONameText <- "Unselected"
      Try(assign("GONameText",GONameText,affylmGUIenvironment))
      Try(tclvalue(.affylmGUIglobals$GONameTcl) <- GONameText)
      Try(tkgrab.release(ttGetGOName));Try(tkdestroy(ttGetGOName));Try(tkfocus(.affylmGUIglobals$ttMain))
  }
  Try(OK.but <-tkbutton(ttGetGOName,text="   OK   ",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
  Try(tkgrid(tklabel(ttGetGOName,text="    ")))
  Try(tkgrid(OK.but))
  Try(tkgrid.configure(OK.but))
  Try(tkgrid(tklabel(ttGetGOName,text="       ")))
  Try(tkfocus(entry.GOName))
  Try(tkbind(entry.GOName, "<Return>",onOK))
  Try(tkbind(ttGetGOName, "<Destroy>", function(){Try(tkgrab.release(ttGetGOName));Try(tkfocus(.affylmGUIglobals$ttMain));return(0)}))
  Try(tkwait.window(ttGetGOName))
  Try(tkfocus(.affylmGUIglobals$ttMain))
  
  Try(x <- get("NormalizedAffyData",envir=affylmGUIenvironment))

#passing a library to a function
#  getDataEnv <- function(name, lib) {
#        	get(paste(lib, name, sep = ""), mode = "environment")
#    	}

#opening a file graphically
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=T, as.is=TRUE)
         return(mySel)
      }

  if(!is.numeric(x)){
     #in case of exon arrays I use the LLMapping libraries
     if(whichArrayPlatform=="EXON"){
         whichLib <- get("whichLib", envir=affylmGUIenvironment)
                    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(i <- get("GONameText",envir=affylmGUIenvironment))
         i.name <- strsplit(i, ":")
         #lltoacc <- as.character(unlist(lookUp(as.character(acc), lib, "ACCNUM2EG")))
         #allGO <- unlist(mget(i, env=getDataEnv("GO2LL", lib)))
         #allGO <- unlist(lookUp(as.character(i), lib, "GO2EG"))    #select only the egs associated to the GO terms
         allGO <- unlist(lookUp(as.character(i), lib, "GO2ALLEGS")) #selects the egs associated to the term and to the childrens
  
     }else{  
         lib= .annotation(x)
         if(length(as.character(unlist(strsplit(lib, "\\.")))) == 1){
                   Try(lib <- paste(lib, ".db", sep=""))
         }
        	require(lib, character.only = TRUE) || stop("need data package: ", lib)
          Try(i <- get("GONameText",envir=affylmGUIenvironment))
          i.name <- strsplit(i, ":")
          allGO <- unlist(lookUp(as.character(i), lib,"GO2ALLPROBES"))
    }
      Try(tkmessageBox(title="DF in GO term",message="Select the file containing the set of differentially expressed probe sets",icon="info",type="ok"))
      tmp.x <- OpenAFile()
      if(dim(tmp.x)[2]>1){
            Try(tkmessageBox(title="Extracting Affy IDs",message=paste("Input file should contain\nonly a column with\nAffymetrix ids")))  
      }
      
      if(whichArrayPlatform=="EXON"){
        #Try(annlibloc <- grep(paste("^",whichLib[[1]][1],sep=""), as.vector(unlist(data(package="oneChannelGUI"))), ignore.case = T))
        #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(gNsel<-as.character(tmp.x[,1]))#gene level ids
        Try(myacc <- as.character(exonannlib$ACC[which(as.character(exonannlib$PROBESETID)%in%gNsel)])) #defining the acc of diff exprs
        Try(myacc <- myacc[!is.na(myacc)])
        #Try(mylltoacc <- mget(myacc,getDataEnv("ACCNUM2LL", lib), ifnotfound=""))#LL ids
        Try(mylltoacc <- as.character(unlist(lookUp(myacc, lib, "ACCNUM2EG"))))
        Try(gNll <- unique(as.character(unlist(mylltoacc))))#ll of diff exprs data
        Try(gNll <- gNll[!is.na(gNll)])
        Try(gNll <- gNll[gNll != ""])
        Try(dfGO <- as.character(unlist(allGO[which(allGO%in% gNll)])))
        #Try(myaccfromll <- mget(as.character(unlist(dfGO)),getDataEnv("LL2ACCNUM", lib), ifnotfound=""))#back to acc
        Try(myaccfromll <- as.character(unlist(lookUp(dfGO,lib, "ACCNUM"))))
        if (length(dfGO)>0){
            Try(mysubset <-  exonannlib[which(exonannlib$ACC%in%myaccfromll),])#To be sure that the subset of probe set associaoted to GO terms is really attached to the sub set of  gene level exon probe set under analysis.
            Try(mysubset <- mysubset[which(mysubset$PROBESETID%in%gNsel),])#To be sure that the subset of probe set associaoted to GO terms is really attached to the sub set of  gene level exon probe set under analysis.
            Try(tkmessageBox(title="DF in GO term",message="Gene level annotation for differentially expressed probe sets will be saved with annotation in a TXT file",icon="info",type="ok"))
            #saving the filtered subset
            SaveTopTable <- function()
           {
               Try(FileName <- tclvalue(tkgetSaveFile(initialfile=paste("df.ids.from.GO.",i.name[[1]][2],".txt",sep=""),filetypes="{{Tab-Delimited Text Files} {.txt .xls}} {{All files} *}")))
               Try(if(!nchar(FileName))
               return())
               Try(write.table(mysubset,file=FileName,quote=FALSE, sep="\t", row.names=F))
          }
          SaveTopTable()
        }
      }else{
        gNsel<-as.character(tmp.x[,1])
        dfGO <- allGO[which(allGO%in% gNsel)]
        if (length(dfGO)>0){
            dfGO <- unique(sort(dfGO))
            anntable <- aafTableAnn(dfGO, lib, colnames=aaf.handler())
            #saving results in a HTML file
            Try(tkmessageBox(title="DF in GO term",message="Differentially expressed probe sets will be saved with annotation in a HTML file",icon="info",type="ok"))
            SaveHtmlTable <- function()
           {
               Try(FileName <- tclvalue(tkgetSaveFile(initialfile=paste("df.ids.from.GO.",i.name[[1]][2],".html",sep=""),filetypes="{{Tab-Delimited Text Files} {.txt .xls}} {{All files} *}")))
               Try(if(!nchar(FileName))
               return())
               Try(saveHTML(anntable, FileName, title = paste("Differentially expressed probe sets in ",i, sep="")))
           }
           SaveHtmlTable()
        } else  Try(tkmessageBox(title="Extract Affy IDs",message="No affy IDs  could be found associated to this GO term", type="ok",icon="error"))
     }
 } else   Try(tkmessageBox(title="Extract Affy IDs",message=paste("A set of arrays should be loaded and normalized"), type="ok",icon="error"))
 Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
}
################################################################################

templA<-function(){
        Try(NormalizedAffyData.Available <- get("NormalizedAffyData.Available",envir=affylmGUIenvironment))
        if(NormalizedAffyData.Available){
           Try(NormalizedAffyData <- get("NormalizedAffyData",envir=affylmGUIenvironment))
        } else {            
           Try(tkmessageBox(title="Creating an Ingenuity Template A",message="Normalized data set is not loaded"))
           return()
        }
        ##selecting the type of differentially expressed topTabe
        Try(ttGetTableMethod <- tktoplevel(.affylmGUIglobals$ttMain))
	      Try(tkwm.deiconify(ttGetTableMethod))
        Try(tkgrab.set(ttGetTableMethod))
        Try(tkfocus(ttGetTableMethod))
        Try(tkwm.title(ttGetTableMethod,"LIMMA/SAM/RankProd output?"))
	      Try(tkgrid(tklabel(ttGetTableMethod,text="    ")))
	      Try(ttGetTableMethodTcl <- tclVar("LIMMA"))
        Try(rbIQR.5 <- tkradiobutton(ttGetTableMethod,text="LIMMA",variable=ttGetTableMethodTcl,value="LIMMA",font=.affylmGUIglobals$affylmGUIfont2))
        Try(rbIQR.25<-tkradiobutton(ttGetTableMethod,text="SAM",variable=ttGetTableMethodTcl,value="SAM",font=.affylmGUIglobals$affylmGUIfont2))
        Try(rbIQR.1<-tkradiobutton(ttGetTableMethod,text="RankProd",variable=ttGetTableMethodTcl,value="RankProd",font=.affylmGUIglobals$affylmGUIfont2))
	      Try(tkgrid(tklabel(ttGetTableMethod,text="    "),rbIQR.5))
	      Try(tkgrid(tklabel(ttGetTableMethod,text="    "),rbIQR.25))
	      Try(tkgrid(tklabel(ttGetTableMethod,text="    "),rbIQR.1))
	      Try(tkgrid.configure(rbIQR.5,rbIQR.25,rbIQR.1,columnspan=2,sticky="w"))
	      Try(tkgrid(tklabel(ttGetTableMethod,text="    "),tklabel(ttGetTableMethod,text="    ")))
	      Try(ReturnVal <- "")
	      Try(onCancel <- function() {Try(ReturnVal <<- "");Try(tkgrab.release(ttGetTableMethod));Try(tkdestroy(ttGetTableMethod));Try(tkfocus(.affylmGUIglobals$ttMain))})
	      Try(onOK <- function() {Try(ReturnVal <<- tclvalue(ttGetTableMethodTcl));Try(tkgrab.release(ttGetTableMethod));Try(tkdestroy(ttGetTableMethod));Try(tkfocus(.affylmGUIglobals$ttMain))})

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

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

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

	      Try(tkwait.window(ttGetTableMethod))
	      
        if(ReturnVal==""){return()} else{
              #loading a topTable
              Try(tkmessageBox(title="Creating an Ingenuity Template A",message=paste("Open the file containing the table generated in oneChannelGUI by ", ReturnVal,  " methods.")))
              Try(tempFileName <- tclvalue(tkgetOpenFile(filetypes="{{Text Files} {.txt, .xls}} {{All files} *}")))
              if(!nchar(tempFileName)){
                  tkfocus(.affylmGUIglobals$ttMain)
                  return()
              }
              Try(tmp<-read.table(tempFileName, sep="\t", header=T, as.is=TRUE, quote = ""))
              if(ReturnVal == "LIMMA"){
                 if(length(tmp[,1]) == length(unique(tmp[,1]))){
                   Try(id <- featureNames(NormalizedAffyData))
                   Try(fc <- rep("",length(id)))#creating a vector of FC empty
                   Try(names(fc) <- featureNames(NormalizedAffyData))
                   Try(whichArrayPlatform <- get("whichArrayPlatform",envir=affylmGUIenvironment))
                   if(whichArrayPlatform == "EXON"){
                   ####getting acc
                   Try(whichLib <- get("whichLib", envir=affylmGUIenvironment)) 
                   #Try(annlibloc <- grep(paste("^",whichLib[[1]][1],sep=""), as.vector(unlist(data(package="oneChannelGUI"))), ignore.case = T))
                   #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(genelist <- featureNames(NormalizedAffyData))#normalizeAffyData in x
                   Try(acc <- as.character(exonannlib$ACC[which(as.character(exonannlib$PROBESETID)%in%id)])) #defining the universe of ll
                   Try(probeset <- as.character(exonannlib$PROBESETID[which(as.character(exonannlib$PROBESETID)%in%id)]))#needed to have the same orientation of probe set ids and acc
                   Try(names(acc) <- probeset)
                    #######
                       Try(fc[which(names(fc)%in%as.character(tmp[,1]))] <- tmp[,6]) 
                   } else {
                       Try(fc[which(names(fc)%in%as.character(tmp[,1]))] <- tmp[,4]) #adding the known fc for the differentially expressed genes 
                   }
                   Try(pval.true <- rep(1,length(id)))#creating a vector of p-val empty
                   Try(names(pval.true) <- featureNames(NormalizedAffyData))
                   if(whichArrayPlatform == "EXON"){
                       Try(pval.true[which(names(pval.true)%in%as.character(tmp[,1]))] <- tmp[,9]) 
                   } else {
                       Try(pval.true[which(names(pval.true)%in%as.character(tmp[,1]))] <- tmp[,7]) #adding the known fc for the differentially expressed genes
                   }
                    Try(pval <- rep(1,length(id)))#creating a vector of p-val empty
                   Try(names(pval) <- featureNames(NormalizedAffyData))
                   Try(pval[which(names(pval)%in%as.character(tmp[,1]))] <- 0) #adding the known fc for the differentially expressed genes 
                   Try(absent <- rep("",length(id)))
                   Try(override <- rep("",length(id)))
                   Try(out<-data.frame(id,fc,pval,pval.true,absent,override))
                   Try(names(out)<-c("Gene/Protein ID","Fold change","P value for subsetting","True P value", "Absent", "Override"))
                   if(whichArrayPlatform == "EXON"){
                        Try(out <- out[order(out[,1]),])
                        Try(acc <- acc[order(names(acc))])
                      if(identical(as.character(out[,1]), as.character(names(acc)))){ 
                           Try(out[,1] <- acc)
                      } else {
                                 Try(tkmessageBox(title="Creating an Ingenuity Template A",message="Internal error in templA for exon arrays.\nPlease, contact the oneChannelGUI mantainer."))
                                 Try(return())
                      }
                   }
               }  else {
                          Try(tkmessageBox(title="Creating an Ingenuity Template A",message="Chech your table of differentially expressed genes for the presence of duplicated probe sets\nremove them before creating the templateA."))
                          Try(return())
                  }
             } else if (ReturnVal == "RankProd"){
                 if(length(tmp[,1]) == length(unique(tmp[,1]))){  
                   Try(id <- featureNames(NormalizedAffyData))
                   Try(fc <- rep("",length(id)))#creating a vector of FC empty
                   Try(names(fc) <- featureNames(NormalizedAffyData))
                   Try(fc[which(names(fc)%in%as.character(tmp[,1]))] <- tmp[,6]) #adding the known fc for the differentially expressed genes
                   Try(pval.true <- rep(1,length(id)))#creating a vector of p-val empty
                   Try(names(pval.true) <- featureNames(NormalizedAffyData))
                   Try(pval.true[which(names(pval.true)%in%as.character(tmp[,1]))] <- tmp[,8]) #adding the known pval for the differentially expressed genes
                   Try(pval <- rep(1,length(id)))#creating a vector of p-val empty
                   Try(names(pval) <- featureNames(NormalizedAffyData))
                   Try(pval[which(names(pval)%in%as.character(tmp[,1]))] <- 0) #adding the selection p val for the differentially expressed genes
                   Try(absent <- rep("",length(id)))
                   Try(override <- rep("",length(id)))
                   Try(out<-data.frame(id,fc,pval,pval.true,absent,override))
                   names(out)<-c("Gene/Protein ID","Fold change","P value for subsetting","True P value", "Absent", "Override")
                 } else {
                          Try(tkmessageBox(title="Creating an Ingenuity Template A",message="Chech your table of differentially expressed genes for the presence of duplicated probe sets\nremove them before creating the templateA."))
                          Try(return())
                   }            
              } else if (ReturnVal == "SAM"){
                 if(length(tmp[,1]) == length(unique(tmp[,1]))){
                   Try(id <- featureNames(NormalizedAffyData))
                   Try(fc <- rep("",length(id)))#creating a vector of FC empty
                   Try(names(fc) <- featureNames(NormalizedAffyData))
                   Try(fc[which(names(fc)%in%as.character(tmp[,1]))] <- tmp[,8]) #adding the known fc for the differentially expressed genes
                   Try(pval.true <- rep(1,length(id)))#creating a vector of p-val empty
                   Try(names(pval.true) <- featureNames(NormalizedAffyData))
                   Try(pval.true[which(names(pval.true)%in%as.character(tmp[,1]))] <- tmp[,6]) #adding the known pval for the differentially expressed genes
                   Try(pval <- rep(1,length(id)))#creating a vector of p-val empty
                   Try(names(pval) <- featureNames(NormalizedAffyData))
                   Try(pval[which(names(pval)%in%as.character(tmp[,1]))] <- 0) #adding the selection p-val for the differentially expressed genes
                   Try(absent <- rep("",length(id)))
                   Try(override <- rep("",length(id)))
                   Try(out<-data.frame(id,fc,pval,pval.true,absent,override))
                   names(out)<-c("Gene/Protein ID","Fold change","P value for subsetting","True P value", "Absent", "Override")             
                }  else {
                          Try(tkmessageBox(title="Creating an Ingenuity Template A",message="Chech your table of differentially expressed genes for the presence of duplicated probe sets\nremove them before creating the templateA."))
                          Try(return())
                   }
                }
      #saving the filtered subset
      SaveTopTable <- function()
      {
               Try(FileName <- tclvalue(tkgetSaveFile(initialfile=paste(tempFileName,".templA",".xls",sep=""),filetypes="{{Tab-Delimited Text Files} {.txt .xls}} {{All files} *}")))
               Try(if(!nchar(FileName))
               return())
               Try(write.table(out,file=FileName,quote=FALSE, sep="\t", row.names=F))
      }
             

      Try(mbVal <- tkmessageBox(title="Ingenuity template A",
                message="Save the templateA for IPA upload\nRemember: the differentially expressed genes can be subsetted in Ingenuity \nsetting to 0 the threshold for P.value.for.subsetting column.",
                icon="question",type="yesno",default="yes"))
                try(if(tclvalue(mbVal)=="yes") SaveTopTable())
   }
}
################################################################################

metaArrayMerge <- function(){
     #    require(metaArray) || stop("library metaArray could not be found !")
     #    require(MergeMaid) || stop("\nMissing MergeMaid package\n")
     #    require(affy) || stop("library affy could not be found !")
         #opening a file graphically
         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=T, as.is=TRUE, row.names=1)
                 return(mySel)
         }
         #error if no data are loaded
         Try(whichArrayPlatform <- get("whichArrayPlatform",envir=affylmGUIenvironment))
         if(whichArrayPlatform ==""){
              Try(tkmessageBox(title="Meta analysis",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(NormalizedAffyData.Available     <- get("NormalizedAffyData.Available" , envir=affylmGUIenvironment))
        if(NormalizedAffyData.Available){
              Try(NormalizedAffyData     <- get("NormalizedAffyData" , envir=affylmGUIenvironment))

              ##makning the menu for selecting IQR threshold
              Try(ttMetaSet <- tktoplevel(.affylmGUIglobals$ttMain))
	            Try(tkwm.deiconify(ttMetaSet))
              Try(tkgrab.set(ttMetaSet))
              Try(tkfocus(ttMetaSet))
              Try(tkwm.title(ttMetaSet,"How many data sets will be merged to NormalizedAffyData?"))
 	            Try(tkgrid(tklabel(ttMetaSet,text="    ")))
	            Try(ttMetaSetTcl <- tclVar("1"))
              Try(rbM1 <- tkradiobutton(ttMetaSet,text="1 data set",variable=ttMetaSetTcl,value="1",font=.affylmGUIglobals$affylmGUIfont2))
              Try(rbM2<-tkradiobutton(ttMetaSet,text="2 data sets",variable=ttMetaSetTcl,value="2",font=.affylmGUIglobals$affylmGUIfont2))
              Try(rbM3<-tkradiobutton(ttMetaSet,text="3 data sets",variable=ttMetaSetTcl,value="3",font=.affylmGUIglobals$affylmGUIfont2))
	            Try(tkgrid(tklabel(ttMetaSet,text="    "),rbM1))
	            Try(tkgrid(tklabel(ttMetaSet,text="    "),rbM2))
	            Try(tkgrid(tklabel(ttMetaSet,text="    "),rbM3))
	            Try(tkgrid.configure(rbM1,rbM2,rbM3,columnspan=2,sticky="w"))
	            Try(tkgrid(tklabel(ttMetaSet,text="    "),tklabel(ttMetaSet,text="    ")))
	            Try(ReturnVal <- "")
	            Try(onCancel <- function() {Try(tkgrab.release(ttMetaSet));Try(tkdestroy(ttMetaSet));Try(tkfocus(.affylmGUIglobals$ttMain)); Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"));Try(return())})
	            Try(onOK <- function() {Try(ReturnVal <<- tclvalue(ttMetaSetTcl));Try(tkgrab.release(ttMetaSet));Try(tkdestroy(ttMetaSet));Try(tkfocus(.affylmGUIglobals$ttMain))})
	            Try(OK.but     <- tkbutton(ttMetaSet,text="OK",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
	            Try(Cancel.but <- tkbutton(ttMetaSet,text="Cancel",command=onCancel,font=.affylmGUIglobals$affylmGUIfont2))

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

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

              if(ReturnVal=="1"){
                   #target second set
                   Try(tkmessageBox(title="Selecting the target file of the data set to be merged to NormalizedAffyData",message="Open the target file of the associated to the data set to be merged\nThis is a standard oneChannelGUI target file!", type="ok", icon="info"))  
                   Try(secondSetpData <- OpenAFile())
                   Try(rownames(secondSetpData) <- secondSetpData$FileName) 
                   Try(var.tmp.pd<-data.frame(names(secondSetpData)))
                   Try(names(var.tmp.pd)<-"labelDescription" )
                   Try(rownames(var.tmp.pd)<-names(secondSetpData))
                   Try(tmp1.pd<-new("AnnotatedDataFrame", data=secondSetpData, varMetadata=var.tmp.pd))
                   #data second set
                   Try(tkmessageBox(title="Selecting the data set to be merged to NormalizedAffyData",message="Only tab delimited files, with array names in header and 1st column with probe set ids", type="ok", icon="info"))  
                   Try(secondSet <- OpenAFile())
                   Try(secondSet <- new("ExpressionSet", exprs=as.matrix(secondSet), phenoData=tmp1.pd, annotation=""))
                   if(identical(featureNames(NormalizedAffyData),featureNames(secondSet))){
                         Try(merged <- mergeExprs(NormalizedAffyData, secondSet))
                         Try(assign("metaData.Available",TRUE,affylmGUIenvironment))
                         Try(assign("metaData",merged,affylmGUIenvironment))
                         Try(tkdelete(.affylmGUIglobals$mainTree,"metaData.Status"))            
                         Try(tkinsert(.affylmGUIglobals$mainTree,"end","metaData","metaData.Status" ,text="Available",font=.affylmGUIglobals$affylmGUIfontTree))
                   } else {
                         Try(common <- length(intersect(featureNames(NormalizedAffyData),featureNames(secondSet))))
                         Try(metaVal <- tkmessageBox(title="Meta analysis",
				    											message=paste("The two datasets have in common ",common," probe sets.\nDo you wish to continue the analysis on them?",sep=""),
						    									icon="question",type="yesno",default="yes"
								    						 )#end of tkmessageBox
		                     )#end of Try(mbVal..
		                     if(tclvalue(metaVal)=="no"){Try(return())}
		                     Try(commonSet <- intersect(featureNames(NormalizedAffyData),featureNames(secondSet)))
                         Try(merged <- mergeExprs(NormalizedAffyData[which(featureNames(NormalizedAffyData)%in%commonSet),], secondSet[which(featureNames(secondSet)%in%commonSet),]))
                         Try(assign("metaData.Available",TRUE,affylmGUIenvironment))
                         Try(assign("metaData",merged,affylmGUIenvironment))
                         Try(tkdelete(.affylmGUIglobals$mainTree,"metaData.Status"))            
                         Try(tkinsert(.affylmGUIglobals$mainTree,"end","metaData","metaData.Status" ,text="Available 2 sets",font=.affylmGUIglobals$affylmGUIfontTree))
                  }
              } else if(ReturnVal=="2"){
                   #target second set
                   Try(tkmessageBox(title="Selecting the target file of the 1st data set to be merged to NormalizedAffyData",message="Open the target file of the associated to the 1ST data set to be merged\nThis is a standard oneChannelGUI target file!", type="ok", icon="info"))  
                   Try(tmppData <- OpenAFile())
                   Try(rownames(tmppData) <- tmppData$FileName) 
                   Try(var.tmp.pd<-data.frame(names(tmppData)))
                   Try(names(var.tmp.pd)<-"labelDescription" )
                   Try(rownames(var.tmp.pd)<-names(tmppData))
                   Try(tmp1.pd<-new("AnnotatedDataFrame", data=tmppData, varMetadata=var.tmp.pd))
                   #data second set
                   Try(tkmessageBox(title="Selecting the 1st data set to be merged to NormalizedAffyData",message="1ST data set: Only tab delimited files, with array names in header and 1st column with probe set ids", type="ok", icon="info"))  
                   Try(tmpSet <- OpenAFile())
                   Try(secondSet <- new("ExpressionSet", exprs=as.matrix(tmpSet), phenoData=tmp1.pd, annotation=""))

                   #target 3rd set
                   Try(tkmessageBox(title="Selecting the target file of the 2nd data set to be merged to NormalizedAffyData",message="Open the target file of the associated to the 2ND data set to be merged\nThis is a standard oneChannelGUI target file!", type="ok", icon="info"))  
                   Try(tmppData <- OpenAFile())
                   Try(rownames(tmppData) <- tmppData$FileName) 
                   Try(var.tmp.pd<-data.frame(names(tmppData)))
                   Try(names(var.tmp.pd)<-"labelDescription" )
                   Try(rownames(var.tmp.pd)<-names(tmppData))
                   Try(tmp1.pd<-new("AnnotatedDataFrame", data=tmppData, varMetadata=var.tmp.pd))
                   #data 3rd set
                   Try(tkmessageBox(title="Selecting the 2nd data set to be merged to NormalizedAffyData",message="2ND dataset: Only tab delimited files, with array names in header and 1st column with probe set ids", type="ok", icon="info"))  
                   Try(tmpSet <- OpenAFile())
                   Try(thirdSet <- new("ExpressionSet", exprs=as.matrix(tmpSet), phenoData=tmp1.pd, annotation=""))

                   if(identical(featureNames(NormalizedAffyData),featureNames(secondSet)) 
                       & identical(featureNames(NormalizedAffyData),featureNames(thirdSet))){
                         Try(merged <- mergeExprs(NormalizedAffyData, secondSet, thirdSet))
                         Try(assign("metaData.Available",TRUE,affylmGUIenvironment))
                         Try(assign("metaData",merged,affylmGUIenvironment))
                         Try(tkdelete(.affylmGUIglobals$mainTree,"metaData.Status"))            
                         Try(tkinsert(.affylmGUIglobals$mainTree,"end","metaData","metaData.Status" ,text="Available 3 sets",font=.affylmGUIglobals$affylmGUIfontTree))
                   } else {
                         Try(tkmessageBox(title="Meta analysis",message="Data sets do not share the same identifiers!",type="ok",icon="error"))
				    	           Try(tkfocus(.affylmGUIglobals$ttMain))
                         Try(return())
    
                  }
              } else if(ReturnVal=="3"){
                   #target second set
                   Try(tkmessageBox(title="Selecting the target file of the 1st data set to be merged to NormalizedAffyData",message="Open the target file of the associated to the 1ST data set to be merged\nThis is a standard oneChannelGUI target file!", type="ok", icon="info"))  
                   Try(tmppData <- OpenAFile())
                   Try(rownames(tmppData) <- tmppData$FileName) 
                   Try(var.tmp.pd<-data.frame(names(tmppData)))
                   Try(names(var.tmp.pd)<-"labelDescription" )
                   Try(rownames(var.tmp.pd)<-names(tmppData))
                   Try(tmp1.pd<-new("AnnotatedDataFrame", data=tmppData, varMetadata=var.tmp.pd))
                   #data second set
                   Try(tkmessageBox(title="Selecting the 1st data set to be merged to NormalizedAffyData",message="1ST data set: Only tab delimited files, with array names in header and 1st column with probe set ids", type="ok", icon="info"))  
                   Try(tmpSet <- OpenAFile())
                   Try(secondSet <- new("ExpressionSet", exprs=as.matrix(tmpSet), phenoData=tmp1.pd, annotation=""))

                   #target 3rd set
                   Try(tkmessageBox(title="Selecting the target file of the 2nd data set to be merged to NormalizedAffyData",message="Open the target file of the associated to the 2ND data set to be merged\nThis is a standard oneChannelGUI target file!", type="ok", icon="info"))  
                   Try(tmppData <- OpenAFile())
                   Try(rownames(tmppData) <- tmppData$FileName) 
                   Try(var.tmp.pd<-data.frame(names(tmppData)))
                   Try(names(var.tmp.pd)<-"labelDescription" )
                   Try(rownames(var.tmp.pd)<-names(tmppData))
                   Try(tmp1.pd<-new("AnnotatedDataFrame", data=tmppData, varMetadata=var.tmp.pd))
                   #data 3rd set
                   Try(tkmessageBox(title="Selecting the 2nd data set to be merged to NormalizedAffyData",message="2ND data file: Only tab delimited files, with array names in header and 1st column with probe set ids", type="ok", icon="info"))  
                   Try(tmpSet <- OpenAFile())
                   Try(thirdSet <- new("ExpressionSet", exprs=as.matrix(tmpSet), phenoData=tmp1.pd, annotation=""))

                   #target 4th set
                   Try(tkmessageBox(title="Selecting the target file of the 3rd data set to be merged to NormalizedAffyData",message="Open the target file of the associated to the 3RD data set to be merged\nThis is a standard oneChannelGUI target file!", type="ok", icon="info"))  
                   Try(tmppData <- OpenAFile())
                   Try(rownames(tmppData) <- tmppData$FileName) 
                   Try(var.tmp.pd<-data.frame(names(tmppData)))
                   Try(names(var.tmp.pd)<-"labelDescription" )
                   Try(rownames(var.tmp.pd)<-names(tmppData))
                   Try(tmp1.pd<-new("AnnotatedDataFrame", data=tmppData, varMetadata=var.tmp.pd))
                   #data 4th set
                   Try(tkmessageBox(title="Selecting the 2nd data set to be merged to NormalizedAffyData",message="3RD data file: Only tab delimited files, with array names in header and 1st column with probe set ids", type="ok", icon="info"))  
                   Try(tmpSet <- OpenAFile())
                   Try(fourthSet <- new("ExpressionSet", exprs=as.matrix(tmpSet), phenoData=tmp1.pd, annotation=""))

                   if(identical(featureNames(NormalizedAffyData),featureNames(secondSet)) 
                      & identical(featureNames(NormalizedAffyData),featureNames(thirdSet)) 
                      & identical(featureNames(NormalizedAffyData),featureNames(fourthSet))){
                         Try(merged <- mergeExprs(NormalizedAffyData, secondSet, thirdSet, fourthSet))
                         Try(assign("metaData.Available",TRUE,affylmGUIenvironment))
                         Try(assign("metaData",merged,affylmGUIenvironment))
                         Try(tkdelete(.affylmGUIglobals$mainTree,"metaData.Status"))            
                         Try(tkinsert(.affylmGUIglobals$mainTree,"end","metaData","metaData.Status" ,text="Available 3 sets",font=.affylmGUIglobals$affylmGUIfontTree))
                   } else {
                         Try(tkmessageBox(title="Meta analysis",message="Data sets do not share the same identifiers!",type="ok",icon="error"))
				    	           Try(tkfocus(.affylmGUIglobals$ttMain))
                         Try(return())
    
                  }
              }

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

metaArrayIC <- function(){
       #  require(metaArray) || stop("library metaArray could not be found !")
        # require(MergeMaid) || stop("\nMissing MergeMaid package\n")

         SaveICTable <- function()
	       {
		                Try(FileName <- tclvalue(tkgetSaveFile(initialfile="IC.table.xls",filetypes="{{Tab-Delimited Text Files} {.txt .xls}} {{All files} *}")))
		                Try(if(!nchar(FileName))
			     	              return())
		                Try(write.table(merged.cor$pair.cor,file=FileName,quote=FALSE,col.names=NA,sep="\t"))
         }

         #error if no data are loaded
         Try(whichArrayPlatform <- get("whichArrayPlatform",envir=affylmGUIenvironment))
         if(whichArrayPlatform ==""){
              Try(tkmessageBox(title="Meta analysis",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(metaData.Available <- get("metaData.Available",envir=affylmGUIenvironment))    
         if(metaData.Available){
                Try(metaData <- get("metaData",envir=affylmGUIenvironment))
                Try(merged.cor <- intcor(metaData))
                #Try(merged.cor <- intCor(metaData))   #from MergeMaid
                #Try(mycor <- pairwise.cors(merged.cor))    #from MergeMaid
                Try(mycor <- as.data.frame(merged.cor$avg.cor))
                if(dim(mycor)[2]==1){
                    Try(hist(mycor[,1], main="Average IC"))
                    Try(SaveICTable())
                } else if (dim(mycor)[2]==2){
                    par(mfrow=c(1,2))
                    Try(hist(mycor[,1], main="Average IC"))
                    Try(hist(mycor[,2], main="Average IC"))
                    Try(SaveICTable())
                } else if (dim(mycor$pair.cor)[2]==3){
                    par(mfrow=c(1,3))
                    Try(hist(mycor[,1], main="Average IC"))
                    Try(hist(mycor[,2], main="Average IC"))
                    Try(hist(mycor[,3], main="Average IC"))
                    Try(SaveICTable())
                }
                  
                    
         } else{
             Try(tkmessageBox(title="Meta analysis",message="No meta data were prepared!\nPlease try Merge function from the Biological interpretation menu.",type="ok",icon="error"))
             Try(tkfocus(.affylmGUIglobals$ttMain))
             Try(return())
         }


}
################################################################################
"getNGSannotation" <- function(){
    #  require(ChIPpeakAnno) || stop("\nMissing ChIPpeakAnno library\n")
      #which organism  and data set
      Try(ReturnAnn <<- "")
      Try(ttIfDialog<-tktoplevel(.affylmGUIglobals$ttMain))
      Try(tkwm.deiconify(ttIfDialog))
      Try(tkgrab.set(ttIfDialog))
      Try(tkfocus(ttIfDialog))
      Try(tkwm.title(ttIfDialog,"ENSEMBL Annotations"))
      Try(tkgrid(tklabel(ttIfDialog,text="    ")))
                                                   
      Try(frame1 <- tkframe(ttIfDialog,relief="groove",borderwidth=2))
      Try(HowManyQuestion1 <- tklabel(frame1,text="Select the organism under analysis",font=.affylmGUIglobals$affylmGUIfont2))
      Try(tkgrid(HowManyQuestion1))
      Try(tkgrid.configure(HowManyQuestion1,columnspan=2,sticky="w"))
      Try(thresholdTcl <- tclVar("hs"))
      Try(I1.but  <- tkradiobutton(frame1,text="Hs",variable=thresholdTcl,value="hs",font=.affylmGUIglobals$affylmGUIfont2))
      Try(I2.but  <- tkradiobutton(frame1,text="Mm",variable=thresholdTcl,value="mm",font=.affylmGUIglobals$affylmGUIfont2))
      Try(I3.but  <- tkradiobutton(frame1,text="Rn",variable=thresholdTcl,value="rn",font=.affylmGUIglobals$affylmGUIfont2))
           
      Try(tkgrid(I1.but,sticky="w"))
      Try(tkgrid(I2.but,sticky="w"))
      Try(tkgrid(I3.but,sticky="w"))
      Try(tkgrid.configure(HowManyQuestion1,I1.but,I2.but,I3.but,sticky="w"))

      Try(frame2 <- tkframe(ttIfDialog,relief="groove",borderwidth=2))
      Try(fractionLabel <- tklabel(frame2,text="ENSEMBL annotation data set",font=.affylmGUIglobals$affylmGUIfont2))
      Try(tkgrid(fractionLabel,sticky="w"))
      Try(tkgrid.configure(fractionLabel,sticky="w"))
      Try(fractionTcl <- tclVar("TSS"))
      Try(F1.but <- tkradiobutton(frame2,text="TSS",variable=fractionTcl,value="TSS",font=.affylmGUIglobals$affylmGUIfont2))
      Try(F2.but <- tkradiobutton(frame2,text="Exon",variable=fractionTcl,value="Exons",font=.affylmGUIglobals$affylmGUIfont2))
      Try(F3.but <- tkradiobutton(frame2,text="miRNA",variable=fractionTcl,value="miRNA",font=.affylmGUIglobals$affylmGUIfont2))

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

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

      Try(onOK <- function()
      {
              ReturnVal1 <- as.character(tclvalue(thresholdTcl))
              ReturnVal2 <- as.character(tclvalue(fractionTcl))
              Try(ReturnAnn <<- 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(tkgrab.release(ttIfDialog))
            Try(tkdestroy(ttIfDialog))
            Try(tkfocus(.affylmGUIglobals$ttMain))
            Try(return())
      })
      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(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
      Try(tmp <- as.character(unlist(strsplit(ReturnAnn, ";"))))
      if(ReturnAnn == ""){
           Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
           Try(return())
      } 
      if (tmp[1] == "hs" & tmp[2] == "TSS"){
         Try(mart <- useMart(biomart="ensembl",dataset="hsapiens_gene_ensembl"))
         Try(cat("\nRetrieving TSS Hs\n"))
         Try(myAnn <- getAnnotation(mart, featureType="TSS"))
      }  else if (tmp[1] == "hs" & tmp[2] == "Exon"){
         Try(mart <- useMart(biomart="ensembl",dataset="hsapiens_gene_ensembl"))
         Try(cat("\nRetrieving Exons Hs\n"))
         Try(myAnn <- getAnnotation(mart, featureType="Exon"))
       }  else if (tmp[1] == "hs" & tmp[2] == "miRNA"){
         Try(mart <- useMart(biomart="ensembl",dataset="hsapiens_gene_ensembl"))
         Try(cat("\nRetrieving miRNAs Hs\n"))
         Try(myAnn <- getAnnotation(mart, featureType="miRNA"))
       } else if (tmp[1] == "mm" & tmp[2] == "TSS"){
         Try(mart <- useMart(biomart="ensembl",dataset="mmusculus_gene_ensembl"))
         Try(cat("\nRetrieving TSS Mm\n"))
         Try(myAnn <- getAnnotation(mart, featureType="TSS"))
      }  else if (tmp[1] == "mm" & tmp[2] == "Exon"){
         Try(mart <- useMart(biomart="ensembl",dataset="mmusculus_gene_ensembl"))
         Try(cat("\nRetrieving Exons Mm\n"))
         Try(myAnn <- getAnnotation(mart, featureType="Exon"))
       }  else if (tmp[1] == "mm" & tmp[2] == "miRNA"){
         Try(mart <- useMart(biomart="ensembl",dataset="mmusculus_gene_ensembl"))
         Try(cat("\nRetrieving miRNAs Mm\n"))
         Try(myAnn <- getAnnotation(mart, featureType="miRNA"))
       }  else if (tmp[1] == "rn" & tmp[2] == "TSS"){
         Try(mart <- useMart(biomart="ensembl",dataset="rnorvegicus_gene_ensembl"))
         Try(cat("\nRetrieving TSS Rn\n"))
         Try(myAnn <- getAnnotation(mart, featureType="TSS"))
      }  else if (tmp[1] == "rn" & tmp[2] == "Exon"){
         Try(mart <- useMart(biomart="ensembl",dataset="rnorvegicus_gene_ensembl"))
         Try(cat("\nRetrieving Exons Rn\n"))
         Try(myAnn <- getAnnotation(mart, featureType="Exon"))
       }  else if (tmp[1] == "rn" & tmp[2] == "miRNA"){
         Try(mart <- useMart(biomart="ensembl",dataset="rnorvegicus_gene_ensembl"))
         Try(cat("\nRetrieving miRNAs Rn\n"))
         Try(myAnn <- getAnnotation(mart, featureType="miRNA"))
       }
       Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
       Try(assign("tmpNGSannotation",myAnn,affylmGUIenvironment))
}
################################################################################
annotateNGSeset <- function(){
     Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
  #   Try(require(ChIPpeakAnno) || stop("\nMissing ChIPpeakAnno library\n"))
     Try(getNGSannotation())
     Try(myAnn <- get("tmpNGSannotation", affylmGUIenvironment))

     #getting the decription of the peak
     Try(desAnn <- values(myAnn))
     Try(desAnn <- as.data.frame(desAnn))
     #extracting only the annotation description with a non NULL description
     Try(desAnnWdes <- setdiff(desAnn$description, desAnn$description[which(desAnn$description == "")]))
     Try(desAnn <- desAnn[which(desAnn$description %in% desAnnWdes),])

     #getting the expression data
     Try(eset <- get("NormalizedAffyData", affylmGUIenvironment))
     Try(myids <- featureNames(eset))
     Try(myidslist <- strsplit(myids, "\\."))
     Try(myspace <- sapply(myidslist, function(x) as.character(x[1]))) #chr
     Try(myspace <- sapply(myspace, function(x) sub("chr","",x)))
     Try(myspace <- as.character(unlist(myspace)))
     Try(mystrand <- sapply(myidslist, function(x) { if(as.character(x[2]) == "plus") 
                                                    return(1)
                                                 else
                                                    return(-1)
                                                }                                               
     )) #strand
     Try(mypositions <- sapply(myidslist, function(x) x[3]))
     Try(mypositions <- strsplit(mypositions, "-"))
     Try(mystart <- sapply(mypositions, function(x) as.numeric(x[1])))
     Try(myend <- sapply(mypositions, function(x) as.numeric(x[2])))
     Try(myrd <- RangedData(ranges = IRanges(start = mystart, end = myend, names = myids), space = myspace, strand = mystrand))
     Try(annotatedPeak <- annotatePeakInBatch(myrd, AnnotationData = myAnn))
     Try(annotatedPeak <- as.data.frame(annotatedPeak))
     
     #extracting only the annotation description present in the annotated peaks
     Try(desAnn <- desAnn[which(rownames(desAnn) %in% as.character(annotatedPeak$feature)),])
     
     Try(annotatedPeak.des <- rep(NA, dim(annotatedPeak)[1]))
     Try(names(annotatedPeak.des) <- as.character(annotatedPeak$feature))
     #assigning annotation
     for(i in 1:dim(desAnn)[1]){
         annotatedPeak.des[which(as.character(annotatedPeak$feature) == rownames(desAnn)[i])] <- as.character(desAnn$description)[i]
     }
     Try(annotatedPeak <- data.frame(annotatedPeak, annotatedPeak.des))
     
     Try(limmaDataSetNameText <- get("limmaDataSetNameText", affylmGUIenvironment))
     Try(FileName <- tclvalue(tkgetSaveFile(initialfile = paste(limmaDataSetNameText, 
        "_annotation.xls", sep = ""), filetypes = "{{Tab-Delimited Text Files} {.txt .xls}} {{All files} *}")))
    Try(if (!nchar(FileName)) 
        return())
    Try(len <- nchar(FileName))
    if (len <= 4) {
        Try(FileName <- paste(FileName, ".xls", sep = ""))
    }
    else if ((substring(FileName, len - 3, len) != ".txt") && 
        (substring(FileName, len - 3, len) != ".xls")) {
        Try(FileName <- paste(FileName, ".xls", sep = ""))
    }
    Try(write.table(annotatedPeak, file = FileName,  sep = "\t", quote = FALSE, col.names = T, row.names = F))
    Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
}

################################################################################
"Reads2logos" <- function(){
  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
  #error if no data are loaded
  Try(whichArrayPlatform <- get("whichArrayPlatform",envir=affylmGUIenvironment))
  if(whichArrayPlatform ==""){
              Try(tkmessageBox(title="RNA-seq analysis",message="No NGS data have been loaded.	Please try New or Open from the File menu.",type="ok",icon="error"))
				    	Try(tkfocus(.affylmGUIglobals$ttMain))
              Try(return())
  }    
  #########################
  Targets <- get("Targets",envir=affylmGUIenvironment)
  #get geneid to be investigated 
  Try(ttGetGOName<-tktoplevel(.affylmGUIglobals$ttMain))
  Try(tkwm.deiconify(ttGetGOName))
  Try(tkgrab.set(ttGetGOName))
  Try(tkfocus(ttGetGOName))
  Try(tkwm.title(ttGetGOName,"GO class identifier"))
  Try(tkgrid(tklabel(ttGetGOName,text="    ")))
  Try(GONameText <- "")
  Try(Local.GOName <- tclVar(init=GONameText))
  Try(entry.GOName <-tkentry(ttGetGOName,width="20",font=.affylmGUIglobals$affylmGUIfont2,textvariable=Local.GOName,bg="white"))
  Try(tkgrid(tklabel(ttGetGOName,text="Please enter the ENSEMBL gene ID",font=.affylmGUIglobals$affylmGUIfont2)))
  Try(tkgrid(entry.GOName))
  onOK <- function()
  {
      Try(GONameText <- tclvalue(Local.GOName))
      if(nchar(GONameText)==0)
        GONameText <- "Unselected"
      Try(assign("ENSEMBLgid",GONameText,affylmGUIenvironment))
      Try(tclvalue(.affylmGUIglobals$GONameTcl) <- GONameText)
      Try(tkgrab.release(ttGetGOName));Try(tkdestroy(ttGetGOName));Try(tkfocus(.affylmGUIglobals$ttMain))
  }
  Try(OK.but <-tkbutton(ttGetGOName,text="   OK   ",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
  Try(tkgrid(tklabel(ttGetGOName,text="    ")))
  Try(tkgrid(OK.but))
  Try(tkgrid.configure(OK.but))
  Try(tkgrid(tklabel(ttGetGOName,text="       ")))
  Try(tkfocus(entry.GOName))
  Try(tkbind(entry.GOName, "<Return>",onOK))
  Try(tkbind(ttGetGOName, "<Destroy>", function(){Try(tkgrab.release(ttGetGOName));Try(tkfocus(.affylmGUIglobals$ttMain));return(0)}))
  Try(tkwait.window(ttGetGOName))
  Try(tkfocus(.affylmGUIglobals$ttMain))
  #########################################
  Try(NormalizedAffyData     <- get("NormalizedAffyData" , envir=affylmGUIenvironment))
  Try(geneid <- get("ENSEMBLgid",envir=affylmGUIenvironment))
  
  #selecting sample or experimental group visualization
  Try(ttGetOrganism <- tktoplevel(.affylmGUIglobals$ttMain))
	Try(tkwm.deiconify(ttGetOrganism))
  Try(tkgrab.set(ttGetOrganism))
  Try(tkfocus(ttGetOrganism))
  Try(tkwm.title(ttGetOrganism,"Which output"))
	
 	Try(tkgrid(tklabel(ttGetOrganism,text="    ")))
  Try(ttGetOrganismTcl <- tclVar("covar"))
  Try(rbIQR.5 <- tkradiobutton(ttGetOrganism,text="Experimental group",variable=ttGetOrganismTcl,value="covar",font=.affylmGUIglobals$affylmGUIfont2))
  Try(rbIQR.25<-tkradiobutton(ttGetOrganism,text="Sample",variable=ttGetOrganismTcl,value="sample",font=.affylmGUIglobals$affylmGUIfont2))

  Try(tkgrid(tklabel(ttGetOrganism,text="    "),rbIQR.5))
	Try(tkgrid(tklabel(ttGetOrganism,text="    "),rbIQR.25))
	Try(tkgrid.configure(rbIQR.5,rbIQR.25,columnspan=2,sticky="w"))
	Try(tkgrid(tklabel(ttGetOrganism,text="    "),tklabel(ttGetOrganism,text="    ")))
  Try(ReturnVal <- "")
  Try(onCancel <- function() {Try(ReturnVal <<- "");Try(tkgrab.release(ttGetOrganism));Try(tkdestroy(ttGetOrganism));Try(tkfocus(.affylmGUIglobals$ttMain))})
  Try(onOK <- function() {Try(ReturnVal <<- tclvalue(ttGetOrganismTcl));Try(tkgrab.release(ttGetOrganism));Try(tkdestroy(ttGetOrganism));Try(tkfocus(.affylmGUIglobals$ttMain))})
  Try(OK.but     <- tkbutton(ttGetOrganism,text="OK",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
  Try(Cancel.but <- tkbutton(ttGetOrganism,text="Cancel",command=onCancel,font=.affylmGUIglobals$affylmGUIfont2))

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

  Try(tkbind(ttGetOrganism,"<Destroy>",function() {ReturnVal <- "";Try(tkgrab.release(ttGetOrganism));Try(tkfocus(.affylmGUIglobals$ttMain));}))
  Try(tkbind(OK.but, "<Return>",onOK))
  Try(tkbind(Cancel.but, "<Return>",onCancel))      
  Try(tkwait.window(ttGetOrganism))
  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
  
  if(ReturnVal == ""){
       Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
       Try(return())
  } else if (ReturnVal == "covar"){
       Try(what <- "covar")
  } else if (ReturnVal == "sample"){
       Try(what <- "sample")
  }
  ###########################################
  
  Try(gene.cmat <- .reads2logos(geneid = geneid, genome = NormalizedAffyData@annotation, target = Targets, what = what))
  Try(assign(geneid,gene.cmat,affylmGUIenvironment))
  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
  Try(tkmessageBox(title="Which output",message="The counts output is available in the main R windows",type="ok",icon="info"))
  Try(tkfocus(.affylmGUIglobals$ttMain))
  Try(return())

}

.maligReads <- function(x, gseq = gseq){
           nX <- c("A","C","G","T")
           nseq <- gsub('[A,C,G,T]', 'N', gseq)
           score <- strsplit(x[2], '[A,C,G,T]')
           score <- unlist(score)
           scoreX <-NULL
           if( length(score) == 1){ 
                     tmpseq <- substr(gseq,as.numeric(x[3]),(as.numeric(x[3]) + as.numeric(score)))
                      substr(nseq,as.numeric(x[3]),(as.numeric(x[3]) + as.numeric(score)))  <- tmpseq
                      
           } else if( length(score) == 2){
                     scoreX[1] <- strsplit(x[2], 'A')
                     scoreX[2] <- strsplit(x[2], 'C')
                     scoreX[3] <- strsplit(x[2], 'G')
                     scoreX[4] <- strsplit(x[2], 'T')
                     
                     start1 <- as.numeric(x[3])
                     end1 <- as.numeric(x[3]) + as.numeric(score[1])
                     tmpseq1 <- substr(gseq,start1, end1)
                     substr(nseq,start1,end1)  <- tmpseq1
                     
                     startSNP <- end1 + 1
                     endSNP <- end1 + 1
                     substr(nseq,startSNP, endSNP)  <- nX[which(sapply(scoreX, length) == 2)]
                     
                     start2 <- end1 + 2
                     end2 <- start2 + as.numeric(score[2])
                     tmpseq2 <- substr(gseq,start2, end2)
                     substr(nseq,start2,end2)  <- tmpseq2
           }
           return(nseq) 
}

".reads2logos" <- function(geneid, genome = c("hg19", "mm9", "rn4"), fasta =TRUE, what = c("covar","sample"), target){
     #selecting the sequence to be used
     #require(Biostrings) || stop("\nBiostrings package is missing\n")
     if(genome=="hg19"){
               data("hsfa" ,package="oneChannelGUI")
               myfa <- get("hsfa",envir=.GlobalEnv)
     } else if(genome=="mm9"){
               data("mmfa" ,package="oneChannelGUI")
               myfa <- get("mmfa",envir=.GlobalEnv)
     } else if(genome=="rn4"){
               data("rnfa" ,package="oneChannelGUI")
               myfa <- get("rnfa",envir=.GlobalEnv)

     } else{
             cat("\nYou have selected a genome which is not implemented. \nImplemented genomes are:\n\thg19\n\tmm9\n\trn4\n")
     }
     #getting the sequence
     mydesc <- sapply(myfa, function(x)x$desc)
     genefa <- myfa[grep(geneid, mydesc)]
     covar <- unique(as.character(target$Target))
     gseq <- genefa[[1]]$seq
     #generate logos at group level
     pwm <- list()
     if(what == "covar"){
         for(i in 1: length(covar)){
              reads.n <- NULL
              cat("\n")
              myreads <- data.frame()
              filenames <- NULL
              filenames <- target$FileName[which(target$Target == covar[i])]
              filenames <- sub("bed", "logos", filenames)
              for(j in 1: length(filenames)){
                   cat("processing ", filenames[j], "\n")
                   tmp <- read.table(filenames[j], sep="\t", as.is=T)
                   tmp <- tmp[which(tmp[,1] == geneid),]
                   myreads <- rbind( myreads, tmp)
              }
              #removing errors and any reads different from the presence of a SNP
              myreads <- myreads[setdiff(seq(1,dim(myreads)[1]), grep("-", myreads[,2])),]  #multiple deletion in thereference: "5----20"
              myreads <- myreads[setdiff(seq(1,dim(myreads)[1]), grep("x", myreads[,2])),]  # sequencing errors
              myreads <- myreads[setdiff(seq(1,dim(myreads)[1]), grep("\\(", myreads[,2])),] #multiple base insertion reference: "3(TGCT)20"
              #count matrix for the geneid seq
              
              gmat <- matrix(rep(0, length(unlist(strsplit(genefa[[1]]$seq, ".")))* 4), nrow=4)
              dimnames(gmat) <- list(c("A","C","G","T"), seq(1,length(unlist(strsplit(genefa[[1]]$seq, ".")))))
              

              sreads <- apply(myreads, 1, .maligReads, gseq = gseq)
              reads.n[i] <- length(sreads)
              sreads.tmp <- DNAStringSet(sreads)
              myconM <- consensusMatrix(sreads.tmp, baseOnly=TRUE)
              myconM <- myconM[1:4,]
              pwm[[covar[i]]] <- myconM
         }
         names(reads.n) <- covar
         barplot(reads.n)
         return(pwm)
     }  else if(what == "sample"){
         for(i in 1:length(target$FileName)){
              reads.n <- NULL
              cat("\n")
              myreads <- data.frame()
              filename <- sub("bed", "logos", target$FileName[i])
              cat("processing ", filename, "\n")
              tmp <- read.table(filename, sep="\t", as.is=T)
              myreads <- tmp[which(tmp[,1] == geneid),]
              #removing errors and any reads different from the presence of a SNP
              myreads <- myreads[setdiff(seq(1,dim(myreads)[1]), grep("-", myreads[,2])),]  #multiple deletion in thereference: "5----20"
              myreads <- myreads[setdiff(seq(1,dim(myreads)[1]), grep("x", myreads[,2])),]  # sequencing errors
              myreads <- myreads[setdiff(seq(1,dim(myreads)[1]), grep("\\(", myreads[,2])),] #multiple base insertion reference: "3(TGCT)20"
              #count matrix for the geneid seq
              
              gmat <- matrix(rep(0, length(unlist(strsplit(genefa[[1]]$seq, ".")))* 4), nrow=4)
              dimnames(gmat) <- list(c("A","C","G","T"), seq(1,length(unlist(strsplit(genefa[[1]]$seq, ".")))))

              sreads <- apply(myreads, 1, .maligReads, gseq = gseq)
              reads.n[i] <- length(sreads)
              sreads.tmp <- DNAStringSet(sreads)
              myconM <- consensusMatrix(sreads.tmp, baseOnly=TRUE)
              myconM <- myconM[1:4,]
              pwm[[target$FileName[i]]] <- myconM
         }
         names(reads.n) <- target$Name
         barplot(reads.n)
         return(pwm)
     }

}
################################################################################
#starting meV clustering
"startmeV" <- function(){
     Try(myWD <- getwd())
     Try(meVDirLocation.Available <- get("meVDirLocation.Available",envir=affylmGUIenvironment))     
     if(meVDirLocation.Available){
         Try(meVdir <- get("meVDirLocation",envir=affylmGUIenvironment))
         Try(setwd(meVdir))
         if(.Platform$OS.type=="windows"){
             Try(system('TMEV.bat'))
         } else{
            Try(system("./tmev.sh")) 
         }
         Try(setwd(myWD))
         Try(tkfocus(.affylmGUIglobals$ttMain))
         Try(return())
     } else{
          Try(tkmessageBox(title="meV clustering software ",message="meV is not installed.\nInstall it using the routine available in General tools menu.",type="ok",icon="error"))
              Try(setwd(myWD))
				    	Try(tkfocus(.affylmGUIglobals$ttMain))
              Try(return())
     }
}
################################################################################
"RmiRInterface" <- function(){
   Try(tkmessageBox(title="Detecting microRNA target",message="This routine uses RmiR package to identify microRNA targets on the basis of expression data."))
   Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
#   require(RmiR) || stop("\nMissing RmiR library\n")
   #loading miRNA data
   Try(mbVal <- tkmessageBox(title="RmiR miRNA data import",
                            message="You need to upload a file compatible with RmiR generated by baySeq analysis\nor a file with two columns, 1st with microRNA ids, 2nd with FC values.\nDo you wish to continue?",
                            icon="question",type="yesno",default="yes"))
       Try(if(tclvalue(mbVal)=="yes"){
          Try(tempFileName1 <- tclvalue(tkgetOpenFile(filetypes = "{{Text Files} {.txt}} {{All files} *}")))
          if (!nchar(tempFileName1)) {
                tkfocus(.affylmGUIglobals$ttMain)
                return()
          }
          Try(mySel1 <- read.table(tempFileName1, sep = "\t", header = T, as.is = TRUE))
          Try(mir.names <- sapply(mySel1[,1], function(x) sub("mir", "miR", x)))
          Try(mySel1[,1] <- mir.names)
      } else{ 
          Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
          tkfocus(.affylmGUIglobals$ttMain)
          return()
      })
   #loading gene data
   Try(mbVal1 <- tkmessageBox(title="RmiR GENE-level DE data import",
                            message="You need to upload a file compatible with RmiR generated by linear model analysis\nor a file with two columns, 1st with gene symbols, 2nd with FC values.\nDo you wish to continue?",
                            icon="question",type="yesno",default="yes"))
       Try(if(tclvalue(mbVal1)=="yes"){
          Try(tempFileName2 <- tclvalue(tkgetOpenFile(filetypes = "{{Text Files} {.txt}} {{All files} *}")))
          if (!nchar(tempFileName2)) {
                tkfocus(.affylmGUIglobals$ttMain)
                return()
          }
          Try(mySel2 <- read.table(tempFileName2, sep = "\t", header = T, as.is = TRUE))
          Try(mySel2 <- mySel2[!is.na(mySel2[,1]),])
      } else{ 
          Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
          tkfocus(.affylmGUIglobals$ttMain)
          return()
      })
      ##making the menu for selecting RmiR parameters
      Try(ttRmiRDialog<-tktoplevel(.affylmGUIglobals$ttMain))
      Try(tkwm.deiconify(ttRmiRDialog))
      Try(tkgrab.set(ttRmiRDialog))
      Try(tkfocus(ttRmiRDialog))
      Try(tkwm.title(ttRmiRDialog,"RmiR Parameters"))
      Try(tkgrid(tklabel(ttRmiRDialog,text="    ")))

      Try(frame1 <- tkframe(ttRmiRDialog,relief="groove",borderwidth=2))
      Try(HowManyQuestion1 <- tklabel(frame1,text=
           "miRNA target database",font=.affylmGUIglobals$affylmGUIfont2))
      Try(tkgrid(HowManyQuestion1))
      Try(tkgrid.configure(HowManyQuestion1,columnspan=2,sticky="w"))

      Try(qTcl <- tclVar("miranda"))
	    Try(q1.but			<- tkradiobutton(frame1,text="miranda",variable=qTcl,value="miranda",font=.affylmGUIglobals$affylmGUIfont2))
	    Try(q2.but	 <- tkradiobutton(frame1,text="mirbase",variable=qTcl,value="mirbase",font=.affylmGUIglobals$affylmGUIfont2))
	    Try(q3.but		<- tkradiobutton(frame1,text="mirtarget2",variable=qTcl,value="mirtarget2",font=.affylmGUIglobals$affylmGUIfont2))
	    Try(q4.but	<- tkradiobutton(frame1,text="pictar",variable=qTcl,value="pictar",font=.affylmGUIglobals$affylmGUIfont2))
	    Try(q5.but <- tkradiobutton(frame1,text="tarbase",variable=qTcl,value="tarbase",font=.affylmGUIglobals$affylmGUIfont2))
	    Try(q6.but <- tkradiobutton(frame1,text="targetscan",variable=qTcl,value="targetscan",font=.affylmGUIglobals$affylmGUIfont2))

	    Try(tkgrid(q1.but,sticky="w"))
	    Try(tkgrid(q2.but,sticky="w"))
      Try(tkgrid(q3.but,sticky="w"))
	    Try(tkgrid(q4.but,sticky="w"))
      Try(tkgrid(q5.but,sticky="w"))
      Try(tkgrid(q6.but,sticky="w"))
	    Try(tkgrid.configure(HowManyQuestion1,q1.but,q2.but,q3.but,q4.but,q5.but,q6.but,sticky="w"))

	    Try(frame2 <- tkframe(ttRmiRDialog,relief="groove",borderwidth=2))
	    Try(alfaLabel <- tklabel(frame2,text="Annotation package",font=.affylmGUIglobals$affylmGUIfont2))
	    Try(tkgrid(alfaLabel,sticky="w"))
	    Try(tkgrid.configure(alfaLabel,sticky="w"))

      Try(alfaTcl <- tclVar("org.Hs.eg.db"))

	    Try(a1.but <- tkradiobutton(frame2,text="Human",variable=alfaTcl,value="org.Hs.eg.db",font=.affylmGUIglobals$affylmGUIfont2))

	    Try(tkgrid(a1.but,sticky="w"))

      Try(frame3 <- tkframe(ttRmiRDialog,relief="groove",borderwidth=2))
	    Try(r2Label <- tklabel(frame3,text="Verbose output",font=.affylmGUIglobals$affylmGUIfont2))
	    Try(tkgrid(r2Label,sticky="w"))
	    Try(tkgrid.configure(r2Label,sticky="w"))

      Try(r2Tcl <- tclVar("FALSE"))
	    Try(r1.but <- tkradiobutton(frame3,text="FALSE",variable=r2Tcl,value="FALSE",font=.affylmGUIglobals$affylmGUIfont2))
	    Try(r2.but	 <- tkradiobutton(frame3,text="TRUE"  ,variable=r2Tcl,value="TRUE"  ,font=.affylmGUIglobals$affylmGUIfont2))
	
	    Try(tkgrid(r1.but,sticky="w"))
	    Try(tkgrid(r2.but	,sticky="w"))

      Try(Abort <- 1)
      RmiR.param <- list()
   
      Try(onOK <- function()
     {
		 	 Try(RmiR.param[[1]] <<- tclvalue(qTcl))
			 Try(tkgrab.release(ttRmiRDialog))
			 Try(tkdestroy(ttRmiRDialog))
			 Try(tkfocus(.affylmGUIglobals$ttMain))
			 Try(RmiR.param[[2]]	<<- tclvalue(alfaTcl))
			 Try(RmiR.param[[3]]	<<- tclvalue(r2Tcl))
			 Try(Abort					<<- 0)
	   })

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

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

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

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

	   Try(if(Abort==1) return())

     Try(mydata <- read.mir(genes = mySel2, mirna = mySel1, id= "alias", annotation = RmiR.param[[2]], dbname=RmiR.param[[1]],org="Hs",at.least=1,id.out="symbol",verbose=RmiR.param[[3]])) 
     
     Try(FileName <- tclvalue(tkgetSaveFile(initialfile=paste("RmiRtable.xls",sep=""),filetypes="{{Tab-Delimited Text Files} {.txt .xls}} {{All files} *}")))
      Try(if(!nchar(FileName))
      return())
      Try(write.table(mydata,file=FileName,quote=FALSE, sep="\t", row.names=F))
      Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
}

################################################################################
         
"extractmirTargets" <- function(){
   Try(tkmessageBox(title="Detecting microRNA target",message="This routine extracst a subset of putative targets\nhaving anti-correlated expression with respect to user defined microRNA.\nYou need to upload an output file generated by the function:\nDetecting miR targets via RmiR package"))
   Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
   Try(tempFileName1 <- tclvalue(tkgetOpenFile(filetypes = "{{Text Files} {.txt}} {{All files} *}")))
   if (!nchar(tempFileName1)) {
                tkfocus(.affylmGUIglobals$ttMain)
                return()
   }
   Try(mydata <- read.table(tempFileName1, sep = "\t", header = T, as.is = TRUE))
   if(dim(mydata)[2] >= 5){
           Try(mycol <- unique(mydata$mature_miRNA))
           Try(mycol1 <- paste(mycol, "=",seq(1, length(mycol)), sep="", collapse="\n"))
           #selecting the column to be removed
           Try(ttcolExtract<-tktoplevel(.affylmGUIglobals$ttMain))
           Try(tkwm.deiconify(ttcolExtract))
           Try(tkgrab.set(ttcolExtract))
           Try(tkfocus(ttcolExtract))
           Try(tkwm.title(ttcolExtract,"Defining the column to be estracted"))
           Try(tkgrid(tklabel(ttcolExtract,text="    ")))
           Try(miRnum <- "1")
           Try(Local.colExtract <- tclVar(init=miRnum))
           Try(entry.colExtract <-tkentry(ttcolExtract,width="4",font=.affylmGUIglobals$affylmGUIfont2,textvariable=Local.colExtract,bg="white"))
           Try(tkgrid(tklabel(ttcolExtract,text=paste("Please enter the number associated to the column of interest\n", mycol1,collapse=" "),font=.affylmGUIglobals$affylmGUIfont2)))
           Try(tkgrid(entry.colExtract))
           onOK <- function()
           {
                     Try(miRnum <- as.numeric(tclvalue(Local.colExtract)))
                     Try(assign("miRnum", as.numeric(tclvalue(Local.colExtract)),affylmGUIenvironment))
                     Try(tkgrab.release(ttcolExtract));Try(tkdestroy(ttcolExtract));Try(tkfocus(.affylmGUIglobals$ttMain))                        
           }
           Try(OK.but <-tkbutton(ttcolExtract,text="   OK   ",command=onOK,font=.affylmGUIglobals$affylmGUIfont2))
           Try(tkgrid(tklabel(ttcolExtract,text="    ")))
           Try(tkgrid(OK.but))
           Try(tkgrid.configure(OK.but))
           Try(tkgrid(tklabel(ttcolExtract,text="       ")))
           Try(tkfocus(entry.colExtract))
           Try(tkbind(entry.colExtract, "<Return>",onOK))
           Try(tkbind(ttcolExtract, "<Destroy>", function(){Try(tkgrab.release(ttcolExtract));Try(tkfocus(.affylmGUIglobals$ttMain));return(0)}))
           Try(tkwait.window(ttcolExtract))
           Try(tkfocus(.affylmGUIglobals$ttMain))
           Try(miRnum <- get("miRnum", affylmGUIenvironment))
           if(miRnum > length(mycol)){
                         Try(tkmessageBox(title="miR selection",message="You have selected a non existing miR!"))
                         Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
                         tkfocus(.affylmGUIglobals$ttMain)
                         return()
           }
           mysubset <- mydata[which(mydata$mature_miRNA %in% mycol[miRnum]),]
           mysubset.neg <- mysubset[intersect(which(mysubset$mirExpr < 0), which(mysubset$geneExpr > 0)),]

           if(dim(mysubset.neg)[1]==0){
                 Try(tkmessageBox(title="miR selection",message=paste("No genes show upregulation associated to a downregulation of", mycol[miRnum],sep=" ")))
           } else{
                 Try(write.table(mysubset.neg,file=paste("gup_miRdw",mycol[miRnum],"txt",sep="."),quote=FALSE, sep="\t", row.names=F))
                 Try(tkmessageBox(title="miR selection",message=paste("Subset of genes show upregulation associated to a downregulation of", mycol[miRnum],"are saved in",paste("gup_miRdw",mycol[miRnum],"txt",sep="."),sep=" ")))
           }
           mysubset.pos <- mysubset[intersect(which(mysubset$mirExpr > 0), which(mysubset$geneExpr < 0)),]
           if(dim(mysubset.pos)[1]==0){
                 Try(tkmessageBox(title="miR selection",message=paste("No genes show downregulation associated to an upregulation of", mycol[miRnum],sep=" ")))
                 Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
                 tkfocus(.affylmGUIglobals$ttMain)
                 return()
           } else{
                 Try(write.table(mysubset.pos,file=paste("gdw_miRup",mycol[miRnum],"txt",sep="."),quote=FALSE, sep="\t", row.names=F))
                 Try(tkmessageBox(title="miR selection",message=paste("Subset of genes show downregulation associated to a upregulation of", mycol[miRnum],"are saved in",paste("gdw_miRup",mycol[miRnum],"txt",sep="."),sep=" ")))
           }
    }else{
         Try(tkmessageBox(title="Detecting microRNA target",message="You have selected a file which does not have the structure of a RmiR output!"))
                         Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
                         tkfocus(.affylmGUIglobals$ttMain)
                         return()
    }
 
   Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))

}
################################################################################     
"retrieveMirTargets" <- function(){
   Try(tkmessageBox(title="Retrieving microRNA human targets",message="This routine retrieves predicted miR targets from RmiR.Hs.miRNA package. HUMAN ONLY!!!."))
   Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
#   require(RmiR.Hs.miRNA) || stop("\nMissing RmiR.Hs.miRNA library\n")
 #  require(org.Hs.eg.db, quietly = TRUE) || stop("\nNeed data package: org.Hs.eg.db\n")
   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(getSYMBOL(as.character(mymirset$gene_id),lib)))))
   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(write.table(mymirset,file=paste(miRname, "_targets_from_",mydb,".txt",sep=""),quote=FALSE, sep="\t", row.names=F))
                 Try(tkmessageBox(title="miR selection",message=paste("Subset of genes associated to ", miRname," are saved in",paste(miRname, "_targets_from_",mydb,".txt",sep=""),sep=" ")))
   }
   
   Try(assign("miRname", "" ,affylmGUIenvironment))
   Try(assign("miRname.available", FALSE,affylmGUIenvironment))
   Try(tkfocus(.affylmGUIglobals$ttMain))
   Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
}
################################################################################
"ctrtrtHeatmap" <- function(){
       Try(mRNAdata <- get("NormalizedAffyData",envir=affylmGUIenvironment))
       Try(mRNAdata <- exprs(mRNAdata))
       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())
       }
       Try(ctrl <- which(mydesign$Control == 1))
       Try(trt <-  which(mydesign$Control == 0))
       Try(time.u <- sort(unique(mydesign$Time)))
       Try(ctrl.g <-list())
       for(i in 1:length(time.u)){
          Try(ctrl.g[[i]]<- intersect(which(mydesign$Control == 1), which(mydesign$Time == time.u[i])))
       }
       Try(trt.g <-list())
       for(i in 1:length(time.u)){
          Try(trt.g[[i]]<- intersect(which(mydesign$Control == 0), which(mydesign$Time == time.u[i])))
       }
       Try(ctrl.list <- list())
       for(i in 1:length(ctrl.g)){
         Try(tmp <-  mRNAdata[, ctrl.g[[i]]])
         Try(tmp1 <- apply(tmp, 1, mean))
         Try(ctrl.list[[i]] <- tmp1)
       }
       Try(ctrl.df <- as.data.frame(ctrl.list))
       Try(names(ctrl.df) <- paste(rep("ctrl", length(time.u)), time.u, sep="")) 
       Try(trt.list <- list())
       for(i in 1:length(trt.g)){
         Try(tmp <-  mRNAdata[, trt.g[[i]]])
         Try(tmp1 <- apply(tmp, 1, mean))
         Try(trt.list[[i]] <- tmp1)
       }
       Try(trt.df <- as.data.frame(trt.list))
       Try(names(trt.df) <- paste(rep("trt", length(time.u)), time.u, sep=""))
       Try(mydf <- trt.df - ctrl.df)
       Try(names(mydf) <- paste(names(trt.df), names(ctrl.df), sep="-"))
       Try(mydf <- data.frame(dimnames(mRNAdata)[[1]], mydf))
       Try(names(mydf)[1] <- "AffyIDs")
       Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
       Try(tkmessageBox(title="Expression ratios",message="Expression ratio ctrl-trt are saved in a tab delimited file suitable for visualization with meV"))
       Try(FileName <- tclvalue(tkgetSaveFile(initialfile="trt-ctrl.xls",filetypes="{{Tab-Delimited Text Files} {.txt .xls}} {{All files} *}")))
       Try(if(!nchar(FileName))
         return())
       Try(write.table(mydf,file=FileName,quote=FALSE, sep="\t", row.names=F, col.names=T))
}
################################################################################
"goseqInterface" <- function(){
	  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="watch"))
	#  Try(require(goseq)||stop("\nsoseq library not found\n"))
	  Try(Targets <- get("Targets", env=affylmGUIenvironment))
      if(affylmGUIenvironment$whichArrayPlatform == "NGS" & affylmGUIenvironment$NormalizedAffyData.Available & affylmGUIenvironment$NGS.Available){
         Try(NormalizedAffyData <- get("NormalizedAffyData", env=affylmGUIenvironment))   
	 }else{
		 Try(tkmessageBox(title="goseq",message="No arrays have been loaded.	Please try New or Open from the File menu.",type="ok",icon="error"))
		  Try(tkfocus(.affylmGUIglobals$ttMain))
		  Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
         Try(return())
	}
	#loading the chr dataset
	Try(gene.vector <- rep(0, dim(NormalizedAffyData)[1]))
	Try(assayed.genes <- featureNames(NormalizedAffyData))
	#loading the differentially expressed vector
	 Try(tkmessageBox(title="goseq",message="Please open a file containing the genes identifiers \ngenerated by oneChannelGUI differential expression\nanalysis of NGS data.\nSuch file can be generated using the function \nextract column from a tab delimited file \nin general tool menu.",type="ok",icon="info"))
	 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){
               de.genes <- mySel[,1]
     } else Try(tkmessageBox(title="goseq",message=paste("File should contain\nonly a column with\noneChannelGUI NGS ids")))
  
	#making eset featureNames identical to knownGenes ids UCSC 
	.myFeature <- function(eset){
	      tmp.names <- featureNames(NormalizedAffyData)
          tmp.names <- sapply(tmp.names, function(x){sub('\\-_','#',x)})
          tmp.names <- as.character(tmp.names)
          tmp.names <- sapply(tmp.names, function(x){sub('\\+_','#',x)})
          tmp.names <- as.character(tmp.names)
          tmp.names <- sapply(tmp.names, function(x){tmp <- strsplit(x, '#');return(tmp[[1]][2])})
          tmp.names <- as.character(tmp.names)
          return(tmp.names)
    }
    Try(protid <- .myFeature(NormalizedAffyData))
	
	#extracting gene length content 
    Try(whichGenome <- annotation(NormalizedAffyData))
    if(whichGenome == ""){
	       Try(tkmessageBox(title="Genome selection",message="No genome is indicated in the annotation slot of ExpressionSet",type="ok", icon="error"))
	       Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
	       Try(return())
	} else if (whichGenome == "hs19"){
	     Try(annlibname <- system.file("bowtie/hg19_gene-level.scaffold.Rda",package="oneChannelGUI"))
	     Try(load(annlibname))
	} else if (whichGenome == "mm9"){
	     Try(annlibname <- system.file("bowtie/mm9_gene-level.scaffold.Rda",package="oneChannelGUI"))
	     Try(load(annlibname))
	} else if (whichGenome == "rn4"){
	     Try(annlibname <- system.file("bowtie/rn4_gene-level.scaffold.Rda",package="oneChannelGUI"))
	     Try(load(annlibname))
	}	 else{
	       Try(tkmessageBox(title="Genome selection",message="In the annotation slot of ExpressionSet is present a genome not annotated in oneChannelGUI!\nContact the maintainer for Genome implementation",type="ok", icon="error"))
	       Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
	       Try(return())
    }
	#detecting the chr under analysis
	Try(chr <- strsplit(Targets$FileName[1], "_")) #getting the chr
	Try(chr <- as.vector(unlist(chr)))
	Try(chr <- chr[length(chr)])
	Try(chr <- sub(".bam", "", chr))  #needed to extract the right subset of gene-level annotation from  makeGeneScaffold generated GRanges list
	Try(chr <- sub("chr0", "chr", chr))
	#selecting the chromosome genomic reanges on which assigning BAM data
	Try(chr.gr <- chr.gr[which(names(chr.gr) == chr)])
	Try(genes.lenght <- width(ranges(chr.gr[[1]])))
	Try(chr.eg <- chr.eg[which(names(chr.eg) == chr)])
    Try(gene.eg <- unique(chr.eg[[1]]$EG))
    Try(gene.vector<-rep(0,length(gene.eg)))
    Try(de.genes <- unique(chr.eg[[1]]$EG[which(chr.eg[[1]]$proteinID%in%protid)]))
	Try(gene.vector <- as.integer(gene.eg%in%de.genes))
	Try(names(gene.vector) <- gene.eg)
	#start go
	if(whichGenome == "hs19"){
	   Try(pwf<- nullp(gene.vector,"hg19","knownGene"))
	   Try(GO.wall<-goseq(pwf,"hg19","knownGene"))	
	}else if(whichGenome == "mm9"){
	   Try(pwf<-nullp(gene.vector,"mm9","knownGene"))
	   Try(GO.wall<-goseq(pwf,"mm9","knownGene"))	
	}else if(whichGenome == "rn4"){
	   Try(pwf<-nullp(gene.vector,"rn4","knownGene"))
	   Try(GO.wall<-goseq(pwf,"rn4","knownGene"))	
	}
	##making the menu for selecting p-value 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("none"))
          Try(rbIQR.a <- tkradiobutton(ttGetFilterMethod,text="none",variable=ttGetFilterMethodTcl,value=1,font=.affylmGUIglobals$affylmGUIfont2))
          Try(rbIQR.b<-tkradiobutton(ttGetFilterMethod,text="0.1",variable=ttGetFilterMethodTcl,value=0.1,font=.affylmGUIglobals$affylmGUIfont2))
          Try(rbIQR.c<-tkradiobutton(ttGetFilterMethod,text="0.05",variable=ttGetFilterMethodTcl,value=0.05,font=.affylmGUIglobals$affylmGUIfont2))
		  Try(rbIQR.d <- tkradiobutton(ttGetFilterMethod,text="0.01",variable=ttGetFilterMethodTcl,value=0.01,font=.affylmGUIglobals$affylmGUIfont2))
          Try(rbIQR.e<-tkradiobutton(ttGetFilterMethod,text="0.005",variable=ttGetFilterMethodTcl,value=0.005,font=.affylmGUIglobals$affylmGUIfont2))
          Try(rbIQR.f<-tkradiobutton(ttGetFilterMethod,text="0.001",variable=ttGetFilterMethodTcl,value=0.001,font=.affylmGUIglobals$affylmGUIfont2))

	      Try(tkgrid(tklabel(ttGetFilterMethod,text="    "),rbIQR.a))
	      Try(tkgrid(tklabel(ttGetFilterMethod,text="    "),rbIQR.b))
	      Try(tkgrid(tklabel(ttGetFilterMethod,text="    "),rbIQR.c))
	      Try(tkgrid(tklabel(ttGetFilterMethod,text="    "),rbIQR.d))
	      Try(tkgrid(tklabel(ttGetFilterMethod,text="    "),rbIQR.e))
	      Try(tkgrid(tklabel(ttGetFilterMethod,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(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(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, tklabel(ttGetFilterMethod,text="    ")))
	      Try(tkgrid.configure(OK.but,sticky="e"))
	      Try(tkgrid.configure(Cancel.but,sticky="w"))
	      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(tkwait.window(ttGetFilterMethod))
	      Try(GO.wallup <- GO.wall[which(GO.wall[,2] <= as.numeric(ReturnVal)),])
	      Try(tkmessageBox(title="GO enrichment",message=paste("The numbero of GO found enhriched with a p-value<", as.numeric(ReturnVal)," are ",dim(GO.wallup)[1]),type="ok", icon="info"))
	      Try(.SaveNGSGO(threshold=as.numeric(ReturnVal), GO.wallup))
	Try(tkconfigure(.affylmGUIglobals$ttMain,cursor="arrow"))
}
.SaveNGSGO <- function(threshold, deTable)
 {
    Try(FileName <- tclvalue(tkgetSaveFile(initialfile=paste("GOTable",".threshold.",threshold,".xls",sep=""),filetypes="{{Tab-Delimited Text Files} {.txt .xls}} {{All files} *}")))
    Try(if(!nchar(FileName))
    return())
    Try(write.table(deTable,file=FileName,quote=FALSE, sep="\t", row.names=F))
 }




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

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.