-
Notifications
You must be signed in to change notification settings - Fork 2
/
cMonkeyWrapper.py
293 lines (277 loc) · 15.9 KB
/
cMonkeyWrapper.py
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
#################################################################
# @Program: cMonkeyWrapper.py #
# @Version: 2 (python-cMonkey) #
# @Author: Chris Plaisier #
# @Sponsored by: #
# Nitin Baliga, ISB #
# Institute for Systems Biology #
# 1441 North 34th Street #
# Seattle, Washington 98103-8904 #
# (216) 732-2139 #
# @Also Sponsored by: #
# Luxembourg Systems Biology Grant #
# #
# If this program is used in your analysis please mention who #
# built it. Thanks. :-) #
# #
# Copyrighted by Chris Plaisier 2/18/2013 #
#################################################################
import os
import sqlite3 as lite
import gzip
from bicluster import bicluster
from subprocess import *
from sys import stdout
# A class designed to hold the information from a cMonkey RData object
# to facilitate downstream analyses.
#
# Variables:
# biclusters = dictionary
# seqsUpstream = dictionary
# seqs3pUTR = dictionary
# nucFreqsUpstream = dictionary
# nucFreqs3pUTR = dictionary
#
# Functions:
# getBicluster(k)
# getBiclusters()
# getBiclusterNames()
# getPssmsUpstream(maxScore='NA',maxNormResid='NA',maxEValue='NA',maxSurv='NA')
# getPssms3pUTR(maxScore='NA',maxNormResid='NA',maxEValue='NA',maxSurv='NA')
# getSeqsUpstream() - returns the upstream sequences
# getSeqs3pUTR()
# getNucFreqsUpstream()
# getNucFreqs3pUTR()
# getBiclusterRCode()
# getPssmRCode(maxEValue)
# getBiclusterSeqsUpstream(k)
# getBiclusterSeqs3pUTR(k)
class cMonkeyWrapper:
# Initialize the pssm, promSize of 700bp = +500bp to -200bp
def __init__(self, sqliteDb, maxEValue='NA', meme_upstream=0, weeder_upstream=0, weeder_3pUTR=0, tfbs_db=0, pita_3pUTR=0, targetscan_3pUTR=0, geneConv=False, promSize=700):
# What has been run on this cMonkey run, legend = [0: not run, 1: run]
de_novo_method_upstream = None
de_novo_method_3pUTR = None
if meme_upstream==1 and weeder_upstream==1:
raise RuntimeError('You trained the same run on both MEME and Weeder! Are you stupid or something?')
elif meme_upstream==1:
de_novo_method_upstream = 'meme'
elif weeder_upstream==1:
de_novo_method_upstream = 'weeder'
self.meme_upstream = meme_upstream
self.weeder_upstream = weeder_upstream
if weeder_3pUTR==1:
de_novo_method_3pUTR = 'weeder'
self.weeder_3pUTR = weeder_3pUTR
self.tfbs_db = tfbs_db
self.pita_3pUTR = pita_3pUTR
self.targetscan_3pUTR = targetscan_3pUTR
# Attach to the database
con = lite.connect(sqliteDb)
con.row_factory = lite.Row
cur = con.cursor()
# Get the number of biclusters in run
q1 = 'SELECT * FROM run_infos'
cur.execute(q1)
data = cur.fetchall()
ks = data[0]['num_clusters']
# Get the final iteration number
q1 = 'SELECT max (iteration) from row_members'
cur.execute(q1)
self.maxIter = cur.fetchall()[0][0]
con.close()
print 'Found '+str(ks)+' clusters.'
self.biclusters = {}
for k in range(1,ks+1):
self.biclusters[k] = bicluster(k, self.maxIter, de_novo_method_upstream=de_novo_method_upstream, de_novo_method_3pUTR=de_novo_method_3pUTR, sqliteDb=sqliteDb)
if k%10==0:
stdout.write(str(k))
else:
stdout.write('.')
stdout.flush()
# Now read in the upstream sequences
upstreamSeqsFile = gzip.open('seqs/promoterSeqs_Homo_sapiens.csv.gz','rb')
upstreamSeqsFile.readline() # Skip header
self.seqsUpstream = {}
for line in upstreamSeqsFile.readlines():
splitUp = line.strip().split(',')
tmp = splitUp[0].strip('"')
tmp2 = splitUp[1].strip('"')
tmp2 = tmp2[(len(tmp2)-700):len(tmp2)]
if geneConv==False:
self.seqsUpstream[tmp] = tmp2
else:
if tmp in geneConv:
for gene in geneConv[tmp]:
self.seqsUpstream[gene] = tmp2
upstreamSeqsFile.close()
# Now read in the 3' UTR sequences
p3utrSeqsFile = gzip.open('seqs/p3utrSeqs_Homo_sapiens.csv.gz','rb')
p3utrSeqsFile.readline() # Skip header
self.seqs3pUTR = {}
for line in p3utrSeqsFile.readlines():
splitUp = line.strip().split(',')
tmp = splitUp[0].strip('"')
if geneConv==False:
self.seqs3pUTR[tmp] = splitUp[1].strip('"')
else:
if tmp in geneConv:
for gene in geneConv[tmp]:
self.seqs3pUTR[gene] = splitUp[1].strip('"')
p3utrSeqsFile.close()
# Now read in nucleotide frequencies
nucFreqsFile = open('seqs/nucFreqs.csv','r')
nucFreqsFile.readline() # Skip header
upFreq = nucFreqsFile.readline().strip().split(',')
self.nucFreqsUpstream = {'A':upFreq[1],'C':upFreq[2],'G':upFreq[2],'T':upFreq[1]}
p3utrFreq = nucFreqsFile.readline().strip().split(',')
self.nucFreqs3pUTR = {'A':p3utrFreq[1],'C':p3utrFreq[2],'G':p3utrFreq[2],'T':p3utrFreq[1]}
nucFreqsFile.close()
# Close database connection
con.close()
print '\nDone loading.\n'
# Return a particular bicluster
def getBicluster(self,k):
return self.biclusters[k]
# Return a dictionary of all biclusters
def getBiclusters(self):
return self.biclusters
# Return a list of bicluster names
def getBiclusterNames(self):
return self.biclusters.keys()
# Get all Upstream pssms
def getPssmsUpstream(self,maxNormResid='NA',maxEValue='NA',maxSurv='NA',de_novo_method='NA'):
pssmsNames = []
pssms = []
for bi in self.biclusters.keys():
# Temporarily store the PSSMs
biOk = 0
if maxNormResid=='NA' or float(self.biclusters[bi].getNormResidual())<=float(maxNormResid):
if maxSurv=='NA' or float(self.biclusters[bi].getSurvival()['"Survival"']['pValue'])<=float(maxSurv):
biOk = 1
if biOk==1:
tmpPssms = self.biclusters[bi].getPssmsUpstream()
for pssm in tmpPssms:
if de_novo_method=='NA' or de_novo_method==pssm.getMethod():
# Only add it if it is less than an E-Value threshold
if maxEValue=='NA' or float(pssm.getEValue())<=float(maxEValue):
pssms.append(pssm)
pssmsNames.append(pssm.getName())
return dict(zip(pssmsNames,pssms))
# Get all 3' UTR pssms
def getPssms3pUTR(self,maxNormResid='NA',maxEValue='NA',maxSurv='NA',de_novo_method='NA'):
pssmsNames = []
pssms = []
for bi in self.biclusters.keys():
# Temporarily store the PSSMs
biOk = 0
if maxNormResid=='NA' or float(self.biclusters[bi].getNormResidual())<=float(maxNormResid):
if maxSurv=='NA' or float(self.biclusters[bi].getSurvival()['"Survival"']['pValue'])<=float(maxSurv):
biOk = 1
if biOk==1:
tmpPssms = self.biclusters[bi].getPssms3pUTR()
for pssm in tmpPssms:
# Only add it if it is less than an E-Value threshold
if de_novo_method=='NA' or de_novo_method==pssm.getMethod():
if maxEValue=='NA' or float(pssm.getEValue())<=float(maxEValue):
pssms.append(pssm)
pssmsNames.append(pssm.getName())
return dict(zip(pssmsNames,pssms))
# getSeqsUpstream() - returns the upstream sequences
def getSeqsUpstream(self):
return self.seqsUpstream
# getSeqs3pUTR() - returns the 3' UTR sequences
def getSeqs3pUTR(self):
return self.seqs3pUTR
# getBiclusterSeqsUpstream() - returns the upstream sequences for a bicluster as a dictionary of {<gene_name>: <seqeunce>, ...}
def getBiclusterSeqsUpstream(self, k):
genes = self.biclusters[k].getGenes()
seqs = dict(zip([gene for gene in genes if gene in self.seqsUpstream], [self.seqsUpstream[gene] for gene in genes if gene in self.seqsUpstream]))
return seqs
# getBiclusterSeqs3pUTR() - returns the 3' UTR sequences for a bicluster as a dictionary of {<gene_name>: <seqeunce>, ...}
def getBiclusterSeqs3pUTR(self, k):
genes = self.biclusters[k].getGenes()
seqs = dict(zip([gene for gene in genes if gene in self.seqs3pUTR], [self.seqs3pUTR[gene] for gene in genes if gene in self.seqs3pUTR]))
return seqs
# getNucFreqsUpstream() - retunres the
def getNucFreqsUpstream(self):
return self.nucFreqsUpstream
# getNucFreqs3pUTR() - returns the nucleotide frequencies for the 3pUTR
def getNucFreqs3pUTR(self):
return self.nucFreqs3pUTR
# The R code to get what is needed for a pssm needs to be run in a loop for k, where k = a cluster number
# useEm = c('SEX.INF.bi','AGE','MODEL.1','MODEL.2','MODEL.3','MODEL.4','MODEL.5','SURVIVAL')
def getBiclusterRCode(self):
# First upstream motif
sendToR = []
sendToR.append('k.rows = e$get.rows(k)')
sendToR.append('write.csv(k.rows,paste(\'biclust/\',k,\'/genes.csv\',sep=\'\'))')
sendToR.append('k.cols = e$get.cols(k)')
sendToR.append('write.csv(k.cols,paste(\'biclust/\',k,\'/conditions.csv\',sep=\'\'))')
sendToR.append('resid = e$cluster.resid(k,varNorm=F)')
sendToR.append('residNorm = e$cluster.resid(k,varNorm=T)')
sendToR.append('write.csv(c(resid,residNorm),paste(\'biclust/\',k,\'/resid.csv\',sep=\'\'))')
# Correlate with traits
sendToR.append('if(length(k.rows)>1) {')
sendToR.append(' mu.1 = apply(e$ratios$ratios[k.rows,k.cols],2,median)')
sendToR.append('} else {')
sendToR.append(' mu.1 = e$ratios$ratios[k.rows,k.cols]')
sendToR.append('}')
sendToR.append('d1 = p1[k.cols,useEm]')
sendToR.append('sex1 = try(cor.test(mu.1,d1[,\'SEX.bi\']), TRUE)')
sendToR.append('if(class(sex1)==\'try-error\') { sex1 = c(); sex1$estimate = NA; sex1$p.value = NA }')
sendToR.append('age1 = try(cor.test(mu.1,d1[,\'AGE\']), TRUE)')
sendToR.append('if(class(age1)==\'try-error\') { age1 = c(); age1$estimate = NA; age1$p.value = NA }')
sendToR.append('c1 = rbind(c(sex1$estimate,sex1$p.value),c(age1$estimate,age1$p.value))')
sendToR.append('rownames(c1) = c(\'Sex\',\'Age\')')
sendToR.append('library(survival)')
sendToR.append('d2 = data.frame(mu.1,d1)')
sendToR.append('cph1 = try(summary(coxph(Surv(SURVIVAL,DEAD==\'DEAD\') ~ mu.1, d2)), TRUE)')
sendToR.append('if(class(cph1)==\'try-error\') { cph1 = c(); cph1$coef = matrix(nrow=2,ncol=5); }')
sendToR.append('cph2 = try(summary(coxph(Surv(SURVIVAL,DEAD==\'DEAD\') ~ mu.1 + AGE, d2)),TRUE)')
sendToR.append('if(class(cph2)==\'try-error\') { cph2 = c(); cph2$coef = matrix(nrow=2,ncol=5); }')
sendToR.append('cph3 = try(summary(coxph(Surv(SURVIVAL,DEAD==\'DEAD\') ~ mu.1 + AGE + SEX.bi, d2)),TRUE)')
sendToR.append('if(class(cph3)==\'try-error\') { cph3 = c(); cph3$coef = matrix(nrow=2,ncol=5); }')
sendToR.append('s1 = rbind(c(cph1$coef[1,4],cph1$coef[1,5]),c(cph2$coef[1,4],cph2$coef[1,5]),c(cph3$coef[1,4],cph3$coef[1,5]))')
sendToR.append('rownames(s1) = c(\'Survival\',\'Survival.Age\',\'Survival.Age.Sex\')')
sendToR.append('write.csv(c1,paste(\'biclust/\',k,\'/correlation.csv\',sep=\'\'))')
sendToR.append('write.csv(s1,paste(\'biclust/\',k,\'/survival.csv\',sep=\'\'))')
return sendToR
# The R code to get what is needed for a pssm needs to be run in a loop for k, where k = a cluster number
def getPssmRCode(self,maxEValue):
# First upstream motif
sendToR = []
sendToR.append('e1 = try(e$meme.scores[[\'upstream\']][[k]]$meme.out[[1]]$e.value,TRUE)')
if maxEValue=='NA':
sendToR.append('if(!class(e1)==\'try-error\' && !is.null(e1)) {')
else:
sendToR.append('if(!class(e1)==\'try-error\' && !is.null(e1) && e1<='+str(maxEValue)+') {')
sendToR.append('tmp1 = unique(e$meme.scores[[\'upstream\']][[k]]$meme.out[[1]]$posns[,1])')
sendToR.append('write.table(rbind(c(e$meme.scores[[\'upstream\']][[k]]$meme.out[[1]]$e,e$meme.scores[[\'upstream\']][[k]]$meme.out[[1]]$sites,NA,NA),cbind(c(tmp1),rep(NA,length(tmp1)),rep(NA,length(tmp1)),rep(NA,length(tmp1))),as.matrix(e$meme.scores[[\'upstream\']][[k]]$meme.out[[1]]$pssm)),file=paste(\'biclust/\',k,\'/upstream/motif1.csv\',sep=\'\'),col.names=F,row.names=F,sep=\',\')')
sendToR.append('}')
# Second upstream motif
sendToR.append('e2 = try(e$meme.scores[[\'upstream\']][[k]]$meme.out[[2]]$e.value,TRUE)')
if maxEValue=='NA':
sendToR.append('if(!class(e2)==\'try-error\' && !is.null(e2)) {')
else:
sendToR.append('if(!class(e2)==\'try-error\' && !is.null(e2) && e2<='+str(maxEValue)+') {')
sendToR.append('tmp1 = unique(e$meme.scores[[\'upstream\']][[k]]$meme.out[[2]]$posns[,1])')
sendToR.append('write.table(rbind(c(e$meme.scores[[\'upstream\']][[k]]$meme.out[[2]]$e,e$meme.scores[[\'upstream\']][[k]]$meme.out[[2]]$sites,NA,NA),cbind(c(tmp1),rep(NA,length(tmp1)),rep(NA,length(tmp1)),rep(NA,length(tmp1))),as.matrix(e$meme.scores[[\'upstream\']][[k]]$meme.out[[2]]$pssm)),file=paste(\'biclust/\',k,\'/upstream/motif2.csv\',sep=\'\'),col.names=F,row.names=F,sep=\',\')')
sendToR.append('}')
# First 3' UTR motif
sendToR.append('e3 = try(e$meme.scores[[\'p3utr\']][[k]]$meme.out[[1]]$e.value,TRUE)')
if maxEValue=='NA':
sendToR.append('if(!class(e3)==\'try-error\' && !is.null(e3)) {')
else:
sendToR.append('if(!class(e3)==\'try-error\' && !is.null(e3) && e3<='+str(maxEValue)+') {')
sendToR.append('write.table(rbind(c(e$meme.scores[[\'p3utr\']][[k]]$meme.out[[1]]$e,e$meme.scores[[\'p3utr\']][[k]]$meme.out[[1]]$sites,NA,NA),cbind(c(unique(e$meme.scores[[\'p3utr\']][[k]]$meme.out[[1]]$posns[,1])),rep(NA,e$meme.scores[[\'p3utr\']][[k]]$meme.out[[1]]$sites),rep(NA,e$meme.scores[[\'p3utr\']][[k]]$meme.out[[1]]$sites),rep(NA,e$meme.scores[[\'p3utr\']][[k]]$meme.out[[1]]$sites)),as.matrix(e$meme.scores[[\'p3utr\']][[k]]$meme.out[[1]]$pssm)),file=paste(\'biclust/\',k,\'/3pUTR/motif1.csv\',sep=\'\'),col.names=F,row.names=F,sep=\',\')')
sendToR.append('}')
# Second 3' UTR motif
sendToR.append('e4 = try(e$meme.scores[[\'p3utr\']][[k]]$meme.out[[2]]$e.value,TRUE)')
if maxEValue=='NA':
sendToR.append('if(!class(e4)==\'try-error\' && !is.null(e4)) {')
else:
sendToR.append('if(!class(e4)==\'try-error\' && !is.null(e4) && e4<='+str(maxEValue)+') {')
sendToR.append('write.table(rbind(c(e$meme.scores[[\'p3utr\']][[k]]$meme.out[[2]]$e,e$meme.scores[[\'p3utr\']][[k]]$meme.out[[2]]$sites,NA,NA),cbind(c(e$meme.scores[[\'p3utr\']][[k]]$meme.out[[2]]$posns[,1]),rep(NA,e$meme.scores[[\'p3utr\']][[k]]$meme.out[[2]]$sites),rep(NA,e$meme.scores[[\'p3utr\']][[k]]$meme.out[[2]]$sites),rep(NA,e$meme.scores[[\'p3utr\']][[k]]$meme.out[[2]]$sites)),as.matrix(e$meme.scores[[\'p3utr\']][[k]]$meme.out[[2]]$pssm)),file=paste(\'biclust/\',k,\'/3pUTR/motif2.csv\',sep=\'\'),col.names=F,row.names=F,sep=\',\')')
sendToR.append('}')
return sendToR