aboutsummaryrefslogtreecommitdiff
path: root/web/webqtl/networkGraph/networkGraphPage.py
blob: fb4021f0fc1a010ab1e00b0655f19d5fb4817f45 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
# Copyright (C) University of Tennessee Health Science Center, Memphis, TN.
#
# This program is free software: you can redistribute it and/or modify it
# under the terms of the GNU Affero General Public License
# as published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
# See the GNU Affero General Public License for more details.
#
# This program is available from Source Forge: at GeneNetwork Project
# (sourceforge.net/projects/genenetwork/).
#
# Contact Drs. Robert W. Williams and Xiaodong Zhou (2010)
# at rwilliams@uthsc.edu and xzhou15@uthsc.edu
#
#
#
# This module is used by GeneNetwork project (www.genenetwork.org)
#
# Created by GeneNetwork Core Team 2010/08/10
#
# Last updated by NL 2010/02/11

#!/usr/bin/python
# networkGraph.py
# Author: Stephen Pitts
# 6/2/2004
#
# a script to take a matrix of data from a WebQTL job and generate a
# graph using the neato package from GraphViz
#
# See graphviz for documentation of the parameters
#


#from mod_python import apache, util, Cookie
#import cgi
import tempfile
import os
import time
import sys
import cgitb
import string

from htmlgen import HTMLgen2 as HT

from base.templatePage import templatePage
import networkGraphUtils
from base import webqtlConfig
from utility import webqtlUtil
from base.webqtlTrait import webqtlTrait
import compareCorrelates.trait as smpTrait
from GraphPage import GraphPage
from networkGraphPageBody import networkGraphPageBody
from correlationMatrix.tissueCorrelationMatrix import tissueCorrelationMatrix

cgitb.enable()


