def plotNormalProbability(vals=None, RISet='', title=None, showstrains=0, specialStrains=[None], size=(750,500)):
		
	dataXZ = vals[:]
	dataXZ.sort(webqtlUtil.cmpOrder)
	dataLabel = []
	dataX = map(lambda X: X[1], dataXZ)

	showLabel = showstrains
	if len(dataXZ) > 50:
		showLabel = 0
	for item in dataXZ:
		strainName = webqtlUtil.genShortStrainName(RISet=RISet, input_strainName=item[0])
		dataLabel.append(strainName)					

	dataY=Plot.U(len(dataX))
	dataZ=map(Plot.inverseCumul,dataY)
	c = pid.PILCanvas(size=(750,500))
	Plot.plotXY(c, dataZ, dataX, dataLabel = dataLabel, XLabel='Expected Z score', connectdot=0, YLabel='Trait value', title=title, specialCases=specialStrains, showLabel = showLabel)

	filename= webqtlUtil.genRandStr("nP_")
	c.save(webqtlConfig.IMGDIR+filename, format='gif')

	img=HT.Image('/image/'+filename+'.gif',border=0)
	
	return img	
def plotBoxPlot(vals):
	
	valsOnly = []
	dataXZ = vals[:]
	for i in range(len(dataXZ)):
		valsOnly.append(dataXZ[i][1])
	
	plotHeight = 320
	plotWidth = 220
	xLeftOffset = 60
	xRightOffset = 40
	yTopOffset = 40
	yBottomOffset = 60

	canvasHeight = plotHeight + yTopOffset + yBottomOffset
	canvasWidth = plotWidth + xLeftOffset + xRightOffset
	canvas = pid.PILCanvas(size=(canvasWidth,canvasHeight))
	XXX = [('', valsOnly[:])]

	Plot.plotBoxPlot(canvas, XXX, offset=(xLeftOffset, xRightOffset, yTopOffset, yBottomOffset), XLabel= "Trait")
	filename= webqtlUtil.genRandStr("Box_")
	canvas.save(webqtlConfig.IMGDIR+filename, format='gif')
	img=HT.Image('/image/'+filename+'.gif',border=0)

	plotLink = HT.Span("More about ", HT.Href(text="Box Plots", url="http://davidmlane.com/hyperstat/A37797.html", target="_blank", Class="fs13"))
	
	return img, plotLink
    def screePlot(self, NNN=0, pearsonEigenValue=None):

        c1 = pid.PILCanvas(size=(700,500))
        Plot.plotXY(canvas=c1, dataX=range(1,NNN+1), dataY=pearsonEigenValue, rank=0, labelColor=pid.blue,plotColor=pid.red, symbolColor=pid.blue, XLabel='Factor Number', connectdot=1,YLabel='Percent of Total Variance %', title='Pearson\'s R Scree Plot')
        filename= webqtlUtil.genRandStr("Scree_")
        c1.save(webqtlConfig.IMGDIR+filename, format='gif')
        img=HT.Image('/image/'+filename+'.gif',border=0)
        
        return img
 def factorLoadingsPlot(self, pearsonEigenVectors=None, traitList=None):
     
     traitname = map(lambda X:str(X.name), traitList)
     c2 = pid.PILCanvas(size=(700,500))
     Plot.plotXY(c2, pearsonEigenVectors[0],pearsonEigenVectors[1], 0, dataLabel = traitname, labelColor=pid.blue, plotColor=pid.red, symbolColor=pid.blue,XLabel='Factor (1)', connectdot=1, YLabel='Factor (2)', title='Factor Loadings Plot (Pearson)', loadingPlot=1)
     filename= webqtlUtil.genRandStr("FacL_")
     c2.save(webqtlConfig.IMGDIR+filename, format='gif')
     img = HT.Image('/image/'+filename+'.gif',border=0)
  
     return img
def plotBarGraph(identification='', RISet='', vals=None, type="name"):
	
	this_identification = "unnamed trait"
	if identification:
		this_identification = identification

	if type=="rank":
		dataXZ = vals[:]
		dataXZ.sort(webqtlUtil.cmpOrder)
		title='%s' % this_identification
	else:
		dataXZ = vals[:]
		title='%s' % this_identification
		
	tvals = []
	tnames = []
	tvars = []
	for i in range(len(dataXZ)):
		tvals.append(dataXZ[i][1])
		tnames.append(webqtlUtil.genShortStrainName(RISet=RISet, input_strainName=dataXZ[i][0]))
		tvars.append(dataXZ[i][2])
	nnStrain = len(tnames)

	sLabel = 1

	###determine bar width and space width
	if nnStrain < 20:
		sw = 4
	elif nnStrain < 40:
		sw = 3
	else:
		sw = 2

	### 700 is the default plot width minus Xoffsets for 40 strains
	defaultWidth = 650
	if nnStrain > 40:
		defaultWidth += (nnStrain-40)*10
	defaultOffset = 100
	bw = int(0.5+(defaultWidth - (nnStrain-1.0)*sw)/nnStrain)
	if bw < 10:
		bw = 10

	plotWidth = (nnStrain-1)*sw + nnStrain*bw + defaultOffset
	plotHeight = 500
	#print [plotWidth, plotHeight, bw, sw, nnStrain]
	c = pid.PILCanvas(size=(plotWidth,plotHeight))
	Plot.plotBarText(c, tvals, tnames, variance=tvars, YLabel='Value', title=title, sLabel = sLabel, barSpace = sw)

	filename= webqtlUtil.genRandStr("Bar_")
	c.save(webqtlConfig.IMGDIR+filename, format='gif')
	img=HT.Image('/image/'+filename+'.gif',border=0)
	
	return img
 def factorLoadingsPlot(self, pearsonEigenVectors=None, traitList=None):
     traitname = map(lambda X:str(X.name), traitList)
     c2 = pid.PILCanvas(size=(700,500))
     if type(pearsonEigenVectors[0][0]).__name__ == 'complex':
         pearsonEigenVectors_0 = self.removeimag_array(values=pearsonEigenVectors[0])
     else:
         pearsonEigenVectors_0 = pearsonEigenVectors[0]
     if type(pearsonEigenVectors[1][0]).__name__ == 'complex':
         pearsonEigenVectors_1 = self.removeimag_array(values=pearsonEigenVectors[1])
     else:
         pearsonEigenVectors_1 = pearsonEigenVectors[1]
     Plot.plotXY(c2, pearsonEigenVectors_0,pearsonEigenVectors_1, 0, dataLabel = traitname, labelColor=pid.blue, plotColor=pid.red, symbolColor=pid.blue,XLabel='Factor (1)', connectdot=1, YLabel='Factor (2)', title='Factor Loadings Plot (Pearson)', loadingPlot=1)
     filename= webqtlUtil.genRandStr("FacL_")
     c2.save(webqtlConfig.IMGDIR+filename, format='gif')
     img = HT.Image('/image/'+filename+'.gif',border=0)
  
     return img
 def do_outliers(self):
     values = [sample.value for sample in self.sample_list if sample.value != None]
     upper_bound, lower_bound = Plot.find_outliers(values)
     
     for sample in self.sample_list:
         if sample.value:
             if upper_bound and sample.value > upper_bound:
                 sample.outlier = True
             elif lower_bound and sample.value < lower_bound:
                 sample.outlier = True
             else:
                 sample.outlier = False
Beispiel #8
0
    def do_outliers(self):
        values = [sample.value for sample in self.sample_list
                  if sample.value is not None]
        upper_bound, lower_bound = Plot.find_outliers(values)

        for sample in self.sample_list:
            if sample.value:
                if upper_bound and sample.value > upper_bound:
                    sample.outlier = True
                elif lower_bound and sample.value < lower_bound:
                    sample.outlier = True
                else:
                    sample.outlier = False
