~tiagoantao/interpopula/trunk

« back to all changes in this revision

Viewing changes to src/interPopula/TableBrowser/__init__.py

  • Committer: Tiago Antao
  • Date: 2010-04-07 13:26:50 UTC
  • Revision ID: tiagoantao@gmail.com-20100407132650-dv1yrnw3rvbtypdo
initial import

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
'''
 
2
Accessing UCSC Table Browser.
 
3
'''
 
4
__docformat__ = 'javadoc en'
 
5
from ftplib import FTP
 
6
import sqlite3
 
7
from sys import exit
 
8
import gzip
 
9
import os
 
10
from interPopula import Config
 
11
 
 
12
ftp_site = 'hgdownload.cse.ucsc.edu'
 
13
ftp_root = 'goldenPath'
 
14
 
 
15
def prepareDataDir(db):
 
16
    tableDir = Config.dataDir + os.sep +  'TableBrowser'
 
17
    try:
 
18
        os.mkdir(tableDir)
 
19
    except OSError:
 
20
        pass #Probably OK, dir already exists
 
21
    dbConn = sqlite3.connect(tableDir + os.sep + db + '.db')
 
22
    try:
 
23
        dbConn.execute('''CREATE TABLE known_gene (
 
24
                            asc_id     VARCHAR(20),
 
25
                            chromosome VARCHAR(2),
 
26
                            strand     CHAR(1),
 
27
                            tx_start   INTEGER,
 
28
                            tx_end     INTEGER,
 
29
                            cds_start  INTEGER,
 
30
                            cds_end    INTEGER,
 
31
                            prot_id    VARCHAR(100)
 
32
                            )''')
 
33
        dbConn.execute('CREATE INDEX kg_asc_id ON known_gene(asc_id)')
 
34
        dbConn.execute('CREATE INDEX kg_prot_id ON known_gene(prot_id)')
 
35
        dbConn.execute('''CREATE TABLE gene_exons (
 
36
                            asc_id     VARCHAR(20),
 
37
                            start      INTEGER,
 
38
                            finish     INTEGER
 
39
                            )''')
 
40
        dbConn.execute('CREATE INDEX ge_asc_id ON gene_exons(asc_id)')
 
41
    except sqlite3.OperationalError:
 
42
        pass
 
43
    return dbConn
 
44
 
 
45
 
 
46
def loadFile(db, dir, file, unzip = False):
 
47
    tableDir = Config.dataDir + os.sep +  'TableBrowser'
 
48
    tempTBFile = tableDir + os.sep + 'tmp_tb'
 
49
    tempTBFileGz = tempTBFile + '.gz'
 
50
 
 
51
    ftp = FTP(ftp_site)
 
52
    ftpDir = ftp_root + '/' + db + '/' + dir
 
53
    fname = ftpDir + '/' + file
 
54
    ftp.login()
 
55
    if unzip:
 
56
        ftp.retrbinary('RETR ' + fname, open(tempTBFileGz, 'wb').write)
 
57
        gz = gzip.open(tempTBFileGz, 'rb')
 
58
        uncomp = open(tempTBFile, 'w')
 
59
        l = gz.readline()
 
60
        while l<>'':
 
61
            l = gz.readline()
 
62
            uncomp.write(l)
 
63
        gz.close()
 
64
        uncomp.close()
 
65
    else:
 
66
        ftp.retrbinary('RETR ' + fname, open(tempTBFile, 'wb').write)
 
67
    ftp.close()
 
68
    return tempTBFile
 
69
 
 
70
def countLines(dbConn, table):
 
71
    c = dbConn.cursor()
 
72
    c.execute('SELECT count(*) FROM ' + table)
 
73
    cnt = iter(c).next()
 
74
    return cnt[0]
 
75
 
 
76
 
 
77
class KnownGene:
 
78
    '''Wrapper class for KnownGene table
 
79
    '''
 
80
    def __init__(self, db):
 
