-
Notifications
You must be signed in to change notification settings - Fork 2
/
offYerBackV2_allBkgd.py~
2345 lines (2146 loc) · 111 KB
/
offYerBackV2_allBkgd.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
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
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#################################################################
# @Program: offYerBackV2.py #
# @Version: 2 #
# @Author: Chris Plaisier #
# @Sponsored by: #
# Nitin Baliga, ISB #
# Institute for Systems Biology #
# 401 Terry Ave North #
# Seattle, Washington 98109-5234 #
# (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 5/21/2012 #
#################################################################
#################################################################
## Parameters ##
#################################################################
# For MEME analysis
bgFile = 'seqs/bgFile.meme'
nMotifs = 2
regions = [ 'upstream' ]
motifWidth = { 'upstream': [6, 12] }
revComp = { 'upstream': True }
# Filtering parameters
maxScore = 0
maxResidual = 0.5
maxEValue = 10
#maxSurv = 0.05/720
#pValueThreshold = 0.05/((375**2)/2)
postProcessedFile = 'postProcessed_cardiomyocyte.csv'
fpcFile = 'biclusterFirstPrincComponents.csv'
#randPssmsDir = 'randPSSMs'
#################################################################
## Functions ##
#################################################################
# Run meme and get the output into PSSMs
def meme(num, seqFile=None, bgFile=None, nMotifs=1, minMotifWidth=6, maxMotifWidth=12, revComp=True, seed=None):
# Arguments for meme
memeArgs = str(seqFile)+' -bfile '+ str(bgFile) +' -nostatus -text -time 600 -dna -maxsize 9999999 -evt 1e9 -mod zoops -minw ' + str(minMotifWidth) + ' -maxw ' + str(maxMotifWidth) + ' -nmotifs ' + str(nMotifs)
if revComp==True:
memeArgs += ' -revcomp'
if not seed==None:
memeArgs += ' -cons ' + str(seed)
print memeArgs
#errOut = open('tmp/meme/stderr.out','w')
memeProc = Popen("meme " + memeArgs, shell=True,stdout=PIPE) #,stderr=errOut)
output = memeProc.communicate()[0].split('\n')
#errOut.close()
PSSMs = []
# Now iterate through output and save data
for i in range(len(output)):
splitUp1 = output[i].strip().split(' ')
if splitUp1[0]=='Motif' and splitUp1[2]=='position-specific' and splitUp1[3]=='probability':
i += 2 # Skip the separator line, go to the summary line
splitUp = output[i].strip().split(' ')
width = int(splitUp[5])
sites = splitUp[7]
eValue = splitUp[9]
matrix = []
for j in range(width):
i += 1
matrix += [[float(let) for let in output[i].strip().split(' ') if let]]
PSSMs.append(pssm(biclusterName=str((seqFile.split('_')[1]).split('.')[0])+'_motif'+str(splitUp1[1])+'_meme',nsites=sites,eValue=eValue,pssm=matrix,genes=[], de_novo_method='meme'))
clusterMemeRuns[num] = PSSMs
# Wrapper function to run the meme function using a multiprocessing pool
def runMeme(i):
meme(i,seqFile=clusterFileNames[i],bgFile=memeVars['bgFile'],nMotifs=memeVars['nMotifs'],minMotifWidth=memeVars['minMotifWidth'], maxMotifWidth=memeVars['maxMotifWidth'], revComp=memeVars['revComp'])
# Run weeder and parse its output
# First weederTFBS -W 6 -e 1, then weederTFBS -W 8 -e 2, and finally adviser
def weeder(bicluster, seqFile=None, bgFile='MM', size='small', enriched='T50', revComp=False):
print seqFile
# First run weederTFBS
weederArgs = str(seqFile)+' '+str(bgFile)+' '+str(size)+' '+str(enriched)
if revComp==True:
weederArgs += ' S'
errOut = open('tmp/weeder/stderr.out','w')
weederProc = Popen("weederlauncher " + weederArgs, shell=True,stdout=PIPE,stderr=errOut)
output = weederProc.communicate()
# Now parse output from weeder
PSSMs = []
output = open(str(seqFile)+'.wee','r')
outLines = [line for line in output.readlines() if line.strip()]
hitBp = {}
for i in range(len(outLines)):
if not outLines[i].find('Searching for motifs of length 8') == -1:
possibleRead=outLines[i+3].split()
if len(possibleRead) == 3:
hitBp[8]=possibleRead[1:]
else:
print 'warning: weeder did not detect any 8 length motif...'
if not outLines[i].find('Searching for motifs of length 6') == -1:
possibleRead=outLines[i+3].split()
if len(possibleRead) == 3:
hitBp[6]=possibleRead[1:]
else:
print 'warning: weeder did not detect any 8 length motif...'
print 'hitBp',hitBp
# Get top hit of 6bp look for "1)"
#while 1:
# outLine = outLines.pop(0)
# if not outLine.find('1) ') == -1:
# break
#hitBp[6] = outLine.strip().split(' ')[1:]
#print 'hitBp6', hitBp[6]
# Scroll to where the 8bp reads will be
#while 1:
# outLine = outLines.pop(0)
# if not outLine.find('Searching for motifs of length 8') == -1:
# break
# Get top hit of 8bp look for "1)"
#while 1:
# outLine = outLines.pop(0)
# if not outLine.find('1) ') == -1:
# break
#hitBp[8] = outLine.strip().split(' ')[1:]
#print 'hitBp8',hitBp[8]
if size=='medium':
# Scroll to where the 10bp reads wll be
while 1:
outLine = outLines.pop(0)
if not outLine.find('Searching for motifs of length 10') == -1:
break
# Get top hit of 10bp look for "1)"
while 1:
outLine = outLines.pop(0)
if not outLine.find('1) ') == -1:
break
hitBp[10] = outLine.strip().split(' ')[1:]
# Scroll to where the 10bp reads will be
while 1:
outLine = outLines.pop(0)
if not outLine.find('Your sequences:') == -1:
break
# Get into the highest ranking motifs
seqDict = {}
while 1:
outLine = outLines.pop(0)
if not outLine.find('**** MY ADVICE ****') == -1:
break
splitUp = outLine.strip().split(' ')
seqDict[splitUp[1]] = splitUp[3].lstrip('>')
# Get into the highest ranking motifs
while 1:
outLine = outLines.pop(0)
if not outLine.find('Interesting motifs (highest-ranking)') == -1:
break
motifId = 1
biclusterId = str((seqFile.split('_')[1]).split('.')[0])
while 1:
if len(outLines)<=1:
break
if revComp==True:
name = outLines.pop(0).strip() # Get match
name += '_'+outLines.pop(0).strip()
if revComp==False:
name = outLines.pop(0).strip() # Get match
if not name.find('(not highest-ranking)') == -1:
break
# Get redundant motifs
outLines.pop(0)
redMotifs = [i for i in outLines.pop(0).strip().split(' ') if not i=='-']
outLines.pop(0)
outLines.pop(0)
line = outLines.pop(0)
instances = []
while line.find('Frequency Matrix') == -1:
splitUp = [i for i in line.strip().split(' ') if i]
instances.append({'gene':seqDict[splitUp[0]], 'strand':splitUp[1], 'site':splitUp[2], 'start':splitUp[3], 'match':splitUp[4].lstrip('(').rstrip(')') })
line = outLines.pop(0)
# Read in Frequency Matrix
outLines.pop(0)
outLines.pop(0)
matrix = []
col = outLines.pop(0)
while col.find('======') == -1:
nums = [i for i in col.strip().split('\t')[1].split(' ') if i]
colSum = 0
for i in nums:
colSum += int(i.strip())
matrix += [[ float(nums[0])/float(colSum), float(nums[1])/float(colSum), float(nums[2])/float(colSum), float(nums[3])/float(colSum)]]
col = outLines.pop(0)
PSSMs += [pssm(biclusterName=str(biclusterId)+'_motif'+str(motifId)+'_weeder',nsites=instances,eValue=hitBp[len(matrix)][1],pssm=matrix,genes=redMotifs, de_novo_method='weeder')]
motifId += 1
weederResults[bicluster] = PSSMs
print 'weederResults[bicluster]',weederResults[bicluster]
# Wrapper function to run weeder using a multiprocessing pool
def runWeeder(i):
try:
weeder(i,seqFile=clusterFileNames[i],bgFile=weederVars['bgFile'], size=weederVars['size'], enriched=weederVars['enriched'], revComp=weederVars['revComp'])
except:
print 'weeder failed, continuing...'
return None
# Run TomTom on the files
def TomTom(num, distMeth='ed', qThresh='1', minOverlap=6):
# Arguments for tomtom
tomtomArgs = ' -dist '+str(distMeth)+' -o tmp/tomtom_out -text -thresh '+str(qThresh)+' -min-overlap '+str(minOverlap)+' -verbosity 1 tmp/query'+str(num)+'.tomtom tmp/target'+str(num)+'.tomtom'
print tomtomArgs
#p = Popen("tomtom" + tomtomArgs, shell=True)
#sts = os.waitpid(p.pid, 0)
errOut = open('tmp/stderr_'+str(num)+'.out','w')
tomtomProc = Popen("tomtom" + tomtomArgs, shell=True,stdout=PIPE, stderr=errOut)
outputFile = open('tmp/tomtom_out/tomtom'+str(num)+'.out','w')
output = tomtomProc.communicate()[0]
outputFile.write(output)
outputFile.close()
errOut.close()
# Wrapper function to run TomTom using multiprocessing pool
def runTomTom(i):
TomTom(i, distMeth='ed', qThresh='1', minOverlap=6) #blic5
def phyper(q, m, n, k):
# Get an array of values to run
rProc = Popen('R --no-save --slave', shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE)
runMe = []
for i in range(len(q)):
runMe.append('phyper('+str(q[i])+','+str(m[i])+','+str(n[i])+','+str(k[i])+',lower.tail=F)')
runMe = '\n'.join(runMe)+'\n'
out = rProc.communicate(runMe)
return [line.strip().split(' ')[1] for line in out[0].strip().split('\n') if line]
"""
# Get first principle component
def firstPrincipalComponent(matrix):
""
Cacluate the first prinicipal component of a gene expression matrix.
Input: Expression matrix gene (rows) x conditions (columns), expects that the
python equivalent will be an array of arrays of expression values (rows).
Returns: Array of first prinicipal component and variance explained by first
principal component.
""
# Fire up R
rProc = Popen('R --no-save --slave', shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE)
runMe = []
# Make the data into an R matrix
rbind = 'm1 = rbind('
rbind += ','.join(['c('+','.join([str(i) for i in row])+')' for row in matrix])
rbind += ')'
runMe.append(rbind)
# Compute first principal component
runMe.append('tmp.pc = try(princomp(t(m1)),TRUE)')
runMe.append('pc.1 = NA')
runMe.append('var.exp = NA')
runMe.append('if(!class(tmp.pc)==\'try-error\') {')
runMe.append(' pc.1 = tmp.pc$scores[,1]')
runMe.append(' var.exp = ((tmp.pc$sdev^2)/sum(tmp.pc$sdev^2))[1]')
runMe.append('}')
runMe.append('var.exp')
runMe.append('pc.1')
runMe = '\n'.join(runMe)+'\n'
out = rProc.communicate(runMe)
# Process output
splitUp = out[0].strip().split('\n')
splitUp.pop(0) # Get rid of header dealie
varExp = float(splitUp.pop(0).strip())
pc1 = []
for r1 in splitUp:
pc1 += [float(i) for i in r1.split(' ') if i and (not i.count('[')==1)]
# Return output
return [pc1, varExp]
"""
# Get a correlation p-value from R
def correlation(a1, a2):
"""
Calculate the correlation coefficient and p-value between two variables.
Input: Two arrays of float or integers.
Returns: Corrleation coefficient and p-value.
"""
# Fire up R
rProc = Popen('R --no-save --slave', shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE)
runMe = []
# Make the data into an R matrix
runMe.append('c1 = cor.test(c('+','.join([str(i) for i in a1])+'),c('+','.join([str(i) for i in a2])+'))')
runMe.append('c1$estimate')
runMe.append('c1$p.value')
runMe = '\n'.join(runMe)+'\n'
out = rProc.communicate(runMe)
# Process output
splitUp = out[0].strip().split('\n')
rho = float(splitUp[1])
pValue = float((splitUp[2].split(' '))[1])
return [rho, pValue]
# Compute survival p-value from R
def survival(survival, dead, pc1, age):
"""
Calculate the survival correlation coefficient and p-value between two variables.
Input: Four arrays of float or integers.
Returns:
"""
# Fire up R
rProc = Popen('R --no-save --slave', shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE)
runMe = []
# Make the data into an R matrix
runMe.append('library(survival)')
runMe.append('s1 = c('+','.join([str(i) for i in survival])+')')
runMe.append('dead1 = c('+','.join(['\''+str(i)+'\'' for i in dead])+')')
runMe.append('pc1 = c('+','.join([str(i) for i in pc1])+')')
runMe.append('age1 = c('+','.join([str(i) for i in age])+')')
runMe.append('scph1 = summary(coxph(Surv(s1,dead1==\'DEAD\') ~ pc1))')
runMe.append('scph2 = summary(coxph(Surv(s1,dead1==\'DEAD\') ~ pc1 + age1))')
runMe.append('scph1$coef[1,4]')
runMe.append('scph1$coef[1,5]')
runMe.append('scph2$coef[1,4]')
runMe.append('scph2$coef[1,5]')
runMe = '\n'.join(runMe)+'\n'
out = rProc.communicate(runMe)
# Process output
splitUp = out[0].strip().split('\n')
z1 = float((splitUp[0].split(' '))[1])
pValue1 = float((splitUp[1].split(' '))[1])
z2 = float((splitUp[2].split(' '))[1])
pValue2 = float((splitUp[3].split(' '))[1])
return [[z1, pValue1], [z2, pValue2]]
# To test the survival function
#survival([10,20,30,10,15], ['DEAD','ALIVE','ALIVE','DEAD','ALIVE'], [0.1,0.25,0.4,0.6,0.9], [25,35,45,55,65])
#################################################################
## Python Modules Loading ##
#################################################################
# Default python libraries
from math import log10
import cPickle, os, re, sys
from multiprocessing import Pool, cpu_count, Manager
from subprocess import *
from shutil import rmtree
from copy import deepcopy
# Custom offYerBack libraries
from cMonkeyWrapper import cMonkeyWrapper
from pssm import pssm
from miRvestigator import miRvestigator
from tomtom import tomtom
# Functions needed to run this script
from utils import *
from sys import stdout, exit
#from weeder import *
import gzip
#################################################################
## Preparing directories for output ##
#################################################################
if not os.path.exists('output'):
os.makedirs('output')
#################################################################
## Load synonym thesaurus to get UCSC ID to Entrez ID ##
#################################################################
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
entrez2ucsc = {}
inFile = open('../synonymsThesaurus.csv','r')
while 1:
line = inFile.readline()
if not line:
break
splitUp = line.strip().split(',')
ucscId = splitUp[0]
entrez = splitUp[1].split(';')
#if len(entrez)==1:
for e1 in entrez:
if not e1 in entrez2ucsc:
entrez2ucsc[e1] = [ucscId]
else:
entrez2ucsc[e1].append(ucscId)
inFile.close()
#######################################################################
## Create a dictionary to convert the miRNAs to there respective ids ##
#######################################################################
inFile = open('miRNA/hsa.mature.fa','r') # Need to update this to the latest database
miRNAIDs = {}
miRNAIDs_rev = {}
clusterFileNames = {}
while 1:
inLine = inFile.readline()
if not inLine:
break
splitUp = inLine.split(' ')
if not splitUp[1] in miRNAIDs_rev:
miRNAIDs_rev[splitUp[1]] = splitUp[0].lower()
if not splitUp[0].lower() in miRNAIDs:
miRNAIDs[splitUp[0].lower()] = splitUp[1]
else:
print 'Uh oh!',splitUp
if not os.path.exists('output/c1_all.pkl'):
#################################################################
## Load cMonkey Object - turns cMonkey data into objects ##
#################################################################
# If this is the first time then load from the RData file
if not os.path.exists('output/c1.pkl'):
c1 = cMonkeyWrapper('../out/cmonkey_run.db',meme_upstream=0,weeder_upstream=0,weeder_3pUTR=0,tfbs_db=0,pita_3pUTR=0,targetscan_3pUTR=0,geneConv=entrez2ucsc)
pklFile = open('output/c1.pkl','wb')
cPickle.dump(c1,pklFile)
# Otherwise load the dumped pickle file if it exists
else:
print 'Loading precached cMonkey object..'
pklFile = open('output/c1.pkl','rb')
c1 = cPickle.load(pklFile)
print 'Done.\n'
pklFile.close()
#c1.meme_upstream = 1 # Works
#c1.weeder_upstream = 1 # Works
#c1.weeder_3pUTR = 1 # Works
#c1.pita_3pUTR = 1 # Works
#c1.targetscan_3pUTR = 1 # Works
#################################################################
## Fill in the missing parts ##
#################################################################
# Check to see if all parts are there: #
# A. Upstream motifs (MEME) #
# B. Upstream motif (Weeder) #
# C. 3' UTR Weeder-miRvestigator (Weeder) #
# D. 3' UTR PITA (Set Enrichment) #
# E. 3' UTR TargetScan (Set Enrichment) #
###############################################################
## A. Upstream motifs (MEME) ##
# If MEME hasn't been run on the biclusters upstream sequences then do so
if not c1.meme_upstream==1:
print 'Running MEME on Upstreams:'
# Use already run MEME results if they exist
if not os.path.exists('output/meme_upstream.pkl'):
# Make needed directories
if os.path.exists('tmp'):
rmtree('tmp')
if not os.path.exists('tmp/meme/fasta'):
os.makedirs('tmp/meme/fasta')
# Run MEME on all biclusters
mgr = Manager()
clusterFileNames = mgr.dict()
o1 = []
# First make fasta files for all biclusters
print 'Making Files for MEME Upstream run...'
for b1 in c1.getBiclusters():
clusterFileName = 'tmp/meme/fasta/bicluster_'+str(b1)+'.fasta'
seqs = c1.getBiclusterSeqsUpstream(b1)
print len(seqs)
if len(seqs)>0:
o1.append(b1)
clusterFileNames[b1] = clusterFileName
fastaFile = open(clusterFileName,'w')
fastaFile.write('\n'.join(['>'+gene+'\n'+seqs[gene] for gene in seqs]))
fastaFile.close()
# Where all the results will be stored
clusterMemeRuns = mgr.dict()
# Parameters to use for running MEME
memeVars = mgr.dict( { 'bgFile': bgFile, 'nMotifs': nMotifs, 'minMotifWidth': motifWidth['upstream'][0], 'maxMotifWidth': motifWidth['upstream'][1], 'revComp': revComp['upstream'] } )
# Then run MEME using all cores available
print 'Running MEME on Upstream sequences...'
cpus = cpu_count()
print 'There are', cpus,'CPUs avialable.'
pool = Pool(processes=cpus)
pool.map(runMeme,[i for i in o1])
pool.close()
pool.join()
# Dump weeder results as a pickle file
pklFile = open('output/meme_upstream.pkl','wb')
cPickle.dump(deepcopy(clusterMemeRuns),pklFile)
else:
print 'Loading from precached object...'
pklFile = open('output/meme_upstream.pkl','rb')
clusterMemeRuns = cPickle.load(pklFile)
pklFile.close()
# Add PSSMs to cMonkey object
print 'Storing output...'
for i in clusterMemeRuns.keys():
for pssm1 in clusterMemeRuns[i]:
b1 = c1.getBicluster(i)
pssm1.setMethod('meme')
b1.addPssmUpstream(pssm1)
print 'Done with MEMEing.\n'
# MEME upstream has been run on cMonkey run
c1.meme_upstream = 1
## B. Upstream motifs (Weeder) ##
# If Weeder hasn't been run on the biclusters upstream sequences then do so
if not c1.weeder_upstream==1:
print 'Running Weeder on Upstreams:'
# If this has been run previously just load it up
if not os.path.exists('output/weeder_upstream.pkl'):
# Make needed directories
if os.path.exists('tmp'):
rmtree('tmp')
if not os.path.exists('tmp/weeder/fasta'):
os.makedirs('tmp/weeder/fasta')
# Run Weeder on all biclusters
mgr = Manager()
clusterFileNames = mgr.dict()
o1 = []
# First make fasta files for all biclusters
print 'Making Files for Upstream Weeder re-run...'
for b1 in c1.getBiclusters():
clusterFileName = 'tmp/weeder/fasta/bicluster_'+str(b1)+'.fasta'
seqs = c1.getBiclusterSeqsUpstream(b1)
if len(seqs)>0:
o1.append(b1)
clusterFileNames[b1] = clusterFileName
fastaFile = open(clusterFileName,'w')
fastaFile.write('\n'.join(['>'+gene+'\n'+seqs[gene] for gene in seqs]))
fastaFile.close()
# Where all the results will be stored
weederResults = mgr.dict()
# Parameters to use for running Weeder
# Set to run Weeder on 'medium' setting which means 6bp, 8bp and 10bp motifs
#weederVars = mgr.dict( { 'bgFile': 'MM', 'size': 'medium', 'enriched': 'T50', 'revComp': True } )
weederVars = mgr.dict( { 'bgFile': 'HS', 'size': 'small', 'enriched': 'T50', 'revComp': True } )
# Run this using all cores available
print 'Running Weeder...'
### in case you want to do it parallel
cpus = cpu_count()
print 'There are', cpus,'CPUs avialable.'
pool = Pool(processes=cpus) #
pool.map(runWeeder,[i for i in o1]) # run it with an index single thread if you need the output.
pool.close()
pool.join()
#for i in range(10):
# runWeeder(i+3)
# Dump weeder results as a pickle file
pklFile = open('output/weeder_upstream.pkl','wb')
cPickle.dump(deepcopy(weederResults),pklFile)
else:
print 'Loading from precached object...'
pklFile = open('output/weeder_upstream.pkl','rb')
weederResults = cPickle.load(pklFile)
pklFile.close()
# Add PSSMs to cMonkey object
print 'Storing output...'
for i in weederResults.keys():
for pssm1 in weederResults[i]:
b1 = c1.getBicluster(i)
pssm1.setMethod('weeder')
b1.addPssmUpstream(pssm1)
print 'Done with Weedering.\n'
# Weeder upstream has been run on cMonkey run
c1.weeder_upstream = 1
# C. 3' UTR Weeder-miRvestigator (Weeder)
# If Weeder hasn't been run on the biclusters 3' UTR sequences then do so
if not c1.weeder_3pUTR==1:
print 'Running Weeder on 3\' UTRs:'
# If this has been run previously just load it up
if not os.path.exists('output/weeder_3pUTR.pkl'):
# Make needed directories
if os.path.exists('tmp'):
rmtree('tmp')
if not os.path.exists('tmp/weeder/fasta'):
os.makedirs('tmp/weeder/fasta')
# Run MEME on all biclusters
mgr = Manager()
clusterFileNames = mgr.dict()
o1 = []
# First make fasta files for all biclusters
print 'Making Files for Upstream Weeder re-run...'
for b1 in c1.getBiclusters():
clusterFileName = 'tmp/weeder/fasta/bicluster_'+str(b1)+'.fasta'
seqs = c1.getBiclusterSeqs3pUTR(b1)
if len(seqs)>0:
o1.append(b1)
clusterFileNames[b1] = clusterFileName
fastaFile = open(clusterFileName,'w')
fastaFile.write('\n'.join(['>'+gene+'\n'+seqs[gene] for gene in seqs]))
fastaFile.close()
# Where all the results will be stored
weederResults = mgr.dict()
# Parameters to use for running Weeder
# Set to run Weeder on 'medium' setting which means 6bp, 8bp and 10bp motifs
weederVars = mgr.dict( { 'bgFile': 'HS3P', 'size': 'small', 'enriched': 'T50', 'revComp': False } )
# Run this using all cores available
print 'Running Weeder...'
cpus = cpu_count()
print 'There are', cpus,'CPUs avialable.'
pool = Pool(processes=cpus)
pool.map(runWeeder,[i for i in o1])
pool.close()
pool.join()
# Dump weeder results as a pickle file
pklFile = open('output/weeder_3pUTR.pkl','wb')
cPickle.dump(deepcopy(weederResults),pklFile)
else:
print 'Loading from precached object...'
pklFile = open('output/weeder_3pUTR.pkl','rb')
weederResults = cPickle.load(pklFile)
pklFile.close()
# Add PSSMs to cMonkey object
print 'Storing output...'
for i in weederResults.keys():
for pssm1 in weederResults[i]:
b1 = c1.getBicluster(i)
pssm1.setMethod('weeder')
b1.addPssm3pUTR(pssm1)
print 'Done with 3\'UTR Weedering.\n'
# Weeder 3pUTR has been run on cMonkey run
c1.weeder_3pUTR = 1
# D. Upstream TFBS DB enrichment Analysis
# If tfbs_db enrichment hasn't been calculated for the biclusters then do so
if not c1.tfbs_db==1:
print 'Running TFBS_DB on Biclusters:'
# If this has been run previously just load it up
if not os.path.exists('output/tfbs_db.pkl'):
# Get ready for multiprocessor goodness
mgr = Manager()
# Get a list of all genes in the biclusters
print 'Get a list of all genes in run...'
tmpDict = c1.getBiclusters()
genesInBiclusters = []
for bicluster in tmpDict:
genes = tmpDict[bicluster].getGenes()
for gene in genes:
if not gene in genesInBiclusters:
genesInBiclusters.append(gene)
biclusters = mgr.dict(tmpDict)
del tmpDict
# Load up TFBS_DB TF ids
if not os.path.exists('TF/tfbs_db.pkl'):
print 'Loading TFBS_DB predictions...'
tmpList = []
tmpDict = {}
inFile = open('TF/tfbsDb_plus_and_minus_5000_entrez.csv','r')
inLines = [i.strip().split(',') for i in inFile.readlines() if i.strip()]
for line in inLines:
ucscIds = []
if line[1] in entrez2ucsc:
ucscIds = entrez2ucsc[line[1]]
if len(ucscIds)>0:
for ucscId in ucscIds:
if not ucscId in tmpList:
tmpList.append(ucscId)
if not line[0] in tmpDict:
tmpDict[line[0]] = []
tmpDict[line[0]].append(ucscId)
inFile.close()
pklFile = open('TF/tfbs_db.pkl','wb')
cPickle.dump(tmpDict,pklFile)
cPickle.dump(tmpList,pklFile)
# Otherwise load the dumped pickle file if it exists
else:
print 'Loading pickled TFBS_DB predictions...'
pklFile = open('TF/tfbs_db.pkl','rb')
tmpDict = cPickle.load(pklFile)
tmpList = cPickle.load(pklFile)
pklFile.close()
# Setup for analysis
predDict = mgr.dict(tmpDict)
pred_totalTargets = mgr.list()
pred_totalTargets.append(set(tmpList))
del tmpDict
del tmpList
print 'TFBS_DB has', len(predDict.keys()),'TFs.'
def clusterHypergeo_tfbs(biclustId, db = predDict, allGenes = pred_totalTargets[0]):
# k = overlap, N = potential target genes, n = miRNA targets, m = cluster genes
# Take gene list and compute overlap with each miRNA
genes = allGenes.intersection(biclusters[biclustId].getGenes())
writeMe = []
keys1 = db.keys()
m1s = []
q = []
m = []
n = []
k = []
for m1 in keys1:
m1s.append(m1)
miRNAGenes = allGenes.intersection(db[m1])
q.append(len(set(miRNAGenes).intersection(genes)))
m.append(len(miRNAGenes))
n.append(len(allGenes)-len(miRNAGenes))
k.append(len(genes))
results = phyper(q,m,n,k)
min_miRNA = []
perc_targets = []
min_pValue = float(1)
for i in range(1,len(results)):
if float(results[i]) <= float(0.05)/float(674) and not q[i]==0 and float(q[i])/float(k[i]) >= 0.1:
if min_miRNA==[] or float(results[i]) < min_pValue:
min_miRNA = [i]
perc_targets = [float(q[i])/float(k[i])]
min_pValue = float(results[i])
elif float(results[i])==min_pValue:
min_miRNA.append(i)
perc_targets.append(float(q[i])/float(k[i]))
print 'Bicluster #', biclustId, ' '.join([m1s[miRNA] for miRNA in min_miRNA])
return [biclustId, ' '.join([m1s[miRNA] for miRNA in min_miRNA]), ' '.join([str(j) for j in perc_targets]), min_pValue]
# Set allGenes as intersect of pita_totalTargets and genesInBiclusters
# allGenes = pred_totalTargets[0].intersection(genesInBiclusters)
allGenes = pred_totalTargets[0]
# Run this using all cores available
print 'Running TFBS_DB enrichment analyses...'
cpus = cpu_count()
biclustIds = biclusters.keys()
pool = Pool(processes=cpus)
res1 = pool.map(clusterHypergeo_tfbs,biclustIds)
pool.close()
pool.join()
# Dump weeder results as a pickle file
pklFile = open('output/tfbs_db.pkl','wb')
cPickle.dump(res1,pklFile)
else:
print 'Loading precached analysis...'
pklFile = open('output/tfbs_db.pkl','rb')
res1 = cPickle.load(pklFile)
pklFile.close()
# Stuff into biclusters
print 'Storing results...'
for r1 in res1:
# r1 = [biclusterId, tf(s), Percent Targets, P-Value]
b1 = c1.getBicluster(r1[0])
b1.addAttribute('tfbs_db',{'tf':r1[1], 'percentTargets':r1[2], 'pValue':r1[3]})
print 'Done.\n'
# TFBS_DB has been run on cMonkey run
c1.tfbs_db = 1
# E. 3' UTR PITA
# If PITA enrichment hasn't been calculated for the biclusters then do so
if not c1.pita_3pUTR==1:
print 'Running PITA on Biclusters:'
# If this has been run previously just load it up
if not os.path.exists('output/pita_3pUTR.pkl'):
# Get ready for multiprocessor goodness
mgr = Manager()
# Get a list of all genes in the biclusters
print 'Get a list of all genes in run...'
tmpDict = c1.getBiclusters()
genesInBiclusters = []
for bicluster in tmpDict:
genes = tmpDict[bicluster].getGenes()
for gene in genes:
if not gene in genesInBiclusters:
genesInBiclusters.append(gene)
biclusters = mgr.dict(tmpDict)
del tmpDict
# Load up PITA miRNA ids
# If this is the first time then load from the RData file
if not os.path.exists('miRNA/pita.pkl'):
print 'Loading PITA predictions...'
tmpList = []
tmpDict = {}
inFile = open('miRNA/pita_miRNA_sets_entrez.csv','r')
inLines = [i.strip().split(',') for i in inFile.readlines() if i.strip()]
for line in inLines:
ucscIds = []
if line[1] in entrez2ucsc:
ucscIds = entrez2ucsc[line[1]]
if len(ucscIds)>0:
for ucscId in ucscIds:
if ucscId in genesInBiclusters:
if not ucscId in tmpList:
tmpList.append(ucscId)
if not line[0] in tmpDict:
tmpDict[line[0]] = []
tmpDict[line[0]].append(ucscId)
inFile.close()
pklFile = open('miRNA/pita.pkl','wb')
cPickle.dump(tmpDict,pklFile)
cPickle.dump(tmpList,pklFile)
# Otherwise load the dumped pickle file if it exists
else:
print 'Loading pickled PITA predictions...'
pklFile = open('miRNA/pita.pkl','rb')
tmpDict = cPickle.load(pklFile)
tmpList = cPickle.load(pklFile)
pklFile.close()
# Setup for analysis
predDict = mgr.dict(tmpDict)
pred_totalTargets = mgr.list()
pred_totalTargets.append(set(tmpList))
del tmpDict
del tmpList
print 'PITA has', len(predDict.keys()),'miRNAs.'
def clusterHypergeo_pita(biclustId, db = predDict, allGenes = pred_totalTargets[0]):
# k = overlap, N = potential target genes, n = miRNA targets, m = cluster genes
# Take gene list and compute overlap with each miRNA
genes = allGenes.intersection(biclusters[biclustId].getGenes())
keys1 = db.keys()
m1s = []
q = []
m = []
n = []
k = []
for m1 in keys1:
m1s.append(m1)
miRNAGenes = allGenes.intersection(db[m1])
q.append(len(set(miRNAGenes).intersection(genes)))
m.append(len(miRNAGenes))
n.append(len(allGenes)-len(miRNAGenes))
k.append(len(genes))
results = phyper(q,m,n,k)
min_miRNA = []
perc_targets = []
min_pValue = float(1)
for i in range(1,len(results)):
overlapValues.append(','.join([str(biclustId), m1s[i], str(q[i]), str(m[i]), str(n[i]), str(k[i]), results[i]]))
if float(results[i]) <= float(0.05)/float(674) and not q[i]==0 and float(q[i])/float(k[i]) >= 0.1:
if min_miRNA==[] or float(results[i]) < min_pValue:
min_miRNA = [i]
perc_targets = [float(q[i])/float(k[i])]
min_pValue = float(results[i])
elif float(results[i])==min_pValue:
min_miRNA.append(i)
perc_targets.append(float(q[i])/float(k[i]))
print 'Bicluster #', biclustId, ' '.join([m1s[miRNA] for miRNA in min_miRNA])
return [biclustId, ' '.join([m1s[miRNA] for miRNA in min_miRNA]), ' '.join([str(j) for j in perc_targets]), min_pValue]
# Set allGenes as intersect of pita_totalTargets and genesInBiclusters
# allGenes = pred_totalTargets[0].intersection(genesInBiclusters)
allGenes = pred_totalTargets[0]
# Run this using all cores available
print 'Running PITA enrichment analyses...'
cpus = cpu_count()
biclustIds = biclusters.keys()
overlapValues = mgr.list()
pool = Pool(processes=cpus)
res1 = pool.map(clusterHypergeo_pita, biclustIds)
pool.close()
pool.join()
# Write out file with overlap values
"""header = ['bicluster,regulator,q,m,n,k,p.value']
outFile = open('output/pita_qmnk.csv','w')
outFile.write('\n'.join(header+list(overlapValues)))
outFile.close()"""
# Dump weeder results as a pickle file
pklFile = open('output/pita_3pUTR.pkl','wb')
cPickle.dump(res1,pklFile)
else:
print 'Loading precached analysis...'
pklFile = open('output/pita_3pUTR.pkl','rb')
res1 = cPickle.load(pklFile)
pklFile.close()
# Stuff into biclusters
print 'Storing results...'
for r1 in res1:
# r1 = [biclusterId, miRNA(s), Percent Targets, P-Value]
b1 = c1.getBicluster(r1[0])
miRNA_mature_seq_ids = []
for m1 in r1[1]:
miRNA_mature_seq_ids += miRNAInDict(m1.lower(),miRNAIDs)
b1.addAttribute('pita_3pUTR',{'miRNA':r1[1], 'percentTargets':r1[2], 'pValue':r1[3], 'mature_seq_ids':miRNA_mature_seq_ids })
print 'Done.\n'
# PITA 3pUTR has been run on cMonkey run
c1.pita_3pUTR = 1
# F. 3' UTR TargetScan
# If TargetScan enrichment hasn't been calculated for the biclusters then do so
if not c1.targetscan_3pUTR==1:
print 'Running TargetScan on Biclusters:'
# If this has been run previously just load it up
if not os.path.exists('output/targetscan_3pUTR.pkl'):
# Get ready for multiprocessor goodness
mgr = Manager()
# Get a list of all genes in the biclusters
print 'Get a list of all genes in run...'
tmpDict = c1.getBiclusters()
genesInBiclusters = []
for bicluster in tmpDict:
genes = tmpDict[bicluster].getGenes()
for gene in genes:
if not gene in genesInBiclusters:
genesInBiclusters.append(gene)
biclusters = mgr.dict(tmpDict)
del tmpDict
# Load up TargetScan miRNA ids
if not os.path.exists('miRNA/targetScan.pkl'):
print 'Loading TargetScan predictions...'
tmpList = []
tmpDict = {}
inFile = open('miRNA/targetscan_miRNA_sets_entrez.csv','r')
inLines = [i.strip().split(',') for i in inFile.readlines() if i.strip()]
for line in inLines:
ucscIds = []
if line[1] in entrez2ucsc:
ucscIds = entrez2ucsc[line[1]]
if len(ucscIds)>0:
for ucscId in ucscIds:
if not ucscId in tmpList:
tmpList.append(ucscId)
if not line[0] in tmpDict:
tmpDict[line[0]] = []
tmpDict[line[0]].append(ucscId)
inFile.close()
pklFile = open('miRNA/targetScan.pkl','wb')
cPickle.dump(tmpDict,pklFile)
cPickle.dump(tmpList,pklFile)
# Otherwise load the dumped pickle file if it exists
else:
print 'Loading pickled TargetScan predictions...'
pklFile = open('miRNA/targetScan.pkl','rb')
tmpDict = cPickle.load(pklFile)
tmpList = cPickle.load(pklFile)
pklFile.close()
# Setup for analysis
predDict = mgr.dict(tmpDict)
pred_totalTargets = mgr.list()
pred_totalTargets.append(set(tmpList))
del tmpDict
del tmpList
print 'TargetScan has', len(predDict.keys()),'miRNAs.'
def clusterHypergeo_ts(biclustId, db = predDict, allGenes = pred_totalTargets[0]):
# k = overlap, N = potential target genes, n = miRNA targets, m = cluster genes
# Take gene list and compute overlap with each miRNA
genes = allGenes.intersection(biclusters[biclustId].getGenes())
writeMe = []
keys1 = db.keys()
m1s = []
q = []
m = []
n = []
k = []
for m1 in keys1:
m1s.append(m1)