Beispiel #9
0
       	def buildCanvas(self, colorScheme='', targetDescriptionChecked='', clusterChecked='', sessionfile='', genotype=None, strainlist=None, ppolar=None, mpolar=None, traitList=None, traitDataList=None, userPrivilege=None, userName=None):
                labelFont = pid.Font(ttf="tahoma",size=14,bold=0)
                topHeight = 0
       	       	NNN = len(traitList)
       	       	#XZ: It's necessory to define canvas here
                canvas = pid.PILCanvas(size=(80+NNN*20,880))
                names = map(webqtlTrait.displayName, traitList)
                #XZ, 7/29/2009: create trait display and find max strWidth
                strWidth = 0
                for j in range(len(names)):
                        thisTrait = traitList[j]
                        if targetDescriptionChecked:
                            if thisTrait.db.type == 'ProbeSet':
                                if thisTrait.probe_target_description:
                                        names[j] += ' [%s at Chr %s @ %2.3fMB, %s]' % (thisTrait.symbol, thisTrait.chr, thisTrait.mb, thisTrait.probe_target_description)
                                else:
                                        names[j] += ' [%s at Chr %s @ %2.3fMB]' % (thisTrait.symbol, thisTrait.chr, thisTrait.mb)
                            elif thisTrait.db.type == 'Geno':
                                names[j] += ' [Chr %s @ %2.3fMB]' % (thisTrait.chr, thisTrait.mb)
                            elif thisTrait.db.type == 'Publish':
                                if thisTrait.confidential:
                                    if webqtlUtil.hasAccessToConfidentialPhenotypeTrait(privilege=userPrivilege, userName=userName, authorized_users=thisTrait.authorized_users):
                                        if thisTrait.post_publication_abbreviation:
                                            names[j] += ' [%s]' % (thisTrait.post_publication_abbreviation)
                                    else:
                                        if thisTrait.pre_publication_abbreviation:
                                            names[j] += ' [%s]' % (thisTrait.pre_publication_abbreviation)
                                else:
                                    if thisTrait.post_publication_abbreviation:
                                        names[j] += ' [%s]' % (thisTrait.post_publication_abbreviation)
                            else:
                                pass

                        i = canvas.stringWidth(names[j], font=labelFont)
                        if i > strWidth:
                                strWidth = i

                width = NNN*20
                xoffset = 40
                yoffset = 40
                cellHeight = 3
                nLoci = reduce(lambda x,y: x+y, map(lambda x: len(x),genotype),0)

                if nLoci > 2000:
                        cellHeight = 1
                elif nLoci > 1000:
                        cellHeight = 2
                elif nLoci < 200:
                        cellHeight = 10
                else:
                        pass

                pos = range(NNN)
                neworder = []
                BWs = Plot.BWSpectrum()
                colors100 = Plot.colorSpectrum()
                colors = Plot.colorSpectrum(130)
                finecolors = Plot.colorSpectrum(250)
                colors100.reverse()
                colors.reverse()
                finecolors.reverse()

                scaleFont=pid.Font(ttf="tahoma",size=10,bold=0)
				
                if not clusterChecked: #XZ: this part is for original order
                        for i in range(len(names)):
                                neworder.append((xoffset+20*(i+1), i))

                        canvas = pid.PILCanvas(size=(80+NNN*20+240,80+ topHeight +5+5+strWidth+nLoci*cellHeight+80+20*cellHeight))

                        self.drawTraitNameBottom(canvas,names,yoffset,neworder,strWidth,topHeight,labelFont)
                else: #XZ: this part is to cluster traits
                        topHeight = 400
                        canvas = pid.PILCanvas(size=(80+NNN*20+240,80+ topHeight +5+5+strWidth+nLoci*cellHeight+80+20*cellHeight))

                        corArray = [([0] * (NNN))[:] for i in range(NNN)]

                        nnCorr = len(strainlist)

                        #XZ, 08/04/2009: I commented out pearsonArray, spearmanArray
                        for i, thisTrait in enumerate(traitList):
                            names1 = [thisTrait.db.name, thisTrait.name, thisTrait.cellid]
                            for j, thisTrait2 in enumerate(traitList):
                                    names2 = [thisTrait2.db.name, thisTrait2.name, thisTrait2.cellid]
                                    if j < i:
                                            corr,nOverlap = webqtlUtil.calCorrelation(traitDataList[i], traitDataList[j],nnCorr)
                                            if (1-corr) < 0:
                                                    distance = 0.0
                                            else:
                                                    distance = 1-corr
                                            corArray[i][j] = distance
                                            corArray[j][i] = distance
                                    elif j == i:
                                            corArray[i][j] = 0.0
                                    else:
                                            pass

                        #XZ, 7/29/2009: The parameter d has info of cluster (group member and distance). The format of d is tricky. Print it out to see it's format.
                        d = slink.slink(corArray)

                        #XZ, 7/29/2009: Attention: The 'neworder' is changed by the 'draw' function
                        #XZ, 7/30/2009: Only toppos[1][0] and top[1][1] are used later. Then what toppos[0] is used for? 
                        toppos = self.draw(canvas,names,d,xoffset,yoffset,neworder,topHeight)
                        self.drawTraitNameTop(canvas,names,yoffset,neworder,strWidth,topHeight,labelFont)

                        #XZ, 7/29/2009: draw the top vertical line
                        canvas.drawLine(toppos[1][0],toppos[1][1],toppos[1][0],yoffset)

                        #XZ: draw string 'distance = 1-r'
                        canvas.drawString('distance = 1-r',neworder[-1][0] + 50, topHeight*3/4,font=labelFont,angle=90)

                        #draw Scale
                        scaleFont=pid.Font(ttf="tahoma",size=10,bold=0)
                        x = neworder[-1][0]
                        canvas.drawLine(x+5, topHeight+yoffset, x+5, yoffset, color=pid.black)
                        y = 0
                        while y <=2:
                                canvas.drawLine(x+5, topHeight*y/2.0+yoffset, x+10, topHeight*y/2.0+yoffset)
                                canvas.drawString('%2.1f' % (2-y), x+12, topHeight*y/2.0+yoffset, font=scaleFont)
                                y += 0.5


                chrname = 0
                chrnameFont=pid.Font(ttf="tahoma",size=24,bold=0)
                Ncol = 0

                nearestMarkers = self.getNearestMarker(traitList, genotype)

                # import cPickle
                if sessionfile:
                        fp = open(os.path.join(webqtlConfig.TMPDIR, sessionfile + '.session'), 'rb')
                        permData = cPickle.load(fp)
                        fp.close()
                else:
                        permData = {}

                areas = []
				#XZ, 7/31/2009: This for loop is to generate the heatmap
                #XZ: draw trait by trait instead of marker by marker
                for order in neworder:
                        #startHeight = 40+400+5+5+strWidth
                        startHeight = topHeight + 40+5+5+strWidth
                        startWidth = order[0]-5
                        if Ncol and Ncol % 5 == 0:
                                drawStartPixel = 8
                        else:
                                drawStartPixel = 9

                        tempVal = traitDataList[order[1]]
                        _vals = []
                        _strains = [] 
                        for i in range(len(strainlist)):
                                if tempVal[i] != None:
                                        _strains.append(strainlist[i])
                                        _vals.append(tempVal[i])

                        qtlresult = genotype.regression(strains = _strains, trait = _vals)

                        if sessionfile:
                                LRSArray = permData[str(traitList[order[1]])]
                        else:
                                LRSArray = genotype.permutation(strains = _strains, trait = _vals, nperm = 1000)
                                permData[str(traitList[order[1]])] = LRSArray

                        sugLRS = LRSArray[369]
                        sigLRS = LRSArray[949]
                        prechr = 0
                        chrstart = 0
                        nearest = nearestMarkers[order[1]]
                        midpoint = []

                        for item in qtlresult:
                                if item.lrs > webqtlConfig.MAXLRS:
                                        adjustlrs = webqtlConfig.MAXLRS
                                else:
                                        adjustlrs = item.lrs

                                if item.locus.chr != prechr:
                                        if prechr:
                                                canvas.drawRect(startWidth-drawStartPixel, startHeight, startWidth+10, startHeight+3,edgeColor=pid.white, edgeWidth=0, fillColor=pid.white)
                                                startHeight+= 3
                                                if not chrname:
                                                        canvas.drawString(prechr,xoffset-20,(chrstart+startHeight)/2,font = chrnameFont,color=pid.dimgray)
                                        prechr = item.locus.chr
                                        chrstart = startHeight
                                if colorScheme == '0':
                                        if adjustlrs <= sugLRS:
                                                colorIndex = int(65*adjustlrs/sugLRS)
                                        else:
                                                colorIndex = int(65 + 35*(adjustlrs-sugLRS)/(sigLRS-sugLRS))
                                        if colorIndex > 99:
                                                colorIndex = 99
                                        colorIndex = colors100[colorIndex]
                                elif colorScheme == '1':
                                        sugLRS = LRSArray[369]/2.0
                                        if adjustlrs <= sugLRS:
                                                colorIndex = BWs[20+int(50*adjustlrs/sugLRS)]
                                        else:
                                                if item.additive > 0:
                                                        colorIndex = int(80 + 50*(adjustlrs-sugLRS)/(sigLRS-sugLRS))
                                                else:
                                                        colorIndex = int(50 - 50*(adjustlrs-sugLRS)/(sigLRS-sugLRS))
                                                if colorIndex > 129:
                                                        colorIndex = 129
                                                if colorIndex < 0:
                                                        colorIndex = 0
                                                colorIndex = colors[colorIndex]
                                elif colorScheme == '2':
                                        if item.additive > 0:
                                                colorIndex = int(150 + 100*(adjustlrs/sigLRS))
                                        else:
                                                colorIndex = int(100 - 100*(adjustlrs/sigLRS))
                                        if colorIndex > 249:
                                                colorIndex = 249
                                        if colorIndex < 0:
                                                        colorIndex = 0
                                        colorIndex = finecolors[colorIndex]
                                else:
                                        colorIndex = pid.white

                                if startHeight > 1:
                                        canvas.drawRect(startWidth-drawStartPixel, startHeight, startWidth+10, startHeight+cellHeight,edgeColor=colorIndex, edgeWidth=0, fillColor=colorIndex)
                                else:
                                        canvas.drawLine(startWidth-drawStartPixel, startHeight, startWidth+10, startHeight, Color=colorIndex)

                                if item.locus.name == nearest:
                                        midpoint = [startWidth,startHeight-5]
                                startHeight+=cellHeight

                        #XZ, map link to trait name and band
                        COORDS = "%d,%d,%d,%d" %(startWidth-drawStartPixel,topHeight+40,startWidth+10,startHeight)
                        HREF = "javascript:showDatabase2('%s','%s','%s');" % (traitList[order[1]].db.name, traitList[order[1]].name, traitList[order[1]].cellid)
                        area = (COORDS, HREF, '%s' % names[order[1]])
                        areas.append(area)

                        if midpoint:
                                traitPixel = ((midpoint[0],midpoint[1]),(midpoint[0]-6,midpoint[1]+12),(midpoint[0]+6,midpoint[1]+12))
                                canvas.drawPolygon(traitPixel,edgeColor=pid.black,fillColor=pid.orange,closed=1)

                        if not chrname:
                                canvas.drawString(prechr,xoffset-20,(chrstart+startHeight)/2,font = chrnameFont,color=pid.dimgray)
                        chrname = 1
                        Ncol += 1


                #draw Spectrum
                startSpect = neworder[-1][0] + 30
                startHeight = topHeight + 40+5+5+strWidth

                if colorScheme == '0':
                        for i in range(100):
                                canvas.drawLine(startSpect+i,startHeight+20,startSpect+i,startHeight+40,color=colors100[i])
                        scaleFont=pid.Font(ttf="tahoma",size=10,bold=0)
                        canvas.drawLine(startSpect,startHeight+45,startSpect,startHeight+39,color=pid.black)
                        canvas.drawString('LRS = 0',startSpect,startHeight+55,font=scaleFont)
                        canvas.drawLine(startSpect+64,startHeight+45,startSpect+64,startHeight+39,color=pid.black)
                        canvas.drawString('Suggestive LRS',startSpect+64,startHeight+55,font=scaleFont)
                        canvas.drawLine(startSpect+99,startHeight+45,startSpect+99,startHeight+39,color=pid.black)
                        canvas.drawString('Significant LRS',startSpect+105,startHeight+40,font=scaleFont)
                elif colorScheme == '1':
                        for i in range(50):
                                canvas.drawLine(startSpect+i,startHeight,startSpect+i,startHeight+40,color=BWs[20+i])
                        for i in range(50,100):
                                canvas.drawLine(startSpect+i,startHeight,startSpect+i,startHeight+20,color=colors[100-i])
                                canvas.drawLine(startSpect+i,startHeight+20,startSpect+i,startHeight+40,color=colors[30+i])

                        canvas.drawLine(startSpect,startHeight+45,startSpect,startHeight+39,color=pid.black)
                        canvas.drawString('LRS = 0',startSpect,startHeight+60,font=scaleFont)
                        canvas.drawLine(startSpect+50,startHeight+45,startSpect+50,startHeight+39,color=pid.black)
                        canvas.drawString('0.5*Suggestive LRS',startSpect+50,startHeight+ 60,font=scaleFont)
                        canvas.drawLine(startSpect+99,startHeight+45,startSpect+99,startHeight+39,color=pid.black)
                        canvas.drawString('Significant LRS',startSpect+105,startHeight+50,font=scaleFont)
                        textFont=pid.Font(ttf="verdana",size=18,bold=0)
                        canvas.drawString('%s +' % ppolar,startSpect+120,startHeight+ 35,font=textFont,color=pid.red)
                        canvas.drawString('%s +' % mpolar,startSpect+120,startHeight+ 15,font=textFont,color=pid.blue)
                elif colorScheme == '2':
                        for i in range(100):
                                canvas.drawLine(startSpect+i,startHeight,startSpect+i,startHeight+20,color=finecolors[100-i])
                                canvas.drawLine(startSpect+i,startHeight+20,startSpect+i,startHeight+40,color=finecolors[150+i])

                        canvas.drawLine(startSpect,startHeight+45,startSpect,startHeight+39,color=pid.black)
                        canvas.drawString('LRS = 0',startSpect,startHeight+60,font=scaleFont)
                        canvas.drawLine(startSpect+99,startHeight+45,startSpect+99,startHeight+39,color=pid.black)
                        canvas.drawString('Significant LRS',startSpect+105,startHeight+50,font=scaleFont)
                        textFont=pid.Font(ttf="verdana",size=18,bold=0)
                        canvas.drawString('%s +' % ppolar,startSpect+120,startHeight+ 35,font=textFont,color=pid.red)
                        canvas.drawString('%s +' % mpolar,startSpect+120,startHeight+ 15,font=textFont,color=pid.blue)
						
                filename= webqtlUtil.genRandStr("Heatmap_")
                canvas.save(webqtlConfig.IMGDIR+filename, format='png')
                if not sessionfile:
                        sessionfile = webqtlUtil.generate_session()
                        webqtlUtil.dump_session(permData, os.path.join(webqtlConfig.TMPDIR, sessionfile +'.session'))
                self.filename=filename
                self.areas=areas
                self.sessionfile=sessionfile
	def drawGraph(self, canvas, data, cLength = 2500, offset= (80, 160, 60, 60), XLabel="QTL location (GMb)", YLabel="Gene location (GMb)"):
		xLeftOffset, xRightOffset, yTopOffset, yBottomOffset = offset
		plotWidth = canvas.size[0] - xLeftOffset - xRightOffset
		plotHeight = canvas.size[1] - yTopOffset - yBottomOffset
		
		#draw Frame
		canvas.drawRect(plotWidth+xLeftOffset, plotHeight + yTopOffset, xLeftOffset, yTopOffset)
		
		#draw Scale
		i = 100
		scaleFont=pid.Font(ttf="cour",size=11,bold=1)
		while i < cLength:
			yCoord = plotHeight + yTopOffset - plotHeight*i/cLength
			canvas.drawLine(xLeftOffset,yCoord ,xLeftOffset-5, yCoord)
			canvas.drawString("%d"% i,	xLeftOffset -40, yCoord +5,font=scaleFont)
			xCoord = xLeftOffset + plotWidth*i/cLength
			canvas.drawLine(xCoord, plotHeight + yTopOffset ,xCoord, plotHeight + yTopOffset+5)
			canvas.drawString("%d"% i,	xCoord -10, plotHeight + yTopOffset+15,font=scaleFont)
			i += 100

		#draw Points
		finecolors = Plot.colorSpectrum(300)
		finecolors.reverse()
		for item in data:
			_pvalue = item[-1]
			try:
				_idx = int((-math.log10(_pvalue))*300/6.0) # XZ, 09/11/2008: add module name
				_color = finecolors[_idx]
			except:
				_color = finecolors[-1]
				
			canvas.drawCross(xLeftOffset + plotWidth*item[0]/cLength, plotHeight + yTopOffset - plotHeight*item[1]/cLength, color=_color,size=3)
		
		#draw grid / always draw grid
		if 1: #self.grid == "on":
			for key in self.mouseChrLengthDict.keys():
				length = self.mouseChrLengthDict[key]
				if length != 0:
					yCoord = plotHeight + yTopOffset - plotHeight*length/cLength
					canvas.drawLine(xLeftOffset,yCoord ,xLeftOffset+plotWidth, yCoord, color=pid.lightgrey)
					xCoord = xLeftOffset + plotWidth*length/cLength
					canvas.drawLine(xCoord, plotHeight + yTopOffset ,xCoord, yTopOffset, color=pid.lightgrey)
		
		#draw spectrum
		i = 0
		j = 0
		middleoffsetX = 40
		labelFont=pid.Font(ttf="tahoma",size=12,bold=0)
		for dcolor in finecolors:
			canvas.drawLine(xLeftOffset+ plotWidth + middleoffsetX -15 , plotHeight + yTopOffset - i, \
				xLeftOffset+ plotWidth + middleoffsetX+15 , plotHeight + yTopOffset - i, color=dcolor)
			if i % 50 == 0:
				canvas.drawLine(xLeftOffset+ plotWidth +middleoffsetX+15 ,plotHeight + yTopOffset - i,  \
				xLeftOffset+ plotWidth +middleoffsetX+20,plotHeight + yTopOffset - i, color=pid.black)
				canvas.drawString("%1.1f" % -j , xLeftOffset+ plotWidth +middleoffsetX+25 ,plotHeight + yTopOffset - i+5, font = labelFont)
				j += 1
			i += 1
		canvas.drawLine(xLeftOffset+ plotWidth +middleoffsetX+15 ,plotHeight + yTopOffset - i+1,  \
			xLeftOffset+ plotWidth +middleoffsetX+20,plotHeight + yTopOffset - i+1, color=pid.black)	
		canvas.drawString("%1.1f" % -j , xLeftOffset+ plotWidth +middleoffsetX+25 ,plotHeight + yTopOffset - i+6, font = labelFont)
		labelFont=pid.Font(ttf="tahoma",size=14,bold=1)	
		canvas.drawString("Log(pValue)" , xLeftOffset+ plotWidth +middleoffsetX+60 ,plotHeight + yTopOffset - 100, font = labelFont, angle =90)
		
		labelFont=pid.Font(ttf="verdana",size=18,bold=0)
		canvas.drawString(XLabel, xLeftOffset + (plotWidth -canvas.stringWidth(XLabel,font=labelFont))/2.0, plotHeight + yTopOffset +40, color=pid.blue, font=labelFont)
		canvas.drawString(YLabel,xLeftOffset-60, plotHeight + yTopOffset-(plotHeight -canvas.stringWidth(YLabel,font=labelFont))/2.0, color=pid.blue, font=labelFont, angle =90)			
		return
	def drawSVG(self, data, cLength = 2500, offset= (80, 160, 60, 60), size=(1280,880), 
			XLabel="Marker GMb", YLabel="Transcript GMb"):
		entities = {
				"colorText" : "fill:darkblue;",
				"strokeText" : ";stroke:none;stroke-width:0;",
				"allText" : "font-family:Helvetica;", 
				"titleText" : "font-size:22;font-weight:bold;", 
				"subtitleText" : "font-size:18;font-weight:bold;", 
				"headlineText" : "font-size:14;font-weight:bold;", 
				"normalText" : "font-size:12;", 
				"legendText" : "font-size:11;text-anchor:end;", 
				"valuesText" : "font-size:12;", 
				"boldValuesText" : "font-size:12;font-weight:bold;", 
				"smallText" : "font-size:10;", 
				"vText" : "writing-mode:tb-rl",
				"rightText" : "text-anchor:end;", 
				"middleText" : "text-anchor:middle;", 
				"bezgrenzstyle" : "fill:none;stroke:#11A0FF;stroke-width:40;stroke-antialiasing:true;", 
				"rectstyle" : "fill:lightblue;stroke:none;opacity:0.2;", 
				"fillUnbebaut" : "fill:#CCFFD4;stroke:none;", 
				"fillNodata" : "fill:#E7E7E7;stroke:black;stroke-width:2;stroke-antialiasing:true;", 
				"fillNodataLegend" : "fill:#E7E7E7;stroke:black;stroke-width:0.5;stroke-antialiasing:true;", 
				"grundzeitstyle" : "fill:none;stroke:#E00004;stroke-width:60;stroke-antialiasing:true;", 
				"bezgrenzstyle" : "fill:none;stroke:#11A0FF;stroke-width:40;stroke-antialiasing:true;", 
				"mapAuthor" : "A. Neumann", 
				}
		cWidth, cHeight = size		
		canvasSVG = svg.drawing(entities) #create a drawing
		drawSpace=svg.svg((0, 0, cWidth, cHeight), cWidth, cHeight, xml__space="preserve", 
			zoomAndPan="disable", onload="initMap(evt);", 
			xmlns__a3="http://ns.adobe.com/AdobeSVGViewerExtensions/3.0/",
			a3__scriptImplementation="Adobe") #create a svg drawingspace
		canvasds=svg.description('Genome Graph') #define a description
		drawSpace.addElement(canvasds) #add the description to the svg
		
		#need to be modified or deleted
		xLeftOffset, xRightOffset, yTopOffset, yBottomOffset = offset
		plotWidth = cWidth - xLeftOffset - xRightOffset
		plotHeight = cHeight - yTopOffset - yBottomOffset
		drawSpace.addElement(svg.script("", language="javascript", xlink__href="/javascript/svg.js"))
		
		#add defs
		defs = svg.defs()
		symbol1= svg.symbol(id="magnifyer", overflow="visible", 
			style="fill:white;stroke:orange;stroke-width:2;")
		symbol1.addElement(svg.line(0, 0, -8, 20))
		symbol1.addElement(svg.circle(0, 0, 8))
		symbol1.addElement(svg.line(-4, 0, 4, 0, style="stroke:orange;stroke-width:2;"))
		defs.addElement(symbol1)
		symbol2= svg.symbol(id="magnifyerZoomIn",overflow="visible")
		symbol2.addElement(svg.use(link="#magnifyer", id="zoomIn"))
		symbol2.addElement(svg.line(0, -4, 0, 4, style="stroke:orange;stroke-width:2;"))
		defs.addElement(symbol2)
		drawSpace.addElement(defs)
		
		symbol3= svg.symbol(id="msgbox", overflow="visible", 
			style="fill:white;stroke:orange;stroke-width:1;opacity:0.8;")
		symbol3.addElement(svg.rect(-80, -190, 300, 150, rx=10, ry=10))
		symbol3.addElement(svg.line(21, -40, 58, -40, style="stroke:white;"))
		symbol3.addElement(svg.polyline([[20, -40], [0, 0], [60, -40]]))
		symbol3.addElement(svg.text(-60, -160, "ProbeSet ", style="&colorText; &allText; &subtitleText; &strokeText;"))
		symbol3.addElement(svg.text(-60, -125, "Marker ", style="&colorText; &allText; &subtitleText; &strokeText;"))
		symbol3.addElement(svg.text(-60, -90, "LRS ", style="&colorText; &allText; &subtitleText; &strokeText;"))
		symbol3.addElement(svg.text(-60, -55, "P value ", style="&colorText; &allText; &subtitleText; &strokeText;"))
		defs.addElement(symbol3)
		
		g = svg.group("title")
		g.addElement(svg.text(cWidth-40, 30, "Genome Graph", style="&colorText; &allText; &titleText; &rightText;"))
		g.addElement(svg.text(cWidth-40, 50, "Whole Transcriptome Mapping", style="&colorText; &allText; &subtitleText; &rightText;"))
		drawSpace.addElement(g)
		
		#draw Main display area border
		mainSquare = cHeight-60
		cordZOOM = 10
		drawSpace.addElement(svg.rect(8, 8, mainSquare+4, mainSquare+4,'none',"orange",0.5, rx="5", ry="5"))
		drawSpace.addElement(svg.text(10+mainSquare/2, 40+mainSquare,'Marker GMb', 
			style="&colorText; &allText; &titleText; &middleText;", id="XLabel"))
		drawSpace.addElement(svg.text(mainSquare + 80, 10+mainSquare/2,'Transcript GMb', 
			style="&colorText; &allText; &titleText; &middleText; &vText;", id="YLabel"))
		
		#draw overview display area
		drawSpace.addElement(svg.rect(cWidth-40-260, 60, 260, 260,'none',"orange",0.5, rx="5", ry="5"))
		drawSpaceThumb= svg.svg(id="overviewPlot",x=cWidth-40-260,y="60",width="260",
			height="260",viewBox=(0, 0, mainSquare*cordZOOM, mainSquare*cordZOOM))
		g = svg.group(style="&bezgrenzstyle;")
		g.addElement(svg.use("#grid"))
		drawSpaceThumb.addElement(g)
		drawSpaceThumb.addElement(svg.rect(id="overviewRect",style="&rectstyle;",
			x="0",y="0",width=mainSquare*cordZOOM,height=mainSquare*cordZOOM, 
			onmouseover="statusChange('click and drag rectangle to change extent');",
			onmousedown="beginPan(evt);", onmousemove="doPan(evt);", 
			onmouseup="endPan();", onmouseout="endPan();"))
		drawSpace.addElement(drawSpaceThumb)
		
		#draw navigator
		g = svg.group(id="navigatorElements")
		g.addElement(svg.use("#magnifyerZoomIn", id="zoomIn", transform="translate(%d,350)" % (cWidth-40-130-20), 
			onmouseover="magnify(evt,1.3,'in');", onmouseout="magnify(evt,1,'in');", onclick="zoomIt('in');"))
		g.addElement(svg.use("#magnifyer", id="zoomOut", transform="translate(%d,350)" % (cWidth-40-130+20),
			onmouseover="magnify(evt,1.3,'out');",onmouseout="magnify(evt,1,'out');", onclick="zoomIt('out');"))
		
		drawSpace.addElement(g)
		
		g = svg.group(id="statusBar")
		g.addElement(svg.text(cWidth-40-260, 360, "ZOOM: 100%", style="fill:orange; font-size:14;", id="zoomValueObj"))
		g.addElement(svg.text(cWidth-40-260, 380, "Status:", style="&colorText; &allText; &smallText;"))
		g.addElement(svg.text(cWidth-40-260, 395, "Loading Plot", style="&colorText; &allText; &smallText;", id="statusText"))
		drawSpace.addElement(g)
		
		#draw main display area
		drawSpaceMain= svg.svg((0, 0, mainSquare*cordZOOM, mainSquare*cordZOOM), mainSquare, mainSquare, 
			id="mainPlot",x="10",y="10")
		mPlotWidth = mPlotHeight = 0.8*mainSquare*cordZOOM
		
		drawSpaceMain.addElement(svg.rect(mainSquare*cordZOOM*0.1, mainSquare*cordZOOM*0.1, mPlotWidth, mPlotHeight,style="fill:white",
			onmousemove="showChr(evt);", onmouseover="showChr(evt);", onmouseout="showNoChr(evt);"))
		#draw grid
		g = svg.group("grid", style="stroke:lightblue;stroke-width:3", 
			transform="translate(%d,%d)" % (mainSquare*cordZOOM*0.1, mainSquare*cordZOOM*0.1))
			
		if 1: #self.grid == "on":
			js = [] 
			for key in self.mouseChrLengthDict.keys():
				length = self.mouseChrLengthDict[key]
				js.append(mPlotWidth*length/cLength)
				if length != 0:
					yCoord = mPlotHeight*(1.0-length/cLength)
					l = svg.line(0,yCoord ,mPlotWidth, yCoord)
					g.addElement(l)	
					xCoord = mPlotWidth*length/cLength
					l = svg.line(xCoord, 0 ,xCoord, mPlotHeight)
					g.addElement(l)
			js.sort()
			drawSpace.addElement(svg.script("",language="javascript", cdata="var openURL=\"%s\";\nvar chrLength=%s;\n" % (self.openURL, js)))
		
		g.addElement(svg.rect(0, 0, mPlotWidth, mPlotHeight,'none','black',10))
		drawSpaceMain.addElement(g)
		
		#draw Scale
		g = svg.group("scale", style="stroke:black;stroke-width:0", 
			transform="translate(%d,%d)" % (mainSquare*cordZOOM*0.1, mainSquare*cordZOOM*0.1))
		i = 100
		scaleFontSize = 11*cordZOOM
		while i < cLength:
			yCoord = mPlotHeight - mPlotHeight*i/cLength
			l = svg.line(0,yCoord ,-5*cordZOOM, yCoord)
			g.addElement(l)
			t = svg.text(-40*cordZOOM, yCoord +5*cordZOOM, "%d"% i, 100, "verdana") # coordinate tag Y
			g.addElement(t)
			xCoord = mPlotWidth*i/cLength
			l = svg.line(xCoord, mPlotHeight, xCoord, mPlotHeight+5*cordZOOM)
			g.addElement(l)
			if i%200 == 0:
				t = svg.text(xCoord, mPlotHeight+10*cordZOOM, "%d"% i, 100, "verdana") # coordinate tag X
				g.addElement(t)
			i += 100
			
		drawSpaceMain.addElement(g)
		#draw Points
		finecolors = Plot.colorSpectrumSVG(12)
		finecolors.reverse()
		g = preColor = ""
		for item in data:
			_probeset, _chr, _Mb, _marker, _pvalue = item[2:]
			try:
				_idx = int((-math.log10(_pvalue))*12/6.0) # add module name
				_color = finecolors[_idx]
			except:
				_color = finecolors[-1]
			if _color != preColor:
				preColor = _color
				if g:
					drawSpaceMain.addElement(g)
				g = svg.group("points", style="stroke:%s;stroke-width:5" % _color, 
					transform="translate(%d,%d)" % (mainSquare*cordZOOM*0.1, mainSquare*cordZOOM*0.1),
					onmouseover="mvMsgBox(evt);", onmouseout="hdMsgBox();", onmousedown="openPage(evt);")
			else:
				pass
			px = mPlotWidth*item[0]/cLength
			py = mPlotHeight*(1.0-item[1]/cLength)
			l = svg.line("%2.1f" % (px-3*cordZOOM), "%2.1f" % py, "%2.1f" % (px+3*cordZOOM), "%2.1f" % py, ps=_probeset, mk=_marker)
			g.addElement(l)	

		drawSpaceMain.addElement(g)
		
		"""
		#draw spectrum
		i = 0
		j = 0
		middleoffsetX = 40
		labelFont=pid.Font(ttf="tahoma",size=12,bold=0)
		for dcolor in finecolors:
			drawSpace.drawLine(xLeftOffset+ plotWidth + middleoffsetX -15 , plotHeight + yTopOffset - i, \
				xLeftOffset+ plotWidth + middleoffsetX+15 , plotHeight + yTopOffset - i, color=dcolor)
			if i % 50 == 0:
				drawSpace.drawLine(xLeftOffset+ plotWidth +middleoffsetX+15 ,plotHeight + yTopOffset - i,  \
				xLeftOffset+ plotWidth +middleoffsetX+20,plotHeight + yTopOffset - i, color=pid.black)
				drawSpace.drawString("%1.1f" % -j , xLeftOffset+ plotWidth +middleoffsetX+25 ,plotHeight + yTopOffset - i+5, font = labelFont)
				j += 1
			i += 1
		drawSpace.drawLine(xLeftOffset+ plotWidth +middleoffsetX+15 ,plotHeight + yTopOffset - i+1,  \
			xLeftOffset+ plotWidth +middleoffsetX+20,plotHeight + yTopOffset - i+1, color=pid.black)	
		drawSpace.drawString("%1.1f" % -j , xLeftOffset+ plotWidth +middleoffsetX+25 ,plotHeight + yTopOffset - i+6, font = labelFont)
		labelFont=pid.Font(ttf="tahoma",size=14,bold=1)	
		drawSpace.drawString("Log(pValue)" , xLeftOffset+ plotWidth +middleoffsetX+60 ,plotHeight + yTopOffset - 100, font = labelFont, angle =90)
		
		labelFont=pid.Font(ttf="verdana",size=18,bold=0)
		drawSpace.drawString(XLabel, xLeftOffset + (plotWidth -drawSpace.stringWidth(XLabel,font=labelFont))/2.0, plotHeight + yTopOffset +40, color=pid.blue, font=labelFont)
		drawSpace.drawString(YLabel,xLeftOffset-60, plotHeight + yTopOffset-(plotHeight -drawSpace.stringWidth(YLabel,font=labelFont))/2.0, color=pid.blue, font=labelFont, angle =90)			
		"""
		drawSpace.addElement(drawSpaceMain)
		
		g= svg.group(id="dispBox", overflow="visible", 
			style="fill:white;stroke:orange;stroke-width:1;opacity:0.85;",
			transform="translate(%d,650)" % (cWidth-40-300), visibility="hidden")
		g.addElement(svg.rect(-80, -190, 300, 150, rx=10, ry=10))
		g.addElement(svg.line(21, -40, 58, -40, style="stroke:white;"))
		g.addElement(svg.polyline([[20, -40], [0, 0], [60, -40]]))
		g.addElement(svg.text(-60, -160, "ProbeSet ", style="&colorText; &allText; &subtitleText; &strokeText;", id="_probeset"))
		g.addElement(svg.text(-60, -125, "Marker ", style="&colorText; &allText; &subtitleText; &strokeText;", id="_marker"))

		drawSpace.addElement(g)

		canvasSVG.setSVG(drawSpace) #set the svg of the drawing to the svg
		return canvasSVG