81
        '''Inits the object. NOTE: will load the database, if not loaded!
 
82
 
 
83
        @param db UCSC table, like hg18 or bosTau1
 
84
        '''
 
85
        self.dbConn = prepareDataDir(db)
 
86
        self.db     = db
 
87
 
 
88
    def loadDB(self):
 
89
        '''Loads the database (also does cleanup).
 
90
        '''
 
91
        self.cleanDB()
 
92
        fName = loadFile(self.db, 'database', 'knownGene.txt.gz' , True)
 
93
        f = open(fName, 'r')
 
94
        l = f.readline()
 
95
        c = self.dbConn.cursor()
 
96
        c.execute('DELETE FROM known_gene')
 
97
        c.execute('DELETE FROM gene_exons')
 
98
        while l<>'':
 
99
            toks       = l.rstrip().split('\t')
 
100
            ascId      = toks[0]
 
101
            chr        = toks[1][3:]
 
102
            strand     = toks[2]
 
103
            txStart    = int(toks[3])
 
104
            txEnd      = int(toks[4])
 
105
            cdsStart   = int(toks[5])
 
106
            cdsEnd     = int(toks[6])
 
107
            numExons   = int(toks[7])
 
108
            exonsStart = toks[8].split(',')
 
109
            exonsEnd   = toks[9].split(',')
 
110
            protId     = toks[10]
 
111
            c.execute('''
 
112
                INSERT INTO known_gene (
 
113
                    asc_id, chromosome, strand, tx_start, tx_end,
 
114
                    cds_start, cds_end, prot_id)
 
115
                VALUES (?,?,?,?,?,?,?,?)''',
 
116
                (ascId, chr, strand, txStart, txEnd,
 
117
                  cdsStart, cdsEnd, protId))
 
118
            for i in range(len(exonsStart)):
 
119
                exonStart = exonsStart[i]
 
120
                if exonStart == '': continue
 
121
                exonEnd = exonsEnd[i]
 
122
                print 'es', exonStart
 
123
                c.execute('''
 
124
                    INSERT INTO gene_exons (asc_id, start, finish)
 
125
                         VALUES (?, ?, ?)
 
126
                ''', (ascId, exonStart, exonEnd))
 
127
            l = f.readline()
 
128
        f.close()
 
129
        self.dbConn.commit()
 
130
 
 
131
    def cleanDB(self):
 
132
        """Cleans the database.
 
133
 
 
134
        Deletes all data from gene_exons and known_gene.
 
135
        """
 
136
        self.dbConn.execute('DELETE FROM gene_exons')
 
137
        self.dbConn.execute('DELETE FROM known_gene')
 
138
        
 
139
    def close(self):
 
140
        '''Closes the database.
 
141
        '''
 
142
        print 'close'
 
143
        self.dbConn.close()
 
144
 
 
145
    def getAscIdsFromProtId(self, protId):
 
146
        '''Returns a list of ascIds for a certain protId.
 
147
 
 
148
        @param protId Protein Id, like P53_HUMAN.
 
149
 
 
150
        @return List of ascIds.
 
151
        '''
 
152
        c = self.dbConn.cursor()
 
153
        c.execute('''
 
154
            SELECT asc_id
 
155
              FROM known_gene
 
156
             WHERE prot_id = ?''', (protId,))
 
157
        asc_list = []
 
158
        for asc in c:
 
159
            asc_list.append(asc[0])
 
160
        return asc_list
 
161
 
 
162
    def getAscId(self, ascId):
 
163
        '''Gets all info (except exons) for a certain ascId.
 
164
 
 
165
        @param ascId ascId.
 
166
        @return a tuple with all data.
 
167
        '''
 
168
        c = self.dbConn.cursor()
 
169
        c.execute('''
 
170
            SELECT *
 
171
              FROM known_gene
 
172
             WHERE asc_id = ?''', (ascId,))
 
173
        for asc in c:
 
174
            return asc
 
175
 
 
176