class networkGraphPage(templatePage):

    def __init__(self,fd,InputData=None):

        templatePage.__init__(self, fd)

        if not self.openMysql():
            return
            
        if not fd.genotype:
            fd.readGenotype()
                
        self.searchResult = fd.formdata.getvalue('searchResult')

        self.tissueProbeSetFeezeId = "1" #XZ, Jan 03, 2010: currently, this dataset is "UTHSC Illumina V6.2 RankInv B6 D2 average CNS GI average (May 08)"
        TissueCorrMatrixObject = tissueCorrelationMatrix(tissueProbeSetFreezeId=self.tissueProbeSetFeezeId)

        if type("1") == type(self.searchResult):
            self.searchResult = string.split(self.searchResult, '\t')
        
        if (not self.searchResult or (len(self.searchResult) < 2)):
            heading = 'Network Graph'
            detail = ['You need to select at least two traits in order to generate Network Graph.']
            self.error(heading=heading,detail=detail)
            print 'Content-type: text/html\n'
            self.write()
            return
        
        if self.searchResult:
            if len(self.searchResult) > webqtlConfig.MAXCORR:
                heading = 'Network Graph'
                detail = ['In order to display Network Graph properly, Do not select more than %d traits for Network Graph.' % webqtlConfig.MAXCORR]
                self.error(heading=heading,detail=detail)
                print 'Content-type: text/html\n'
                self.write()
                return
            else:    
                pass
                
            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 = 'Network Graph'
            detail = [HT.Font('Error : ',color='red'),HT.Font('Error occurs while retrieving data from database.',color='black')]
            self.error(heading=heading,detail=detail)
            print 'Content-type: text/html\n'
            self.write()
            return

        NNN = len(traitList)
        
        if NNN < 2:
            templatePage.__init__(self, fd)
            heading = 'Network Graph'
            detail = ['You need to select at least two traits in order to generate a Network Graph']
            print 'Content-type: text/html\n'
            self.write()
            return
        else:
            pearsonArray = [([0] * (NNN))[:] for i in range(NNN)]
            spearmanArray = [([0] * (NNN))[:] for i in range(NNN)]
            GeneIdArray = []
            GeneSymbolList = [] #XZ, Jan 03, 2011: holds gene symbols for calculating tissue correlation
            traitInfoArray = []

            i = 0
            nnCorr = len(fd.strainlist)
            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)
                        pearsonArray[i][j] = corr
                        pearsonArray[j][i] = corr
                    elif j == i:
                        pearsonArray[i][j] = 1.0
                        spearmanArray[i][j] = 1.0
                    else:
                        corr,nOverlap = webqtlUtil.calCorrelationRank(traitDataList[i],traitDataList[j],nnCorr)
                        spearmanArray[i][j] = corr
                        spearmanArray[j][i] = corr
                    
                GeneId1 = None
                tmpSymbol = None
                if thisTrait.db.type == 'ProbeSet':
                    try:
                        GeneId1 = int(thisTrait.geneid)
                    except:
                        GeneId1 = 0
                    if thisTrait.symbol:
                        tmpSymbol = thisTrait.symbol.lower()
                GeneIdArray.append(GeneId1)
                GeneSymbolList.append(tmpSymbol)

            _traits = []
            _matrix = []

            for i in range(NNN):
                turl = webqtlConfig.CGIDIR + webqtlConfig.SCRIPTFILE + '?FormID=showDatabase&database=%s&ProbeSetID=%s' % (traitList[i].db.name, traitList[i].name)
                if traitList[i].cellid:
                    turl += "&CellID=%s" % traitList[i].cellid
                    
                if traitList[i].db.type == 'ProbeSet':
                    if traitList[i].symbol:
                        _symbol = traitList[i].symbol
                    else:
                        _symbol = 'unknown'
                elif traitList[i].db.type == 'Publish':
                    _symbol = traitList[i].name
                    if traitList[i].confidential:
                        if webqtlUtil.hasAccessToConfidentialPhenotypeTrait(privilege=self.privilege, userName=self.userName, authorized_users=traitList[i].authorized_users):
                            if traitList[i].post_publication_abbreviation:
                                _symbol = traitList[i].post_publication_abbreviation
                        else:
                            if traitList[i].pre_publication_abbreviation:
                                _symbol = traitList[i].pre_publication_abbreviation
                    else:
                        if traitList[i].post_publication_abbreviation:
                            _symbol = traitList[i].post_publication_abbreviation

                #XZ, 05/26/2009: Xiaodong add code for Geno data
                elif traitList[i].db.type == 'Geno':
                    _symbol = traitList[i].name
                else:
                    _symbol = traitList[i].description
                    #####if this trait entered by user
                    if _symbol.__contains__('entered'):
                        _symbol = _symbol[:_symbol.index('entered')]
                    #####if this trait generaged by genenetwork
                    elif _symbol.__contains__('generated'):
                        _symbol = _symbol[_symbol.rindex(':')+1:]
                
                newTrait = smpTrait.Trait(name=str(traitList[i]), href=turl, symbol=_symbol)
                newTrait.color = "black"
                _traits.append(newTrait)
                
                for j in range(i+1, NNN):
                    dataPoint = smpTrait.RawPoint(i, j)
                    dataPoint.spearman = spearmanArray[i][j]
                    dataPoint.pearson = pearsonArray[i][j]

                    #XZ: get literature correlation info.
                    if GeneIdArray[i] and GeneIdArray[j]:
                        if GeneIdArray[i] == GeneIdArray[j]:
                            dataPoint.literature = 1
                        else:
                            self.cursor.execute("SELECT Value from LCorrRamin3 WHERE (GeneId1 = %d and GeneId2 = %d) or (GeneId1 = %d and GeneId2 = %d)" % (GeneIdArray[i], GeneIdArray[j], GeneIdArray[j], GeneIdArray[i]))
                            try:    
                                dataPoint.literature = self.cursor.fetchone()[0]
                            except:
                                dataPoint.literature = 0
                    else:
                        dataPoint.literature = 0

                    #XZ: get tissue correlation info
                    if GeneSymbolList[i] and GeneSymbolList[j]:
                        dataPoint.tissue = 0
                        geneSymbolPair = []
                        geneSymbolPair.append(GeneSymbolList[i])
                        geneSymbolPair.append(GeneSymbolList[j])
                        corrArray,pvArray = TissueCorrMatrixObject.getCorrPvArrayForGeneSymbolPair(geneNameLst=geneSymbolPair)
                        if corrArray[1][0]:
                            dataPoint.tissue = corrArray[1][0]
                    else:
                        dataPoint.tissue = 0

                    _matrix.append(dataPoint)
        
            OrigDir = os.getcwd()

            sessionfile = fd.formdata.getvalue('session')
            
            inputFilename = fd.formdata.getvalue('inputFile')

            #If there is no sessionfile generate one and dump all matrix/trait values
            if not sessionfile:
                filename = webqtlUtil.generate_session()    
                webqtlUtil.dump_session([_matrix, _traits], os.path.join(webqtlConfig.TMPDIR, filename + '.session'))
                sessionfile = filename
            
            startTime = time.time()
            
            #Build parameter dictionary used by networkGraphPage class using buildParamDict function
            params = networkGraphUtils.buildParamDict(fd, sessionfile)
    
            nodes = len(_traits)
            rawEdges = len(_matrix)
            
            if params["tune"] == "yes":
                params = networkGraphUtils.tuneParamDict(params, nodes, rawEdges)
              
            matrix = networkGraphUtils.filterDataMatrix(_matrix, params)
            
            optimalNode = networkGraphUtils.optimalRadialNode(matrix)
            
            if not inputFilename:
                inputFilename = tempfile.mktemp()
            
            inputFilename = webqtlConfig.IMGDIR + inputFilename.split("/")[2]
                                           
            #writes out 4 graph files for exporting
            graphFile = "/image/" + networkGraphUtils.writeGraphFile(matrix, _traits, inputFilename, params)
            
            networkGraphUtils.processDataMatrix(matrix, params)

            edges = 0

            for edge in matrix:
                if edge.value != 0:
                    edges +=1

            for trait in _traits:
                trait.name = networkGraphUtils.fixLabel(trait.name)
            
            RootDir = webqtlConfig.IMGDIR
            RootDirURL = "/image/"                  


                  
                        #This code writes the datafile that the graphviz function runNeato uses to generate the 
                        #"digraph" file that defines the graphs parameters
            datafile = networkGraphUtils.writeNeatoFile(matrix=matrix, traits=_traits, filename=inputFilename, GeneIdArray=GeneIdArray, p=params)
            
            #Generate graph in various file types                      
            layoutfile = networkGraphUtils.runNeato(datafile, "dot", "dot", params["gType"]) # XZ, 09/11/2008: add module name
            # ZS 03/04/2010 This second output file (layoutfile_pdf) is rotated by 90 degrees to prevent an issue with pdf output being cut off at the edges
            layoutfile_pdf = networkGraphUtils.runNeato(datafile + "_pdf", "dot", "dot", params["gType"]) # ZS 03/04/2010
            pngfile = networkGraphUtils.runNeato(layoutfile, "png", "png", params["gType"]) 
            mapfile = networkGraphUtils.runNeato(layoutfile, "cmapx", "cmapx", params["gType"])# XZ, 09/11/2008: add module name    
            giffile = networkGraphUtils.runNeato(layoutfile, "gif", "gif", params["gType"])# XZ, 09/11/2008:add module name
            psfile = networkGraphUtils.runNeato(layoutfile_pdf, "ps", "ps", params["gType"])# XZ, 09/11/2008: add module name
            pdffile = networkGraphUtils.runPsToPdf(psfile, params["width"], params["height"])# XZ, 09/11/2008: add module name
            
                        #This generates text files in XGGML (standardized graphing language) and plain text
                        #so the user can create his/her own graphs in a program like Cytoscape
                    
            htmlfile1 = datafile + ".html"
            htmlfile2 = datafile + ".graph.html"

            os.chdir(OrigDir)

            #This generates the graph in various image formats
            giffile = RootDirURL + giffile
            pngfile = RootDirURL + pngfile
            pdffile = RootDirURL + pdffile
            endTime = time.time()
            totalTime = endTime - startTime

            os.chdir(RootDir)

            page2 = GraphPage(giffile, mapfile)
            page2.writeToFile(htmlfile2)
            
            #This generates the HTML for the body of the Network Graph page
            page1 = networkGraphPageBody(fd, matrix, _traits, htmlfile2, giffile, pdffile, nodes, edges, rawEdges, totalTime, params, page2.content, graphFile, optimalNode)
            
            #Adds the javascript colorSel to the body to allow line color selection
            self.dict["js1"] = '<SCRIPT SRC="/javascript/colorSel.js"></SCRIPT><BR>'   
            #self.dict["js1"] += '<SCRIPT SRC="/javascript/networkGraph.js"></SCRIPT>' 
                        
            #Set body of current templatePage to body of the templatePage networkGraphPage                        
            self.dict['body'] = page1.dict['body']