Beispiel #12
0
    def __init__(self, fd):
        templatePage.__init__(self, fd)
        self.initializeDisplayParameters(fd)
        if not fd.genotype:
            fd.readGenotype()
        mdpchoice = None
        strainlist = fd.strainlist
        fd.readData()
        if not self.openMysql():
            return
        isSampleCorr = 1
        isTissueCorr = 0
        TD_LR = HT.TD(colspan=2, height=200, width="100%", bgColor="#eeeeee", align="left", wrap="off")
        dataX = []
        dataY = []
        dataZ = []  # shortname
        fullTissueName = []
        xlabel = ""
        ylabel = ""
        if isSampleCorr:
            plotHeading = HT.Paragraph("Sample Correlation Scatterplot")
            plotHeading.__setattr__("class", "title")

            # XZ: retrieve trait 1 info, Y axis
            trait1_data = []  # trait 1 data
            trait1Url = ""
            try:
                Trait1 = webqtlTrait(db=self.database, name=self.ProbeSetID, cellid=self.CellID, cursor=self.cursor)
                Trait1.retrieveInfo()
                Trait1.retrieveData()
            except:
                heading = "Retrieve Data"
                detail = ["The database you just requested has not been established yet."]
                self.error(heading=heading, detail=detail)
                return
            trait1_data = Trait1.exportData(strainlist)
            trait1Url = Trait1.genHTML(dispFromDatabase=1)
            ylabel = "%s : %s" % (Trait1.db.shortname, Trait1.name)
            if Trait1.cellid:
                ylabel += " : " + Trait1.cellid

                # XZ, retrieve trait 2 info, X axis
            trait2_data = []  # trait 2 data
            trait2Url = ""
            try:
                Trait2 = webqtlTrait(db=self.database2, name=self.ProbeSetID2, cellid=self.CellID2, cursor=self.cursor)
                Trait2.retrieveInfo()
                Trait2.retrieveData()
            except:
                heading = "Retrieve Data"
                detail = ["The database you just requested has not been established yet."]
                self.error(heading=heading, detail=detail)
                return
            trait2_data = Trait2.exportData(strainlist)
            trait2Url = Trait2.genHTML(dispFromDatabase=1)
            xlabel = "%s : %s" % (Trait2.db.shortname, Trait2.name)
            if Trait2.cellid:
                xlabel += " : " + Trait2.cellid

            for strain in Trait1.data.keys():
                if Trait2.data.has_key(strain):
                    dataX.append(Trait2.data[strain].val)
                    dataY.append(Trait1.data[strain].val)
                    if self.showstrains:
                        dataZ.append(webqtlUtil.genShortStrainName(RISet=fd.RISet, input_strainName=strain))

                # XZ: We have gotten all data for both traits.
        if len(dataX) >= self.corrMinInformative:

            if self.rankOrder == 0:
                rankPrimary = 0
                rankSecondary = 1
            else:
                rankPrimary = 1
                rankSecondary = 0

            lineColor = self.setLineColor()
            symbolColor = self.setSymbolColor()
            idColor = self.setIdColor()

            c = pid.PILCanvas(size=(self.plotSize, self.plotSize * 0.90))
            data_coordinate = Plot.plotXY(
                canvas=c,
                dataX=dataX,
                dataY=dataY,
                rank=rankPrimary,
                dataLabel=dataZ,
                labelColor=pid.black,
                lineSize=self.lineSize,
                lineColor=lineColor,
                idColor=idColor,
                idFont=self.idFont,
                idSize=self.idSize,
                symbolColor=symbolColor,
                symbolType=self.symbol,
                filled=self.filled,
                symbolSize=self.symbolSize,
                XLabel=xlabel,
                connectdot=0,
                YLabel=ylabel,
                title="",
                fitcurve=self.showline,
                displayR=1,
                offset=(90, self.plotSize / 20, self.plotSize / 10, 90),
                showLabel=self.showIdentifiers,
            )

            if rankPrimary == 1:
                dataXlabel, dataYlabel = webqtlUtil.calRank(xVals=dataX, yVals=dataY, N=len(dataX))
            else:
                dataXlabel, dataYlabel = dataX, dataY

            gifmap1 = HT.Map(name="CorrelationPlotImageMap1")

            for i, item in enumerate(data_coordinate):
                one_rect_coordinate = "%d, %d, %d, %d" % (item[0] - 5, item[1] - 5, item[0] + 5, item[1] + 5)
                if isTissueCorr:
                    one_rect_title = "%s (%s, %s)" % (fullTissueName[i], dataXlabel[i], dataYlabel[i])
                else:
                    one_rect_title = "%s (%s, %s)" % (dataZ[i], dataXlabel[i], dataYlabel[i])
                gifmap1.areas.append(HT.Area(shape="rect", coords=one_rect_coordinate, title=one_rect_title))

            filename = webqtlUtil.genRandStr("XY_")
            c.save(webqtlConfig.IMGDIR + filename, format="gif")
            img1 = HT.Image("/image/" + filename + ".gif", border=0, usemap="#CorrelationPlotImageMap1")

            mainForm_1 = 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,
                "ProbeSetID2": "_",
                "database2": "_",
                "CellID2": "_",
                "allstrainlist": string.join(fd.strainlist, " "),
                "traitList": fd.formdata.getvalue("traitList"),
            }
            if fd.incparentsf1:
                hddn["incparentsf1"] = "ON"
            for key in hddn.keys():
                mainForm_1.append(HT.Input(name=key, value=hddn[key], type="hidden"))

            if isSampleCorr:
                mainForm_1.append(
                    HT.P(),
                    HT.Blockquote(
                        HT.Strong("X axis:"),
                        HT.Blockquote(trait2Url),
                        HT.Strong("Y axis:"),
                        HT.Blockquote(trait1Url),
                        style="width: %spx;" % self.plotSize,
                        wrap="hard",
                    ),
                )

            graphForm = HT.Form(
                cgi=os.path.join(webqtlConfig.CGIDIR, webqtlConfig.SCRIPTFILE),
                name="MDP_Form",
                submit=HT.Input(type="hidden"),
            )
            graph_hddn = self.setHiddenParameters(fd, rankPrimary)
            webqtlUtil.exportData(
                graph_hddn, fd.allTraitData
            )  # XZ: This is necessary to replot with different groups of strains

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

            options = self.createOptionsMenu(fd, mdpchoice)

            if self.showOptions == "0":
                showOptionsButton = HT.Input(
                    type="button",
                    name="optionsButton",
                    value="Hide Options",
                    onClick="showHideOptions();",
                    Class="button",
                )
            else:
                showOptionsButton = HT.Input(
                    type="button",
                    name="optionsButton",
                    value="Show Options",
                    onClick="showHideOptions();",
                    Class="button",
                )

                # updated by NL: 12-07-2011 add variables for tissue abbreviation page
            if isTissueCorr:
                graphForm.append(HT.Input(name="shortTissueName", value="", type="hidden"))
                graphForm.append(HT.Input(name="fullTissueName", value="", type="hidden"))
                shortTissueNameStr = string.join(dataZ, ",")
                fullTissueNameStr = string.join(fullTissueName, ",")

                tissueAbbrButton = HT.Input(
                    type="button",
                    name="tissueAbbrButton",
                    value="Show Abbreviations",
                    onClick="showTissueAbbr('MDP_Form','%s','%s')" % (shortTissueNameStr, fullTissueNameStr),
                    Class="button",
                )
                graphForm.append(showOptionsButton, "&nbsp;&nbsp;&nbsp;&nbsp;", tissueAbbrButton, HT.BR(), HT.BR())
            else:
                graphForm.append(showOptionsButton, HT.BR(), HT.BR())

            graphForm.append(options, HT.BR())
            graphForm.append(HT.HR(), HT.BR(), HT.P())

            TD_LR.append(plotHeading, HT.BR(), graphForm, HT.BR(), gifmap1, HT.P(), img1, HT.P(), mainForm_1)
            TD_LR.append(HT.BR(), HT.HR(color="grey", size=5, width="100%"))

            c = pid.PILCanvas(size=(self.plotSize, self.plotSize * 0.90))
            data_coordinate = Plot.plotXY(
                canvas=c,
                dataX=dataX,
                dataY=dataY,
                rank=rankSecondary,
                dataLabel=dataZ,
                labelColor=pid.black,
                lineColor=lineColor,
                lineSize=self.lineSize,
                idColor=idColor,
                idFont=self.idFont,
                idSize=self.idSize,
                symbolColor=symbolColor,
                symbolType=self.symbol,
                filled=self.filled,
                symbolSize=self.symbolSize,
                XLabel=xlabel,
                connectdot=0,
                YLabel=ylabel,
                title="",
                fitcurve=self.showline,
                displayR=1,
                offset=(90, self.plotSize / 20, self.plotSize / 10, 90),
                showLabel=self.showIdentifiers,
            )

            if rankSecondary == 1:
                dataXlabel, dataYlabel = webqtlUtil.calRank(xVals=dataX, yVals=dataY, N=len(dataX))
            else:
                dataXlabel, dataYlabel = dataX, dataY

            gifmap2 = HT.Map(name="CorrelationPlotImageMap2")

            for i, item in enumerate(data_coordinate):
                one_rect_coordinate = "%d, %d, %d, %d" % (item[0] - 6, item[1] - 6, item[0] + 6, item[1] + 6)
                if isTissueCorr:
                    one_rect_title = "%s (%s, %s)" % (fullTissueName[i], dataXlabel[i], dataYlabel[i])
                else:
                    one_rect_title = "%s (%s, %s)" % (dataZ[i], dataXlabel[i], dataYlabel[i])

                gifmap2.areas.append(HT.Area(shape="rect", coords=one_rect_coordinate, title=one_rect_title))

            filename = webqtlUtil.genRandStr("XY_")
            c.save(webqtlConfig.IMGDIR + filename, format="gif")
            img2 = HT.Image("/image/" + filename + ".gif", border=0, usemap="#CorrelationPlotImageMap2")

            mainForm_2 = HT.Form(
                cgi=os.path.join(webqtlConfig.CGIDIR, webqtlConfig.SCRIPTFILE),
                enctype="multipart/form-data",
                name="showDatabase2",
                submit=HT.Input(type="hidden"),
            )
            hddn = {
                "FormID": "showDatabase2",
                "ProbeSetID": "_",
                "database": "_",
                "CellID": "_",
                "RISet": fd.RISet,
                "ProbeSetID2": "_",
                "database2": "_",
                "CellID2": "_",
                "allstrainlist": string.join(fd.strainlist, " "),
                "traitList": fd.formdata.getvalue("traitList"),
            }
            if fd.incparentsf1:
                hddn["incparentsf1"] = "ON"
            for key in hddn.keys():
                mainForm_2.append(HT.Input(name=key, value=hddn[key], type="hidden"))

            if isSampleCorr:
                mainForm_2.append(
                    HT.P(),
                    HT.Blockquote(
                        HT.Strong("X axis:"),
                        HT.Blockquote(trait2Url),
                        HT.Strong("Y axis:"),
                        HT.Blockquote(trait1Url),
                        style="width:%spx;" % self.plotSize,
                    ),
                )

            TD_LR.append(HT.BR(), HT.P())
            TD_LR.append("\n", gifmap2, HT.P(), HT.P(), img2, HT.P(), mainForm_2)

            self.dict["body"] = str(TD_LR)
        else:
            heading = "Correlation Plot"
            detail = [
                "Fewer than %d strain data were entered for %s data set. No statitical analysis has been attempted."
                % (self.corrMinInformative, fd.RISet)
            ]
            self.error(heading=heading, detail=detail)
            return
	def __init__(self, fd):

		LRSFullThresh = 30
		LRSInteractThresh = 25
		maxPlotSize = 800
		mainfmName = webqtlUtil.genRandStr("fm_")

		templatePage.__init__(self, fd)

		if not fd.genotype:
			fd.readData()

		##Remove F1 and Parents
		fd.genotype = fd.genotype_1

		plotType = fd.formdata.getvalue('plotType')
		self.dict['title'] = '%s Plot' % plotType
		main_title = HT.Paragraph("%s Plot" % plotType)
		main_title.__setattr__("class","title")

		interval1 = fd.formdata.getvalue('interval1')
		interval2 = fd.formdata.getvalue('interval2')

		flanka1, flanka2, chram = string.split(interval1)
		flankb1, flankb2, chrbm = string.split(interval2)

		traitValues = string.split(fd.formdata.getvalue('traitValues'), ',')
		traitValues = map(webqtlUtil.StringAsFloat, traitValues)
		traitStrains = string.split(fd.formdata.getvalue('traitStrains'), ',')

		flankaGeno = []
		flankbGeno = []

		for chr in fd.genotype:
			for locus in chr:
				if locus.name in (flanka1, flankb1):
					if locus.name == flanka1:
						flankaGeno = locus.genotype[:]
					else:
						flankbGeno = locus.genotype[:]
			if flankaGeno and flankbGeno:
				break

		flankaDict = {}
		flankbDict = {}
		for i in range(len(fd.genotype.prgy)):
			flankaDict[fd.genotype.prgy[i]] = flankaGeno[i]
			flankbDict[fd.genotype.prgy[i]] = flankbGeno[i]

		BB = []
		BD = []
		DB = []
		DD = []

		iValues = []
		for i in range(len(traitValues)):
			if traitValues[i] != None:
				iValues.append(traitValues[i])
				thisstrain = traitStrains[i]
				try:
					a1 = flankaDict[thisstrain]
					b1 = flankbDict[thisstrain]
				except:
					continue
				if a1 == -1.0:
					if b1 == -1.0:
						BB.append((thisstrain, traitValues[i]))
					elif b1 == 1.0:
						BD.append((thisstrain, traitValues[i]))
				elif a1 == 1.0:
					if b1 == -1.0:
						DB.append((thisstrain, traitValues[i]))
					elif b1 == 1.0:
						DD.append((thisstrain, traitValues[i]))
				else:
					pass

		#print BB, BD, DB, DD, max(iValues), min(iValues)

		plotHeight = 400
		plotWidth = 600
		xLeftOffset = 60
		xRightOffset = 40
		yTopOffset = 40
		yBottomOffset = 60

		canvasHeight = plotHeight + yTopOffset + yBottomOffset
		canvasWidth = plotWidth + xLeftOffset + xRightOffset
		canvas = pid.PILCanvas(size=(canvasWidth,canvasHeight))
		XXX = [('Mat/Mat', BB), ('Mat/Pat', BD), ('Pat/Mat', DB), ('Pat/Pat', DD)]
		XLabel = "Interval 1 / Interval 2"

		if plotType == "Box":
			Plot.plotBoxPlot(canvas, XXX, offset=(xLeftOffset, xRightOffset, yTopOffset, yBottomOffset), XLabel = XLabel)
		else:
			#Could be a separate function, but seems no other uses
			max_Y = max(iValues)
			min_Y = min(iValues)
			scaleY = Plot.detScale(min_Y, max_Y)
			Yll = scaleY[0]
			Yur = scaleY[1]
			nStep = scaleY[2]
			stepY = (Yur - Yll)/nStep
			stepYPixel = plotHeight/(nStep)
			canvas.drawRect(plotWidth+xLeftOffset, plotHeight + yTopOffset, xLeftOffset, yTopOffset)

			##draw Y Scale
			YYY = Yll
			YCoord = plotHeight + yTopOffset
			scaleFont=pid.Font(ttf="cour",size=11,bold=1)
			for i in range(nStep+1):
				strY = Plot.cformat(d=YYY, rank=0)
				YCoord = max(YCoord, yTopOffset)
				canvas.drawLine(xLeftOffset,YCoord,xLeftOffset-5,YCoord)
				canvas.drawString(strY,	xLeftOffset -30,YCoord +5,font=scaleFont)
				YYY += stepY
				YCoord -= stepYPixel


			##draw X Scale
			stepX = plotWidth/len(XXX)
			XCoord = xLeftOffset + 0.5*stepX
			YCoord = plotHeight + yTopOffset
			scaleFont = pid.Font(ttf="tahoma",size=12,bold=0)
			labelFont = pid.Font(ttf="tahoma",size=13,bold=0)
			for item in XXX:
				itemname, itemvalue = item
				canvas.drawLine(XCoord, YCoord,XCoord, YCoord+5, color=pid.black)
				canvas.drawString(itemname, XCoord - canvas.stringWidth(itemname,font=labelFont)/2.0,YCoord +20,font=labelFont)
				itemvalue.sort(webqtlUtil.cmpOrder2)
				j = 0
				for item2 in itemvalue:
					tstrain, tvalue = item2
					canvas.drawCross(XCoord, plotHeight + yTopOffset - (tvalue-Yll)*plotHeight/(Yur - Yll), color=pid.red,size=5)
					if j % 2 == 0:
						canvas.drawString(tstrain, XCoord+5, plotHeight + yTopOffset - \
						(tvalue-Yll)*plotHeight/(Yur - Yll) +5, font=scaleFont, color=pid.blue)
					else:
						canvas.drawString(tstrain, XCoord-canvas.stringWidth(tstrain,font=scaleFont)-5, \
						plotHeight + yTopOffset - (tvalue-Yll)*plotHeight/(Yur - Yll) +5, font=scaleFont, color=pid.blue)
					j += 1
				XCoord += stepX


			labelFont=pid.Font(ttf="verdana",size=18,bold=0)
			canvas.drawString(XLabel, xLeftOffset + (plotWidth -canvas.stringWidth(XLabel,font=labelFont))/2.0, YCoord +40, font=labelFont)
			canvas.drawString("Value",xLeftOffset-40,  YCoord-(plotHeight -canvas.stringWidth("Value",font=labelFont))/2.0, font=labelFont, angle =90)


		filename= webqtlUtil.genRandStr("Cate_")
		canvas.save(webqtlConfig.IMGDIR+filename, format='gif')
		img=HT.Image('/image/'+filename+'.gif',border=0)

		TD_LR = HT.TD(height=200,width="100%",bgColor='#eeeeee',valign='top')
		TD_LR.append(main_title, HT.Center(img))#, traitValues , len(traitValues), traitStrains, len(traitStrains), len(fd.genotype.prgy))
		#TD_LR.append(main_title, HT.BR(), flanka1, flanka2, chram, HT.BR(), flankb1, flankb2, chrbm)
		self.dict['body'] = str(TD_LR)
    def __init__(self, fd):

        templatePage.__init__(self, fd)

        if not fd.genotype:
            fd.readGenotype()
            strainlist2 = fd.strainlist

        if fd.allstrainlist:
            strainlist2 = fd.allstrainlist

        fd.readData(strainlist2)

        specialStrains = []
        setStrains = []
        for item in strainlist2:
            if item not in fd.strainlist and item.find('F1') < 0:
                specialStrains.append(item)
            else:
                setStrains.append(item)
        specialStrains.sort()
        #So called MDP Panel
        if specialStrains:
            specialStrains = fd.f1list+fd.parlist+specialStrains

        self.plotType = fd.formdata.getvalue('ptype', '0')
        plotStrains = strainlist2
        if specialStrains:
            if self.plotType == '1':
                plotStrains = setStrains
            if self.plotType == '2':
                plotStrains = specialStrains

        self.dict['title'] = 'Basic Statistics'
        if not self.openMysql():
            return

        self.showstrains = 1
        self.identification = "unnamed trait"

        self.fullname = fd.formdata.getvalue('fullname', '')
        if self.fullname:
            self.Trait = webqtlTrait(fullname=self.fullname, cursor=self.cursor)
            self.Trait.retrieveInfo()
        else:
            self.Trait = None

        if fd.identification:
            self.identification = fd.identification
            self.dict['title'] = self.identification + ' / '+self.dict['title']
        TD_LR = HT.TD(height=200,width="100%",bgColor='#eeeeee')

        ##should not display Variance, but cannot convert Variance to SE
        #print plotStrains, fd.allTraitData.keys()
        if len(fd.allTraitData) > 0:
            vals=[]
            InformData = []
            for _strain in plotStrains:
                if fd.allTraitData.has_key(_strain):
                    _val, _var = fd.allTraitData[_strain].val, fd.allTraitData[_strain].var
                    if _val != None:
                        vals.append([_strain, _val, _var])
                        InformData.append(_val)

            if len(vals) >= self.plotMinInformative:
                supertable2 = HT.TableLite(border=0, cellspacing=0, cellpadding=5,width="800")

                staIntro1 = HT.Paragraph("The table and plots below list the basic statistical analysis result of trait",HT.Strong(" %s" % self.identification))

                #####
                #anova
                #####
                traitmean, traitmedian, traitvar, traitstdev, traitsem, N = reaper.anova(InformData)
                TDStatis = HT.TD(width="360", valign="top")
                tbl2 = HT.TableLite(cellpadding=5, cellspacing=0, Class="collap")
                dataXZ = vals[:]
                dataXZ.sort(self.cmpValue)
                tbl2.append(HT.TR(HT.TD("Statistic",align="center", Class="fs14 fwb ffl b1 cw cbrb", width = 200),
                                HT.TD("Value", align="center", Class="fs14 fwb ffl b1 cw cbrb", width = 140)))
                tbl2.append(HT.TR(HT.TD("N of Cases",align="center", Class="fs13 b1 cbw c222"),
                                HT.TD(N,nowrap="yes",align="center", Class="fs13 b1 cbw c222")))
                tbl2.append(HT.TR(HT.TD("Mean",align="center", Class="fs13 b1 cbw c222",nowrap="yes"),
                                HT.TD("%2.3f" % traitmean,nowrap="yes",align="center", Class="fs13 b1 cbw c222")))
                tbl2.append(HT.TR(HT.TD("Median",align="center", Class="fs13 b1 cbw c222",nowrap="yes"),
                                HT.TD("%2.3f" % traitmedian,nowrap="yes",align="center", Class="fs13 b1 cbw c222")))
                #tbl2.append(HT.TR(HT.TD("Variance",align="center", Class="fs13 b1 cbw c222",nowrap="yes"),
                #               HT.TD("%2.3f" % traitvar,nowrap="yes",align="center", Class="fs13 b1 cbw c222")))
                tbl2.append(HT.TR(HT.TD("SEM",align="center", Class="fs13 b1 cbw c222",nowrap="yes"),
                                HT.TD("%2.3f" % traitsem,nowrap="yes",align="center", Class="fs13 b1 cbw c222")))
                tbl2.append(HT.TR(HT.TD("SD",align="center", Class="fs13 b1 cbw c222",nowrap="yes"),
                                HT.TD("%2.3f" % traitstdev,nowrap="yes",align="center", Class="fs13 b1 cbw c222")))
                tbl2.append(HT.TR(HT.TD("Minimum",align="center", Class="fs13 b1 cbw c222",nowrap="yes"),
                                HT.TD("%s" % dataXZ[0][1],nowrap="yes",align="center", Class="fs13 b1 cbw c222")))
                tbl2.append(HT.TR(HT.TD("Maximum",align="center", Class="fs13 b1 cbw c222",nowrap="yes"),
                                HT.TD("%s" % dataXZ[-1][1],nowrap="yes",align="center", Class="fs13 b1 cbw c222")))
                if self.Trait and self.Trait.db.type == 'ProbeSet':
                    #IRQuest = HT.Href(text="Interquartile Range", url=webqtlConfig.glossaryfile +"#Interquartile",target="_blank", Class="fs14")
                    #IRQuest.append(HT.BR())
                    #IRQuest.append(" (fold difference)")
                    tbl2.append(HT.TR(HT.TD("Range (log2)",align="center", Class="fs13 b1 cbw c222",nowrap="yes"),
                            HT.TD("%2.3f" % (dataXZ[-1][1]-dataXZ[0][1]),nowrap="yes",align="center", Class="fs13 b1 cbw c222")))
                    tbl2.append(HT.TR(HT.TD(HT.Span("Range (fold)"),align="center", Class="fs13 b1 cbw c222",nowrap="yes"),
                            HT.TD("%2.2f" % pow(2.0,(dataXZ[-1][1]-dataXZ[0][1])), nowrap="yes",align="center", Class="fs13 b1 cbw c222")))
                    tbl2.append(HT.TR(HT.TD(HT.Span("Quartile Range",HT.BR()," (fold difference)"),align="center", Class="fs13 b1 cbw c222",nowrap="yes"),
                            HT.TD("%2.2f" % pow(2.0,(dataXZ[int((N-1)*3.0/4.0)][1]-dataXZ[int((N-1)/4.0)][1])), nowrap="yes",align="center", Class="fs13 b1 cbw c222")))

                    # (Lei Yan)
                    # 2008/12/19
                    self.Trait.retrieveData()
                    #XZ, 04/01/2009: don't try to get H2 value for probe.
                    if self.Trait.cellid:
                        pass
                    else:
                        self.cursor.execute("SELECT DataId, h2 from ProbeSetXRef WHERE DataId = %d" % self.Trait.mysqlid)
                        dataid, heritability = self.cursor.fetchone()
                        if heritability:
                            tbl2.append(HT.TR(HT.TD(HT.Span("Heritability"),align="center", Class="fs13 b1 cbw c222",nowrap="yes"),HT.TD("%s" % heritability, nowrap="yes",align="center", Class="fs13 b1 cbw c222")))
                        else:
                            tbl2.append(HT.TR(HT.TD(HT.Span("Heritability"),align="center", Class="fs13 b1 cbw c222",nowrap="yes"),HT.TD("NaN", nowrap="yes",align="center", Class="fs13 b1 cbw c222")))

                    # Lei Yan
                    # 2008/12/19

                TDStatis.append(tbl2)

                plotHeight = 220
                plotWidth = 120
                xLeftOffset = 60
                xRightOffset = 25
                yTopOffset = 20
                yBottomOffset = 53

                canvasHeight = plotHeight + yTopOffset + yBottomOffset
                canvasWidth = plotWidth + xLeftOffset + xRightOffset
                canvas = pid.PILCanvas(size=(canvasWidth,canvasHeight))
                XXX = [('', InformData[:])]

                Plot.plotBoxPlot(canvas, XXX, offset=(xLeftOffset, xRightOffset, yTopOffset, yBottomOffset), XLabel= "Trait")
                filename= webqtlUtil.genRandStr("Box_")
                canvas.save(webqtlConfig.IMGDIR+filename, format='gif')
                img=HT.Image('/image/'+filename+'.gif',border=0)

                #supertable2.append(HT.TR(HT.TD(staIntro1, colspan=3 )))
                tb = HT.TableLite(border=0, cellspacing=0, cellpadding=0)
                tb.append(HT.TR(HT.TD(img, align="left", style="border: 1px solid #999999; padding:0px;")))
                supertable2.append(HT.TR(TDStatis, HT.TD(tb)))

                dataXZ = vals[:]
                tvals = []
                tnames = []
                tvars = []
                for i in range(len(dataXZ)):
                    tvals.append(dataXZ[i][1])
                    tnames.append(webqtlUtil.genShortStrainName(fd, dataXZ[i][0]))
                    tvars.append(dataXZ[i][2])
                nnStrain = len(tnames)

                sLabel = 1

                ###determine bar width and space width
                if nnStrain < 20:
                    sw = 4
                elif nnStrain < 40:
                    sw = 3
                else:
                    sw = 2

                ### 700 is the default plot width minus Xoffsets for 40 strains
                defaultWidth = 650
                if nnStrain > 40:
                    defaultWidth += (nnStrain-40)*10
                defaultOffset = 100
                bw = int(0.5+(defaultWidth - (nnStrain-1.0)*sw)/nnStrain)
                if bw < 10:
                    bw = 10

                plotWidth = (nnStrain-1)*sw + nnStrain*bw + defaultOffset
                plotHeight = 500
                #print [plotWidth, plotHeight, bw, sw, nnStrain]
                c = pid.PILCanvas(size=(plotWidth,plotHeight))
                Plot.plotBarText(c, tvals, tnames, variance=tvars, YLabel='Value', title='%s by Case (sorted by name)' % self.identification, sLabel = sLabel, barSpace = sw)

                filename= webqtlUtil.genRandStr("Bar_")
                c.save(webqtlConfig.IMGDIR+filename, format='gif')
                img0=HT.Image('/image/'+filename+'.gif',border=0)

                dataXZ = vals[:]
                dataXZ.sort(self.cmpValue)
                tvals = []
                tnames = []
                tvars = []
                for i in range(len(dataXZ)):
                    tvals.append(dataXZ[i][1])
                    tnames.append(webqtlUtil.genShortStrainName(fd, dataXZ[i][0]))
                    tvars.append(dataXZ[i][2])

                c = pid.PILCanvas(size=(plotWidth,plotHeight))
                Plot.plotBarText(c, tvals, tnames, variance=tvars, YLabel='Value', title='%s by Case (ranked)' % self.identification, sLabel = sLabel, barSpace = sw)

                filename= webqtlUtil.genRandStr("Bar_")
                c.save(webqtlConfig.IMGDIR+filename, format='gif')
                img1=HT.Image('/image/'+filename+'.gif',border=0)

                # Lei Yan
                # 05/18/2009
                # report

                title = HT.Paragraph('REPORT on the variation of Shh (or PCA Composite Trait XXXX) (sonic hedgehog) in the (insert Data set name) of (insert Species informal name, e.g., Mouse, Rat, Human, Barley, Arabidopsis)', Class="title")
                header = HT.Paragraph('''This report was generated by GeneNetwork on May 11, 2009, at 11.20 AM using the Basic Statistics module (v 1.0) and data from the Hippocampus Consortium M430v2 (Jun06) PDNN data set. For more details and updates on this data set please link to URL:get Basic Statistics''')
                hr = HT.HR()
                p1 = HT.Paragraph('''Trait values for Shh were taken from the (insert Database name, Hippocampus Consortium M430v2 (Jun06) PDNN). GeneNetwork contains data for NN (e.g., 99) cases. In general, data are averages for each case. A summary of mean, median, and the range of these data are provided in Table 1 and in the box plot (Figure 1). Data for individual cases are provided in Figure 2A and 2B, often with error bars (SEM). ''')
                p2 = HT.Paragraph('''Trait values for Shh range 5.1-fold: from a low of 8.2 (please round value) in 129S1/SvImJ to a high of 10.6 (please round value) in BXD9.  The interquartile range (the difference between values closest to the 25% and 75% levels) is a more modest 1.8-fold. The mean value is XX. ''')
                t1 = HT.Paragraph('''Table 1.  Summary of Shh data from the Hippocampus Consortium M430v2 (june06) PDNN data set''')
                f1 = HT.Paragraph('''Figure 1. ''')
                f1.append(HT.Href(text="Box plot", url="http://davidmlane.com/hyperstat/A37797.html", target="_blank", Class="fs14"))
                f1.append(HT.Text(''' of Shh data from the Hippocampus Consortium M430v2 (june06) PDNN data set'''))
                f2A = HT.Paragraph('''Figure 2A: Bar chart of Shh data ordered by case from the Hippocampus Consortium M430v2 (june06) PDNN data set''')
                f2B = HT.Paragraph('''Figure 2B: Bar chart of Shh values ordered by from the Hippocampus Consortium M430v2 (june06) PDNN data set''')
                TD_LR.append(HT.Blockquote(title, HT.P(), header, hr, p1, HT.P(), p2, HT.P(), supertable2, t1, f1, HT.P(), img0, f2A, HT.P(), img1, f2B))
                self.dict['body'] = str(TD_LR)
            else:
                heading = "Basic Statistics"
                detail = ['Fewer than %d case data were entered for %s data set. No statitical analysis has been attempted.' % (self.plotMinInformative, fd.RISet)]
                self.error(heading=heading,detail=detail)
                return
        else:
            heading = "Basic Statistics"
            detail = ['Empty data set, please check your data.']
            self.error(heading=heading,detail=detail)
            return
	def __init__(self, fd):

		LRSFullThresh = 30
		LRSInteractThresh = 25

		templatePage.__init__(self, fd)

		if not fd.genotype:
			fd.readData()

		incVars = 0
		_genotype = fd.genotype_1
		_strains, _vals, _vars, N = fd.informativeStrains(_genotype.prgy, incVars)

		self.dict['title'] = 'Pair-Scan Plot'
		if not self.openMysql():
			return

		iPermuCheck = fd.formdata.getvalue('directPermuCheckbox')

		try:
			graphtype = int(fd.formdata.getvalue('graphtype'))
		except:
			graphtype = 1
		try:
			graphsort = int(fd.formdata.getvalue('graphSort'))
		except:
			graphsort = 1
		try:
			returnIntervalPairNum = int(fd.formdata.getvalue('pairScanReturn'))
		except:
			returnIntervalPairNum = 50

		pairIntro = HT.Blockquote("The graph below displays pair-scan results for the trait ",HT.Strong(" %s" % fd.identification))
		if not graphsort:
			tblIntro = HT.Blockquote('This table lists LRS scores for the top %d pairs of intervals (Interval 1 on the left and Interval 2 on the right). Pairs are sorted by the "LRS Full" column. Both intervals are defined by proximal and distal markers that flank the single best position.' % returnIntervalPairNum)
		else:
			tblIntro = HT.Blockquote('This table lists LRS scores for the top %d pairs of intervals (Interval 1 on the left and Interval 2 on the right). Pairs are sorted by the "LRS Interaction" column. Both intervals are defined by proximal and distal markers that flank the single best position.' % returnIntervalPairNum)

		try:
			thisTrait = webqtlTrait(fullname=fd.formdata.getvalue("fullname"), cursor=self.cursor)
			pairIntro.append(' from the database ' , thisTrait.db.genHTML())
		except:
			pass

		pairIntro.append('. The upper left half of the plot highlights any epistatic interactions (corresponding to the column labeled "LRS Interact"). In contrast, the lower right half provides a summary of LRS of the full model, representing cumulative effects of linear and non-linear terms (column labeled "LRS Full"). The WebQTL implementation of the scan for 2-locus epistatic interactions is based on the DIRECT global optimization algorithm developed by ',HT.Href(text ="Ljungberg",url='http://user.it.uu.se/~kl/qtl_software.html',target="_blank", Class = "fs14 fwn"),', Holmgren, and Carlborg (',HT.Href(text = "2004",url='http://bioinformatics.oupjournals.org/cgi/content/abstract/bth175?ijkey=21Pp0pgOuBL6Q&keytype=ref', Class = "fs14 fwn"),').')

		main_title = HT.Paragraph("Pair-Scan Results: An Analysis of Epistatic Interactions")
		main_title.__setattr__("class","title")

		subtitle1 = HT.Paragraph("Pair-Scan Graph")
		subtitle3 = HT.Paragraph("Pair-Scan Top LRS")
		subtitle1.__setattr__("class","subtitle")
		subtitle3.__setattr__("class","subtitle")

		self.identification = "unnamed trait"
		if fd.identification:
			self.identification = fd.identification
			self.dict['title'] = self.identification + ' / '+self.dict['title']

		#####################################
		#
		# Remove the Parents & F1 data
		#
		#####################################

		if _vals:
			if len(_vals) > webqtlConfig.KMININFORMATIVE:
				ResultFull = []
				ResultInteract = []
				ResultAdd = []

				#permutation test
				subtitle2 = ''
				permuTbl = ''
				permuIntro = ''
				if iPermuCheck:
					subtitle2 = HT.Paragraph("Pair-Scan Permutation Results")
					subtitle2.__setattr__("class","subtitle")
					permuIntro = HT.Blockquote("Phenotypes were randomly permuted 500 times among strains or individuals and reanalyzed using the pair-scan algorithm. We extracted the single highest LRS for the full model for each of these permuted data sets. The histograms of these highest LRS values provide an empirical way to estimate the probability of obtaining an LRS above suggestive or significant thresholds.")

					prtmuTblIntro1 = HT.Paragraph("The following table gives threshold values for Suggestive (P=0.63) and Significant associations (P=0.05) defined by Lander & Kruglyak and for the slightly more stringent P=0.01 level. (The Highly Significant level of Lander & Kruglyak corresponds to P=0.001 and cannot be estimated with 500 permutations.)")
					prtmuTblIntro2 = HT.Paragraph("If the full model exceeds the permutation-based Significant threshold, then different models for those locations can be tested by conventional chi-square tests at P<0.01. Interaction is significant if LRS Interact exceeds 6.64 for RI strains or 13.28 for an F2. If interaction is not significant, the two-QTL model is better than a one-QTL model if LRS Additive exceeds LRS 1 or LRS 2 by 6.64 for RI strains or 9.21 for an F2.")
					ResultFull, ResultInteract, ResultAdd = direct.permu(webqtlConfig.GENODIR, _vals, _strains, fd.RISet, 500) #XZ, 08/14/2008: add module name webqtlConfig
					ResultFull.sort()
					ResultInteract.sort()
					ResultAdd.sort()
					nPermuResult = len(ResultFull)
					# draw Histogram
					cFull = pid.PILCanvas(size=(400,300))
					Plot.plotBar(cFull, ResultFull,XLabel='LRS',YLabel='Frequency',title=' Histogram of LRS Full')
					#plotBar(cFull,10,10,390,290,ResultFull,XLabel='LRS',YLabel='Frequency',title=' Histogram of LRS Full')
					filename= webqtlUtil.genRandStr("Pair_")
					cFull.save(webqtlConfig.IMGDIR+filename, format='gif')
					imgFull=HT.Image('/image/'+filename+'.gif',border=0,alt='Histogram of LRS Full')


					superPermuTbl = HT.TableLite(border=0, cellspacing=0, cellpadding=0,bgcolor ='#999999')
					permuTbl2 = HT.TableLite(border=0, cellspacing= 1, cellpadding=5)
					permuTbl2.append(HT.TR(HT.TD(HT.Font('LRS', color = '#FFFFFF')), HT.TD(HT.Font('p = 0.63', color = '#FFFFFF'), width = 150, align='Center'), HT.TD(HT.Font('p = 0.05', color = '#FFFFFF'), width = 150, align='Center'), HT.TD(HT.Font('p = 0.01', color = '#FFFFFF'), width = 150, align='Center'),bgColor='royalblue'))
					permuTbl2.append(HT.TR(HT.TD('Full'), HT.TD('%2.1f' % ResultFull[int(nPermuResult*0.37 -1)], align="Center"), HT.TD('%2.1f' % ResultFull[int(nPermuResult*0.95 -1)], align="Center"), HT.TD('%2.1f' % ResultFull[int(nPermuResult*0.99 -1)], align="Center"),bgColor="#eeeeee"))
					superPermuTbl.append(HT.TD(HT.TD(permuTbl2)))

					permuTbl1 = HT.TableLite(border=0, cellspacing= 0, cellpadding=5,width='100%')
					permuTbl1.append(HT.TR(HT.TD(imgFull, align="Center", width = 410), HT.TD(prtmuTblIntro1, superPermuTbl, prtmuTblIntro2, width = 490)))

					permuTbl = HT.Center(permuTbl1, HT.P())

					#permuTbl.append(HT.TR(HT.TD(HT.BR(), 'LRS Full  = %2.1f, ' % ResultFull[int(nPermuResult*0.37 -1)], 'LRS Full  = %2.1f, ' % ResultFull[int(nPermuResult*0.95 -1)], 'LRS Full highly significant (p=0.001) = %2.1f, ' % ResultFull[int(nPermuResult*0.999 -1)] , HT.BR(), 'LRS Interact suggestive (p=0.63) = %2.1f, ' % ResultInteract[int(nPermuResult*0.37 -1)], 'LRS Interact significant (p=0.05) = %2.1f, ' % ResultInteract[int(nPermuResult*0.95 -1)], 'LRS Interact  = %2.1f, ' % ResultInteract[int(nPermuResult*0.999 -1)] , HT.BR(),'LRS Additive suggestive (p=0.63) = %2.1f, ' % ResultAdd[int(nPermuResult*0.37 -1)], 'LRS Additive significant (p=0.05) = %2.1f, ' % ResultAdd[int(nPermuResult*0.95 -1)], 'LRS Additive highly significant (p=0.001) = %2.1f, ' % ResultAdd[int(nPermuResult*0.999 -1)], HT.BR(), 'Total number of permutation is %d' % nPermuResult, HT.BR(), HT.BR(),colspan=2)))
					#tblIntro.append(HT.P(), HT.Center(permuTbl))

				#print vals, strains, fd.RISet
				d = direct.direct(webqtlConfig.GENODIR, _vals, _strains, fd.RISet, 8000)#XZ, 08/14/2008: add module name webqtlConfig
				chrsInfo = d[2]
				sum = 0
				offsets = [0]
				i = 0
				for item in chrsInfo:
					if i > 0:
						offsets.append(sum)
					sum += item[0]
					i += 1
				offsets.append(sum)
				#print sum,offset,d[2]
				canvasWidth = 880
				canvasHeight = 880
				if graphtype:
					colorAreaWidth = 230
				else:
					colorAreaWidth = 0
				c = pid.PILCanvas(size=(canvasWidth + colorAreaWidth ,canvasHeight))
				xoffset = 40
				yoffset = 40
				width = canvasWidth - xoffset*2
				height = canvasHeight - yoffset*2

				xscale = width/sum
				yscale = height/sum

				rectInfo = d[1]
				rectInfo.sort(webqtlUtil.cmpLRSFull)

				finecolors = Plot.colorSpectrum(250)
				finecolors.reverse()
				regLRS = [0]*height
				#draw LRS Full

				for item in rectInfo:
					LRSFull,LRSInteract,LRSa,LRSb,chras,chram,chrae,chrbs,chrbm,chrbe,chra,chrb,flanka,flankb = item
					if LRSFull > 30:
						dcolor = pid.red
					elif LRSFull > 20:
						dcolor = pid.orange
					elif LRSFull > 10:
						dcolor = pid.olivedrab
					elif LRSFull > 0:
						dcolor = pid.grey
					else:
						LRSFull = 0
						dcolor = pid.grey

					chras += offsets[chra]
					chram += offsets[chra]
					chrae += offsets[chra]
					chrbs += offsets[chrb]
					chrbm += offsets[chrb]
					chrbe += offsets[chrb]

					regLRSD = int(chram*yscale)
					if regLRS[regLRSD] < LRSa:
						regLRS[regLRSD] = LRSa
					regLRSD = int(chrbm*yscale)
					if regLRS[regLRSD] < LRSb:
						regLRS[regLRSD] = LRSb

					if graphtype:
						colorIndex = int(LRSFull *250 /LRSFullThresh)
						if colorIndex >= 250:
							colorIndex = 249
						dcolor = finecolors[colorIndex]
						if chra != chrb or ((chrbe - chrae) > 10 and (chrbs - chras) > 10):
							c.drawRect(xoffset+chrbs*xscale,yoffset+height-chras*yscale,xoffset+chrbe*xscale,yoffset+height-chrae*yscale,edgeColor=dcolor,fillColor=dcolor,edgeWidth = 0)
						else:
							c.drawPolygon([(xoffset+chrbs*xscale,yoffset+height-chras*yscale),(xoffset+chrbe*xscale,yoffset+height-chras*yscale),(xoffset+chrbe*xscale,yoffset+height-chrae*yscale)],edgeColor=dcolor,fillColor=dcolor,edgeWidth = 0,closed =1)
					else:
						c.drawCross(xoffset+chrbm*xscale,yoffset+height-chram*yscale,color=dcolor,size=2)
				#draw Marker Regression LRS
				if graphtype:
					"""
					maxLRS = max(regLRS)
					pts = []
					i = 0
					for item in regLRS:
						pts.append((xoffset+width+35+item*50/maxLRS, yoffset+height-i))
						i += 1
					c.drawPolygon(pts,edgeColor=pid.blue,edgeWidth=1,closed=0)
					"""
					LRS1Thresh = 16.2
					i = 0
					for item in regLRS:
						colorIndex = int(item *250 /LRS1Thresh)
						if colorIndex >= 250:
							colorIndex = 249
						dcolor = finecolors[colorIndex]
						c.drawLine(xoffset+width+35,yoffset+height-i,xoffset+width+55,yoffset+height-i,color=dcolor)
						i += 1
					labelFont=pid.Font(ttf="arial",size=20,bold=0)
					c.drawString('Single Locus Regression',xoffset+width+90,yoffset+height, font = labelFont,color=pid.dimgray,angle=90)
				#draw LRS Interact
				rectInfo.sort(webqtlUtil.cmpLRSInteract)
				for item in rectInfo:
					LRSFull,LRSInteract,LRSa,LRSb,chras,chram,chrae,chrbs,chrbm,chrbe,chra,chrb,flanka,flankb = item
					if LRSInteract > 30:
						dcolor = pid.red
					elif LRSInteract > 20:
						dcolor = pid.orange
					elif LRSInteract > 10:
						dcolor = pid.olivedrab
					elif LRSInteract > 0:
						dcolor = pid.grey
					else:
						LRSInteract = 0
						dcolor = pid.grey
					chras += offsets[chra]
					chram += offsets[chra]
					chrae += offsets[chra]
					chrbs += offsets[chrb]
					chrbm += offsets[chrb]
					chrbe += offsets[chrb]
					if graphtype:
						colorIndex = int(LRSInteract *250 / LRSInteractThresh )
						if colorIndex >= 250:
							colorIndex = 249
						dcolor = finecolors[colorIndex]
						if chra != chrb or ((chrbe - chrae) > 10 and (chrbs - chras) > 10):
							c.drawRect(xoffset+chras*xscale,yoffset+height-chrbs*yscale,xoffset+chrae*xscale,yoffset+height-chrbe*yscale,edgeColor=dcolor,fillColor=dcolor,edgeWidth = 0)
						else:
							c.drawPolygon([(xoffset+chras*xscale,yoffset+height-chrbs*yscale),(xoffset+chras*xscale,yoffset+height-chrbe*yscale),(xoffset+chrae*xscale,yoffset+height-chrbe*yscale)],edgeColor=dcolor,fillColor=dcolor,edgeWidth = 0,closed =1)
					else:
						c.drawCross(xoffset+chram*xscale,yoffset+height-chrbm*yscale,color=dcolor,size=2)
				#draw chromosomes label
				labelFont=pid.Font(ttf="tahoma",size=24,bold=0)
				i = 0
				for item in chrsInfo:
					strWidth = c.stringWidth(item[1],font=labelFont)
					c.drawString(item[1],xoffset+offsets[i]*xscale +(item[0]*xscale-strWidth)/2,canvasHeight -15,font = labelFont,color=pid.dimgray)
					c.drawString(item[1],xoffset+offsets[i]*xscale +(item[0]*xscale-strWidth)/2,yoffset-10,font = labelFont,color=pid.dimgray)
					c.drawString(item[1],xoffset-strWidth-5,yoffset+height - offsets[i]*yscale -(item[0]*yscale-22)/2,font = labelFont,color=pid.dimgray)
					c.drawString(item[1],canvasWidth-xoffset+5,yoffset+height - offsets[i]*yscale -(item[0]*yscale-22)/2,font = labelFont,color=pid.dimgray)
					i += 1


				c.drawRect(xoffset,yoffset,xoffset+width,yoffset+height)
				for item in offsets:
					c.drawLine(xoffset,yoffset+height-item*yscale,xoffset+width,yoffset+height-item*yscale)
					c.drawLine(xoffset+item*xscale,yoffset,xoffset+item*xscale,yoffset+height)

				#draw pngMap
				pngMap = HT.Map(name='pairPlotMap')
				#print offsets, len(offsets)
				for i in range(len(offsets)-1):
					for j in range(len(offsets)-1):
						COORDS = "%d,%d,%d,%d" %(xoffset+offsets[i]*xscale, yoffset+height-offsets[j+1]*yscale, xoffset+offsets[i+1]*xscale, yoffset+height-offsets[j]*yscale)
						HREF = "javascript:showPairPlot(%d,%d);" % (i,j)
						Areas = HT.Area(shape='rect',coords=COORDS,href=HREF)
						pngMap.areas.append(Areas)

				#draw spectrum
				if graphtype:
					i = 0
					labelFont=pid.Font(ttf="tahoma",size=14,bold=0)
					middleoffsetX = 180
					for dcolor in finecolors:
						if i % 50 == 0:
							c.drawLine(xoffset+ width +middleoffsetX-15 , height + yoffset -i, xoffset+ width +middleoffsetX-20,height + yoffset -i, color=pid.black)
							c.drawString('%d' % int(LRSInteractThresh*i/250.0),xoffset+ width+ middleoffsetX-40,height + yoffset -i +5, font = labelFont,color=pid.black)
							c.drawLine(xoffset+ width +middleoffsetX+15 , height + yoffset -i, xoffset+ width +middleoffsetX+20 ,height + yoffset -i, color=pid.black)
							c.drawString('%d' % int(LRSFullThresh*i/250.0),xoffset+ width + middleoffsetX+25,height + yoffset -i +5, font = labelFont,color=pid.black)
						c.drawLine(xoffset+ width +middleoffsetX-15 , height + yoffset -i, xoffset+ width +middleoffsetX+15 ,height + yoffset -i, color=dcolor)
						i += 1

					if i % 50 == 0:
						i -= 1
						c.drawLine(xoffset+ width +middleoffsetX-15 , height + yoffset -i, xoffset+ width +middleoffsetX-20,height + yoffset -i, color=pid.black)
						c.drawString('%d' % ceil(LRSInteractThresh*i/250.0),xoffset+ width + middleoffsetX-40,height + yoffset -i +5, font = labelFont,color=pid.black)
						c.drawLine(xoffset+ width +middleoffsetX+15 , height + yoffset -i, xoffset+ width +middleoffsetX+20 ,height + yoffset -i, color=pid.black)
						c.drawString('%d' % ceil(LRSFullThresh*i/250.0),xoffset+ width + middleoffsetX+25,height + yoffset -i +5, font = labelFont,color=pid.black)

					labelFont=pid.Font(ttf="verdana",size=20,bold=0)
					c.drawString('LRS Interaction',xoffset+ width + middleoffsetX-50,height + yoffset, font = labelFont,color=pid.dimgray,angle=90)
					c.drawString('LRS Full',xoffset+ width + middleoffsetX+50,height + yoffset, font = labelFont,color=pid.dimgray,angle=90)

				filename= webqtlUtil.genRandStr("Pair_")
				c.save(webqtlConfig.IMGDIR+filename, format='png')
				img2=HT.Image('/image/'+filename+'.png',border=0,usemap='#pairPlotMap')


				form0 = HT.Form( cgi= os.path.join(webqtlConfig.CGIDIR, webqtlConfig.SCRIPTFILE), enctype='multipart/form-data', name='showPairPlot', submit=HT.Input(type='hidden'))
				hddn0 = {'FormID':'pairPlot','Chr_A':'_','Chr_B':'','idata':string.join(map(str, _vals), ','),'istrain':string.join(_strains, ','),'RISet':fd.RISet}
				for key in hddn0.keys():
					form0.append(HT.Input(name=key, value=hddn0[key], type='hidden'))

				form0.append(img2, pngMap)

				mainfmName = webqtlUtil.genRandStr("fm_")
				txtform = HT.Form( cgi= os.path.join(webqtlConfig.CGIDIR, webqtlConfig.SCRIPTFILE), enctype='multipart/form-data', name=mainfmName, submit=HT.Input(type='hidden'))
				hddn = {'FormID':'showDatabase','ProbeSetID':'_','database':fd.RISet+"Geno",'CellID':'_','RISet':fd.RISet}
				#XZ, Aug 11, 2010: The variable traitStrains is not assigned right values before (should not be assigned fd.strainlist).
				#hddn['traitStrains'] = string.join(fd.strainlist, ',')
				hddn['traitStrains'] = string.join(_strains, ',')
				hddn['traitValues'] = string.join(map(str, _vals), ',')
				hddn['interval1'] = ''
				hddn['interval2'] = ''
				if fd.incparentsf1:
					hddn['incparentsf1']='ON'
				for key in hddn.keys():
					txtform.append(HT.Input(name=key, value=hddn[key], type='hidden'))

				tbl = HT.TableLite(Class="collap", cellspacing=1, cellpadding=5,width=canvasWidth + colorAreaWidth)

				c1 = HT.TD('Interval 1',colspan=3,align="Center", Class="fs13 fwb ffl b1 cw cbrb")
				c2 = HT.TD('Interval 2',colspan=3,align="Center", Class="fs13 fwb ffl b1 cw cbrb")
				c11 = HT.TD('Position',rowspan=2,align="Center", Class="fs13 fwb ffl b1 cw cbrb")
				c12 = HT.TD('Flanking Markers',colspan=2,align="Center", Class="fs13 fwb ffl b1 cw cbrb")
				c111 = HT.TD('Proximal',align="Center", Class="fs13 fwb ffl b1 cw cbrb")
				c112 = HT.TD('Distal',align="Center", Class="fs13 fwb ffl b1 cw cbrb")


				c3 = HT.TD('LRS Full',rowspan=3,align="Center", Class="fs13 fwb ffl b1 cw cbrb")
				c4 = HT.TD('LRS Additive',rowspan=3,align="Center", Class="fs13 fwb ffl b1 cw cbrb")
				c5 = HT.TD('LRS Interact',rowspan=3,align="Center", Class="fs13 fwb ffl b1 cw cbrb")
				c6 = HT.TD('LRS 1',rowspan=3,align="Center", Class="fs13 fwb ffl b1 cw cbrb")
				c7 = HT.TD('LRS 2',rowspan=3,align="Center", Class="fs13 fwb ffl b1 cw cbrb")


				tbl.append(HT.TR(c1,c3,c4,c5,c6,c7,c2))

				tbl.append(HT.TR(c11,c12,c11,c12))
				tbl.append(HT.TR(c111,c112,c111,c112))
				if not graphsort: #Sort by LRS Full
					rectInfo.sort(webqtlUtil.cmpLRSFull)
				rectInfoReturned = rectInfo[len(rectInfo) - returnIntervalPairNum:]
				rectInfoReturned.reverse()

				for item in rectInfoReturned:
					LRSFull,LRSInteract,LRSa,LRSb,chras,chram,chrae,chrbs,chrbm,chrbe,chra,chrb,flanka,flankb = item
					LRSAdditive = LRSFull - LRSInteract
					flanka1,flanka2 = string.split(flanka)
					flankb1,flankb2 = string.split(flankb)
					urla1 = HT.Href(text = flanka1, url = "javascript:showTrait('%s','%s');" % (mainfmName, flanka1),Class= "fs12 fwn")
					urla2 = HT.Href(text = flanka2, url = "javascript:showTrait('%s','%s');" % (mainfmName, flanka2),Class= "fs12 fwn")
					urlb1 = HT.Href(text = flankb1, url = "javascript:showTrait('%s','%s');" % (mainfmName, flankb1),Class= "fs12 fwn")
					urlb2 = HT.Href(text = flankb2, url = "javascript:showTrait('%s','%s');" % (mainfmName, flankb2),Class= "fs12 fwn")
					urlGenGraph = HT.Href(text = "Plot", url = "javascript:showCateGraph('%s',  '%s %s %2.3f', '%s %s %2.3f');" % (mainfmName, flanka1, flanka2, chram, flankb1, flankb2, chrbm),Class= "fs12 fwn")
					tr1 = HT.TR(
						HT.TD('Chr %s @ %2.1f cM ' % (chrsInfo[chra][1],chram),Class= "fs12 b1 fwn"),
						HT.TD(urla1,Class= "fs12 b1 fwn"),
						HT.TD(urla2,Class= "fs12 b1 fwn"),
						HT.TD('%2.3f ' % LRSFull, urlGenGraph,Class= "fs12 b1 fwn"),
						HT.TD('%2.3f' % LRSAdditive,Class= "fs12 b1 fwn"),
						HT.TD('%2.3f' % LRSInteract,Class= "fs12 b1 fwn"),
						HT.TD('%2.3f' % LRSa,Class= "fs12 b1 fwn"),
						HT.TD('%2.3f' % LRSb,Class= "fs12 b1 fwn"),
						HT.TD('Chr %s @ %2.1f cM' % (chrsInfo[chrb][1],chrbm),Class= "fs12 b1 fwn"),
						HT.TD(urlb1,Class= "fs12 b1 fwn"),
						HT.TD(urlb2,Class= "fs12 b1 fwn"))
					tbl.append(tr1)

				plotType1 = HT.Input(type="radio", name="plotType", value ="Dot", checked=1)
				plotType2 = HT.Input(type="radio", name="plotType", value ="Box")
				plotText = HT.Paragraph("Plot Type : ", plotType1, " Dot ", plotType2, " Box",  )

				txtform.append(plotText, tbl)
				TD_LR = HT.TD(colspan=2,height=200,width="100%",bgColor='#eeeeee')
				TD_LR.append(main_title,HT.Blockquote(subtitle1, pairIntro, HT.P(), HT.Center(form0,HT.P())),HT.Blockquote(subtitle2, permuIntro,HT.P(), HT.Center(permuTbl)), HT.Blockquote(subtitle3, tblIntro, HT.P(),HT.Center(txtform), HT.P()))
				self.dict['body'] = str(TD_LR)
			else:
				heading = "Direct Plot"
				detail = ['Fewer than %d strain data were entered for %s data set. No statitical analysis has been attempted.' % (webqtlConfig.KMININFORMATIVE, fd.RISet)]
				self.error(heading=heading,detail=detail)
				return
		else:
			heading = "Direct Plot"
			detail = ['Empty data set, please check your data.']
			self.error(heading=heading,detail=detail)
			return
	def __init__(self, fd):

		templatePage.__init__(self, fd)

		self.initializeDisplayParameters(fd)

		if not fd.genotype:
			fd.readGenotype()

		if fd.allstrainlist:
			mdpchoice = fd.formdata.getvalue('MDPChoice')
			if mdpchoice == "1":
				strainlist = fd.f1list + fd.strainlist
			elif mdpchoice == "2":
				strainlist = []
				strainlist2 = fd.f1list + fd.strainlist
				for strain in fd.allstrainlist:
					if strain not in strainlist2:
						strainlist.append(strain)
				#So called MDP Panel
				if strainlist:
					strainlist = fd.f1list+fd.parlist+strainlist
			else:
				strainlist = fd.allstrainlist
			fd.readData(fd.allstrainlist)
		else:
			mdpchoice = None
			strainlist = fd.strainlist
			fd.readData()

		#if fd.allstrainlist:
		#	fd.readData(fd.allstrainlist)
		#	strainlist = fd.allstrainlist
		#else:
		#	fd.readData()
		#	strainlist = fd.strainlist
		
		
		if not self.openMysql():
			return

		isSampleCorr = 0 #XZ: initial value is false
		isTissueCorr = 0 #XZ: initial value is false

		#Javascript functions (showCorrelationPlot2, showTissueCorrPlot) have made sure the correlation type is either sample correlation or tissue correlation.
		if (self.database and (self.ProbeSetID != 'none')):
			isSampleCorr = 1
		elif (self.X_geneSymbol and self.Y_geneSymbol):
			isTissueCorr = 1
		else:
			heading = "Correlation Type Error"
			detail = ["For the input parameters, GN can not recognize the correlation type is sample correlation or tissue correlation."]
			self.error(heading=heading,detail=detail)
			return


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


		dataX=[]
		dataY=[]
		dataZ=[] # shortname
		fullTissueName=[]

		if isTissueCorr:
			dataX, dataY, xlabel, ylabel, dataZ, fullTissueName = self.getTissueLabelsValues(X_geneSymbol=self.X_geneSymbol, Y_geneSymbol=self.Y_geneSymbol, TissueProbeSetFreezeId=self.TissueProbeSetFreezeId)
			plotHeading = HT.Paragraph('Tissue Correlation Scatterplot')
			plotHeading.__setattr__("class","title")

			if self.xAxisLabel == '':
				self.xAxisLabel = xlabel

			if self.yAxisLabel == '':
				self.yAxisLabel = ylabel
			
		if isSampleCorr:
			plotHeading = HT.Paragraph('Sample Correlation Scatterplot')
                        plotHeading.__setattr__("class","title")

			#XZ: retrieve trait 1 info, Y axis
			trait1_data = [] #trait 1 data
			trait1Url = ''

			try:
				Trait1 = webqtlTrait(db=self.database, name=self.ProbeSetID, cellid=self.CellID, cursor=self.cursor)
				Trait1.retrieveInfo()
				Trait1.retrieveData()
			except:
				heading = "Retrieve Data"
				detail = ["The database you just requested has not been established yet."]
				self.error(heading=heading,detail=detail)
				return
	
			trait1_data = Trait1.exportData(strainlist)
			if Trait1.db.type == 'Publish' and Trait1.confidential:
				trait1Url = Trait1.genHTML(dispFromDatabase=1, privilege=self.privilege, userName=self.userName, authorized_users=Trait1.authorized_users)
			else:
				trait1Url = Trait1.genHTML(dispFromDatabase=1)
			
			if self.yAxisLabel == '':
				self.yAxisLabel= '%s : %s' % (Trait1.db.shortname, Trait1.name)
				if Trait1.cellid:
					self.yAxisLabel += ' : ' + Trait1.cellid


			#XZ, retrieve trait 2 info, X axis
			traitdata2 = [] #trait 2 data
			_vals = [] #trait 2 data
			trait2Url = ''

			if ( self.database2 and (self.ProbeSetID2 != 'none') ):
				try:
					Trait2 = webqtlTrait(db=self.database2, name=self.ProbeSetID2, cellid=self.CellID2, cursor=self.cursor)
					Trait2.retrieveInfo()
					Trait2.retrieveData()
				except:
					heading = "Retrieve Data"
					detail = ["The database you just requested has not been established yet."]
					self.error(heading=heading,detail=detail)
					return

				if Trait2.db.type == 'Publish' and Trait2.confidential:
					trait2Url = Trait2.genHTML(dispFromDatabase=1, privilege=self.privilege, userName=self.userName, authorized_users=Trait2.authorized_users)
				else:
					trait2Url = Trait2.genHTML(dispFromDatabase=1)
				traitdata2 = Trait2.exportData(strainlist)
				_vals = traitdata2[:]
				
				if self.xAxisLabel == '':
					self.xAxisLabel = '%s : %s' % (Trait2.db.shortname, Trait2.name)
					if Trait2.cellid:
						self.xAxisLabel += ' : ' + Trait2.cellid
			else:
				for item in strainlist:
					if fd.allTraitData.has_key(item):
						_vals.append(fd.allTraitData[item].val)
					else:
						_vals.append(None)

				if self.xAxisLabel == '':
					if fd.identification:
						self.xAxisLabel = fd.identification
					else:
						self.xAxisLabel = "User Input Data"

				try:
					Trait2 = webqtlTrait(fullname=fd.formdata.getvalue('fullname'), cursor=self.cursor)
					trait2Url = Trait2.genHTML(dispFromDatabase=1)
				except:
					trait2Url = self.xAxisLabel

			if (_vals and trait1_data):
				if len(_vals) != len(trait1_data):
					errors = HT.Blockquote(HT.Font('Error: ',color='red'),HT.Font('The number of traits are inconsistent, Program quit',color='black'))
					errors.__setattr__("class","subtitle")
					TD_LR.append(errors)
					self.dict['body'] = str(TD_LR)
					return

				for i in range(len(_vals)):
					if _vals[i]!= None and trait1_data[i]!= None:
						dataX.append(_vals[i])
						dataY.append(trait1_data[i])
						strainName = strainlist[i]
						if self.showstrains:
							dataZ.append(webqtlUtil.genShortStrainName(RISet=fd.RISet, input_strainName=strainName))
			else:
				heading = "Correlation Plot"
				detail = ['Empty Dataset for sample correlation, please check your data.']
				self.error(heading=heading,detail=detail)
				return


		#XZ: We have gotten all data for both traits.
		if len(dataX) >= self.corrMinInformative:

			if self.rankOrder == 0:
				rankPrimary = 0
				rankSecondary = 1
			else:
				rankPrimary = 1
				rankSecondary = 0

			lineColor = self.setLineColor();
			symbolColor = self.setSymbolColor();
			idColor = self.setIdColor();					
				
			c = pid.PILCanvas(size=(self.plotSize, self.plotSize*0.90))
			data_coordinate = Plot.plotXY(canvas=c, dataX=dataX, dataY=dataY, rank=rankPrimary, dataLabel = dataZ, labelColor=pid.black, lineSize=self.lineSize, lineColor=lineColor, idColor=idColor, idFont=self.idFont, idSize=self.idSize, symbolColor=symbolColor, symbolType=self.symbol, filled=self.filled, symbolSize=self.symbolSize, XLabel=self.xAxisLabel, connectdot=0, YLabel=self.yAxisLabel, title='', fitcurve=self.showline, displayR =1, offset= (90, self.plotSize/20, self.plotSize/10, 90), showLabel = self.showIdentifiers)
				
			if rankPrimary == 1:
				dataXlabel, dataYlabel = webqtlUtil.calRank(xVals=dataX, yVals=dataY, N=len(dataX))
			else:
				dataXlabel, dataYlabel = dataX, dataY
					
			gifmap1 = HT.Map(name='CorrelationPlotImageMap1')
				
			for i, item in enumerate(data_coordinate):
				one_rect_coordinate = "%d, %d, %d, %d" % (item[0] - 5, item[1] - 5, item[0] + 5, item[1] + 5)
				if isTissueCorr:
					one_rect_title = "%s (%s, %s)" % (fullTissueName[i], dataXlabel[i], dataYlabel[i])
				else:
					one_rect_title = "%s (%s, %s)" % (dataZ[i], dataXlabel[i], dataYlabel[i])
				gifmap1.areas.append(HT.Area(shape='rect',coords=one_rect_coordinate, title=one_rect_title) )

			filename= webqtlUtil.genRandStr("XY_")
			c.save(webqtlConfig.IMGDIR+filename, format='gif')
			img1=HT.Image('/image/'+filename+'.gif',border=0, usemap='#CorrelationPlotImageMap1')

			mainForm_1 = 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, 'ProbeSetID2':'_', 'database2':'_', 'CellID2':'_', 'allstrainlist':string.join(fd.strainlist, " "), 'traitList': fd.formdata.getvalue("traitList")}
			if fd.incparentsf1:
				hddn['incparentsf1'] = 'ON'		
			for key in hddn.keys():
				mainForm_1.append(HT.Input(name=key, value=hddn[key], type='hidden'))
			
			if isSampleCorr:
					mainForm_1.append(HT.P(), HT.Blockquote(HT.Strong('X axis:'),HT.Blockquote(trait2Url),HT.Strong('Y axis:'),HT.Blockquote(trait1Url), style='width: %spx;' % self.plotSize, wrap="hard"))
			
			graphForm = HT.Form(cgi= os.path.join(webqtlConfig.CGIDIR, webqtlConfig.SCRIPTFILE), name='MDP_Form',submit=HT.Input(type='hidden'))
			graph_hddn = self.setHiddenParameters(fd, rankPrimary)
			webqtlUtil.exportData(graph_hddn, fd.allTraitData) #XZ: This is necessary to replot with different groups of strains
							
			for key in graph_hddn.keys():
				graphForm.append(HT.Input(name=key, value=graph_hddn[key], type='hidden'))			

			options = self.createOptionsMenu(fd, mdpchoice)	
			
			if (self.showOptions == '0'):
					showOptionsButton = HT.Input(type='button' ,name='optionsButton',value='Hide Options', onClick="showHideOptions();", Class="button")
			else:
					showOptionsButton = HT.Input(type='button' ,name='optionsButton',value='Show Options', onClick="showHideOptions();", Class="button")
					
			# updated by NL: 12-07-2011 add variables for tissue abbreviation page
			if isTissueCorr: 
				graphForm.append(HT.Input(name='shortTissueName', value='', type='hidden'))
				graphForm.append(HT.Input(name='fullTissueName', value='', type='hidden'))
				shortTissueNameStr=string.join(dataZ, ",")
				fullTissueNameStr=string.join(fullTissueName, ",")
		
				tissueAbbrButton=HT.Input(type='button' ,name='tissueAbbrButton',value='Show Abbreviations', onClick="showTissueAbbr('MDP_Form','%s','%s')" % (shortTissueNameStr,fullTissueNameStr), Class="button")
				graphForm.append(showOptionsButton,'&nbsp;&nbsp;&nbsp;&nbsp;',tissueAbbrButton, HT.BR(), HT.BR())
			else:
				graphForm.append(showOptionsButton, HT.BR(), HT.BR())

			graphForm.append(options, HT.BR())				
			graphForm.append(HT.HR(), HT.BR(), HT.P())
						
			TD_LR.append(plotHeading, HT.BR(),graphForm, HT.BR(), gifmap1, HT.P(), img1, HT.P(), mainForm_1)
			TD_LR.append(HT.BR(), HT.HR(color="grey", size=5, width="100%"))



			c = pid.PILCanvas(size=(self.plotSize, self.plotSize*0.90))
			data_coordinate = Plot.plotXY(canvas=c, dataX=dataX, dataY=dataY, rank=rankSecondary, dataLabel = dataZ, labelColor=pid.black,lineColor=lineColor, lineSize=self.lineSize, idColor=idColor, idFont=self.idFont, idSize=self.idSize, symbolColor=symbolColor, symbolType=self.symbol, filled=self.filled, symbolSize=self.symbolSize, XLabel=self.xAxisLabel, connectdot=0, YLabel=self.yAxisLabel,title='', fitcurve=self.showline, displayR =1, offset= (90, self.plotSize/20, self.plotSize/10, 90), showLabel = self.showIdentifiers)

			if rankSecondary == 1:
				dataXlabel, dataYlabel = webqtlUtil.calRank(xVals=dataX, yVals=dataY, N=len(dataX))
			else:
				dataXlabel, dataYlabel = dataX, dataY
				
			gifmap2 = HT.Map(name='CorrelationPlotImageMap2')
				
			for i, item in enumerate(data_coordinate):
				one_rect_coordinate = "%d, %d, %d, %d" % (item[0] - 6, item[1] - 6, item[0] + 6, item[1] + 6)
				if isTissueCorr:
					one_rect_title = "%s (%s, %s)" % (fullTissueName[i], dataXlabel[i], dataYlabel[i])
				else:
					one_rect_title = "%s (%s, %s)" % (dataZ[i], dataXlabel[i], dataYlabel[i])
					
				gifmap2.areas.append(HT.Area(shape='rect',coords=one_rect_coordinate, title=one_rect_title) )

			filename= webqtlUtil.genRandStr("XY_")
			c.save(webqtlConfig.IMGDIR+filename, format='gif')
			img2=HT.Image('/image/'+filename+'.gif',border=0, usemap='#CorrelationPlotImageMap2')

			mainForm_2 = HT.Form( cgi= os.path.join(webqtlConfig.CGIDIR, webqtlConfig.SCRIPTFILE), enctype='multipart/form-data', name='showDatabase2', submit=HT.Input(type='hidden'))
			hddn = {'FormID':'showDatabase2','ProbeSetID':'_','database':'_','CellID':'_','RISet':fd.RISet, 'ProbeSetID2':'_', 'database2':'_', 'CellID2':'_', 'allstrainlist':string.join(fd.strainlist, " "), 'traitList': fd.formdata.getvalue("traitList")}
			if fd.incparentsf1:
				hddn['incparentsf1'] = 'ON'
			for key in hddn.keys():
				mainForm_2.append(HT.Input(name=key, value=hddn[key], type='hidden'))
				
			if isSampleCorr:
				mainForm_2.append(HT.P(), HT.Blockquote(HT.Strong('X axis:'),HT.Blockquote(trait2Url),HT.Strong('Y axis:'),HT.Blockquote(trait1Url), style='width:%spx;' % self.plotSize))

	
			TD_LR.append(HT.BR(), HT.P())
			TD_LR.append('\n', gifmap2, HT.P(), HT.P(), img2, HT.P(), mainForm_2)

			self.dict['body'] = str(TD_LR)
		else:
			heading = "Correlation Plot"
			detail = ['Fewer than %d strain data were entered for %s data set. No statitical analysis has been attempted.' % (self.corrMinInformative, fd.RISet)]
			self.error(heading=heading,detail=detail)
			return
	def GenReport(self, fd, _genotype, _strains, _vals, _vars= []):
		'Create an HTML division which reports any loci which are significantly associated with the submitted trait data.'	
		if webqtlUtil.ListNotNull(_vars):
			qtlresults = _genotype.regression(strains = _strains, trait = _vals, variance = _vars, control = self.controlLocus)
			LRSArray = _genotype.permutation(strains = _strains, trait = _vals, variance = _vars, nperm=fd.nperm)
		else:
			qtlresults = _genotype.regression(strains = _strains, trait = _vals, control = self.controlLocus)
			LRSArray = _genotype.permutation(strains = _strains, trait = _vals,nperm=fd.nperm)
		
		myCanvas = pid.PILCanvas(size=(400,300))
		#plotBar(myCanvas,10,10,390,290,LRSArray,XLabel='LRS',YLabel='Frequency',title=' Histogram of Permutation Test',identification=fd.identification)
		Plot.plotBar(myCanvas, LRSArray,XLabel='LRS',YLabel='Frequency',title=' Histogram of Permutation Test')
		filename= webqtlUtil.genRandStr("Reg_")
		myCanvas.save(webqtlConfig.IMGDIR+filename, format='gif')
		img=HT.Image('/image/'+filename+'.gif',border=0,alt='Histogram of Permutation Test')
			
		if fd.suggestive == None:
			fd.suggestive = LRSArray[int(fd.nperm*0.37-1)]
		else:
			fd.suggestive = float(fd.suggestive)
		if fd.significance == None:
			fd.significance = LRSArray[int(fd.nperm*0.95-1)]
		else:
			fd.significance = float(fd.significance)
		
		#########################################
		#      Permutation Graph
		#########################################
		permutationHeading = HT.Paragraph('Histogram of Permutation Test')
		permutationHeading.__setattr__("class","title")
		lrs = HT.Blockquote('Total of %d permutations' % fd.nperm,HT.P(),'Suggestive LRS = %2.2f' % LRSArray[int(fd.nperm*0.37-1)],\
			HT.BR(),'Significant LRS = %2.2f' % LRSArray[int(fd.nperm*0.95-1)],HT.BR(),'Highly Significant LRS =%2.2f' % LRSArray[int(fd.nperm*0.99-1)])  
		
		permutation = HT.TableLite()
		permutation.append(HT.TR(HT.TD(img)),HT.TR(HT.TD(lrs)))

		_dispAllLRS = 0
		if fd.formdata.getvalue('displayAllLRS'):
			_dispAllLRS = 1
		qtlresults2 = []
		if _dispAllLRS:
			filtered = qtlresults[:]
		else:
			filtered = filter(lambda x, y=fd.suggestive: x.lrs > y, qtlresults)
		if len(filtered) == 0:
			qtlresults2 = qtlresults[:]
			qtlresults2.sort()
			filtered = qtlresults2[-10:]
		
		#########################################
		#      Marker regression report
		#########################################
		locusFormName = webqtlUtil.genRandStr("fm_")
		locusForm = HT.Form(cgi = os.path.join(webqtlConfig.CGIDIR, webqtlConfig.SCRIPTFILE), \
			enctype='multipart/form-data', name=locusFormName, submit=HT.Input(type='hidden'))
		hddn = {'FormID':'showDatabase','ProbeSetID':'_','database':fd.RISet+"Geno",'CellID':'_', \
			'RISet':fd.RISet, 'incparentsf1':'on'}
		for key in hddn.keys():
			locusForm.append(HT.Input(name=key, value=hddn[key], type='hidden'))
		
		regressionHeading = HT.Paragraph('Marker Regression Report')
		regressionHeading.__setattr__("class","title")
		if qtlresults2 != []:
			report = HT.Blockquote(HT.Font('No association ',color="#FF0000"),HT.Font('with a likelihood ratio statistic greater than %3.1f was found. Here are the top 10 LRSs.' % fd.suggestive,color="#000000"))
		else:
			report = HT.Blockquote('The following loci in the %s data set have associations with the above trait data.\n' % fd.RISet, HT.P())
		report.__setattr__("class","normalsize")
		
		fpText = open('%s.txt' % (webqtlConfig.TMPDIR+filename), 'wb')
		textUrl = HT.Href(text = 'Download', url= '/tmp/'+filename+'.txt', target = "_blank", Class='fs12 fwn')
		
		bottomInfo = HT.Paragraph(textUrl, ' result in tab-delimited text format.', HT.BR(), HT.BR(),'LRS values marked with',HT.Font(' * ',color="red"), 'are greater than the significance threshold (specified by you or by permutation test). ' , HT.BR(), HT.BR(), HT.Strong('Additive Effect'), ' is half the difference in the mean phenotype of all cases that are homozygous for one parental allel at this marker minus the mean of all cases that are homozygous for the other parental allele at this marker. ','In the case of %s strains, for example,' % fd.RISet,' A positive additive effect indicates that %s alleles increase trait values. Negative additive effect indicates that %s alleles increase trait values.'% (fd.ppolar,fd.mpolar),Class="fs12 fwn")

		c1 = HT.TD('LRS',Class="fs14 fwb ffl b1 cw cbrb")
		c2 = HT.TD('Chr',Class="fs14 fwb ffl b1 cw cbrb")
		c3 = HT.TD('Mb',Class="fs14 fwb ffl b1 cw cbrb")
		c4 = HT.TD('Locus',Class="fs14 fwb ffl b1 cw cbrb")
		c5 = HT.TD('Additive Effect',Class="fs14 fwb ffl b1 cw cbrb")
		
		fpText.write('LRS\tChr\tMb\tLocus\tAdditive Effect\n')
		hr = HT.TR(c1, c2, c3, c4, c5)
		tbl = HT.TableLite(border=0, width="90%", cellpadding=0, cellspacing=0, Class="collap")
		tbl.append(hr)
		for ii in filtered:
			#add by NL 06-22-2011: set LRS to 460 when LRS is infinite, 
			if ii.lrs==float('inf') or ii.lrs>webqtlConfig.MAXLRS:
				LRS=webqtlConfig.MAXLRS #maximum LRS value
			else:
				LRS=ii.lrs		
			fpText.write('%2.3f\t%s\t%s\t%s\t%2.3f\n' % (LRS, ii.locus.chr, ii.locus.Mb, ii.locus.name, ii.additive))
			if LRS > fd.significance:
				c1 = HT.TD('%3.3f*' % LRS, Class="fs13 b1 cbw cr")
			else:
				c1 = HT.TD('%3.3f' % LRS,Class="fs13 b1 cbw c222")
			tbl.append(HT.TR(c1, HT.TD(ii.locus.chr,Class="fs13 b1 cbw c222"), HT.TD(ii.locus.Mb,Class="fs13 b1 cbw c222"), HT.TD(HT.Href(text=ii.locus.name, url = "javascript:showTrait('%s','%s');" % (locusFormName, ii.locus.name), Class='normalsize'), Class="fs13 b1 cbw c222"), HT.TD('%3.3f' % ii.additive,Class="fs13 b1 cbw c222"),bgColor='#eeeeee'))
		
		locusForm.append(tbl)
		tbl2 = HT.TableLite(border=0, cellspacing=0, cellpadding=0,width="90%")
		tbl2.append(HT.TR(HT.TD(bottomInfo)))
		rv=HT.TD(permutationHeading,HT.Center(permutation),regressionHeading,report, HT.Center(locusForm,HT.P(),tbl2,HT.P()),width='55%',valign='top', bgColor='#eeeeee')
		return rv
        def __init__(self,fd):

                templatePage.__init__(self, fd)

                if not self.openMysql():
                        return
                if not fd.genotype:
                        fd.readGenotype()


                self.searchResult = fd.formdata.getvalue('searchResult')

                if not self.searchResult:
                        templatePage.__init__(self, fd)
                        heading = 'QTL Heatmap'
                        detail = ['You need to select at least two traits in order to generate correlation matrix.']
                        self.error(heading=heading,detail=detail)
                        return
                if type("1") == type(self.searchResult):
                        self.searchResult = string.split(self.searchResult,'\t')


                if self.searchResult:
                        if len(self.searchResult) > webqtlConfig.MAXCORR:
                                heading = 'QTL Heatmap'
                                detail = ['In order to display the QTL heat map properly, do not select more than %d traits for analysis.' % webqtlConfig.MAXCORR]
                                self.error(heading=heading,detail=detail)
                                return

                        traitList = []
                        traitDataList = []
                        for item in self.searchResult:
                                thisTrait = webqtlTrait(fullname=item, cursor=self.cursor)
                                thisTrait.retrieveInfo()
                                thisTrait.retrieveData(fd.strainlist)
                                traitList.append(thisTrait)
                                traitDataList.append(thisTrait.exportData(fd.strainlist))
                else:
                        heading = 'QTL Heatmap'
                        detail = [HT.Font('Error : ',color='red'),HT.Font('Error occurs while retrieving data from database.',color='black')]
                        self.error(heading=heading,detail=detail)
                        return

                self.colorScheme = fd.formdata.getvalue('colorScheme')
                if not self.colorScheme:
                        self.colorScheme = '1'

                self.dict['title'] = 'QTL heatmap'

                NNN = len(traitList)

                if NNN == 0:
                        heading = "QTL Heatmap"
                        detail = ['No trait was selected for %s data set. No QTL heatmap was generated.' % fd.RISet]
                        self.error(heading=heading,detail=detail)
                        return
                elif NNN < 2:
                        templatePage.__init__(self, fd)
                        heading = 'QTL Heatmap'
                        detail = ['You need to select at least two traits in order to generate QTL heatmap.']
                        self.error(heading=heading,detail=detail)
                        return
                else:
                        #XZ: It's necessory to define canvas here
                        canvas = pid.PILCanvas(size=(80+NNN*20,880))

                        names = map(webqtlTrait.displayName, traitList)

                        self.targetDescriptionChecked = fd.formdata.getvalue('targetDescriptionCheck', '')

                        #XZ, 7/29/2009: create trait display and find max strWidth
                        strWidth = 0
                        for j in range(len(names)):
                                thisTrait = traitList[j]

                                if self.targetDescriptionChecked:
                                    if thisTrait.db.type == 'ProbeSet':
                                        if thisTrait.probe_target_description:
                                                names[j] += ' [%s at Chr %s @ %2.3fMB, %s]' % (thisTrait.symbol, thisTrait.chr, thisTrait.mb, thisTrait.probe_target_description)
                                        else:
                                                names[j] += ' [%s at Chr %s @ %2.3fMB]' % (thisTrait.symbol, thisTrait.chr, thisTrait.mb)
                                    elif thisTrait.db.type == 'Geno':
                                        names[j] += ' [Chr %s @ %2.3fMB]' % (thisTrait.chr, thisTrait.mb)
                                    elif thisTrait.db.type == 'Publish':
                                        if thisTrait.abbreviation:
                                            names[j] += ' [%s]' % (thisTrait.abbreviation)
                                        else:
                                            pass
                                    else:
                                        pass

                                i = canvas.stringWidth(names[j],font=self.labelFont)
                                if i > strWidth:
                                        strWidth = i

                        width = NNN*20
                        xoffset = 40
                        yoffset = 40
                        cellHeight = 3
                        nLoci = reduce(lambda x,y: x+y, map(lambda x: len(x),fd.genotype),0)

                        if nLoci > 2000:
                                cellHeight = 1
                        elif nLoci > 1000:
                                cellHeight = 2
                        elif nLoci < 200:
                                cellHeight = 10
                        else:
                                pass

                        pos = range(NNN)
                        neworder = []
                        BWs = Plot.BWSpectrum()
                        colors100 = Plot.colorSpectrum()
                        colors = Plot.colorSpectrum(130)
                        finecolors = Plot.colorSpectrum(250)
                        colors100.reverse()
                        colors.reverse()
                        finecolors.reverse()

                        scaleFont=pid.Font(ttf="tahoma",size=10,bold=0)

                        self.clusterChecked = fd.formdata.getvalue('clusterCheck', '')


                        if not self.clusterChecked: #XZ: this part is for original order
                                for i in range(len(names)):
                                        neworder.append((xoffset+20*(i+1), i))

                                canvas = pid.PILCanvas(size=(80+NNN*20+240,80+ self.topHeight +5+5+strWidth+nLoci*cellHeight+80+20*cellHeight))

                                self.drawTraitNameBottom(canvas,names,yoffset,neworder,strWidth)
                        else: #XZ: this part is to cluster traits
                                self.topHeight = 400
                                canvas = pid.PILCanvas(size=(80+NNN*20+240,80+ self.topHeight +5+5+strWidth+nLoci*cellHeight+80+20*cellHeight))

                                corArray = [([0] * (NNN))[:] for i in range(NNN)]

                                nnCorr = len(fd.strainlist)

                                #XZ, 08/04/2009: I commented out pearsonArray, spearmanArray
                                for i, thisTrait in enumerate(traitList):
                                    names1 = [thisTrait.db.name, thisTrait.name, thisTrait.cellid]
                                    for j, thisTrait2 in enumerate(traitList):
                                            names2 = [thisTrait2.db.name, thisTrait2.name, thisTrait2.cellid]
                                            if j < i:
                                                    corr,nOverlap = webqtlUtil.calCorrelation(traitDataList[i],traitDataList[j],nnCorr)
                                                    if (1-corr) < 0:
                                                            distance = 0.0
                                                    else:
                                                            distance = 1-corr
                                                    corArray[i][j] = distance
                                                    corArray[j][i] = distance
                                            elif j == i:
                                                    corArray[i][j] = 0.0
                                            else:
                                                    pass

                                #XZ, 7/29/2009: The parameter d has info of cluster (group member and distance). The format of d is tricky. Print it out to see it's format.
                                d = slink.slink(corArray)

                                #XZ, 7/29/2009: Attention: The 'neworder' is changed by the 'draw' function
                                #XZ, 7/30/2009: Only toppos[1][0] and top[1][1] are used later. Then what toppos[0] is used for? 
                                toppos = self.draw(canvas,names,d,xoffset,yoffset,neworder)
                                self.drawTraitNameTop(canvas,names,yoffset,neworder,strWidth)

                                #XZ, 7/29/2009: draw the top vertical line
                                canvas.drawLine(toppos[1][0],toppos[1][1],toppos[1][0],yoffset)

                                #XZ: draw string 'distance = 1-r'
                                canvas.drawString('distance = 1-r',neworder[-1][0] + 50, self.topHeight*3/4,font=self.labelFont,angle=90)

                                #draw Scale
                                scaleFont=pid.Font(ttf="tahoma",size=10,bold=0)
                                x = neworder[-1][0]
                                canvas.drawLine(x+5, self.topHeight+yoffset, x+5, yoffset, color=pid.black)
                                y = 0
                                while y <=2:
                                        canvas.drawLine(x+5, self.topHeight*y/2.0+yoffset, x+10, self.topHeight*y/2.0+yoffset)
                                        canvas.drawString('%2.1f' % (2-y), x+12, self.topHeight*y/2.0+yoffset, font=scaleFont)
                                        y += 0.5


                        chrname = 0
                        chrnameFont=pid.Font(ttf="tahoma",size=24,bold=0)
                        Ncol = 0

                        gifmap = HT.Map(name='traitMap')

                        nearestMarkers = self.getNearestMarker(traitList, fd.genotype)

                        # import cPickle
                        sessionfile = fd.formdata.getvalue("session")

                        if sessionfile:
                                fp = open(os.path.join(webqtlConfig.TMPDIR, sessionfile + '.session'), 'rb')
                                permData = cPickle.load(fp)
                                fp.close()
                        else:
                                permData = {}

                        #XZ, 7/31/2009: This for loop is to generate the heatmap
                        #XZ: draw trait by trait instead of marker by marker
                        for order in neworder:
                                #startHeight = 40+400+5+5+strWidth
                                startHeight = self.topHeight + 40+5+5+strWidth
                                startWidth = order[0]-5
                                if Ncol and Ncol % 5 == 0:
                                        drawStartPixel = 8
                                else:
                                        drawStartPixel = 9

                                tempVal = traitDataList[order[1]]
                                _vals = []
                                _strains = [] 
                                for i in range(len(fd.strainlist)):
                                        if tempVal[i] != None:
                                                _strains.append(fd.strainlist[i])
                                                _vals.append(tempVal[i])

                                qtlresult = fd.genotype.regression(strains = _strains, trait = _vals)

                                if sessionfile:
                                        LRSArray = permData[str(traitList[order[1]])]
                                else:
                                        LRSArray = fd.genotype.permutation(strains = _strains, trait = _vals, nperm = 1000)
                                        permData[str(traitList[order[1]])] = LRSArray

                                sugLRS = LRSArray[369]
                                sigLRS = LRSArray[949]
                                prechr = 0
                                chrstart = 0
                                nearest = nearestMarkers[order[1]]
                                midpoint = []

                                for item in qtlresult:
                                        if item.lrs > webqtlConfig.MAXLRS:
                                                adjustlrs = webqtlConfig.MAXLRS
                                        else:
                                                adjustlrs = item.lrs

                                        if item.locus.chr != prechr:
                                                if prechr:
                                                        canvas.drawRect(startWidth-drawStartPixel, startHeight, startWidth+10, startHeight+3,edgeColor=pid.white, edgeWidth=0, fillColor=pid.white)
                                                        startHeight+= 3
                                                        if not chrname:
                                                                canvas.drawString(prechr,xoffset-20,(chrstart+startHeight)/2,font = chrnameFont,color=pid.dimgray)
                                                prechr = item.locus.chr
                                                chrstart = startHeight
                                        if self.colorScheme == '0':
                                                if adjustlrs <= sugLRS:
                                                        colorIndex = int(65*adjustlrs/sugLRS)
                                                else:
                                                        colorIndex = int(65 + 35*(adjustlrs-sugLRS)/(sigLRS-sugLRS))
                                                if colorIndex > 99:
                                                        colorIndex = 99
                                                colorIndex = colors100[colorIndex]
                                        elif self.colorScheme == '1':
                                                sugLRS = LRSArray[369]/2.0
                                                if adjustlrs <= sugLRS:
                                                        colorIndex = BWs[20+int(50*adjustlrs/sugLRS)]
                                                else:
                                                        if item.additive > 0:
                                                                colorIndex = int(80 + 50*(adjustlrs-sugLRS)/(sigLRS-sugLRS))
                                                        else:
                                                                colorIndex = int(50 - 50*(adjustlrs-sugLRS)/(sigLRS-sugLRS))
                                                        if colorIndex > 129:
                                                                colorIndex = 129
                                                        if colorIndex < 0:
                                                                colorIndex = 0
                                                        colorIndex = colors[colorIndex]
                                        elif self.colorScheme == '2':
                                                if item.additive > 0:
                                                        colorIndex = int(150 + 100*(adjustlrs/sigLRS))
                                                else:
                                                        colorIndex = int(100 - 100*(adjustlrs/sigLRS))
                                                if colorIndex > 249:
                                                        colorIndex = 249
                                                if colorIndex < 0:
                                                                colorIndex = 0
                                                colorIndex = finecolors[colorIndex]
                                        else:
                                                colorIndex = pid.white

                                        if startHeight > 1:
                                                canvas.drawRect(startWidth-drawStartPixel, startHeight, startWidth+10, startHeight+cellHeight,edgeColor=colorIndex, edgeWidth=0, fillColor=colorIndex)
                                        else:
                                                canvas.drawLine(startWidth-drawStartPixel, startHeight, startWidth+10, startHeight, Color=colorIndex)

                                        if item.locus.name == nearest:
                                                midpoint = [startWidth,startHeight-5]
                                        startHeight+=cellHeight

                                #XZ, map link to trait name and band
                                COORDS = "%d,%d,%d,%d" %(startWidth-drawStartPixel,self.topHeight+40,startWidth+10,startHeight)
                                HREF = "javascript:showDatabase2('%s','%s','%s');" % (traitList[order[1]].db.name, traitList[order[1]].name, traitList[order[1]].cellid)
                                Areas = HT.Area(shape='rect',coords=COORDS,href=HREF, title='%s' % names[order[1]])
                                gifmap.areas.append(Areas)

                                if midpoint:
                                        traitPixel = ((midpoint[0],midpoint[1]),(midpoint[0]-6,midpoint[1]+12),(midpoint[0]+6,midpoint[1]+12))
                                        canvas.drawPolygon(traitPixel,edgeColor=pid.black,fillColor=pid.orange,closed=1)

                                if not chrname:
                                        canvas.drawString(prechr,xoffset-20,(chrstart+startHeight)/2,font = chrnameFont,color=pid.dimgray)
                                chrname = 1
                                Ncol += 1


                        #draw Spectrum
                        startSpect = neworder[-1][0] + 30
                        startHeight = self.topHeight + 40+5+5+strWidth

                        if self.colorScheme == '0':
                                for i in range(100):
                                        canvas.drawLine(startSpect+i,startHeight+20,startSpect+i,startHeight+40,color=colors100[i])
                                scaleFont=pid.Font(ttf="tahoma",size=10,bold=0)
                                canvas.drawLine(startSpect,startHeight+45,startSpect,startHeight+39,color=pid.black)
                                canvas.drawString('LRS = 0',startSpect,startHeight+55,font=scaleFont)
                                canvas.drawLine(startSpect+64,startHeight+45,startSpect+64,startHeight+39,color=pid.black)
                                canvas.drawString('Suggestive LRS',startSpect+64,startHeight+55,font=scaleFont)
                                canvas.drawLine(startSpect+99,startHeight+45,startSpect+99,startHeight+39,color=pid.black)
                                canvas.drawString('Significant LRS',startSpect+105,startHeight+40,font=scaleFont)
                        elif self.colorScheme == '1':
                                for i in range(50):
                                        canvas.drawLine(startSpect+i,startHeight,startSpect+i,startHeight+40,color=BWs[20+i])
                                for i in range(50,100):
                                        canvas.drawLine(startSpect+i,startHeight,startSpect+i,startHeight+20,color=colors[100-i])
                                        canvas.drawLine(startSpect+i,startHeight+20,startSpect+i,startHeight+40,color=colors[30+i])

                                canvas.drawLine(startSpect,startHeight+45,startSpect,startHeight+39,color=pid.black)
                                canvas.drawString('LRS = 0',startSpect,startHeight+60,font=scaleFont)
                                canvas.drawLine(startSpect+50,startHeight+45,startSpect+50,startHeight+39,color=pid.black)
                                canvas.drawString('0.5*Suggestive LRS',startSpect+50,startHeight+ 60,font=scaleFont)
                                canvas.drawLine(startSpect+99,startHeight+45,startSpect+99,startHeight+39,color=pid.black)
                                canvas.drawString('Significant LRS',startSpect+105,startHeight+50,font=scaleFont)
                                textFont=pid.Font(ttf="verdana",size=18,bold=0)
                                canvas.drawString('%s +' % fd.ppolar,startSpect+120,startHeight+ 35,font=textFont,color=pid.red)
                                canvas.drawString('%s +' % fd.mpolar,startSpect+120,startHeight+ 15,font=textFont,color=pid.blue)
                        elif self.colorScheme == '2':
                                for i in range(100):
                                        canvas.drawLine(startSpect+i,startHeight,startSpect+i,startHeight+20,color=finecolors[100-i])
                                        canvas.drawLine(startSpect+i,startHeight+20,startSpect+i,startHeight+40,color=finecolors[150+i])

                                canvas.drawLine(startSpect,startHeight+45,startSpect,startHeight+39,color=pid.black)
                                canvas.drawString('LRS = 0',startSpect,startHeight+60,font=scaleFont)
                                canvas.drawLine(startSpect+99,startHeight+45,startSpect+99,startHeight+39,color=pid.black)
                                canvas.drawString('Significant LRS',startSpect+105,startHeight+50,font=scaleFont)
                                textFont=pid.Font(ttf="verdana",size=18,bold=0)
                                canvas.drawString('%s +' % fd.ppolar,startSpect+120,startHeight+ 35,font=textFont,color=pid.red)
                                canvas.drawString('%s +' % fd.mpolar,startSpect+120,startHeight+ 15,font=textFont,color=pid.blue)


                        filename= webqtlUtil.genRandStr("Heatmap_")
                        canvas.save(webqtlConfig.IMGDIR+filename, format='png')
                        img2=HT.Image('/image/'+filename+'.png',border=0,usemap='#traitMap')
                        imgUrl = 'Right-click or control-click on the link to download this graph as a <a href="/image/%s.png" class="normalsize" target="_blank">PNG file</a>' % filename

                        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':fd.RISet+"Geno",'CellID':'_','RISet':fd.RISet,'searchResult':string.join(self.searchResult,'\t')}
                        if fd.incparentsf1:
                                hddn['incparentsf1']='ON'
                        for key in hddn.keys():
                                form.append(HT.Input(name=key, value=hddn[key], type='hidden'))

                        heatmap = HT.Input(type='button' ,name='mintmap',value='Redraw QTL Heatmap', onClick="databaseFunc(this.form,'heatmap');",Class="button")
                        spects = {'0':'Single Spectrum','1':'Grey + Blue + Red','2':'Blue + Red'}
                        schemeMenu = HT.Select(name='colorScheme')
                        schemeMenu.append(('Single Spectrum',0))
                        schemeMenu.append(('Grey + Blue + Red',1))
                        schemeMenu.append(('Blue + Red',2))
                        schemeMenu.selected.append(spects[self.colorScheme])

                        clusterCheck= HT.Input(type='checkbox', Class='checkbox', name='clusterCheck',checked=0)
                        targetDescriptionCheck = HT.Input(type='checkbox', Class='checkbox', name='targetDescriptionCheck',checked=0)

                        form.append(gifmap,schemeMenu, heatmap, HT.P(), clusterCheck, '  Cluster traits  ', targetDescriptionCheck, '  Add description', HT.P(),img2, HT.P(), imgUrl)

                        if not sessionfile:
                                filename = webqtlUtil.generate_session()
                                webqtlUtil.dump_session(permData, os.path.join(webqtlConfig.TMPDIR, filename +'.session'))
                                sessionfile=filename

                        form.append(HT.Input(name='session', value=sessionfile, type='hidden'))

                        heatmapHelp = HT.Input(type='button' ,name='heatmapHelpButton',value='Info', onClick="openNewWin('/heatmap.html');",Class="button")

                        heatmapHeading = HT.Paragraph('QTL Heatmap ', heatmapHelp, Class="title")

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

                        self.dict['body'] = str(TD_LR)
	def insertUpdateCheck(self, fd, warning= ""):
		self.dict['title'] = "%s GeneWiki Entry for %s" % (self.action.title(), self.symbol)
		#mailsrch = re.compile('([\w\-][\w\-\.]*@[\w\-][\w\-\.]+[a-zA-Z]{1,4})([\s,;])*')
		mailsrch = re.compile('([\w\-][\w\-\.]*)@([\w\-\.]+)\.([a-zA-Z]{1,4})([\s,;])*')
		httpsrch = re.compile('((?:http|ftp|gopher|file)://(?:[^ \n\r<\)]+))([\s,;])*')
		if not self.comment or not self.email:
			heading = self.dict['title']
			detail = ["Please don't leave text field or email field empty."]
			self.error(heading=heading,detail=detail,error="Error")
			return
		if self.action == 'update' and not self.reason:
			heading = self.dict['title']
			detail = ["Please submit your reason for this modification."]
			self.error(heading=heading,detail=detail,error="Error")
			return
		if len(self.comment) >500:
			heading = self.dict['title']
			detail = ["Your entry is more than 500 characters."]
			self.error(heading=heading,detail=detail,error="Error")
			return
		if self.email and re.sub(mailsrch, "", self.email) != "":
			heading = self.dict['title']
			detail = ["The format of your email address is incorrect."]
			self.error(heading=heading,detail=detail,error="Error")
			return
		
		if self.weburl == "http://":
			self.weburl = ""
		
		if self.weburl and re.sub(httpsrch, "", self.weburl) != "":
			heading = self.dict['title']
			detail = ["The format of web resource link is incorrect."]
			self.error(heading=heading,detail=detail,error="Error")
			return
		
		if self.pubmedid:
			try:
				test = map(int, string.split(self.pubmedid))
			except:
				heading = self.dict['title']
				detail = ["PubMed IDs can only be integers."]
				self.error(heading=heading,detail=detail,error="Error")
				return
		
		form = HT.Form(cgi= os.path.join(webqtlConfig.CGIDIR, webqtlConfig.SCRIPTFILE), name='addgenerif',submit=HT.Input(type='hidden'))
		recordInfoTable = HT.TableLite(border=0, cellspacing=1, cellpadding=5,align="center")
		
		addButton = HT.Input(type='submit',name='submit', value='%s GeneWiki Entry' % self.action.title(),Class="button")
		hddn = {'curStatus':'insertResult', 'FormID':'geneWiki', 'symbol':self.symbol, 
			'comment':self.comment, 'email':self.email, 'species':self.species, 
			'action':self.action, 'reason':self.reason}
		if self.Id:
			hddn['Id']=self.Id
		
		formBody = HT.TableLite()
		
		formBody.append(HT.TR(
			HT.TD(HT.Strong("Species: ")), 
			HT.TD(width=10), 
			HT.TD(string.split(self.species, ":")[0])
		))
		if self.pubmedid:
			try:
				formBody.append(HT.TR(
					HT.TD(HT.Strong("PubMed IDs: ")), 
					HT.TD(width=10), 
					HT.TD(self.pubmedid)
				))
				hddn['pubmedid'] = self.pubmedid
			except:
				pass
		if self.weburl:
			try:
				formBody.append(HT.TR(
					HT.TD(HT.Strong("Web URL: ")), 
					HT.TD(width=10), 
					HT.TD(HT.Href(text=self.weburl, url=self.weburl, Class='fwn'))
				))
				hddn['weburl'] = self.weburl
			except:
				pass
		formBody.append(HT.TR(
			HT.TD(HT.Strong("Gene Notes: ")), 
			HT.TD(width=10), 
			HT.TD(self.comment)
		))
		formBody.append(HT.TR(
			HT.TD(HT.Strong("Email: ")), 
			HT.TD(width=10), 
			HT.TD(self.email)
		))
		if self.initial:
			formBody.append(HT.TR(
				HT.TD(HT.Strong("Initial: ")), 
				HT.TD(width=10), 
				HT.TD(self.initial)
			))
			hddn['initial'] = self.initial
		
		if self.genecategory:
			cTD = HT.TD()
			if type(self.genecategory) == type(""):
				self.genecategory = string.split(self.genecategory)
			self.cursor.execute("Select Id, Name from GeneCategory where Id in (%s) order by Name " % string.join(self.genecategory, ', '))
			results = self.cursor.fetchall()
			for item in results:
				cTD.append(item[1], HT.BR())
				
			formBody.append(HT.TR(
				HT.TD(HT.Strong("Category: ")), 
				HT.TD(width=10), 
				cTD
			))
			hddn['genecategory'] = string.join(self.genecategory, " ")
			
		formBody.append(HT.TR(
			HT.TD(
				HT.BR(), HT.BR(), 
				HT.Div("For security reasons, enter the code (case insensitive) in the image below to finalize your submission"), HT.BR(), 
				addButton, HT.Input(type="password", size = 25, name="password"), 
			colspan=3)
		))
		
		
		code = webqtlUtil.genRandStr(length=5, chars="abcdefghkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789")
		filename= webqtlUtil.genRandStr("Sec_")
		hddn['filename'] = filename 
		securityCanvas = pid.PILCanvas(size=(300,100))
		Plot.plotSecurity(securityCanvas, text=code)
		
		os.system("touch %s_.%s" % (os.path.join(webqtlConfig.IMGDIR,filename), code))
		securityCanvas.save(os.path.join(webqtlConfig.IMGDIR,filename), format='png')
		
		formBody.append(HT.TR(
			HT.TD(HT.Image("/image/"+filename+".png"), colspan=3)
		))
		
		hddn['filename'] = filename 
		TD_LR = HT.TD(valign="top", bgcolor="#eeeeee")
		title = HT.Paragraph("%s GeneWiki Entry for %s" % (self.action.title(), self.symbol), Class="title")
		
		form.append(HT.P(), HT.Blockquote(formBody))
		
		for key in hddn.keys():
			form.append(HT.Input(name=key, value=hddn[key], type='hidden'))
			
		TD_LR.append(title, HT.Blockquote(warning, Id="red"), form)
		
		self.dict['body'] = TD_LR		
	def __init__(self, fd):

		LRSFullThresh = 30
		LRSInteractThresh = 25
		maxPlotSize = 1000
		mainfmName = webqtlUtil.genRandStr("fm_")

		templatePage.__init__(self, fd)

		self.dict['title'] = 'Pair-Scan Plot'

		if not self.openMysql():
			return

		TD_LR = HT.TD(height=200,width="100%",bgColor='#eeeeee')
		vals = fd.formdata.getvalue('idata')
		vals = map(float,string.split(vals,','))
		strains = fd.formdata.getvalue('istrain')
		strains = string.split(strains,',')
		Chr_A = int(fd.formdata.getvalue('Chr_A'))
		Chr_B = int(fd.formdata.getvalue('Chr_B'))
		if len(vals) > webqtlConfig.KMININFORMATIVE:
			d = direct.exhaust(webqtlConfig.GENODIR, vals, strains, fd.RISet, Chr_A, Chr_B)#XZ, 08/14/2008: add module name webqtlConfig
			chrsInfo = d[2]
			longerChrLen = max(chrsInfo[Chr_A][0], chrsInfo[Chr_B][0])
			shorterChrlen = min(chrsInfo[Chr_A][0], chrsInfo[Chr_B][0])

			plotHeight = int(chrsInfo[Chr_B][0]*maxPlotSize/longerChrLen)
			plotWidth = int(chrsInfo[Chr_A][0]*maxPlotSize/longerChrLen)


			xLeftOffset = 200
			xRightOffset = 40
			yTopOffset = 40
			yBottomOffset = 200
			colorAreaWidth = 120

			canvasHeight = plotHeight + yTopOffset + yBottomOffset
			canvasWidth = plotWidth + xLeftOffset + xRightOffset + colorAreaWidth


			canvas = pid.PILCanvas(size=(canvasWidth,canvasHeight))
			plotScale = plotHeight/chrsInfo[Chr_B][0]

			rectInfo = d[1]
			finecolors = Plot.colorSpectrum(250)
			finecolors.reverse()
			#draw LRS Full
			for item in rectInfo:
				LRSFull,LRSInteract,LRSa,LRSb,chras,chram,chrae,chrbs,chrbm,chrbe,chra,chrb,flanka,flankb = item
				if Chr_A > Chr_B:
					colorIndex = int(LRSFull *250 /LRSFullThresh)
				else:
					colorIndex = int(LRSInteract *250 /LRSInteractThresh)
				if colorIndex >= 250:
					colorIndex = 249
				elif colorIndex < 0:
					colorIndex = 0
				dcolor = finecolors[colorIndex]
				if chra != chrb or (abs(chrbe - chrae) > 10 and abs(chrbs - chras) > 10):
					canvas.drawRect(xLeftOffset+chras*plotScale,yTopOffset+plotHeight- \
					chrbs*plotScale,xLeftOffset+chrae*plotScale,yTopOffset+plotHeight- \
					chrbe*plotScale,edgeColor=dcolor,fillColor=dcolor,edgeWidth = 0)
				elif chrbs >= chras:
					canvas.drawPolygon([(xLeftOffset+chras*plotScale,yTopOffset+plotHeight-chrbs*plotScale),\
					(xLeftOffset+chras*plotScale,yTopOffset+plotHeight-chrbe*plotScale),\
					(xLeftOffset+chrae*plotScale,yTopOffset+plotHeight-chrbe*plotScale)],\
					edgeColor=dcolor,fillColor=dcolor,edgeWidth = 0,closed =1)
				else:
					canvas.drawPolygon([(xLeftOffset+chras*plotScale,yTopOffset+plotHeight-chrbs*plotScale),\
					(xLeftOffset+chrae*plotScale,yTopOffset+plotHeight-chrbs*plotScale), \
					(xLeftOffset+chrae*plotScale,yTopOffset+plotHeight-chrbe*plotScale)], \
					edgeColor=dcolor,fillColor=dcolor,edgeWidth = 0,closed =1)

			labelFont=pid.Font(ttf="verdana",size=24,bold=0)
			chrName = "chromosome %s" % chrsInfo[Chr_A][1]
			canvas.drawString(chrName,xLeftOffset + (plotWidth - canvas.stringWidth(chrName,font=labelFont))/2,\
			yTopOffset+plotHeight+ 170,font=labelFont)
			chrName = "chromosome %s" % chrsInfo[Chr_B][1]
			canvas.drawString(chrName, 30, yTopOffset +(canvas.stringWidth(chrName,font=labelFont) + plotHeight)/2,\
			font=labelFont, angle = 90)
			if Chr_A == Chr_B:
				infoStr = "minimum distance = 10 cM"
				infoStrWidth = canvas.stringWidth(infoStr,font=labelFont)
				canvas.drawString(infoStr, xLeftOffset + (plotWidth-infoStrWidth*0.707)/2, yTopOffset + \
				(plotHeight+infoStrWidth*0.707)/2,font=labelFont, angle = 45, color=pid.red)

			labelFont=pid.Font(ttf="verdana",size=12,bold=0)
			gifmap = HT.Map(name='markerMap')

			lineColor = pid.lightblue
			#draw ChrA Loci
			ChrAInfo = d[3]
			preLpos = -1
			i = 0
			for item in ChrAInfo:
				Lname,Lpos = item
				if Lpos != preLpos:
					i += 1
				preLpos = Lpos
			stepA = float(plotWidth)/i

			offsetA = -stepA
			LRectWidth = 10
			LRectHeight = 3
			i = 0
			preLpos = -1
			for item in ChrAInfo:
				Lname,Lpos = item
				if Lpos != preLpos:
					offsetA += stepA
					differ = 1
				else:
					differ = 0
				preLpos = Lpos
				Lpos *= plotScale
				Zorder = i % 5
				"""
				LStrWidth = canvas.stringWidth(Lname,font=labelFont)
				canvas.drawString(Lname,xLeftOffset+offsetA+4,yTopOffset+plotHeight+140,\
				font=labelFont,color=pid.blue,angle=90)
				canvas.drawLine(xLeftOffset+Lpos,yTopOffset+plotHeight,xLeftOffset+offsetA,\
				yTopOffset+plotHeight+25,color=lineColor)
				canvas.drawLine(xLeftOffset+offsetA,yTopOffset+plotHeight+25,xLeftOffset+offsetA,\
				yTopOffset+plotHeight+140-LStrWidth,color=lineColor)
				COORDS="%d,%d,%d,%d"%(xLeftOffset+offsetA+4,yTopOffset+plotHeight+140,\
				xLeftOffset+offsetA-6,yTopOffset+plotHeight+140-LStrWidth)
				"""
				if differ:
					canvas.drawLine(xLeftOffset+Lpos,yTopOffset+plotHeight,xLeftOffset+offsetA,\
					yTopOffset+plotHeight+25,color=lineColor)
					canvas.drawLine(xLeftOffset+offsetA,yTopOffset+plotHeight+25,xLeftOffset+offsetA,\
					yTopOffset+plotHeight+80+Zorder*(LRectWidth+3),color=lineColor)
					rectColor = pid.orange
				else:
					canvas.drawLine(xLeftOffset+offsetA, yTopOffset+plotHeight+80+Zorder*(LRectWidth+3)-3,\
					xLeftOffset+offsetA, yTopOffset+plotHeight+80+Zorder*(LRectWidth+3),color=lineColor)
					rectColor = pid.deeppink
				canvas.drawRect(xLeftOffset+offsetA, yTopOffset+plotHeight+80+Zorder*(LRectWidth+3),\
					xLeftOffset+offsetA-LRectHeight,yTopOffset+plotHeight+80+Zorder*(LRectWidth+3)+LRectWidth,\
					edgeColor=rectColor,fillColor=rectColor,edgeWidth = 0)
				COORDS="%d,%d,%d,%d"%(xLeftOffset+offsetA, yTopOffset+plotHeight+80+Zorder*(LRectWidth+3),\
					xLeftOffset+offsetA-LRectHeight,yTopOffset+plotHeight+80+Zorder*(LRectWidth+3)+LRectWidth)
				HREF="javascript:showTrait('%s','%s');" % (mainfmName, Lname)
				Areas=HT.Area(shape='rect',coords=COORDS,href=HREF, title="Locus : " + Lname)
				gifmap.areas.append(Areas)
				i += 1
				#print (i , offsetA, Lname, Lpos, preLpos)
				#print "<BR>"

			#draw ChrB Loci
			ChrBInfo = d[4]
			preLpos = -1
			i = 0
			for item in ChrBInfo:
				Lname,Lpos = item
				if Lpos != preLpos:
					i += 1
				preLpos = Lpos
			stepB = float(plotHeight)/i

			offsetB = -stepB
			LRectWidth = 10
			LRectHeight = 3
			i = 0
			preLpos = -1
			for item in ChrBInfo:
				Lname,Lpos = item
				if Lpos != preLpos:
					offsetB += stepB
					differ = 1
				else:
					differ = 0
				preLpos = Lpos
				Lpos *= plotScale
				Zorder = i % 5
				Lname,Lpos = item
				Lpos *= plotScale
				"""
				LStrWidth = canvas.stringWidth(Lname,font=labelFont)
				canvas.drawString(Lname, 45,yTopOffset+plotHeight-offsetB+4,font=labelFont,color=pid.blue)
				canvas.drawLine(45+LStrWidth,yTopOffset+plotHeight-offsetB,xLeftOffset-25,\
				yTopOffset+plotHeight-offsetB,color=lineColor)
				canvas.drawLine(xLeftOffset-25,yTopOffset+plotHeight-offsetB,xLeftOffset,\
				yTopOffset+plotHeight-Lpos,color=lineColor)
				COORDS = "%d,%d,%d,%d" %(45,yTopOffset+plotHeight-offsetB+4,45+LStrWidth,\
				yTopOffset+plotHeight-offsetB-6)
				"""
				if differ:
					canvas.drawLine(xLeftOffset,yTopOffset+plotHeight-Lpos, xLeftOffset-25,\
					yTopOffset+plotHeight-offsetB,color=lineColor)
					canvas.drawLine(xLeftOffset -25, yTopOffset+plotHeight-offsetB, \
					xLeftOffset-80 -Zorder*(LRectWidth+3),yTopOffset+plotHeight-offsetB, color=lineColor)
					rectColor = pid.orange
				else:
					canvas.drawLine(xLeftOffset -80 -Zorder*(LRectWidth+3)+3, yTopOffset+plotHeight-offsetB, \
					xLeftOffset-80 -Zorder*(LRectWidth+3),yTopOffset+plotHeight-offsetB, color=lineColor)
					rectColor = pid.deeppink
				HREF = "javascript:showTrait('%s','%s');" % (mainfmName, Lname)
				canvas.drawRect(xLeftOffset-80 -Zorder*(LRectWidth+3),yTopOffset+plotHeight-offsetB,\
					xLeftOffset-80 -Zorder*(LRectWidth+3)-LRectWidth,yTopOffset+plotHeight-offsetB +LRectHeight,\
					edgeColor=rectColor,fillColor=rectColor,edgeWidth = 0)
				COORDS="%d,%d,%d,%d"%(xLeftOffset-80 -Zorder*(LRectWidth+3),yTopOffset+plotHeight-offsetB,\
					xLeftOffset-80 -Zorder*(LRectWidth+3)-LRectWidth,yTopOffset+plotHeight-offsetB +LRectHeight)
				Areas=HT.Area(shape='rect',coords=COORDS,href=HREF, title="Locus : " + Lname)
				gifmap.areas.append(Areas)
				i += 1

			canvas.drawRect(xLeftOffset, yTopOffset, xLeftOffset+plotWidth, yTopOffset+plotHeight,edgeColor=pid.black)

			#draw spectrum
			i = 0
			labelFont=pid.Font(ttf="tahoma",size=14,bold=0)
			middleoffsetX = 80
			for dcolor in finecolors:
				canvas.drawLine(xLeftOffset+ plotWidth +middleoffsetX-15 , plotHeight + yTopOffset - i, \
				xLeftOffset+ plotWidth +middleoffsetX+15 , plotHeight + yTopOffset - i, color=dcolor)
				if i % 50 == 0:
					if Chr_A >= Chr_B:
						canvas.drawLine(xLeftOffset+ plotWidth +middleoffsetX+15 ,plotHeight + yTopOffset - i, \
						xLeftOffset+ plotWidth +middleoffsetX+20,plotHeight + yTopOffset - i, color=pid.black)
						canvas.drawString('%d' % int(LRSFullThresh*i/250.0),xLeftOffset+ plotWidth +middleoffsetX+22,\
						plotHeight + yTopOffset - i +5, font = labelFont,color=pid.black)
					if Chr_A <= Chr_B:
						canvas.drawLine(xLeftOffset+ plotWidth +middleoffsetX-15 ,plotHeight + yTopOffset - i, \
						xLeftOffset+ plotWidth +middleoffsetX-20,plotHeight + yTopOffset - i, color=pid.black)
						canvas.drawString('%d' % int(LRSInteractThresh*i/250.0),xLeftOffset+plotWidth+middleoffsetX-40,\
						plotHeight + yTopOffset - i +5, font = labelFont,color=pid.black)
				i += 1
			#draw spectrum label
			labelFont2=pid.Font(ttf="verdana",size=20,bold=0)
			if i % 50 == 0:
				i -= 1
				if Chr_A >= Chr_B:
					canvas.drawLine(xLeftOffset+ plotWidth +middleoffsetX+15 ,plotHeight + yTopOffset - i, \
					xLeftOffset+ plotWidth +middleoffsetX+20,plotHeight + yTopOffset - i, color=pid.black)
					canvas.drawString('%d' % int(LRSFullThresh*(i+1)/250.0),xLeftOffset+ plotWidth +middleoffsetX+22,\
					plotHeight + yTopOffset - i +5, font = labelFont,color=pid.black)
					canvas.drawString('LRS Full',xLeftOffset+ plotWidth +middleoffsetX+50,plotHeight + yTopOffset, \
					font = labelFont2,color=pid.dimgray,angle=90)
				if Chr_A <= Chr_B:
					canvas.drawLine(xLeftOffset+ plotWidth +middleoffsetX-15 ,plotHeight + yTopOffset - i, \
					xLeftOffset+ plotWidth +middleoffsetX-20,plotHeight + yTopOffset - i, color=pid.black)
					canvas.drawString('%d' % int(LRSInteractThresh*(i+1)/250.0),xLeftOffset+ plotWidth+middleoffsetX-40,\
					plotHeight + yTopOffset - i +5, font = labelFont,color=pid.black)
					canvas.drawString('LRS Interaction',xLeftOffset+ plotWidth +middleoffsetX-50,\
					plotHeight + yTopOffset, font = labelFont2,color=pid.dimgray,angle=90)

			filename= webqtlUtil.genRandStr("Pair_")
			canvas.save(webqtlConfig.IMGDIR+filename, format='png')
			img2=HT.Image('/image/'+filename+'.png',border=0,usemap='#markerMap')

			main_title = HT.Paragraph("Pair-Scan Results: Chromosome Pair")
			main_title.__setattr__("class","title")
			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','ProbeSetID':'_','database':fd.RISet+"Geno",'CellID':'_','RISet':fd.RISet, 'incparentsf1':'on'}
			if fd.incparentsf1:
				hddn['incparentsf1']='ON'
			for key in hddn.keys():
				form.append(HT.Input(name=key, value=hddn[key], type='hidden'))
			form.append(img2,gifmap)
			TD_LR.append(main_title, HT.Center(form), HT.P())
		else:
			heading = "Direct Plot"
			detail = ['Fewer than %d strain data were entered for %s data set. No statitical analysis has been attempted.'\
			 % (webqtlConfig.KMININFORMATIVE, fd.RISet)]
			self.error(heading=heading,detail=detail)
			return
		self.dict['body'] = str(TD_LR)