forked from baliga-lab/sygnal
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsygnal.py
executable file
·1919 lines (1645 loc) · 89.9 KB
/
sygnal.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
#!/usr/bin/env python
#################################################################
# @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 #
#################################################################
from math import log10
import cPickle, os, re, sys
from sys import stdout, exit
from multiprocessing import Pool, cpu_count, Manager
from subprocess import *
import subprocess
from shutil import rmtree
from copy import deepcopy
from collections import defaultdict
import gzip
import rpy2.robjects as robj
from rpy2.robjects import FloatVector, IntVector, StrVector
from rpy2 import rinterface
# Custom offYerBack libraries
from cMonkeyWrapper import cMonkeyWrapper
from pssm import PSSM
import pssm as pssm_mod
from miRvestigator import miRvestigator
import utils
import config
#################################################################
## rpy2 integration ##
#################################################################
def make_rint_vector(a):
return IntVector(map(lambda i: rinterface.NA_Integer if i == 'NA' else int(i), a))
def make_rfloat_vector(a):
return FloatVector(map(lambda f: rinterface.NA_Real if f == 'NA' else float(f), a))
#################################################################
## Parameters ##
#################################################################
# global state for concurrent operations
g_weeder_args = None
g_weeder_results = None
g_meme_args = None
g_cluster_meme_runs = None
g_pred_dict = None
g_pred_total_targets = None
g_biclusters = None
g_ratios = None
g_phenotypes = None
#################################################################
## Functions ##
#################################################################
def meme(num, seqfile, bgfile, nmotifs, min_motif_width, max_motif_width, revcomp, seed=None):
""" Run meme and get the output into PSSMs"""
global g_cluster_meme_runs
# Arguments for meme
args = '%s -bfile %s -nostatus -text -time 600 -dna -maxsize 9999999 -evt 1e9 -mod zoops -minw %d -maxw %d -nmotifs %d' % (seqfile, bgfile, min_motif_width, max_motif_width, nmotifs)
if revcomp:
args += ' -revcomp'
if not seed is None:
args += ' -cons ' + str(seed)
print "MEME args: '%s'" % args
meme_proc = Popen("meme %s" % args, shell=True, stdout=PIPE)
output = meme_proc.communicate()[0].split('\n')
PSSMs = []
for i in range(len(output)):
desc_comps = output[i].strip().split(' ')
if desc_comps[0] == 'Motif' and desc_comps[2] == 'position-specific' and desc_comps[3] == 'probability':
i += 2 # Skip the separator line, go to the summary line
summary_comps = output[i].strip().split(' ')
width = int(summary_comps[5])
sites = int(summary_comps[7])
evalue = float(summary_comps[9])
matrix = []
for j in range(width):
i += 1
matrix += [[float(let) for let in output[i].strip().split(' ') if let]]
PSSMs.append(PSSM('%s_motif%s_meme' % (os.path.basename(seqfile).split('_')[1].split('.')[0], desc_comps[1]),
sites, evalue, matrix, [], 'meme'))
g_cluster_meme_runs[num] = PSSMs
def run_meme(runarg):
"""Wrapper function to run the meme function using a multiprocessing pool
"""
global g_meme_args
run_num, filepath = runarg
meme(run_num, filepath, g_meme_args['bgfile'], g_meme_args['nmotifs'], g_meme_args['min_motif_width'],
g_meme_args['max_motif_width'], g_meme_args['revcomp'])
def weeder(bicluster, seqfile, bgfile, size, enriched, revcomp):
"""
Run weeder and parse its output
First weederTFBS -W 6 -e 1, then weederTFBS -W 8 -e 2, and finally adviser
"""
global g_weeder_results
print "run weeder on '%s'" % seqfile
# First run weederTFBS
weeder_args = "%s %s %s %s" % (seqfile, bgfile, size, enriched)
if revcomp:
weeder_args += ' S'
errout = open(cfg['tmpdir']+'/weeder/stderr.out','w')
weeder_proc = Popen("weederlauncher %s" % weeder_args, shell=True, stdout=PIPE, stderr=errout)
output = weeder_proc.communicate()
# Now parse output from weeder
PSSMs = []
output = open(str(seqfile)+'.wee','r')
outLines = [line for line in output.readlines() if line.strip()]
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:]
# 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:]
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
motif_id = 1
bicluster_id = int(os.path.basename(seqfile).split('_')[1].split('.')[0])
while 1:
if len(outLines)<=1:
break
if revcomp:
name = outLines.pop(0).strip() # Get match
name += '_'+outLines.pop(0).strip()
else:
name = outLines.pop(0).strip() # Get match
if not name.find('(not highest-ranking)') == -1:
break
# Get redundant motifs
outLines.pop(0)
red_motifs = [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 = [float(i.strip()) for i in col.strip().split('\t')[1].split(' ') if i]
colsum = sum(nums)
matrix += [[ nums[0] / colsum, nums[1] / colsum, nums[2] / colsum, nums[3] / colsum]]
col = outLines.pop(0)
PSSMs += [PSSM('%d_motif%d_weeder' % (bicluster_id, motif_id),
len(instances), hitBp[len(matrix)][1], matrix, red_motifs, 'weeder')]
motif_id += 1
g_weeder_results[bicluster] = PSSMs
def run_weeder(run_arg):
global g_weeder_args
run_num, filepath = run_arg
weeder(run_num, filepath, g_weeder_args['bgfile'], g_weeder_args['size'],
g_weeder_args['enriched'], g_weeder_args['revcomp'])
def tomtom(num, dist_meth='ed', q_thresh=1, min_overlap=6):
args = '-dist %s -o tmp/tomtom_out -text -thresh %d -min-overlap %d -verbosity 1 tmp/query%d.tomtom tmp/target%d.tomtom' % (dist_meth, q_thresh, min_overlap, num, num)
print args
with open(cfg['tmpdir']+'/stderr_%d.out' % num,'w') as errout:
tomtom_proc = Popen("tomtom %s" % args, shell=True, stdout=PIPE, stderr=errout)
with open(cfg['tmpdir']+'/tomtom_out/tomtom%d.out' % num, 'w') as outfile:
output = tomtom_proc.communicate()[0]
outfile.write(output)
def run_tomtom(i):
tomtom(i, 'ed', 1, 6)
def phyper(q, m, n, k, lower_tail=False):
"""calls the R function phyper, input values are lists and returns a list"""
r_phyper = robj.r['phyper']
kwargs = {'lower.tail': lower_tail}
return [f for f in
r_phyper(FloatVector(q), FloatVector(m), FloatVector(n), FloatVector(k), **kwargs)]
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.
"""
cor_test = robj.r['cor.test']
result = cor_test(make_rfloat_vector(a1), make_rfloat_vector(a2))
res = dict(zip(result.names, list(result)))
return res['estimate'][0], res['p.value'][0]
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:
"""
surv = robj.r("""
library('survival')
surv <- function(s, dead, pc1, age) {
scph1 = summary(coxph(Surv(s,dead == 'DEAD') ~ pc1))
scph2 = summary(coxph(Surv(s,dead == 'DEAD') ~ pc1 + age))
c(scph1$coef[1,4], scph1$coef[1,5], scph2$coef[1,4], scph2$coef[1,5])
}
""")
res = surv(make_rint_vector(survival), StrVector(dead), make_rfloat_vector(pc1), make_rint_vector(age))
return [[res[0], res[1]], [res[2], res[3]]]
def compareMiRNANames(a, b):
"""
Match miRNA names.
Input: Two miRNA names to be compared.
Returns:
"""
if a==b:
return 1
if len(a)<len(b):
if a[-3:]=='-3p':
re1 = re.compile(a+'[a-oq-z]?(-\d)?-3p$')
else:
re1 = re.compile(a+'[a-oq-z]?(-\d)?(-5p)?$')
if re1.match(b):
return 1
else:
if b[-3:]=='-3p':
re1 = re.compile(b+'[a-oq-z]?(-\d)?-3p$')
else:
re1 = re.compile(b+'[a-oq-z]?(-\d)?(-5p)?$')
if re1.match(a):
return 1
return 0
def is_number(s):
try:
float(s)
return True
except ValueError:
return False
def read_synonyms(cfg):
""" Load synonym thesaurus to get a mapping from entrez id to a list
of UCSC IDs.
The synonym file is assumed to be in the format
<UCSC ID>,<alt1>;<alt2>;...
and the Entrez ID is assumed to be the first numerical value in the
alternatives."""
entrez2id = defaultdict(list)
with gzip.open(cfg['synonyms-file'], 'r') as infile:
for line in infile:
row = line.strip().split(',')
id = row[0]
entrez = [i for i in row[1].split(';') if is_number(i)]
if len(entrez) == 1:
entrez2id[entrez[0]].append(id)
return entrez2id
def miRNA_mappings(cfg):
"""Create a dictionary to convert the miRNAs to there respective ids"""
mirna_ids = {}
mirna_ids_rev = {}
with open(cfg['mirna-fasta-file'], 'r') as infile:
for line in infile:
splitUp = line.split(' ')
if not splitUp[1] in mirna_ids_rev:
mirna_ids_rev[splitUp[1]] = splitUp[0].lower()
if not splitUp[0].lower() in mirna_ids:
mirna_ids[splitUp[0].lower()] = splitUp[1]
else:
print 'Uh oh!', splitUp
return mirna_ids, mirna_ids_rev
def read_cmonkey_run(cfg, entrez2id):
""" Load cMonkey Object - turns cMonkey data into objects"""
output_path = cfg.outdir_path('c1.pkl')
# If this is the first time then load from the RData file
if not os.path.exists(output_path):
c1 = cMonkeyWrapper(cfg['cmonkey-rundb'], meme_upstream=False, weeder_upstream=False,
weeder_3pUTR=False, tfbs_db=False,
pita_3pUTR=False,
targetscan_3pUTR=False,
promoterSeq=cfg['promoterSeq'],
p3utrSeq=cfg['p3utrSeq'],
geneConv=entrez2id)
with open(output_path, 'wb') as pklFile:
cPickle.dump(c1, pklFile)
# Otherwise load the dumped pickle file if it exists
else:
print 'Loading precached cMonkey object...'
with open(output_path, 'rb') as pklFile:
c1 = cPickle.load(pklFile)
print 'Done.\n'
return c1
def compute_upstream_motifs_meme(cfg, c1):
"""
A. Upstream motifs (MEME) ##
If MEME hasn't been run on the biclusters upstream sequences then do so
"""
global g_meme_args, g_cluster_meme_runs
if not c1.meme_upstream:
print 'Running MEME on Upstreams:'
pkl_path = cfg.outdir_path('meme_upstream.pkl')
# Use already run MEME results if they exist
if not os.path.exists(pkl_path):
# Make needed directories
#cfg.clear_tmp()
cfg.create_tmpdir('meme/fasta')
# Run MEME on all biclusters
mgr = Manager()
run_args = []
# First make fasta files for all biclusters
print 'Making Files for MEME Upstream run...'
for cluster_num in c1.biclusters:
print cluster_num
seqs = c1.bicluster_seqs_upstream(cluster_num)
print len(seqs)
if len(seqs) > 0:
cluster_filename = cfg.tmpdir_path('meme/fasta/bicluster_%d.fasta' % cluster_num)
run_args.append((cluster_num, cluster_filename))
with open(cluster_filename, 'w') as outfile:
outfile.write('\n'.join(['>'+gene+'\n'+seqs[gene] for gene in seqs]))
# Where all the results will be stored
g_cluster_meme_runs = mgr.dict()
# Parameters to use for running MEME
g_meme_args = mgr.dict({'bgfile': cfg['meme']['upstream']['bgfile'], 'nmotifs': cfg['meme']['upstream']['nmotifs'],
'min_motif_width': cfg['meme']['upstream']['motif-widths'][0],
'max_motif_width': cfg['meme']['upstream']['motif-widths'][1],
'revcomp': bool(cfg['meme']['upstream']['revcomp'])})
print 'Running MEME on Upstream sequences...'
print 'There are %d CPUs available.' % cpu_count()
pool = Pool(processes=cpu_count())
pool.map(run_meme, run_args)
pool.close()
pool.join()
# Dump weeder results as a pickle file
with open(pkl_path, 'wb') as outfile:
cPickle.dump(deepcopy(g_cluster_meme_runs), outfile)
else:
print 'Loading from precached object...'
with open(pkl_path, 'rb') as outfile:
g_cluster_meme_runs = cPickle.load(outfile)
# Add PSSMs to cMonkey object
print 'Storing output...'
for cluster_num, pssms in g_cluster_meme_runs.items():
for pssm1 in pssms:
bicluster = c1.biclusters[cluster_num]
pssm1.de_novo_method = 'meme'
bicluster.add_pssm_upstream(pssm1)
print 'Done with MEMEing.\n'
# MEME upstream has been run on cMonkey run
c1.meme_upstream = True
def __compute_motifs_weeder(cfg, pkl_path, biclusters, add_result, bicluster_seqs, args_dict):
"""Generic motif detection function with weeder
"""
global g_weeder_args, g_weeder_results
if not os.path.exists(pkl_path):
#cfg.clear_tmp()
cfg.create_tmpdir('weeder/fasta')
# Run MEME on all biclusters
mgr = Manager()
run_args = []
# First make fasta files for all biclusters
for cluster_num in biclusters:
seqs = bicluster_seqs(cluster_num)
if len(seqs) > 0:
cluster_filename = cfg.tmpdir_path('weeder/fasta/bicluster_%d.fasta' % cluster_num)
run_args.append((cluster_num, cluster_filename))
with open(cluster_filename, 'w') as outfile:
outfile.write('\n'.join(['>'+gene+'\n'+seqs[gene] for gene in seqs]))
# Where all the results will be stored
g_weeder_results = mgr.dict()
# Parameters to use for running Weeder
# Set to run Weeder on 'medium' setting which means 6bp, 8bp and 10bp motifs
g_weeder_args = mgr.dict(args_dict)
print 'Running Weeder...'
print 'There are %d CPUs available.' % cpu_count()
pool = Pool(processes=cpu_count())
pool.map(run_weeder, run_args)
pool.close()
pool.join()
# Dump weeder results as a pickle file
with open(pkl_path,'wb') as outfile:
cPickle.dump(deepcopy(g_weeder_results), outfile)
else:
print 'Loading from precached object...'
with open(pkl_path,'rb') as infile:
g_weeder_results = cPickle.load(infile)
print 'Storing output...'
for i, pssms in g_weeder_results.items():
for p in pssms:
p.de_novo_method = 'weeder'
add_result(i, p)
def compute_upstream_motifs_weeder(cfg, c1):
if not c1.weeder_upstream:
__compute_motifs_weeder(cfg, cfg.outdir_path('weeder_upstream.pkl'),
c1.biclusters,
lambda bi, p: c1.biclusters[bi].add_pssm_upstream(p),
lambda bi: c1.bicluster_seqs_upstream(bi),
{'bgfile': cfg['weeder']['upstream']['bgfile'],
'size': cfg['weeder']['upstream']['size'],
'enriched': cfg['weeder']['upstream']['enriched'],
'revcomp': bool(cfg['weeder']['upstream']['revcomp'])})
c1.weeder_upstream = True
def compute_3pUTR_weeder(cfg, c1):
if not c1.weeder_3pUTR:
__compute_motifs_weeder(cfg, cfg.outdir_path('weeder_3pUTR.pkl'),
c1.biclusters,
lambda bi, p: c1.biclusters[bi].add_pssm_3putr(p),
lambda bi: c1.bicluster_seqs_3putr(bi),
{'bgfile': cfg['weeder']['3pUTR']['bgfile'],
'size': cfg['weeder']['3pUTR']['size'],
'enriched': cfg['weeder']['3pUTR']['enriched'],
'revcomp': bool(cfg['weeder']['3pUTR']['revcomp'])})
c1.weeder_3pUTR = True
def cluster_hypergeo(bicluster_id):
"""concurrent computation
k = overlap, N = potential target genes, n = miRNA targets, m = cluster genes
Take gene list and compute overlap with each miRNA
"""
global g_pred_dict, g_pred_total_targets, g_biclusters
db = g_pred_dict
all_genes = g_pred_total_targets[0]
genes = all_genes.intersection(g_biclusters[bicluster_id].genes)
m1s = []
q = []
m = []
n = []
k = []
for m1, m1_genes in db.items():
m1s.append(m1)
miRNAGenes = all_genes.intersection(m1_genes)
q.append(len(set(miRNAGenes).intersection(genes)))
m.append(len(miRNAGenes))
n.append(len(all_genes) - len(miRNAGenes))
k.append(len(genes))
results = phyper(q,m,n,k)
min_mirna = []
perc_targets = []
min_pvalue = 1.0
for i in range(1, len(results)):
if float(results[i]) <= 0.05 / 674.0 and 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 #%d' % bicluster_id, ' '.join([m1s[miRNA] for miRNA in min_mirna])
return [bicluster_id, ' '.join([m1s[i] for i in min_mirna]),
' '.join(map(str, perc_targets)), min_pvalue]
def __bicluster_genes(c1):
result = set()
for key, bicluster in c1.biclusters.items():
for gene in bicluster.genes:
result.add(gene)
return result
def __read_predictions(pred_path, pkl_path, genes_in_biclusters, manager):
if not os.path.exists(pkl_path):
print 'loading predictions...'
tmp_set = set()
tmp_dict = {}
with gzip.open(pred_path, 'r') as infile:
inLines = [i.strip().split(',') for i in infile.readlines() if i.strip()]
for line in inLines:
if line[1] in genes_in_biclusters:
tmp_set.add(line[1])
if not line[0] in tmp_dict:
tmp_dict[line[0]] = []
tmp_dict[line[0]].append(line[1])
with open(pkl_path,'wb') as pklFile:
cPickle.dump(tmp_dict, pklFile)
cPickle.dump(tmp_set, pklFile)
# Otherwise load the dumped pickle file if it exists
else:
print 'Loading pickled predictions...'
with open(pkl_path,'rb') as pklFile:
tmp_dict = cPickle.load(pklFile)
tmp_set = cPickle.load(pklFile)
pred_dict = manager.dict(tmp_dict)
pred_total_targets = manager.list()
pred_total_targets.append(set(tmp_set))
return pred_dict, pred_total_targets
def __compute_enrichment(c1, name, pkl_path, pred_path, pred_pkl_path):
"""General enrichment analysis function"""
global g_pred_dict, g_pred_total_targets, g_biclusters
print 'Running %s enrichment on Biclusters:' % name
if not os.path.exists(pkl_path):
print 'Get a list of all genes in run...'
mgr = Manager()
g_biclusters = mgr.dict(c1.biclusters)
g_pred_dict, g_pred_total_targets = __read_predictions(pred_path, pred_pkl_path,
__bicluster_genes(c1), mgr)
print '%s prediction has %d TFs.' % (name, len(g_pred_dict))
print 'Running %s enrichment analyses...' % name
pool = Pool(processes=cpu_count())
result = pool.map(cluster_hypergeo, c1.biclusters.keys())
pool.close()
pool.join()
with open(pkl_path, 'wb') as pklFile:
cPickle.dump(result, pklFile)
else:
print 'Loading precached analysis...'
with open(pkl_path, 'rb') as pklFile:
result = cPickle.load(pklFile)
return result
def compute_tfbsdb_enrichment(cfg, c1):
"""D. Upstream TFBS DB enrichment Analysis"""
if not c1.tfbs_db:
res1 = __compute_enrichment(c1, 'TFBS_DB', cfg.outdir_path('tfbs_db.pkl'),
'TF/tfbsDb_5000_gs.csv.gz',
'TF/tfbs_db.pkl')
print 'Storing results...'
for r1 in res1:
# r1 = [biclusterId, tf(s), Percent Targets, P-Value]
bicluster = c1.biclusters[r1[0]]
bicluster.add_attribute('tfbs_db', {'tf':r1[1], 'percentTargets': r1[2],
'pValue':r1[3]})
print 'Done.\n'
c1.tfbs_db = True
def compute_3pUTR_pita_set_enrichment(cfg, c1, mirna_ids):
"""E. 3' UTR PITA"""
if not c1.pita_3pUTR:
res1 = __compute_enrichment(c1, 'PITA', cfg.outdir_path('pita_3pUTR.pkl'),
'miRNA/pita_miRNA_sets_geneSymbol.csv.gz',
'miRNA/pita.pkl')
print 'Storing results...'
for r1 in res1:
# r1 = [biclusterId, miRNA(s), Percent Targets, P-Value]
bicluster = c1.biclusters[r1[0]]
miRNA_mature_seq_ids = []
for m1 in r1[1]:
miRNA_mature_seq_ids += utils.mirna_in_dict(m1.lower(), mirna_ids)
bicluster.add_attribute('pita_3pUTR', {'miRNA': r1[1],
'percentTargets': r1[2],
'pValue': r1[3],
'mature_seq_ids': miRNA_mature_seq_ids})
print 'Done.\n'
c1.pita_3pUTR = True
def compute_3pUTR_targetscan_set_enrichment(cfg, c1, mirna_ids):
"""F. 3' UTR TargetScan"""
if not c1.targetscan_3pUTR:
res1 = __compute_enrichment(c1, 'TargetScan', cfg.outdir_path('targetscan_3pUTR.pkl'),
'miRNA/targetscan_miRNA_sets_geneSymbol.csv.gz',
'miRNA/targetScan.pkl')
print 'Storing results...'
for r1 in res1:
# r1 = [biclusterId, miRNA(s), Percent Targets, P-Value]
bicluster = c1.biclusters[r1[0]]
miRNA_mature_seq_ids = []
for m1 in r1[1]:
miRNA_mature_seq_ids += utils.mirna_in_dict(m1.lower(), mirna_ids)
bicluster.add_attribute('targetscan_3pUTR',
{'miRNA': r1[1], 'percentTargets': r1[2],
'pValue':r1[3], 'mature_seq_ids': miRNA_mature_seq_ids})
print 'Done.\n'
c1.targetscan_3pUTR = True
def compute_additional_info(cfg, mirna_ids, entrez2id):
cm_pkl_path = cfg.outdir_path('c1_all.pkl')
if not os.path.exists(cm_pkl_path):
c1 = read_cmonkey_run(cfg, entrez2id)
################################################################
## 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. TFBS DB Enrichment #
# E. 3' UTR PITA (Set Enrichment) #
# F. 3' UTR TargetScan (Set Enrichment) #
################################################################
compute_upstream_motifs_meme(cfg, c1)
compute_upstream_motifs_weeder(cfg, c1)
compute_3pUTR_weeder(cfg, c1)
compute_tfbsdb_enrichment(cfg, c1)
compute_3pUTR_pita_set_enrichment(cfg, c1, mirna_ids)
compute_3pUTR_targetscan_set_enrichment(cfg, c1, mirna_ids)
with open(cm_pkl_path, 'wb') as outfile:
cPickle.dump(c1, outfile)
else:
print 'Loading prechached cMonkey Object (c1_all.pkl):'
with open(cm_pkl_path, 'rb') as infile:
c1 = cPickle.load(infile)
return c1
def post_process(cluster_num):
global g_ratios, g_phenotypes
def clean_name(name):
comps = name.split('.')
return '%s.%s.%s' % (comps[0], comps[1], comps[2])
attributes = {}
print ' Postprocessing cluster:', cluster_num
bicluster = c1.biclusters[cluster_num]
attributes['k'] = cluster_num
# Add number of genes and conditions
attributes['k.rows'] = bicluster.num_genes()
attributes['k.cols'] = bicluster.num_conditions()
# Get matrix of expression for genes
genes = bicluster.genes
conditions = g_ratios[genes[0]].keys()
matrix = [[g_ratios[gene][condition] for condition in conditions] for gene in genes]
# Get first principal component variance explained
fpc = bicluster.attributes['pc1']
if not g_phenotypes=='NA':
# Corrleation with patient traits
cleanNames = dict(zip([clean_name(i) for i in conditions], conditions))
cond2 = set(cleanNames.keys()).intersection(g_phenotypes['SURVIVAL'].keys())
pc1_1 = [fpc[cleanNames[i]] for i in cond2]
for phenotype in ['AGE', 'SEX.bi', 'chemo_therapy', 'radiation_therapy']:
p1_1 = [g_phenotypes[phenotype][i] for i in cond2]
cor1 = correlation(pc1_1, p1_1)
attributes[phenotype] = dict(zip(['rho', 'pValue'], cor1))
# Association of bicluster expression with patient survival
surv = [g_phenotypes['SURVIVAL'][i] for i in cond2]
dead = [g_phenotypes['DEAD'][i] for i in cond2]
age = [g_phenotypes['AGE'][i] for i in cond2]
s1 = survival(surv, dead, pc1_1, age)
attributes['Survival'] = dict(zip(['z', 'pValue'], s1[0]))
attributes['Survival.AGE'] = dict(zip(['z', 'pValue'], s1[1]))
return attributes
def __read_ratios(cfg, c1):
print "reading ratios matrix"
with open(cfg['ratios-file'], 'r') as infile:
conditions = [i.strip('"') for i in infile.readline().strip().split('\t')]
ratios = {}
for line in infile:
comps = line.strip().split('\t')
ratios[comps[0].strip('"')] = dict(zip(conditions, comps[1:]))
print "dump cluster row members"
with open(cfg.outdir_path('cluster.members.genes.txt'), 'w') as outfile:
for cluster_num in c1.biclusters:
outfile.write('%s %s\n' % (cluster_num, ' '.join(c1.biclusters[cluster_num].genes)))
print "dump cluster condition members"
with open(cfg.outdir_path('cluster.members.conditions.txt'), 'w') as outfile:
for cluster_num in c1.biclusters:
outfile.write('%s %s\n' % (cluster_num, ' '.join(c1.biclusters[cluster_num].conditions)))
return ratios
def __get_cluster_eigengenes(cfg, c1):
# Calculate bicluster eigengene (first principal components)
print "compute bicluster eigengenes"
cluster_eigengenes_path = cfg.outdir_path('biclusterEigengenes.csv')
if not os.path.exists(cluster_eigengenes_path):
ret = subprocess.check_call(['./getEigengene.R',
'-r', cfg['ratios-file'],
'-o', cfg['outdir']],
stderr=subprocess.STDOUT)
if ret == 1:
print "could not create Eigengenes"
exit(1)
# Read in bicluster eigengene
print "read bicluster eigengenes"
with open(cluster_eigengenes_path, 'r') as infile:
patients = [i.strip('"') for i in infile.readline().strip().split(',')]
patients.pop(0) # Get rid of rowname placeholder
for line in infile:
eigengene = line.strip().split(',')
cluster_num = int(eigengene.pop(0).strip('"'))
bicluster = c1.biclusters[cluster_num]
bicluster.add_attribute('pc1', dict(zip(patients, eigengene)))
def __get_cluster_variance_explained(cfg, c1):
print "read bicluster variance explained"
with open(cfg.outdir_path('biclusterVarianceExplained.csv'), 'r') as infile:
infile.readline() # Get rid of header
for line in infile:
varExplained = line.strip().split(',')
cluster_num = int(varExplained.pop(0).strip('"'))
bicluster = c1.biclusters[cluster_num]
bicluster.add_attribute('pc1.var.exp', varExplained[0])
def __get_phenotype_info(cfg, c1):
# AGE,chemo_therapy,SURVIVAL,days_to_tumor_progression,SEX.bi,radiation_therapy,DEAD
print "read phenotype information"
phenotypes = {}
with open(cfg['phenotypes-file'], 'r') as infile:
ids = infile.readline().strip().split(',')[1:]
for i in ids:
phenotypes[i] = {}
for line in infile:
splitUp = line.strip().split(',')
phenotypes[splitUp[0]] = {}
for i in range(len(ids)):
phenotypes[ids[i]][splitUp[0]] = splitUp[i+1]
return phenotypes
def __do_postprocess(postprocess_pkl_path, c1, ratios, phenotypes):
global g_ratios, g_phenotypes
if not os.path.exists(postprocess_pkl_path):
g_ratios = ratios
g_phenotypes = phenotypes
print 'Do post processing...'
pool = Pool(processes=cpu_count())
res1 = pool.map(post_process, c1.biclusters)
pool.close()
pool.join()
print 'Done.\n'
# Dump res1 into a pkl
with open(postprocess_pkl_path, 'wb') as outfile:
cPickle.dump(res1, outfile)
else:
with open(postprocess_pkl_path, 'rb') as infile:
res1 = cPickle.load(infile)
# Put results in cMonkey object
for entry in res1:
bicluster = c1.biclusters[entry['k']]
for attribute in entry:
if not attribute == 'k':
bicluster.add_attribute(attribute, entry[attribute])
def __tomtom_upstream_motifs(cfg):
#################################################################
## TomTom Upstream motifs versus Jaspar and Transfac ##
#################################################################
print 'Running TOMTOM on Upstream Motifs:'
# Make needed directories
#cfg.clear_tmp()
cfg.create_tmpdir('tomtom_out')
pssms = c1.pssms_upstream()
upstreamMatches = {}
comparison_pkl_path = cfg.outdir_path('upstreamJasparTransfacComparison.pkl')
comparison_csv_path = cfg.outdir_path('upstreamComparison_jaspar_transfac.csv')
target_pssms_in = []
for motif_file in cfg['tomtom']['upstream']['motif-files']:
pssms = pssm_mod.load_pssms_json(motif_file)
for pssm in pssms.values():
pssm.de_novo_method = 'meme'
target_pssms_in.append(pssms)
if not os.path.exists(comparison_pkl_path):
# Write out results
with open(comparison_csv_path, 'w') as outFile:
outFile.write('Motif Name,Original E-Value,Consensus,JASPAR Motif,JASPAR Consensus,TomTom.pValue,TomTom.qValue,Probe In Bicluster,Bicluster Residual')
# Making MEME formatted files (make_files function in utils)
print 'Making files...'
for i, target_pssms in enumerate(target_pssms_in):
utils.make_files(c1.nucFreqsUpstream, pssms.values(),
target_pssms.values(), i)
# Run TomTom
print 'Comparing Upstream motifs against databases...'
pool = Pool(processes=cpu_count())
res1 = pool.map(run_tomtom, [i for i in range(len(target_pssms_in))])
pool.close()
pool.join()
print 'Reading in Tomtom run...'
output_lines = []
for i in range(len(target_pssms_in)):
with open(cfg.tmpdir_path('tomtom_out/tomtom%d.out' % i), 'r') as tomtom_outfile:
tomtom_outfile.readline() # skip header
output_lines += [line.strip().split('\t') for line in tomtom_outfile
if float(line.split('\t')[5]) <= 0.05]
# Now iterate through output and save data
print 'Now parsing output for %d matches...' % len(output_lines)
for outputLine in output_lines:
if len(outputLine) == 10 and float(outputLine[5]) <= 0.05:
tfName = outputLine[1].split('_')[0]
if not outputLine[0] in upstreamMatches:
upstreamMatches[outputLine[0]] = [{'factor':outputLine[1],'confidence':outputLine[5]}]
else:
upstreamMatches[outputLine[0]].append({'factor':outputLine[1],'confidence':outputLine[5]})
with open(comparison_pkl_path,'wb') as pklFile:
cPickle.dump(upstreamMatches, pklFile)
else:
print 'Loading precached upstream matches...'
with open(comparison_pkl_path, 'rb') as pklFile:
upstreamMatches = cPickle.load(pklFile)
# Pump into pssms
for pssmName in upstreamMatches:
for match in upstreamMatches[pssmName]:
pssms[pssmName].add_match(factor=match['factor'], confidence=match['confidence'])
print 'We matched '+str(len(upstreamMatches))+' upstream motifs.\n'
def __expand_tf_factor_list(entrez2id):
#################################################################
## Prepare to get expanded set of TFs from TFClass ##
## (http://tfclass.bioinf.med.uni-goettingen.de/) ##
#################################################################
print 'Expanding TF factor list with TFClass families...'
# Read in humanTFs_All.csv with <TF Name>,<Entrez ID>
tfName2entrezId = {}
with open(cfg['tfExpansion']['tfs'],'r') as inFile:
inFile.readline() # Get rid of header
for line in inFile:
splitUp = line.strip().split(',')
if splitUp[2] in entrez2id:
for i in entrez2id[splitUp[2]]:
tfName2entrezId[splitUp[0]] = i
# Read in tfFamilies.csv for expanded list of possible TFs
tfFamilies = {}
with open(cfg['tfExpansion']['tfFamilies'],'r') as inFile:
inFile.readline() # Get rid of header
for line in inFile: