示例#1
0
    def __init__(self, fd):

        templatePage.__init__(self, fd)

        if not self.openMysql():
            return

        searchResult = fd.formdata.getvalue("searchResult")

        if not searchResult:
            heading = "Partial Correlation"
            detail = ["You need to select at least three traits in order to calculate partial correlation."]
            self.error(heading=heading, detail=detail)
            return

        ## Adds the Trait instance for each trait name from the collection
        traits = []

        for item in searchResult:
            traits.append(webqtlTrait(fullname=item, cursor=self.cursor))

        RISet = fd.formdata.getvalue("RISet")
        species = webqtlDatabaseFunction.retrieveSpecies(cursor=self.cursor, RISet=RISet)

        # XZ: HTML part
        TD_LR = HT.TD(colspan=2, height=200, width="100%", bgColor="#eeeeee")
        TD_LR.append(
            "Please select one primary trait, one to three control traits, and at least one target trait.", HT.P()
        )

        mainFormName = "showDatabase"
        mainForm = HT.Form(
            cgi=os.path.join(webqtlConfig.CGIDIR, webqtlConfig.SCRIPTFILE),
            name=mainFormName,
            submit=HT.Input(type="hidden"),
        )

        # XZ: Add hidden form values
        hddn = {
            "FormID": "calPartialCorrTrait",
            "database": "",
            "ProbeSetID": "",
            "CellID": "",  # XZ: These four parameters are required by javascript function showDatabase2.
            "controlTraits": "",
            "primaryTrait": "",
            "targetTraits": "",
            "pcMethod": "",
            "RISet": RISet,
        }

        for key in hddn.keys():
            mainForm.append(HT.Input(type="hidden", name=key, value=hddn[key]))

        radioNames = []

        for thisTrait in traits:
            oneRadioName = thisTrait.getName()
            radioNames.append(oneRadioName)

        radioNamesString = ",".join(radioNames)

        # Creates the image href that runs the javascript setting all traits as target or ignored
        setAllTarget = HT.Href(
            url="#redirect",
            onClick="setAllAsTarget(document.getElementsByName('showDatabase')[0], '%s');" % radioNamesString,
        )
        setAllTargetImg = HT.Image("/images/select_all.gif", alt="Select All", title="Select All", style="border:none;")
        setAllTarget.append(setAllTargetImg)
        setAllIgnore = HT.Href(
            url="#redirect",
            onClick="setAllAsIgnore(document.getElementsByName('showDatabase')[0], '%s');" % radioNamesString,
        )
        setAllIgnoreImg = HT.Image("/images/select_all.gif", alt="Select All", title="Select All", style="border:none;")
        setAllIgnore.append(setAllIgnoreImg)

        tblobj = {}
        tblobj["header"] = self.getCollectionTableHeader()

        sortby = self.getSortByValue()

        tblobj["body"] = self.getCollectionTableBody(traitList=traits, formName=mainFormName, species=species)

        filename = webqtlUtil.genRandStr("Search_")

        objfile = open("%s.obj" % (webqtlConfig.TMPDIR + filename), "wb")
        cPickle.dump(tblobj, objfile)
        objfile.close()

        div = HT.Div(
            webqtlUtil.genTableObj(tblobj=tblobj, file=filename, sortby=sortby, tableID="sortable", addIndex="1"),
            Id="sortable",
        )

        mainForm.append(div)

        # XZ: Add button
        radioNamesString = ",".join(radioNames)
        jsCommand_1 = "validateTrait(this.form, '" + radioNamesString + "', 0, 1);"
        jsCommand_2 = "validateTrait(this.form, '" + radioNamesString + "', 0, 2);"
        partialCorrTraitButton_1 = HT.Input(
            type="button",
            name="submitPartialCorrTrait_1",
            value="Pearson's r",
            onClick="%s" % jsCommand_1,
            Class="button",
        )
        partialCorrTraitButton_2 = HT.Input(
            type="button",
            name="submitPartialCorrTrait_2",
            value="Spearman's rho",
            onClick="%s" % jsCommand_2,
            Class="button",
        )
        mainForm.append(
            HT.BR(),
            "Compute partial correlation for target selected above:",
            HT.BR(),
            partialCorrTraitButton_1,
            partialCorrTraitButton_2,
            HT.BR(),
            HT.BR(),
            HT.HR(color="gray", size=3),
        )

        jsCommand = "validateTrait(this.form, '" + radioNamesString + "', 1);"
        partialCorrDBButton = HT.Input(
            type="button", name="submitPartialCorrDB", value="Calculate", onClick="%s" % jsCommand, Class="button"
        )

        methodText = HT.Span("Calculate:", Class="ffl fwb fs12")

        methodMenu = HT.Select(name="method")
        methodMenu.append(("Genetic Correlation, Pearson's r", "1"))
        methodMenu.append(("Genetic Correlation, Spearman's rho", "2"))
        methodMenu.append(("SGO Literature Correlation", "3"))
        methodMenu.append(("Tissue Correlation, Pearson's r", "4"))
        methodMenu.append(("Tissue Correlation, Spearman's rho", "5"))

        databaseText = HT.Span("Choose Database:", Class="ffl fwb fs12")
        databaseMenu = HT.Select(name="database2")

        nmenu = 0

        self.cursor.execute(
            'SELECT PublishFreeze.FullName,PublishFreeze.Name FROM \
                                PublishFreeze,InbredSet WHERE PublishFreeze.InbredSetId = InbredSet.Id \
                                and InbredSet.Name = "%s" and PublishFreeze.public > %d'
            % (RISet, webqtlConfig.PUBLICTHRESH)
        )
        for item in self.cursor.fetchall():
            databaseMenu.append(item)
            nmenu += 1

        self.cursor.execute(
            'SELECT GenoFreeze.FullName,GenoFreeze.Name FROM GenoFreeze,\
                                InbredSet WHERE GenoFreeze.InbredSetId = InbredSet.Id and InbredSet.Name = \
                                "%s" and GenoFreeze.public > %d'
            % (RISet, webqtlConfig.PUBLICTHRESH)
        )
        for item in self.cursor.fetchall():
            databaseMenu.append(item)
            nmenu += 1

        # 03/09/2009: Xiaodong changed the SQL query to order by Name as requested by Rob.
        self.cursor.execute("SELECT Id, Name FROM Tissue order by Name")
        for item in self.cursor.fetchall():
            TId, TName = item
            databaseMenuSub = HT.Optgroup(label="%s ------" % TName)
            self.cursor.execute(
                'SELECT ProbeSetFreeze.FullName,ProbeSetFreeze.Name FROM ProbeSetFreeze, ProbeFreeze, \
                                InbredSet WHERE ProbeSetFreeze.ProbeFreezeId = ProbeFreeze.Id and ProbeFreeze.TissueId = %d and \
                                ProbeSetFreeze.public > %d and ProbeFreeze.InbredSetId = InbredSet.Id and InbredSet.Name like "%s%%" \
                                order by ProbeSetFreeze.CreateTime desc, ProbeSetFreeze.AvgId '
                % (TId, webqtlConfig.PUBLICTHRESH, RISet)
            )
            for item2 in self.cursor.fetchall():
                databaseMenuSub.append(item2)
                nmenu += 1
            databaseMenu.append(databaseMenuSub)

        if nmenu:
            criteriaText = HT.Span("Return:", Class="ffl fwb fs12")
            criteriaMenu = HT.Select(name="criteria", selected="500")
            criteriaMenu.append(("top 100", "100"))
            criteriaMenu.append(("top 200", "200"))
            criteriaMenu.append(("top 500", "500"))
            criteriaMenu.append(("top 1000", "1000"))
            criteriaMenu.append(("top 2000", "2000"))
            criteriaMenu.append(("top 5000", "5000"))
            criteriaMenu.append(("top 10000", "10000"))
            criteriaMenu.append(("top 15000", "15000"))
            criteriaMenu.append(("top 20000", "20000"))

            self.MPDCell = HT.TD()
            correlationMenus = HT.TableLite(
                HT.TR(HT.TD(databaseText, HT.BR(), databaseMenu, colspan=4)),
                HT.TR(HT.TD(methodText, HT.BR(), methodMenu), self.MPDCell, HT.TD(criteriaText, HT.BR(), criteriaMenu)),
                border=0,
                cellspacing=4,
                cellpadding=0,
            )
        else:
            correlationMenus = ""

        mainForm.append(
            HT.Font("or", color="red", size=4),
            HT.BR(),
            HT.BR(),
            "Compute partial correlation for each trait in the database selected below:",
            HT.BR(),
        )
        mainForm.append(partialCorrDBButton, HT.BR(), HT.BR(), correlationMenus)

        TD_LR.append(mainForm)

        self.dict["body"] = str(TD_LR)
        self.dict["js1"] = ""
        self.dict["title"] = "Partial Correlation Input"
	def __init__(self, fd):

		templatePage.__init__(self, fd)

		if not self.openMysql():
			return
		
		fd.readGenotype()
		TD_LR = HT.TD(height=200,width="100%",bgColor='#eeeeee')
		self.database = fd.formdata.getfirst('database')
		self.ProbeSetID = fd.formdata.getfirst('ProbeSetID')
		self.CellID = fd.formdata.getfirst('CellID')
		
		self.db = webqtlDataset(self.database, self.cursor)
		thisTrait = webqtlTrait(db= self.db, cursor=self.cursor, name=self.ProbeSetID) #, cellid=CellID)
		thisTrait.retrieveInfo()
		
		try:
			self.cursor.execute('SELECT ProbeFreeze.Name FROM ProbeFreeze,ProbeSetFreeze WHERE ProbeFreeze.Id = ProbeSetFreeze.ProbeFreezeId and ProbeSetFreeze.Name = "%s"' % self.db.name)
			self.probeDatabase = self.cursor.fetchall()[0][0]
			self.probeInfoDatabase = 'Probe'
		except:
			heading = 'Probe Information'
			intro = ['Trying to retrieve the probe information for ProbeSet ',HT.Span('%s' % self.ProbeSetID, Class="fwb cdg"),' in Database ',HT.Href(text='%s' % self.db.fullname,url=webqtlConfig.infopagehref % self.database)]
			detail = ['The information you just requested is not available at this time.']
			self.error(heading=heading,intro=intro,detail=detail)
			return


		form = HT.Form(cgi= os.path.join(webqtlConfig.CGIDIR, webqtlConfig.SCRIPTFILE), enctype='multipart/form-data', name='showDatabase', submit=HT.Input(type='hidden'))
		hddn = {'FormID':'showDatabase','ProbeSetID':'_','database':'_','CellID':'_','RISet':fd.RISet, 'incparentsf1':'on'}
		if fd.RISet == 'BXD':
			hddn['parentsf1']='ON'
			
		for key in hddn.keys():
			form.append(HT.Input(name=key, value=hddn[key], type='hidden'))


		#Buttons on search page
		linkinfo ="%s/probeInfo.html" % webqtlConfig.PORTADDR
		mintmap = "" 
		probeinfo = HT.Input(type='button' ,name='mintmap',value='Info', onClick="openNewWin('%s');" % linkinfo, Class="button")
		cormatrix = HT.Href(url="#redirect", onClick="databaseFunc(document.getElementsByName('showDatabase')[0], 'corMatrix');")
		cormatrix_img = HT.Image("/images/correlation_matrix1_final.jpg", alt="Correlation Matrix and PCA", title="Correlation Matrix and PCA", style="border:none;")
		cormatrix.append(cormatrix_img)
		heatmap = HT.Href(url="#redirect", onClick="databaseFunc(document.getElementsByName('showDatabase')[0], 'heatmap');")
		heatmap_img = HT.Image("/images/heatmap2_final.jpg", name='mintmap', alt="QTL Heat Map and Clustering", title="QTL Heatmap and Clustering", style="border:none;")
		heatmap.append(heatmap_img)
		if self.ProbeSetID[-2:] in ('_A', '_B'):
			thisProbeSetID = self.ProbeSetID[:-2]
		else:
			thisProbeSetID = self.ProbeSetID
		thisurl = 'http://www.ensembl.org/Mus_musculus/featureview?type=AffyProbe&id=%s' % thisProbeSetID
		verifyButton = HT.Input(type="button",value="Verify Ensembl",onClick= "openNewWin('%s')" % thisurl, Class="button")
		
		addselect = HT.Input(type='button' ,name='addselect',value='Add to Collection', onClick="addRmvSelection('%s', this.form, 'addToSelection');"  % fd.RISet,Class="button")
		selectall = HT.Input(type='button' ,name='selectall',value='Select All', onClick="checkAll(this.form);",Class="button")
		selectpm = HT.Input(type='button' ,name='selectall',value='Select PM', onClick="checkPM(this.form);",Class="button")
		selectmm = HT.Input(type='button' ,name='selectall',value='Select MM', onClick="checkMM(this.form);",Class="button")
		selectinvert = HT.Input(type='button' ,name='selectinvert',value='Select Invert', onClick="checkInvert(this.form);",Class="button")
		reset = HT.Input(type='reset',name='',value='Select None',Class="button")
		chrMenu = HT.Input(type='hidden',name='chromosomes',value='all')
		probedata = HT.Input(type='hidden',name='probedata',value='all')
		
		url_rudi_track = self.getProbeTrackURL(self.probeDatabase, self.ProbeSetID)
		if url_rudi_track:		
		   rudi_track = HT.Input(type='button', name='ruditrack', value='Probe Track', onClick="openNewWin('%s')"%url_rudi_track, Class="button")
		else: rudi_track = None
		
		pinfopage = "/probeInfo.html"
		
		#updated by NL: 07-22-2011  get chosenStrains
		_f1, _f12, _mat, _pat = webqtlUtil.ParInfo[fd.RISet]
		chosenStrains="%s,%s"%(_mat,_pat)
		tblobj = {}
		tblobj['header']=[]

		tblobj['header'].append([
			THCell(HT.TD("", Class="cbrb cw fwb fs13 b1", rowspan=2,nowrap='ON'), sort=0),
			THCell(HT.TD(HT.Href(target="_PROBEINFO", url=pinfopage+"#probe", text=HT.Span('Probe', Class="cw fwb fs13")), HT.Sup(HT.Italic('1')), Class="cbrb cw fwb fs13 b1",align='center',rowspan=2,nowrap='ON'), text="probe", idx=1), 
			THCell(HT.TD(HT.Href(text=HT.Span('Sequence', Class="cw fwb fs13"), target="_PROBEINFO", url=pinfopage+"#Sequence"),HT.Sup(HT.Italic('2')), Class="cbrb cw fwb fs13 b1", align='center',rowspan=2,nowrap='ON'), text="seq", idx=2), 
			THCell(HT.TD(HT.Href(text=HT.Span('bl2seq', Class="cw fwb fs13"), target="_PROBEINFO", url=pinfopage+"#bl2seq"),HT.Sup(HT.Italic('3')), Class="cbrb cw fwb fs13 b1", align='center',rowspan=2,nowrap='ON'), sort=0), 
			THCell(HT.TD(HT.Href(text=HT.Span('Exons', Class="cw fwb fs13"), target="_PROBEINFO", url=pinfopage+"#Exon"),HT.Sup(HT.Italic('4')), Class="cbrb cw fwb fs13 b1",align='center',rowspan=2,nowrap='ON'), sort=0),
			THCell(HT.TD(HT.Href(text=HT.Span('Tm °C', Class="cw fwb fs13"), target="_PROBEINFO", url=pinfopage+"#Tm"),HT.Sup(HT.Italic('5')), Class="cbrb cw fwb fs13 b1",align='center',rowspan=2,nowrap='ON'), text="tm", idx=5),
			THCell(HT.TD(HT.Href(text=HT.Span('Stacking Energy K', HT.Sub('B'),'T', Class="cw fwb fs13"), target="_PROBEINFO", url=pinfopage+"#KBT"),HT.Sup(HT.Italic('6')), Class="cbrb cw fwb fs13 b1",align='center',colspan=2,NOWRAP="yes",nowrap='ON'), sort=0),
			THCell(HT.TD(HT.Href(text=HT.Span('Mean', Class="cw fwb fs13"), target="_PROBEINFO", url=pinfopage+"#Mean"),HT.Sup(HT.Italic('7')), Class="cbrb cw fwb fs13 b1",align='center',rowspan=2,nowrap='ON'), text="mean", idx=8),
			THCell(HT.TD(HT.Href(text=HT.Span('Stdev', Class="cw fwb fs13"), target="_PROBEINFO", url=pinfopage+"#Stdev"),HT.Sup(HT.Italic('8')), Class="cbrb cw fwb fs13 b1",align='center',rowspan=2,nowrap='ON'), text="std", idx=9),
			THCell(HT.TD(HT.Href(text=HT.Span('Probe h2', Class="cw fwb fs13"), target="_PROBEINFO", url=pinfopage+"#h2"),HT.Sup(HT.Italic('9')), Class="cbrb cw fwb fs13 b1",align='center',rowspan=2,NOWRAP="yes"), text="h2", idx=10),
			THCell(HT.TD(HT.Href(text=HT.Span('Probe Location', Class="cw fwb fs13"), target="_PROBEINFO", url=pinfopage+"#location"), HT.Sup(HT.Italic('10')),Class="cbrb cw fwb fs13 b1",align='center',colspan=3)),
			THCell(HT.TD(HT.Href(text=HT.Span('SNPs', HT.BR(), '(Across all strains)', Class="cw fwb fs13"), target="_PROBEINFO", url=pinfopage+"#snps"), HT.Sup(HT.Italic('11')),Class="cbrb cw fwb fs13 b1",align='center',rowspan=2,NOWRAP="yes")),
			THCell(HT.TD(HT.Href(text=HT.Span('SNPs', HT.BR(),'(Different alleles only between %s and %s)'%(_mat,_pat), Class="cw fwb fs13"), target="_PROBEINFO", url=pinfopage+"#snps"), HT.Sup(HT.Italic('11')),Class="cbrb cw fwb fs13 b1",align='center',rowspan=2,NOWRAP="yes"))

		])
		
		tblobj['header'].append([
			THCell(HT.TD(HT.Span('GSB', Class="cw fwb fs13"),align='center', Class="cbrb ffl fwb fs13 b1",), text="gsb", idx=6),
			THCell(HT.TD(HT.Span('NSB', Class="cw fwb fs13"),align='center', Class="cbrb ffl fwb fs13 b1",), text="nsb", idx=7),
			THCell(HT.TD(HT.Span('Chr', Class="cw fwb fs13"), align='center', Class="cbrb ffl2 fwb fs13 b1",)),
			THCell(HT.TD(HT.Span('Start', Class="cw fwb fs13"),align='center', Class="cbrb ffl fwb fs13 b1",)),
			THCell(HT.TD(HT.Span('End', Class="cw fwb fs13"),align='center', Class="cbrb ffl fwb fs13 b1",)),
		])
		
		tblobj['body'] = []
		
		blatbutton = ''

		fetchField = ['Probe.Name','Probe.Sequence','Probe.ExonNo','Probe.Tm', 'Probe.E_GSB','Probe.E_NSB', 'ProbeH2.h2', 'ProbeH2.weight']

		query = "SELECT %s FROM (Probe, ProbeSet, ProbeFreeze) left join ProbeH2  on ProbeH2.ProbeId = Probe.Id and ProbeH2.ProbeFreezeId = ProbeFreeze.Id WHERE ProbeSet.Name = '%s' and Probe.ProbeSetId = ProbeSet.Id and ProbeFreeze.Name = '%s' order by Probe.SerialOrder" % (string.join(fetchField,','), self.ProbeSetID, self.probeDatabase)
		self.cursor.execute(query)
		results = self.cursor.fetchall()
		
		blatsequence = ""
		
		# add by NL: get strains' name in SnpPattern database table
		strainsInSnpPatternDBtable=self.getStrainNameIndexPair()  # after snpBrowserPage.py change to MVC, this function can be removed in this class and called from other class; 
		allStrainNameList=[v[0] for v in strainsInSnpPatternDBtable]
			
		speciesid = webqtlDatabaseFunction.retrieveSpeciesId(cursor=self.cursor,RISet=fd.RISet)
		for result in results:
			"""
			ProbeId, CellID,Sequence,ExonNo,Tm, E_GSB,E_NSB = map(self.nullRecord,result)
			h2 = ''
			query = "SELECT h2 FROM ProbeH2 WHERE ProbeFreezeId = '%s' and ProbeId=%s" % (self.probeDatabase, ProbeId)
			self.cursor.execute(query)
			results = self.cursor.fetchall()
			"""

			CellID,Sequence,ExonNo,Tm, E_GSB,E_NSB,h2, weight = map(self.nullRecord,result)
			
	
			Average = ''
			STDEV = ''
			mean = -10000.0
			stdev = -10000.0
			try:
				thisTrait.cellid = CellID
				thisTrait.retrieveData()
		
				mean, median, var, stdev, sem, N = reaper.anova(thisTrait.exportInformative()[1])
			
				if mean:
					Average = '%2.2f' % mean
				if stdev:
					STDEV = '%2.2f' % stdev
			except:
				pass

			if CellID == self.CellID:
				bkColor = "cbrdull fs11 b1"
			else:
				bkColor = "fs11 b1"
			seqcolor= ''
			
			if thisTrait.blatseq:
				blatsequence = thisTrait.blatseq
				if int(CellID[-1]) % 2 == 1:
					seqcolor= 'cdg'
			else:
				if int(CellID[-1]) % 2 == 1:
					seqcolor= 'cdg'
					blatsequence += string.strip(Sequence)
						
			if thisTrait.genbankid  and (int(CellID[-1]) % 2 == 1):
				probeurl = 'http://www.ncbi.nlm.nih.gov/blast/bl2seq/wblast2.cgi?one=%s&sseq=%s'  % (thisTrait.genbankid, Sequence)
				probefy1 = HT.Input(type="button",value="Blast",onClick= "openNewWin('%s')" % probeurl, Class="buttonsmaller")
			else:  
				probefy1 = ''
			
			traitName = str(thisTrait)

			#XZ, Aug 08, 2011: Note that probesets on some affy chips are not name as "xxx_at" (i.e., Affy Mouse Gene 1.0 ST (GPL6246)). 
			#EnsemblProbeSetID = self.ProbeSetID[0:self.ProbeSetID.index('_at')+3]
			EnsemblProbeSetID = self.ProbeSetID
			if '_at' in self.ProbeSetID:
				EnsemblProbeSetID = self.ProbeSetID[0:self.ProbeSetID.index('_at')+3]

			self.cursor.execute('''
					SELECT EnsemblProbeLocation.* 
					FROM EnsemblProbeLocation, EnsemblProbe, EnsemblChip, GeneChipEnsemblXRef, ProbeFreeze
					WHERE EnsemblProbeLocation.ProbeId=EnsemblProbe.Id and EnsemblProbe.ChipId=GeneChipEnsemblXRef.EnsemblChipId and
						GeneChipEnsemblXRef.GeneChipId=ProbeFreeze.ChipId and EnsemblProbe.Name=%s and EnsemblProbe.ProbeSet=%s and 
						ProbeFreeze.Name=%s group by Chr, Start, End'''
					,(CellID, EnsemblProbeSetID, self.probeDatabase))
			LocationFields = self.cursor.fetchall()

			Chr=''
			Start=''
			End=''
			if (len(LocationFields)>=1):
				Chr,Start,End,Strand,MisMatch,ProbeId = map(self.nullRecord,LocationFields[0])
				Start /= 1000000.0
				End /= 1000000.0
			if (len(LocationFields)>1):
				self.cursor.execute('''
						SELECT ProbeSet.Chr, ProbeSet.Mb FROM ProbeSet, ProbeFreeze 
						WHERE ProbeSet.ChipId=ProbeFreeze.ChipId and ProbeSet.Name=%s and ProbeFreeze.Name=%s'''
						,(self.ProbeSetID, self.probeDatabase))
				ProbeSetChr, ProbeSetMb = map(self.nullRecord,self.cursor.fetchall()[0])
					
				self.cursor.execute('''
						SELECT EnsemblProbeLocation.*, ABS(EnsemblProbeLocation.Start/1000000-%s) as Mb 
						FROM EnsemblProbeLocation, EnsemblProbe, EnsemblChip, GeneChipEnsemblXRef, ProbeFreeze
						WHERE EnsemblProbeLocation.ProbeId=EnsemblProbe.Id and EnsemblProbe.ChipId=GeneChipEnsemblXRef.EnsemblChipId and
							GeneChipEnsemblXRef.GeneChipId=ProbeFreeze.ChipId and EnsemblProbe.Name=%s and EnsemblProbe.ProbeSet=%s and
							EnsemblProbeLocation.Chr=%s and ProbeFreeze.Name=%s order by Mb limit 1'''
						,(ProbeSetMb, CellID, EnsemblProbeSetID, ProbeSetChr, self.probeDatabase))
				NewLocationFields = self.cursor.fetchall()
				if (len(NewLocationFields)>0):
					Chr,Start,End,Strand,MisMatch,ProbeId,Mb = map(self.nullRecord,NewLocationFields[0])
					Start /= 1000000.0
					End /= 1000000.0
					
			snp_collection = []	
			snpDiff_collection=[]
			
			startIndex=3
			if Chr != '' and Start != '' and End != '' and speciesid != None:
									
				self.cursor.execute('''
						   SELECT a.SnpName, a.Id, b.* FROM SnpAll a, SnpPattern b
						   WHERE a.Chromosome=%s and a.Position>=%s and a.Position<=%s 
						   and a.SpeciesId=%s and a.Id=b.SnpId'''
							,(Chr, Start, End, speciesid)) #chr,Start, End, 1))							
				snpresults = self.cursor.fetchall()
				
				index1=allStrainNameList.index(_mat) #_mat index in results
				index2=allStrainNameList.index(_pat) #_pat index in results
			
				for v in snpresults:
					#updated by NL: 07-22-2011  check 'limit to' to get snpBrowser snpresults
					snp_collection.append(HT.Href(text=v[0], url=os.path.join(webqtlConfig.CGIDIR, 
							"main.py?FormID=SnpBrowserResultPage&submitStatus=1&customStrain=1")+ "&geneName=%s" % v[0], Class="fs12 fwn", target="_blank"))
					snp_collection.append(HT.BR())
					#updated by NL: 07-27-2011  link snp info for different allele only	
					strain1_allele=v[startIndex+index1]
					strain2_allele=v[startIndex+index2]
					
					if strain1_allele!=strain2_allele:
						snpDiff_collection.append(HT.Href(text=v[0], url=os.path.join(webqtlConfig.CGIDIR, 
								"main.py?FormID=SnpBrowserResultPage&submitStatus=1&customStrain=1&diffAlleles=1&chosenStrains=%s"%chosenStrains)+ "&geneName=%s" % v[0], Class="fs12 fwn", target="_blank"))
						snpDiff_collection.append(HT.BR())
							

			tr = []	
			tr.append(TDCell(HT.TD(HT.Input(type="checkbox", Class='checkbox', name="searchResult",value=traitName, onClick="highlight(this)"), align="right", Class=bkColor, nowrap="on"), text=traitName))
			
			tr.append(TDCell(HT.TD(HT.Href(text=CellID, url = "javascript:showDatabase2('%s','%s','%s');" % (self.database,self.ProbeSetID,CellID),Class="fs12 fwn"),Class=bkColor), traitName, traitName.upper()))
			
			tr.append(TDCell(HT.TD(Sequence, Class=bkColor + " %s ffmono fs14" % seqcolor),Sequence,Sequence.upper()))
			tr.append(TDCell(HT.TD(probefy1,align='center',Class=bkColor))) 
			tr.append(TDCell(HT.TD(ExonNo,align='center',Class=bkColor)))
			
			try:
				TmValue = float(Tm)
			except:
				TmValue = 0.0
			tr.append(TDCell(HT.TD(Tm,align='center',Class=bkColor), Tm, TmValue))
			
			try:
				E_GSBValue = float(E_GSB)
			except:
				E_GSBValue = -10000.0
			tr.append(TDCell(HT.TD(E_GSB,align='center',Class=bkColor), E_GSB, E_GSBValue))

			try:
				E_NSBValue = float(E_NSB)
			except:
				E_NSBValue = -10000.0
			tr.append(TDCell(HT.TD(E_NSB,align='center',Class=bkColor), E_NSB, E_NSBValue))
			
			tr.append(TDCell(HT.TD(Average,align='center',Class=bkColor), Average, mean))
			tr.append(TDCell(HT.TD(STDEV,align='center',Class=bkColor), STDEV, stdev))

			try:
				h2Value = float(h2)
			except:
				h2Value = -10000.0
			tr.append(TDCell(HT.TD(h2,align='center',Class=bkColor), h2, h2Value))

			tr.append(TDCell(HT.TD(Chr,align='left',Class=bkColor)))
			tr.append(TDCell(HT.TD(Start,align='left',Class=bkColor)))
			tr.append(TDCell(HT.TD(End,align='left',Class=bkColor)))

			snp_td = HT.TD(align='left',Class=bkColor)
			for one_snp_href in snp_collection:
			    snp_td.append(one_snp_href)
	
			tr.append(TDCell(snp_td)) 
			
			#07-27-2011:add by NL: show SNP results for different allele only
			snpDiff_td= HT.TD(align='left', valign='top', Class=bkColor)
			for one_snpDiff_href in snpDiff_collection:
			    snpDiff_td.append(one_snpDiff_href)
			tr.append(TDCell(snpDiff_td))
			
			tblobj['body'].append(tr)
		
		# import cPickle
		filename = webqtlUtil.genRandStr("Probe_")
		objfile = open('%s.obj' % (webqtlConfig.TMPDIR+filename), 'wb')
		cPickle.dump(tblobj, objfile)
		objfile.close()
		# NL, 07/27/2010. genTableObj function has been moved from templatePage.py to webqtlUtil.py;		
		div = HT.Div(webqtlUtil.genTableObj(tblobj=tblobj, file=filename, sortby=("", ""), tableID = "sortable", addIndex = "1"), Id="sortable")

		#UCSC
		_Species = webqtlDatabaseFunction.retrieveSpecies(cursor=self.cursor, RISet=fd.RISet)
		if _Species == "rat":
			thisurl = webqtlConfig.UCSC_BLAT % ('rat', 'rn3', blatsequence)
		elif _Species == "mouse":
			thisurl = webqtlConfig.UCSC_BLAT % ('mouse', 'mm9', blatsequence)
		else:
			thisurl = ""
		if thisurl:	
			blatbutton = HT.Input(type='button' ,name='blatPM',value='Verify UCSC', onClick="window.open('%s','_blank')" % thisurl,Class="button")
		else:
			blatbutton = ""
		
		#GenBank
		genbankSeq = ""
		if thisTrait.genbankid:
			self.cursor.execute("SELECT Sequence FROM Genbank WHERE Id = '%s'" % thisTrait.genbankid )
			genbankSeq = self.cursor.fetchone()
			if genbankSeq:
				genbankSeq = genbankSeq[0]
		
		if genbankSeq: 
			if _Species == "rat":
				thisurl2 = webqtlConfig.UCSC_BLAT % ('rat', 'rn3', genbankSeq)
			if _Species == "mouse":
				thisurl2 = webqtlConfig.UCSC_BLAT % ('mouse', 'mm9', genbankSeq)
		else:
			thisurl2 = ''
		if thisurl2:	
			blatbutton2 = HT.Input(type='button' ,name='blatPM',value='Verify GenBank', onClick="window.open('%s','_blank')" % thisurl2,Class="button")
		else:
			blatbutton2 = ""
		
		#Snp
		snpBrowser = ""
		if thisTrait.symbol and _Species == 'mouse':
			self.cursor.execute("select geneSymbol from GeneList where geneSymbol = %s", thisTrait.symbol)
			geneName = self.cursor.fetchone()
			if geneName:
				snpurl = os.path.join(webqtlConfig.CGIDIR, "main.py?FormID=snpBrowser") + "&geneName=%s" % geneName[0]	
			else:
				if thisTrait.chr and thisTrait.mb:
					snpurl = os.path.join(webqtlConfig.CGIDIR, "main.py?FormID=snpBrowser") + \
							"&chr=%s&start=%2.6f&end=%2.6f" % (thisTrait.chr, thisTrait.mb-0.002, thisTrait.mb+0.002)
				else:
					snpurl = ""

			if snpurl:
				snpBrowser = HT.Input(type="button",value="SNP Browser",onClick= \
						"openNewWin('%s')" % snpurl, Class="button")

			else:
				snpBrowser = ""
		#end if
		
		heading = HT.Paragraph('Probe Information', Class="title")
		intro = HT.Paragraph('The table below lists information of all probes of probe set ',HT.Span(self.ProbeSetID, Class="fwb fs13"),' from database ', HT.Span(self.probeDatabase, Class="fwb fs13"), ".")
		buttons = HT.Paragraph(probedata,probeinfo,heatmap,cormatrix,blatbutton,blatbutton2,verifyButton,snpBrowser, HT.P(),selectall,selectpm,selectmm,selectinvert,reset,addselect)
		if rudi_track:
		   buttons.append(rudi_track)	
		form.append(buttons,div,HT.P())
	
		TD_LR.append(heading,intro,form, HT.P())
		self.dict['basehref'] = ''
		self.dict['body'] = str(TD_LR)
		self.dict['title'] = self.db.shortname + ' : ' + self.ProbeSetID +' / Probe Information'
        # updated by NL, javascript function xmlhttpPost(strURL, div, querystring) and function updatepage(Id, str)
		# have been moved to dhtml.js
	   	self.dict['js1'] = ''
	def displaySingleSymbolResultPage(self,primaryGeneSymbol=None, datasetFullName=None,tProbeSetFreezeId=None, TissueCorrMatrixObject =None,recordReturnNum=None,method=None,note=None,TissueCount =None):
		formName = webqtlUtil.genRandStr("fm_")
		form = HT.Form(cgi= os.path.join(webqtlConfig.CGIDIR, webqtlConfig.SCRIPTFILE), enctype='multipart/form-data',name= formName, submit=HT.Input(type='hidden'))
		# the following hidden elements are required parameter in Class(PlotCorrelationPage). So we need to define them here. 
		form.append(HT.Input(type="hidden", name="action", value="disp"))
		form.append(HT.Input(type="hidden", name="FormID", value="dispSingleTissueCorrelation"))
		form.append(HT.Input(type="hidden", name="X_geneSymbol", value=""))
		form.append(HT.Input(type="hidden", name="Y_geneSymbol", value=""))
		form.append(HT.Input(type="hidden", name="ProbeSetID", value=""))
		# RISet is not using in Tissue correlation, but is a required parameter in Class(PlotCorrelationPage). So we set dummy value(BXD). 
		form.append(HT.Input(type="hidden", name="RISet", value="BXD"))
		form.append(HT.Input(type="hidden", name="ShowLine", value="1"))
		form.append(HT.Input(type="hidden", name="TissueProbeSetFreezeId", value=tProbeSetFreezeId))
		form.append(HT.Input(type="hidden", name="rankOrder", value=0))	
		
		traitList =[]
		try:
			symbolCorrDict, symbolPvalueDict = TissueCorrMatrixObject.calculateCorrOfAllTissueTrait(primaryTraitSymbol=primaryGeneSymbol,method=method)
		except:
			heading = "Tissue Correlation"
			detail = ['Please use the official NCBI gene symbol.' ]
			self.error(heading=heading,detail=detail)			
			return
		
		symbolList0,geneIdDict,dataIdDict,ChrDict,MbDict,descDict,pTargetDescDict=TissueCorrMatrixObject.getTissueProbeSetXRefInfo(GeneNameLst=[])					
		# In case, upper case and lower case issue of symbol, mappedByTargetList function will update input geneSymbolLst based on database search result
		tempPrimaryGeneSymbol =self.mappedByTargetList(primaryList=symbolList0,targetList=[primaryGeneSymbol])
		primaryGeneSymbol =tempPrimaryGeneSymbol[0]
		
		returnNum = self.getReturnNum(recordReturnNum)
		symbolListSorted=[]
		symbolList=[]
		# get key(list) of symbolCorrDict(dict) based on sorting symbolCorrDict(dict) by its' value in desc order
		symbolListSorted=sorted(symbolCorrDict, key=symbolCorrDict.get, reverse=True)
		symbolList = self.mappedByTargetList(primaryList=symbolList0,targetList=symbolListSorted)
		
		if returnNum==None:
			returnNum =len(symbolList0)
			IntroReturnNum ="All %d "%returnNum
		else:
			IntroReturnNum ="The Top %d" %returnNum
			
		symbolList = symbolList[:returnNum]

		pageTable = HT.TableLite(cellSpacing=0,cellPadding=0,width="100%", border=0, align="Left")
		
		##############
		# Excel file #
		##############
		filename= webqtlUtil.genRandStr("Corr_")								
		xlsUrl = HT.Input(type='button', value = 'Download Table', onClick= "location.href='/tmp/%s.xls'" % filename, Class='button')
		# Create a new Excel workbook
		workbook = xl.Writer('%s.xls' % (webqtlConfig.TMPDIR+filename))
		headingStyle = workbook.add_format(align = 'center', bold = 1, border = 1, size=13, fg_color = 0x1E, color="white")
		#There are 6 lines of header in this file. 
		worksheet = self.createExcelFileWithTitleAndFooter(workbook=workbook, datasetName=datasetFullName, returnNumber=returnNum)
		newrow = 6				
		pageTable.append(HT.TR(HT.TD(xlsUrl,height=40)))
		
		# get header part of result table and export excel file
		tblobj = {}
		tblobj['header'], worksheet = self.getTableHeader( method=method, worksheet=worksheet, newrow=newrow, headingStyle=headingStyle)
		newrow += 1

		# get body part of result table and export excel file
		tblobj['body'], worksheet = self.getTableBody(symbolCorrDict=symbolCorrDict, symbolPvalueDict=symbolPvalueDict,symbolList=symbolList,geneIdDict=geneIdDict,ChrDict=ChrDict,MbDict=MbDict,descDict=descDict,pTargetDescDict=pTargetDescDict,primarySymbol=primaryGeneSymbol,TissueCount=TissueCount, formName=formName, worksheet=worksheet, newrow=newrow,method=method)
		workbook.close()
		# creat object for result table for sort function
		objfile = open('%s.obj' % (webqtlConfig.TMPDIR+filename), 'wb')
		cPickle.dump(tblobj, objfile)
		objfile.close()	

		sortby = ("tissuecorr", "down")
		div = HT.Div(webqtlUtil.genTableObj(tblobj=tblobj, file=filename, sortby=sortby, tableID = "sortable", addIndex = "1"), Id="sortable")								
		
		if method =="0":
			IntroMethod="Pearson\'s r "
		else:
			IntroMethod="Spearman\'s rho "				
		Intro = HT.Blockquote('%s correlations ranked by the %s are displayed.' % (IntroReturnNum,IntroMethod),
				' You can resort this list using the small arrowheads in the top row.')	
		Intro.append(HT.BR(),' Click the correlation values to generate scatter plots. Select the symbol to open NCBI Entrez.')
				
		pageTable.append(HT.TR(HT.TD(div)))
		form.append(HT.P(), HT.P(),pageTable)
		corrHeading = HT.Paragraph('Tissue Correlation Table', Class="title")
		TD_LR = HT.TD(height=200,width="100%",bgcolor='#eeeeee',align="left")
		TD_LR.append(corrHeading,note,Intro, form, HT.P())

		self.dict['body'] =  str(TD_LR)
		self.dict['js1'] = '<SCRIPT SRC="/javascript/correlationMatrix.js"></SCRIPT><BR>'
		self.dict['title'] = 'Tissue Correlation Result'						
	
		return
    def writeHTML(self,fd):
        TD_LR = HT.TD(height=100,width="100%",bgColor='#eeeeee',valign="top")
        pageTable = HT.TableLite(cellSpacing=0,cellPadding=0,width="100%",border=0, align="Left")
        tbl = HT.TableLite(cellSpacing=2,cellPadding=0,width="90%",border=0, align="Left")
        seq = 1
        SelectionHeading = HT.Paragraph('%s Trait Collection' % fd.RISet, Class="title")

        mintmap = HT.Href(url="#redirect", onClick="if(validateTraitNumber()){databaseFunc(document.getElementsByName('showDatabase')[0], 'showIntMap');}")
        mintmap_img = HT.Image("/images/multiple_interval_mapping1_final.jpg", name='mintmap', alt="Multiple Interval Mapping", title="Multiple Interval Mapping", style="border:none;")
        mintmap.append(mintmap_img)
        mcorr = HT.Href(url="#redirect", onClick="if(validateTraitNumber()){databaseFunc(document.getElementsByName('showDatabase')[0], 'compCorr');}")
        mcorr_img = HT.Image("/images/compare_correlates2_final.jpg", name='comparecorr', alt="Compare Correlates", title="Compare Correlates", style="border:none;")
        mcorr.append(mcorr_img)
        cormatrix = HT.Href(url="#redirect", onClick="if(validateTraitNumber()){databaseFunc(document.getElementsByName('showDatabase')[0], 'corMatrix');}")
        cormatrix_img = HT.Image("/images/correlation_matrix1_final.jpg", name='corrmatrix', alt="Correlation Matrix and PCA", title="Correlation Matrix and PCA", style="border:none;")
        cormatrix.append(cormatrix_img)
        networkGraph = HT.Href(url="#redirect", onClick="if(validateTraitNumber()){databaseFunc(document.getElementsByName('showDatabase')[0], 'networkGraph');}")
        networkGraph_img = HT.Image("/images/network_graph1_final.jpg", name='networkgraph', alt="Network Graphs", title="Network Graphs", style="border:none;")
        networkGraph.append(networkGraph_img)
        heatmap = HT.Href(url="#redirect", onClick="if(validateTraitNumber()){databaseFunc(document.getElementsByName('showDatabase')[0], 'heatmap');}")
        heatmap_img = HT.Image("/images/heatmap2_final.jpg", name='heatmap', alt="QTL Heat Map and Clustering", title="QTL Heatmap and Clustering", style="border:none;")
        heatmap.append(heatmap_img)
        partialCorr = HT.Href(url="#redirect", onClick="if(validateTraitNumber()){databaseFunc(document.getElementsByName('showDatabase')[0], 'partialCorrInput');}")
        partialCorr_img = HT.Image("/images/partial_correlation_final.jpg", name='partialCorr', alt="Partial Correlation", title="Partial Correlation", style="border:none;")
        partialCorr.append(partialCorr_img)

        BN = HT.Href(url="#redirect", onClick="if(validateTraitNumber()){databaseFunc(document.getElementsByName('showDatabase')[0], 'BNInput');}")
        networkGraph_img = HT.Image("/images/network_graph1_final.jpg", name='BayesianNetwork', alt="Bayesian Network", title="Bayesian Network", style="border:none;")
        BN.append(networkGraph_img)

        removeselect = HT.Href(url="#redirect", onClick="addRmvSelection('%s', document.getElementsByName('showDatabase')[0], 'removeSelection');" % fd.RISet)
        removeselect_img = HT.Image("/images/remove_selection1_final.jpg", name="removeselect", alt="Remove Selection", title="Remove Selection", style="border:none;")
        removeselect.append(removeselect_img)
        selectall = HT.Href(url="#redirect", onClick="$('.checkallbox').attr('checked', true);")
        selectall_img = HT.Image("/images/select_all2_final.jpg", name="selectall", alt="Select All", title="Select All", style="border:none;")
        selectall.append(selectall_img)
        reset = HT.Href(url="#redirect", onClick="$('.checkallbox').attr('checked', false);")
        reset_img = HT.Image("/images/select_none2_final.jpg", alt="Select None", title="Select None", style="border:none;")
        reset.append(reset_img)
        exportSelect = HT.Href(url="#redirect", onClick="databaseFunc(document.getElementsByName('showDatabase')[0], 'exportSelectionDetailInfo');")
        exportSelect_img = HT.Image("/images/export2_final.jpg", name="exportSelection", alt="Export Selection", title="Export Selection", style="border:none;")
        exportSelect.append(exportSelect_img)
        selectinvert = HT.Href(url="#redirect", onClick = "checkInvert(document.getElementsByName('showDatabase')[0]);")
        selectinvert_img = HT.Image("/images/invert_selection2_final.jpg", name="selectinvert", alt="Invert Selection", title="Invert Selection", style="border:none;")
        selectinvert.append(selectinvert_img)

        chrMenu = HT.Input(type='hidden',name='chromosomes',value='all')

        importFile = HT.Input(type='file', name='importfile', size=15)
        importButton = HT.Input(type='button',name='importSelection',value='Load Collection', onClick="addRmvSelection('%s', this.form, 'importSelect');" % fd.RISet,Class="button")
        exportButton = HT.Input(type='button' ,name='exportSelection',value='Save Collection', onClick="databaseFunc(this.form,'exportSelect');", Class="button")
        importMenu = HT.Select(name='importmethod')
        importMenu.append(('append','append'))
        importMenu.append(('replace','replace'))

        GeneWeaver = HT.Href(url="#redirect", onClick="databaseFunc(document.getElementsByName('showDatabase')[0], 'ODE');")
        GeneWeaver_img = HT.Image("/images/ODE_logo_final.jpg", name="GeneWeaver", alt="GeneWeaver", title="GeneWeaver", style="border:none")
        GeneWeaver.append(GeneWeaver_img)

        GCATButton = HT.Href(url="#redirect", onClick="databaseFunc(document.getElementsByName('showDatabase')[0], 'GCAT');")
        GCATButton_img = HT.Image("/images/GCAT_logo_final.jpg", name="GCAT", alt="GCAT", title="GCAT", style="border:none")
        GCATButton.append(GCATButton_img)

        GeneSet = HT.Href(url="#redirect", onClick="databaseFunc(document.getElementsByName('showDatabase')[0],'GOTree');")
        GeneSet_img = HT.Image("/images/webgestalt_icon_final.jpg", name="webgestalt", alt="Gene Set Analysis Toolkit", title="Gene Set Analysis Toolkit", style="border:none")
        GeneSet.append(GeneSet_img)
        
        BNW = HT.Href(url="#redirect", onClick="databaseFunc(document.getElementsByName('showDatabase')[0], 'BNW');")
        BNW_img = HT.Image("/images/bnw.jpg", name="BNW", alt="Bayesian Network Webserver", title="Bayesian Network Webserver", style="border:none; width:57px; height:55px;")
        BNW.append(BNW_img)

        #need to be refined
        if fd.genotype.Mbmap:
            scale = HT.Input(name="scale", value="physic", type="hidden")
        else:
            scale = ""

        formMain = HT.Form(cgi=os.path.join(webqtlConfig.CGIDIR, webqtlConfig.SCRIPTFILE), enctype='multipart/form-data', name='showDatabase', submit=HT.Input(type='hidden'))

        #XZ, July 22, 2011: I add parameters for interval mapping
        hddn = {'FormID':'showDatabase','ProbeSetID':'_','database':'_','CellID':'_','RISet':fd.RISet,'incparentsf1':'ON','showHideOptions':'more','scale':'physic','additiveCheck':'ON', 'showSNP':'ON', 'showGenes':'ON', 'intervalAnalystCheck':'ON','bootCheck':None, 'permCheck':None, 'applyVarianceSE':None}
        for key in hddn.keys():
            formMain.append(HT.Input(name=key, value=hddn[key], type='hidden'))

        if not self.searchResult:
            SelectionHeading = HT.Paragraph('%s Trait Collection' % fd.RISet, Class="title")
            formMain.append(HT.HR(width="70%", color = "blue"),importFile, ' ', importMenu, ' ', importButton)
            TD_LR.append(SelectionHeading,HT.Blockquote('No trait has been added to this selection.'), HT.Center(HT.BR(), HT.BR(), HT.BR(), HT.BR(), formMain))
            self.dict['body'] = str(TD_LR)
            self.dict['title'] = "%s Trait Collection" % fd.RISet
            return

        #########################################
        # Creating table object for AJAX table  #
        #########################################
        tblobj = {}
        mainfmName = 'showDatabase'
        # NL, 07/27/2010. retrieveSpecies function has been moved from webqtlTrait.py to webqtlDatabaseFunction.py;
        species = webqtlDatabaseFunction.retrieveSpecies(cursor=self.cursor, RISet=fd.RISet)
        if species == 'human':
            chrMenu = scale = mintmap = heatmap = ""

        tblobj['header'] = self.getCollectionTableHeader()

        sortby = self.getSortByValue()

        thisRISet = fd.RISet
        tblobj['body'] = self.getCollectionTableBody(RISet=thisRISet, traitList=self.theseTraits, formName=mainfmName, species=species)

        filename= webqtlUtil.genRandStr("Search_")

        objfile = open('%s.obj' % (webqtlConfig.TMPDIR+filename), 'wb')
        cPickle.dump(tblobj, objfile)
        objfile.close()


        div = HT.Div(webqtlUtil.genTableObj(tblobj=tblobj, file=filename, sortby=sortby, tableID = "sortable", addIndex = "1"), Id="sortable")


        containerTable = HT.TableLite(cellSpacing=2,cellPadding=0,width="90%",border=0,align="Left")
        postContainerTable = HT.TableLite(cellSpacing=2,cellPadding=0,width="90%",border=0,align="Left")

        optionsTable = HT.TableLite(cellSpacing=2, cellPadding=0, width="640", border=0, align="Left")
        optionsTable.append(HT.TR(
            HT.TD(selectall,	width="77", style="text-align:center"),
            HT.TD(reset,		width="77", style="text-align:center"),
            HT.TD(selectinvert, width="77", style="text-align:center"),
            HT.TD(removeselect, width="77", style="text-align:center"),
            HT.TD(exportSelect, width="77", style="text-align:center"),
			HT.TD("&nbsp;",		width="8"),
            HT.TD(GeneWeaver,	width="77", style="text-align:center"),
            HT.TD(GCATButton,	width="77", style="text-align:center"),
            HT.TD(GeneSet,		width="77", style="text-align:center"),
            HT.TD(BNW,			width="77", style="text-align:center")))
        optionsTable.append(HT.TR(
            HT.TD("Select",						style="text-align:center"),
            HT.TD("Deselect",					style="text-align:center"),
            HT.TD("Invert",						style="text-align:center"),
            HT.TD("Remove",						style="text-align:center"),
            HT.TD("Export",						style="text-align:center"),
			HT.TD("&nbsp;"),
            HT.TD("Gene", HT.BR(), "Weaver",	style="text-align:center"),
            HT.TD("GCAT",						style="text-align:center"),
            HT.TD("Gene Set",					style="text-align:center"),
            HT.TD("BNW",						style="text-align:center")))
        postContainerTable.append(HT.TR(HT.TD(optionsTable)))
        containerTable.append(HT.TR(HT.TD(optionsTable)))

        functionTable = HT.TableLite(cellSpacing=2,cellPadding=0,width="480",border=0, align="Left")
        functionRow = HT.TR(HT.TD(networkGraph, width="16.7%"), HT.TD(cormatrix, width="16.7%"), HT.TD(partialCorr, width="16.7%"), HT.TD(mcorr, width="16.7%"), HT.TD(mintmap, width="16.7%"), HT.TD(heatmap))
        if species == "human":
            labelRow = HT.TR(HT.TD("&nbsp;"*2,HT.Text("Graph")), HT.TD("&nbsp;"*2,HT.Text("Matrix")), HT.TD("&nbsp;"*2, HT.Text("Partial")), HT.TD(HT.Text("Compare")))
        else:
            labelRow = HT.TR(HT.TD("&nbsp;"*2,HT.Text("Graph")), HT.TD("&nbsp;"*2,HT.Text("Matrix")), HT.TD("&nbsp;"*2, HT.Text("Partial")), HT.TD(HT.Text("Compare")), HT.TD(HT.Text("QTL Map")), HT.TD(HT.Text(text="Heat Map")))
        functionTable.append(functionRow, labelRow)
        postContainerTable.append(HT.TR(HT.TD(functionTable)))
        containerTable.append(HT.TR(HT.TD(functionTable)))
        containerTable.append(HT.TR(HT.TD("&nbsp;")))

        pageTable.append(HT.TR(HT.TD(containerTable)))
        chrMenu = scale = ""

        pageTable.append(HT.TR(HT.TD(div)))
        pageTable.append(HT.TR(HT.TD("&nbsp;")))
        if len(self.theseTraits) > 20:
            pageTable.append(HT.TR(HT.TD(postContainerTable)))
        pageTable.append(HT.TR(HT.TD(importFile, ' ', importMenu, ' ', importButton, '&nbsp;'*10, exportButton)))
            #Took out scaleMenu since it will be replaced with a jquery popup in the future - Zach 5/10/2010
        formMain.append(chrMenu,scale,pageTable)

        #Updated by NL, deleted showHideJS, moved jquery to jqueryFunction.js
        self.dict['js1'] = ''
        TD_LR.append(SelectionHeading,formMain)

        self.dict['body'] = str(TD_LR)
        self.dict['js2'] = 'onLoad="pageOffset()"'
        self.dict['layer'] = self.generateWarningLayer()
        self.dict['title'] = "%s Trait Collection" % thisRISet
    def __init__(self,fd):

        templatePage.__init__(self, fd)

        if not self.openMysql():
            return

        TD_LR = HT.TD(colspan=2,height=200,width="100%",bgColor='#eeeeee')

        TD_LR.append(HT.Paragraph("Partial Correlation Table", Class="title"), '\n')

        pc_method = fd.formdata.getvalue('pcMethod')

        primaryTraitString = fd.formdata.getvalue('primaryTrait')
        primaryTrait = (webqtlTrait(fullname=primaryTraitString, cursor=self.cursor))

        controlTraitsString = fd.formdata.getvalue('controlTraits')
        controlTraitsList = list(string.split(controlTraitsString,','))
        controlTraits = []
        for item in controlTraitsList:
            controlTraits.append(webqtlTrait(fullname=item, cursor=self.cursor))

        targetTraitsString = fd.formdata.getvalue('targetTraits')
        targetTraitsList = list(string.split(targetTraitsString,','))
        targetTraits = []
        _targetnames = []
        for item in targetTraitsList:
            oneTargetTrait = webqtlTrait(fullname=item, cursor=self.cursor)
            oneTargetTrait.retrieveInfo()
            targetTraits.append( oneTargetTrait )
            _targetnames.append( oneTargetTrait.name )

        #XZ: filter out the strains that have no value.
        primaryTrait.retrieveData()
        _strains, _vals, _vars = primaryTrait.exportInformative()

        #XZ: _controlstrains, _controlvals and _controlvars are list of list [ [], [], ...]. _controlNs is number
        _controlstrains,_controlvals,_controlvars,_controlNs = correlationFunction.controlStrains(controlTraitsString,_strains)

        N = len(_strains)

        allsame = True
        ##allsame is boolean for whether or not primary and control trait have values for the same strains
        for i in _controlstrains:
                if _strains != i:
                        allsame=False
                        break

        ##   If the strains for which each of the control traits and the primary trait have values are not identical, 
        ## we must remove from the calculation all vlaues for strains that are not present in each. Without doing this,
        ## undesirable biases would be introduced.
        # XZ, 01/11/2010: After execution of function fixStrains, variables _vals,_controlvals,_vars,_controlvars have the same number and same order of strains as strains in variable _strains. The _controlstrains remains intact.
        if not allsame:
                _strains,_vals,_controlvals,_vars,_controlvars = correlationFunction.fixStrains(_strains,_controlstrains,_vals,_controlvals,_vars,_controlvars)
                N = len(_strains)

        #XZ: We should check the value of control trait and primary trait here.
        nameOfIdenticalTraits = correlationFunction.findIdenticalTraits ( _vals, primaryTraitString, _controlvals, controlTraitsList )
        if nameOfIdenticalTraits:
            heading = "Partial Correlation Table"
            detail = ['%s and %s have same values for the %s strains that will be used to calculate partial correlation (common for all primary and control traits). In such case, partial correlation can NOT be calculated. Please re-select your traits.' % (nameOfIdenticalTraits[0], nameOfIdenticalTraits[1], len(_vals))]
            self.error(heading=heading,detail=detail)
            return


        if N < self.corrMinInformative:
            heading = "Partial Correlation Table"
            detail = ['Fewer than %d strain data were entered for %s data set. No calculation of correlation has been attempted.' % (self.corrMinInformative, fd.RISet)]
            self.error(heading=heading,detail=detail)
            return

        #XZ, 01/11/2010: Pay attention to the target trait strain number and order!
        #XZ 03/29/2010: need to input target trait values to this function.

        _targetvals = []
        for oneTargetTrait in targetTraits:
            oneTargetTrait.retrieveData()
            oneTraitVals = oneTargetTrait.exportData( _strains )
            _targetvals.append(oneTraitVals)


        if pc_method == 'spearman':
            allcorrelations = correlationFunction.determinePartialsByR(primaryVal = _vals, controlVals = _controlvals, targetVals = _targetvals, targetNames = _targetnames, method='s')
        else:
            allcorrelations = correlationFunction.determinePartialsByR(primaryVal = _vals, controlVals = _controlvals, targetVals = _targetvals, targetNames = _targetnames)

        totalTraits = len(allcorrelations)


        info_form = HT.Form(cgi= os.path.join(webqtlConfig.CGIDIR, webqtlConfig.SCRIPTFILE), enctype='multipart/form-data', name='showDatabase', submit=HT.Input(type='hidden'))

        hddn = {'FormID':'showDatabase', 'database':'_', 'ProbeSetID':'_', 'CellID':'_' }#XZ: These four parameters are required by javascript function showDatabase2.
        
        for key in hddn.keys():
            info_form.append(HT.Input(name=key, value=hddn[key], type='hidden'))

        info_form.append(HT.Paragraph("Primary Trait", Class="subtitle"), '\n')

        primaryTraitTable = HT.TableLite(cellSpacing=4,cellPadding=0,width="90%",border=0)

        descriptionString = primaryTrait.genHTML(dispFromDatabase=1)
        if primaryTrait.db.type == 'Publish' and primaryTrait.confidential:
            descriptionString = primaryTrait.genHTML(dispFromDatabase=1, privilege=self.privilege, userName=self.userName, authorized_users=primaryTrait.authorized_users)
        primaryTraitTable.append(HT.TR(HT.TD(HT.Href(text='%s' % descriptionString, url="javascript:showDatabase2('%s','%s','%s')" % (primaryTrait.db.name,primaryTrait.name,primaryTrait.cellid), Class="fs12 fwn") )))

        info_form.append(primaryTraitTable)

        info_form.append(HT.Paragraph("Control Traits", Class="subtitle"), '\n')

        controlTraitsTable = HT.TableLite(cellSpacing=4,cellPadding=0,width="90%",border=0)

        seq = 1

        ## Generate the listing table for control traits
        for thisTrait in controlTraits:
            descriptionString = thisTrait.genHTML(dispFromDatabase=1)
            if thisTrait.db.type == 'Publish' and thisTrait.confidential:
                descriptionString = thisTrait.genHTML(dispFromDatabase=1, privilege=self.privilege, userName=self.userName, authorized_users=thisTrait.authorized_users)
            controlTraitsTable.append(HT.TR(HT.TD("%d."%seq,align="left", width=10),
                                            HT.TD(HT.Href(text='%s' % descriptionString,url="javascript:showDatabase2('%s','%s','%s')" % (thisTrait.db.name,thisTrait.name,thisTrait.cellid), Class="fs12 fwn") )))
            seq += 1

        info_form.append(controlTraitsTable)


        TD_LR.append(info_form)        


        mainfmName = webqtlUtil.genRandStr("fm_")
        form = HT.Form(cgi= os.path.join(webqtlConfig.CGIDIR, webqtlConfig.SCRIPTFILE), enctype='multipart/form-data', name= mainfmName, submit=HT.Input(type='hidden'))

        hddn = {'FormID':'showDatabase', 'database':'_', 'ProbeSetID':'_', 'CellID':'_' }#XZ: These four parameters are required by javascript function showDatabase2.

        for key in hddn.keys():
            form.append(HT.Input(name=key, value=hddn[key], type='hidden'))


        filename= webqtlUtil.genRandStr("Corr_")

        tblobj = {}

        if pc_method == 'spearman':
            tblobj['header'] = \
            [[THCell(HT.TD('', Class="fs13 fwb ffl b1 cw cbrb"), sort=0),
              THCell(HT.TD('Database', Class="fs13 fwb ffl b1 cw cbrb",align='center'), text='db', idx=1),
              THCell(HT.TD('Record', Class="fs13 fwb ffl b1 cw cbrb",align='center'), text='id', idx=2),
              THCell(HT.TD('Symbol', Class="fs13 fwb ffl b1 cw cbrb"), text='symbol', idx=3),
              THCell(HT.TD('Description', Class="fs13 fwb ffl b1 cw cbrb", align='center'), text='desc', idx=4),
              THCell(HT.TD('N ', nowrap="on", Class="fs13 fwb ffl b1 cw cbrb"), text='nstr', idx=5),
              THCell(HT.TD('Partial rho ', nowrap="on", Class="fs13 fwb ffl b1 cw cbrb"), text='partial_corr', idx=6),
              THCell(HT.TD('p(partial rho)', Class="fs13 fwb ffl b1 cw cbrb",nowrap='ON'), text='partial_pv', idx=7),
              THCell(HT.TD('rho ', nowrap="on", Class="fs13 fwb ffl b1 cw cbrb"), text='corr', idx=8),
              THCell(HT.TD('p(rho)', Class="fs13 fwb ffl b1 cw cbrb",nowrap='ON'), text='pv', idx=9),
              THCell(HT.TD('delta rho', Class="fs13 fwb ffl b1 cw cbrb",nowrap='ON'), text='delta_rho', idx=10)]]
        else:
            tblobj['header'] = \
            [[THCell(HT.TD('', Class="fs13 fwb ffl b1 cw cbrb"), sort=0),
              THCell(HT.TD('Database', Class="fs13 fwb ffl b1 cw cbrb",align='center'), text='db', idx=1),
              THCell(HT.TD('Record', Class="fs13 fwb ffl b1 cw cbrb",align='center'), text='id', idx=2),
              THCell(HT.TD('Symbol', Class="fs13 fwb ffl b1 cw cbrb"), text='symbol', idx=3),
              THCell(HT.TD('Description', Class="fs13 fwb ffl b1 cw cbrb", align='center'), text='desc', idx=4),
              THCell(HT.TD('N ', nowrap="on", Class="fs13 fwb ffl b1 cw cbrb"), text='nstr', idx=5),
              THCell(HT.TD('Partial r ', nowrap="on", Class="fs13 fwb ffl b1 cw cbrb"), text='partial_corr', idx=6),
              THCell(HT.TD('p(partial r)', Class="fs13 fwb ffl b1 cw cbrb",nowrap='ON'), text='partial_pv', idx=7),
              THCell(HT.TD('r ', nowrap="on", Class="fs13 fwb ffl b1 cw cbrb"), text='corr', idx=8),
              THCell(HT.TD('p(r)', Class="fs13 fwb ffl b1 cw cbrb",nowrap='ON'), text='pv', idx=9),
              THCell(HT.TD('delta r', Class="fs13 fwb ffl b1 cw cbrb",nowrap='ON'), text='delta_r', idx=10)]]

        sortby = ("partial_pv", "up")

        tblobj['body'] = []
        for i, thisTrait in enumerate(targetTraits):
            tr = []

            trId = str(thisTrait)
            tr.append(TDCell(HT.TD(HT.Input(type="checkbox", Class="checkbox", name="searchResult",value=trId, onClick="highlight(this)"), nowrap="on", Class="fs12 fwn ffl b1 c222"), text=trId))
            tr.append(TDCell(HT.TD(HT.Href(text=thisTrait.db.fullname,url=webqtlConfig.INFOPAGEHREF % thisTrait.db.name,target="_blank", Class="fs12 fwn"), Class="fs12 fwn ffl b1 c222"), text=thisTrait.db.name, val=thisTrait
.db.name.upper()))
            tr.append(TDCell(HT.TD(HT.Href(text=thisTrait.name,url="javascript:showDatabase3('%s', '%s', '%s', '%s')" % (mainfmName,thisTrait.db.name,thisTrait.name,thisTrait.cellid), Class="fs12 fwn"), Class="fs12 fwn b1 c222"), text=thisTrait.name, val=thisTrait.name))

            #XZ: Symbol column
            if thisTrait.db.type =="ProbeSet":
                if thisTrait.symbol:
                    tr.append(TDCell(HT.TD(thisTrait.symbol, Class="fs12 fwn ffl b1 c222"), text=thisTrait.symbol, val=thisTrait.symbol.upper()))
                else:
                    tr.append(TDCell(HT.TD('NA', Class="fs12 fwn ffl b1 c222"), text='NA', val='NA'))
            elif thisTrait.db.type =="Publish":
                AbbreviationString = "--"
                if (thisTrait.post_publication_abbreviation != None):
                    AbbreviationString = thisTrait.post_publication_abbreviation

                if thisTrait.confidential:
                    if not webqtlUtil.hasAccessToConfidentialPhenotypeTrait(privilege=self.privilege, userName=self.userName, authorized_users=thisTrait.authorized_users):
                        if thisTrait.pre_publication_abbreviation:
                            AbbreviationString = thisTrait.pre_publication_abbreviation
                        else:
                            AbbreviationString = "--"

                if AbbreviationString == "--":
                    tr.append(TDCell(HT.TD('NA', Class="fs12 fwn ffl b1 c222"), text='NA', val='NA'))
                else:
                    tr.append(TDCell(HT.TD(AbbreviationString, Class="fs12 fwn ffl b1 c222"), text=AbbreviationString, val=AbbreviationString.upper()))
            else:
                tr.append(TDCell(HT.TD(thisTrait.name, Class="fs12 fwn ffl b1 c222"), text=thisTrait.name, val=thisTrait.name))

            #XZ: Description column
            if thisTrait.db.type =="ProbeSet" or thisTrait.db.type == "Temp":
                tr.append(TDCell(HT.TD(thisTrait.description, Class="fs12 fwn ffl b1 c222"), text=thisTrait.description, val=thisTrait.description.upper()))
            elif thisTrait.db.type =="Publish":
		PhenotypeString = thisTrait.post_publication_description
		if thisTrait.confidential:
			if not webqtlUtil.hasAccessToConfidentialPhenotypeTrait(privilege=self.privilege, userName=self.userName, authorized_users=thisTrait.authorized_users):
				PhenotypeString = thisTrait.pre_publication_description
                tr.append(TDCell(HT.TD(PhenotypeString, Class="fs12 fwn ffl b1 c222"), text=PhenotypeString, val=PhenotypeString.upper()))
            else:
                tr.append(TDCell(HT.TD(thisTrait.name, Class="fs12 fwn ffl b1 c222"), text=thisTrait.name, val=thisTrait.name))

            tr.append(TDCell(HT.TD(allcorrelations[i][1], Class="fs12 fwn ffl b1 c222", align='right'), text=allcorrelations[i][1], val=allcorrelations[i][1]))

            #partial correlation result
            try:
                repr = '%3.3f' % float(allcorrelations[i][2])
                tr.append(TDCell(HT.TD(repr, Class="fs12 fwn ffl b1 c222", align='right'), text=repr, val=abs(allcorrelations[i][2])))
            except:
                repr = 'NA'
                tr.append(TDCell(HT.TD(repr, Class="fs12 fwn ffl b1 c222", align='left'), text=repr, val=0 ))

            repr = webqtlUtil.SciFloat(allcorrelations[i][3])
            tr.append(TDCell(HT.TD(repr, Class="fs12 fwn ffl b1 c222", nowrap='ON', align='right'), text=repr, val=allcorrelations[i][3]))

            #zero order correlation result
            repr = '%3.3f' % float(allcorrelations[i][4])
            tr.append(TDCell(HT.TD(repr, Class="fs12 fwn ffl b1 c222", align='right'), text=repr, val=abs(allcorrelations[i][4])))

            repr = webqtlUtil.SciFloat(allcorrelations[i][5])
            tr.append(TDCell(HT.TD(repr, Class="fs12 fwn ffl b1 c222", nowrap='ON', align='right'), text=repr, val=allcorrelations[i][5]))

            #delta
            try:
                repr = '%3.3f' % ( float(allcorrelations[i][2]) - float(allcorrelations[i][4]) )
                tr.append(TDCell(HT.TD(repr, Class="fs12 fwn ffl b1 c222", align='right'), text=repr, val=repr ))
            except:
                repr = 'NA'
                tr.append(TDCell(HT.TD(repr, Class="fs12 fwn ffl b1 c222", align='left'), text=repr, val=0 ))

            tblobj['body'].append(tr)

        objfile = open('%s.obj' % (webqtlConfig.TMPDIR+filename), 'wb')
        cPickle.dump(tblobj, objfile)
        objfile.close()
		# NL, 07/27/2010. genTableObj function has been moved from templatePage.py to webqtlUtil.py;
        div = HT.Div(webqtlUtil.genTableObj(tblobj=tblobj, file=filename, sortby=sortby, tableID = "sortable", addIndex = "1"), Id="sortable")
        form.append(div)


        TD_LR.append(HT.Center(form),HT.P())

        self.dict['body'] =  str(TD_LR)
		# updated by NL, moved js function xmlhttpPost() and updatepage() to dhtml.js
        self.dict['js1'] = ''
        self.dict['title'] = 'Partial Correlation Result'
	def __init__(self, fd):

		templatePage.__init__(self, fd)

                if not self.openMysql():
                        return

		# updated by NL, deleted jquery here, move it to dhtml.js
		self.dict['js1'] = ''

		species_list = [] #List of species (mouse, rat, human), with the selected species listed first

		input_species = string.strip(string.lower(fd.formdata.getfirst('species', "mouse"))) #XZ, Oct 28, 2009: I changed the default species to mouse.
		species_list.append(input_species)
		#Create list of species (mouse, rat, human) with the species the user selected first
		for species in ["mouse","rat","human"]:
			if species not in species_list:
				species_list.append(species)

		ADMIN_tissue_alias = admin.ADMIN_tissue_alias

		tissue = string.strip(string.lower(fd.formdata.getfirst('tissue', "")))
		if tissue:
			try:
				rev_ADMIN_tissue_alias = {}
				for key in ADMIN_tissue_alias.keys():
					rev_ADMIN_tissue_alias[key] = key
					for alias in ADMIN_tissue_alias[key]:
						rev_ADMIN_tissue_alias[alias.upper()] = key
				tissue = rev_ADMIN_tissue_alias[tissue.upper()]
			except:
				tissue = "UNKNOWN"

		#possibly text output
		txtOutput = [] #ZS: if format=text
		all_species_dataset_count = 0 #XZ: count of datasets across all species; used in the opening text of the page
		all_species_trait_count = 0  #XZ: count of records across all species; used in opening text of the page and text file (if format = text)

		#div containing the tabs (species_container), the tabs themselves (species_tab_list, which is inserted into species_tabs), and the table (species_table) containing both the tissue and results tables for each tab
		species_container = HT.Div(id="species_tabs", Class="tab_container") #Div that will contain tabs for mouse/rat/human species; each tab contains a table with the result count for each tissue group
		species_tab_list = [HT.Href(text="%s" % species_list[0].capitalize(), url="#species1"), HT.Href(text="%s" % species_list[1].capitalize(), url="#species2"), HT.Href(text="%s" % species_list[2].capitalize(), url="#species3")]
		species_tabs = HT.List(species_tab_list, Class="tabs")
		species_table = HT.TableLite(cellSpacing=0,cellPadding=0,width="100%",border=0, align="Left")

		for i in range(len(species_list)):
			species_container_table = HT.TableLite(cellSpacing=0,cellPadding=0,width="100%",border=0, align="Left") #ZS: Table containing both the tissue record count and trait record tables as cells; this fixes a display issue in some browsers that places the tables side by side instead of top/bottom

			species = species_list[i]
			ADMIN_search_dbs = admin.ADMIN_search_dbs[species]
			this_species_dataset_count = 0 #XZ: count of the datasets containing results for this species
			this_species_trait_count = 0  #XZ: count of the trait records for this species

			div = HT.Div(id="species%s" % (i+1), Class="tab_content")
			tab_container = HT.Span() #ZS: Contains species_container_table within the species' tab

			tissuePageTable = HT.TableLite(cellSpacing=0,cellPadding=0,width="100%",border=0, align="Left")				
			tissue_tblobj = {} # object used to create the table listing the results for each tissue
			tissue_tblobj['header'] = self.getTissueTableHeader() # creates header for table listing results for selected tissue

			traitPageTable = HT.TableLite(cellSpacing=0,cellPadding=0,width="100%",border=0, align="Left")
			trait_tblobj = {} # object used to create the table listing the trait results for each tissue
			trait_tblobj['header'] = self.getTraitTableHeader() # creates header for table listing trait results for selected tissue

			tissue_tblobj['body'], trait_tblobj['body'], this_species_dataset_count, this_species_trait_count, this_species_txtOutput = self.createTableBodies(fd, species, tissue, ADMIN_search_dbs)

			if species == input_species:
				txtOutput = this_species_txtOutput

			filename1 = webqtlUtil.genRandStr("Search_") #filename for tissue table object
			tissue_objfile = open('%s.obj' % (webqtlConfig.TMPDIR+filename1), 'wb')
			cPickle.dump(tissue_tblobj, tissue_objfile)
			tissue_objfile.close()

			tissue_sortby = self.getTissueSortByValue() # sets how the tissue table should be sorted by default
			tissue_div = HT.Div(webqtlUtil.genTableObj(tblobj=tissue_tblobj, file=filename1, sortby=tissue_sortby, tableID = "tissue_sort%s" % (i+1), addIndex = "1"), Id="tissue_sort%s" % (i+1))

			tissuePageTable.append(HT.TR(HT.TD("&nbsp;")))
			tissuePageTable.append(HT.TR(HT.TD(tissue_div)))
			tissuePageTable.append(HT.TR(HT.TD("&nbsp;")))
			species_container_table.append(HT.TR(HT.TD(tissuePageTable)), HT.TR(HT.TD("&nbsp;")))


			filename2 = webqtlUtil.genRandStr("Search_") #filename for trait table object
			trait_objfile = open('%s.obj' % (webqtlConfig.TMPDIR+filename2), 'wb')
			cPickle.dump(trait_tblobj, trait_objfile)
			trait_objfile.close()

			trait_sortby = self.getTraitSortByValue() # sets how the trait table should be sorted by default
			trait_div = HT.Div(webqtlUtil.genTableObj(tblobj=trait_tblobj, file=filename2, sortby=trait_sortby, tableID = "results_sort%s" % (i+1), addIndex = "0"), Id="results_sort%s" % (i+1))

			traitPageTable.append(HT.TR(HT.TD("&nbsp;")))
			traitPageTable.append(HT.TR(HT.TD(trait_div)))
			traitPageTable.append(HT.TR(HT.TD("&nbsp;")))
			species_container_table.append(HT.TR(HT.TD(traitPageTable)), HT.TR(HT.TD("&nbsp;")))

			if this_species_trait_count == 0:
				tab_container.append(HT.Div("No records retrieved for this species.", align="left", valign="top", style="font-size:42"))
			else:
				tab_container.append(species_container_table)

			all_species_dataset_count += this_species_dataset_count
			all_species_trait_count += this_species_trait_count

			div.append(tab_container)
			species_table.append(HT.TR(HT.TD(div)))

		species_container.append(species_table)
		



		if fd.returnFmt != 'text': #if the format is not 'text'
			self.dict['title'] = 'Search Results'
			TD_LR = HT.TD(height=100,width="100%",bgColor='#fafafa',valign="top")
			pageTable = HT.TableLite(cellSpacing=0,cellPadding=0,width="100%",border=0, align="Left") # Table containing all of the page's elements (opening text, form); in some browers the elements arrange themselves horizontally if you don't put them into a table, so this fixes that problem

			formTable = HT.TableLite(cellSpacing=2,cellPadding=0,width="100%",border=0) # Table containing all of the form's elements (tabs, option buttons); used to correct the same issue mentioned in pageTable's comment

			mainForm = HT.Form( cgi= os.path.join(webqtlConfig.CGIDIR, webqtlConfig.SCRIPTFILE), enctype='multipart/form-data', name='showDatabase', submit=HT.Input(type='hidden'))
			hddn = {'FormID':'showDatabase','ProbeSetID':'_','database':'_','CellID':'_','RISet':fd.RISet}
			hddn['incparentsf1']='ON'
			for key in hddn.keys():
				mainForm.append(HT.Input(name=key, value=hddn[key], type='hidden'))

			#Add to collection, select all, invert selection, and deselect all ("reset") buttons
			addselect = HT.Href(url="#redirect", Class="add_traits")
			addselect_img = HT.Image("/images/add_collection1_final.jpg", name="addselect", alt="Add To Collection", title="Add To Collection", style="border:none;")
			addselect.append(addselect_img)
			selectall = HT.Href(url="#redirect", onClick="checkAll(document.getElementsByName('showDatabase')[0]);")
			selectall_img = HT.Image("/images/select_all2_final.jpg", name="selectall", alt="Select All", title="Select All", style="border:none;")
			selectall.append(selectall_img)
			selectinvert = HT.Href(url="#redirect", onClick="checkInvert(document.getElementsByName('showDatabase')[0];")
			selectinvert_img = HT.Image("/images/invert_selection2_final.jpg", name="selectinvert", alt="Invert Selection", title="Invert Selection", style="border:none;")
			selectinvert.append(selectinvert_img)
			reset = HT.Href(url="#redirect", onClick="checkNone(document.getElementsByName('showDatabase')[0]); return false;")
			reset_img = HT.Image("/images/select_none2_final.jpg", alt="Select None", title="Select None", style="border:none;")
			reset.append(reset_img)

			#Table with select, deselect, invert, etc. It is used for the results table.
			optionsTable = HT.TableLite(cellSpacing=2,cellPadding=0,width="20%",border=0)
			optionsRow = HT.TR(HT.TD(selectall, width="25%"), HT.TD(reset, width="25%"), HT.TD(selectinvert, width="25%"), HT.TD(addselect, width="25%"))
			labelsRow = HT.TR(HT.TD("&nbsp;"*2,"Select", width="25%"), HT.TD("&nbsp;","Deselect", width="25%"), HT.TD("&nbsp;"*3,"Invert", width="25%"), HT.TD("&nbsp;"*4,"Add", width="25%"))
			optionsTable.append(HT.TR(HT.TD("&nbsp;")), optionsRow, labelsRow)
			
			if fd.geneName:
				searchType = "gene name " + fd.geneName
			elif fd.refseq:
				searchType = "RefSeq accession number " + fd.refseq
			elif fd.genbankid:
				searchType = "Genbank ID " + fd.genbankid
			elif fd.geneid:
				searchType = "Gene ID " + fd.geneid
			else:
				searchType = ""

			SearchText = HT.Span("You searched for the %s in GeneNetwork." % searchType, HT.BR(),
						"We queried %s expression datasets across %s species and listed the results" % (all_species_dataset_count, len(species_list)), HT.BR(),
						"below. A total of %s records that may be of interest to you were found. The" % all_species_trait_count, HT.BR(),
						"top table lists the number of results found for each relevant tissue, and the", HT.BR(),
						"bottom gives a basic summary of each result. To study one of the results, click", HT.BR(),
						"its Record ID. More detailed information is also available for each result's group", HT.BR() ,
						"and dataset. To switch between species, click the tab with the corresponding", HT.BR(),
						"label.", HT.BR(), HT.BR(),
						"Please visit the links to the right to learn more about the variety of features", HT.BR(),
						"available within GeneNetwork.")	
			
			LinkText = HT.Span()
			
			mainLink = HT.Href(url="/webqtl/main.py", text = "Main Search Page", target="_blank")
			homeLink = HT.Href(url="/home.html", text = "What is GeneNetwork?", target="_blank")
			tourLink = HT.Href(url="/tutorial/WebQTLTour/", text = "Tour of GeneNetwork (20-40 min)", target="_blank")
			faqLink = HT.Href(url="/faq.html", text = "Frequently Asked Questions", target="_blank")
			glossaryLink = HT.Href(url="/glossary.html", text = "Glossary of terms used throughout GeneNetwork", target="_blank")
			
			LinkText.append(mainLink, HT.BR(), homeLink, HT.BR(), tourLink, HT.BR(), faqLink, HT.BR(), glossaryLink)
			
			formTable.append(HT.TR(HT.TD(species_tabs, species_container)), HT.TR(HT.TD(optionsTable)))
			mainForm.append(formTable)
			

			if fd.geneName:
				SearchHeading = HT.Paragraph('Search Results for gene name ', fd.geneName)
			elif fd.refseq:
				SearchHeading = HT.Paragraph('Search Results for RefSeq accession number ', fd.refseq)
			elif fd.genbankid:
				SearchHeading = HT.Paragraph('Search Results for Genbank ID ', fd.genbankid)
			elif fd.geneid:
				SearchHeading = HT.Paragraph('Search Results for Gene ID ', fd.geneid)
			else:
				SearchHeading = HT.Paragraph('')

			SearchHeading.__setattr__("class","title")

			pageTable.append(HT.TR(HT.TD(SearchText, width=600), HT.TD(LinkText, align="left", valign="top")), HT.TR(HT.TD("&nbsp;", colspan=2)), HT.TR(HT.TD(mainForm, colspan=2)))
			TD_LR.append(SearchHeading, pageTable)
			self.dict['body'] = TD_LR
		else:
		    if len(txtOutput) == 0:
			self.output = "##No records were found for this species. \n"
		    else:
			self.output = "##A total of %d records were returned. \n" % all_species_trait_count
			newOutput = []
			strainLists = {}
			for item in txtOutput:
				tissueGrp, thisTrait = item
				RISet = thisTrait.riset
				if strainLists.has_key(RISet):
					thisStrainlist = strainLists[RISet]
				else:
					thisGenotype = reaper.Dataset()
					thisGenotype.read(os.path.join(webqtlConfig.GENODIR, RISet + '.geno'))
					if thisGenotype.type == "riset": 
						_f1, _f12, _mat, _pat = webqtlUtil.ParInfo[RISet]
						thisGenotype = thisGenotype.add(Mat=_mat, Pat=_pat, F1=_f1)
					thisStrainlist = list(thisGenotype.prgy)
					strainLists[RISet] = thisStrainlist
				thisTrait.retrieveData(strainlist=thisStrainlist)
				thisData = []
				for item in thisStrainlist:
					if thisTrait.data.has_key(item): thisData.append(thisTrait.data[item].val)
					else: thisData.append(None)
				newOutput.append(["Structure", "Database", "ProbeSetID", "Cross"] + thisStrainlist)
				newOutput.append([tissueGrp, '"%s"' % thisTrait.db.fullname, thisTrait.name, RISet]+map(str,thisData))
			newOutput = webqtlUtil.asymTranspose(newOutput)
			for item in newOutput:
				 self.output += string.join(item, "\t") + "\n"