-
Notifications
You must be signed in to change notification settings - Fork 0
/
SubCAnalysis.py
1320 lines (1010 loc) · 41.2 KB
/
SubCAnalysis.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
# -*- coding: utf-8 -*-
# <nbformat>3.0</nbformat>
# <codecell>
from __future__ import division
import pandas as pd
import csv
import sys
import os, os.path
import numpy as np
sys.path.append('/home/will/PySeqUtils/')
import GeneralSeqTools
# <codecell>
print 2+2
# <codecell>
import glob
from Bio import SeqIO
from concurrent.futures import ProcessPoolExecutor
from itertools import islice, imap
import os, os.path
import csv
def get_gi_acc(fname):
gb = fname.split('/')[-1].split('.')[0]
with open(fname) as handle:
for line in handle:
if line.startswith('ACCESSION'):
acc = line.strip().split()[-1]
return gb, acc
raise AssertionError
gi_to_acc_dict = {}
fname = '/home/will/WLAHDB_data/gi_to_acc.csv'
if os.path.exists(fname):
with open(fname) as handle:
for row in csv.reader(handle):
gi_to_acc_dict[row[0]] = row[1]
else:
gb_files = glob.glob('/home/will/WLAHDB_data/GenbankDL/*.gb')
with open(fname, 'w') as handle:
writer = csv.writer(handle)
for num, (gbm, acc) in enumerate(imap(get_gi_acc, gb_files)):
if (num == 100) or (num % 50000 == 0):
print num
gi_to_acc_dict[gbm] = acc
writer.writerow((gbm, acc))
# <codecell>
files = [('C', sorted(glob.glob('/home/will/WLAHDB_data/SeqDump/C_*'))),
('B', sorted(glob.glob('/home/will/WLAHDB_data/SeqDump/B_*')))]
seqs = []
for sub, sfiles in files:
for f in sfiles:
with open(f) as handle:
base_name = f.rsplit(os.sep,1)[1].rsplit('.',1)[0]
prot = base_name.split('_')[1]
for name, seq in GeneralSeqTools.fasta_reader(handle):
seqs.append({
'Seq':seq,
'ID':gi_to_acc_dict[name],
'Prot':prot,
'Subtype':sub
})
seqdf = pd.DataFrame(seqs)
# <codecell>
pseqdf = pd.pivot_table(seqdf,
rows = ['Subtype', 'ID'],
cols = 'Prot',
values = 'Seq',
aggfunc = 'first')
# <codecell>
checker = pd.read_csv('/home/will/Downloads/hivseqdb/HIVSeqDB-MetaData.tsv', sep = '\t')
check_res = pd.merge(checker, pseqdf.ix['B'],
left_on = 'Accession',
right_index=True,
how = 'inner')
check_res
#pseqdf
# <codecell>
mat_dict = {'B':'x4r5', 'C':'subC'}
v3_res = []
for sub, df in pseqdf.groupby(level = 'Subtype'):
v3_seqs = [(gi, seq) for (_, gi), seq in df['v3'].dropna().to_dict().items()]
for num, row in enumerate(GeneralSeqTools.WebPSSM_V3_series(v3_seqs, matrix=mat_dict[sub])):
if (num == 0) or (num == 100) or (num == 10) or (num % 5000 == 0):
print num
v3_res.append(row)
v3_res[-1]['Subtype'] = sub
# <codecell>
def safe_mean(vals):
if len(vals.dropna()):
return np.mean(vals.map(float).dropna())
else:
return np.nan
v3_df = pd.DataFrame(v3_res).convert_objects()
x4_pred = v3_df.groupby(['Subtype', 'name'])['pred'].agg(safe_mean) > 0.5
# <codecell>
conb_ltr = """tGGAaGGGcTaaTttacTCcCaaaaaAgacAagAtATcCTTGAtcTGTGG
gtctAccAcAcaCAaGGCTacTTCCCtGAtTgGCAgAAcTACACAccAGG
gccaGGgatcAGaTatCCacTgaccTTTGGaTGgTGcTtcAAgcTAGTAC
CAgTtgAgCcAGagaaggTagAagagGccAatgaaggagagaacaacagc
tTGtTaCAcCCtatgagCCtgCATGGgatgGAgGAcccgGAgaaagAAGt
gtTagtgTGGAagTttGACAgccgccTaGcatttcatCAcatggCccgaG
AgctgcATCCggAgTactacaaggActGcTGACatcgagctttctacaaG
GGACTTTCCgCtgGGGACTTTccagggagGcGtggcctGGgcgggaCtgg
GGAgtggCgagCCCtcAGAtgcTgCATATAAGCAGCtGCttTttGccTGT
ACtGGgTCTCTCTggttaGaCCAGATCtGAGCctGGGAGcTCtctggcta
actagggaacccactgcttaagcctcaataaagcttgccttgagtgcttc
aagtagtgtgtgcccgtctgttgtgtgactctggtaactagagatccctc
agacccttttagtcagtgtggaaaatctctagca""".replace('\n', '').upper()
conc_ltr = """tggaagggttaatttactctaagaaaaggcaagagatccttgatttgtgg
gtctatcacacaCaAGgctactTcCCtGAtTGGCAaaacTacACACCgGG
aCCaGGggtcAgatacCCacTgACctttGGaTGGtgcTtcAAgctaGTaC
CAgTtgacCCaaggGaagtaGAagAggccaacgaaggaGAaaacaaCtGt
tTgcTaCAcCCtatgagcCagCatGGaatgGAggAtgaacacagagAAgt
atTaaagTGGaagtttgacagtcaccTaGcacgcagacacatggcCcGcg
aGctacATCcGGAgTatTAcAaagACTGCTGacACagaaGGgACTtTccg
ctgggactttccactgGGGcgttccaggaggtgtggtctGGGCGGgActG
GGAGTGGtcaaCCCtCaGatGctgCATATAAGCagcTGCTTTtcgcctgt
actgggtctctctaggtagaccagatctgagcctgggagctctctggcta
tctagggaacccactgcttaagcctcaataaagcttgccttgagtgctct
aagtagtgtgtgccctctgttttgactctggtaactagagatccctcaga
cccttttggtagtgaggaaatctctagca""".replace('\n', '').upper()
ltrs = {'B':conb_ltr, 'C':conc_ltr}
# <codecell>
ltr_aligns = []
for align_sub, ltr_seq in ltrs.items():
for sub, df in pseqdf.groupby(level = 'Subtype'):
ltr_seqs = [(gi, seq) for (_, gi), seq in df['ltr'].dropna().to_dict().items()]
for num, (gi, align) in enumerate(GeneralSeqTools.seq_align_to_ref(ltr_seqs, ltr_seq)):
if (num == 0) or (num == 100) or (num == 10) or (num % 1000 == 0):
print align_sub, sub, num
ltr_aligns.append({
'Subtype':sub,
'ID':gi,
'Align-Con'+align_sub:align
})
# <codecell>
ltr_align_df = pd.pivot_table(pd.DataFrame(ltr_aligns),
rows = ['Subtype', 'ID'],
values = ['Align-ConC', 'Align-ConB'],
aggfunc = 'first')
# <codecell>
tmp_seqs = []
for col in ltr_align_df.columns:
res = ltr_align_df[col].apply(lambda x: pd.Series(list(x)))
res.columns = pd.MultiIndex.from_tuples([(col, pos+1) for pos in res.columns],
names = ['AlignType', 'OCol'])
tmp_seqs.append(res.copy())
ltr_cols = pd.concat(tmp_seqs, axis = 1).replace('-', np.nan)
ltr_cols
# <codecell>
from scipy.stats import fisher_exact
from sklearn.metrics import adjusted_mutual_info_score
from functools import partial
def fishers_apply(group_series, seq_series):
vgroup, vseq = group_series.dropna().align(seq_series.dropna(), join = 'inner')
let = vseq.value_counts().idxmax()
ftable = [[(vseq[vgroup]==let).sum(), (vseq[vgroup]!=let).sum()],
[(vseq[~vgroup]==let).sum(), (vseq[~vgroup]!=let).sum()]]
ratio, pval = fisher_exact(ftable)
mi = max(adjusted_mutual_info_score(vgroup.values, vseq.values), 0)
true_con = (vseq[vgroup]==let).mean()
false_con = (vseq[~vgroup]==let).mean()
ser = pd.Series([ratio, pval, mi, true_con, false_con],
index = ['Ratio', 'Pval', 'NMI', 'TrueCons', 'FalseCons'])
return ser
v3_fishers = partial(fishers_apply, x4_pred.ix['C'])
col_pvals = ltr_cols['Align-ConC'].ix['C'].apply(v3_fishers, axis=0).T
# <codecell>
from statsmodels.sandbox.stats.multicomp import multipletests
from scipy.stats import gaussian_kde
reject, adjpval, _, _ = multipletests(col_pvals.dropna()['Pval'], method = 'fdr_bh', alpha = 0.01)
pval_threshold = adjpval[reject].max()
# <codecell>
fig, axs = plt.subplots(4,1, figsize = (10,8), sharex=True)
col_pvals['LogP'] = -np.log10(col_pvals['Pval'])
col_pvals['NMI-P'] = 100*col_pvals['NMI']
plot_cols = [('LogP', '-log10(p-value)'),
('NMI-P', '% Explained Variation'),
('TrueCons', 'X4 Cons'),
('FalseCons', 'R5 Cons')]
for (col, label), ax in zip(plot_cols, axs.flatten()):
ax.plot(col_pvals.index, col_pvals[col])
ax.set_ylabel(label)
if col == 'LogP':
ax.hlines(-np.log10(pval_threshold), 0, max(col_pvals.index), 'r')
elif 'Cons' in col:
ax.set_ylim([0,1])
if ax.is_first_row():
ax.set_title('SubC X4/R5')
elif ax.is_last_row():
ax.set_xlabel('ConC')
ax.set_xlim([0, max(col_pvals.index)])
fig.tight_layout()
plt.savefig('/home/will/Dropbox/Wigdahl HIV Lab/SubCAnalysis/subC_x4_r5.png')
# <codecell>
ld = []
for f in glob.glob('/home/will/SubCData/LANLRes/*.txt'):
ld.append(pd.read_csv(f, sep='\t', index_col=0))
lanl_data = pd.concat(ld, axis = 0, ignore_index=True)
# <codecell>
pd.crosstab(lanl_data['Georegion'], lanl_data['Subtype'])
# <codecell>
geo_regions = lanl_data.groupby('Accession')['Georegion'].first()
# <codecell>
def mni_apply(group_series, seq_series):
vgroup, vseq = group_series.dropna().align(seq_series.dropna(), join = 'inner')
let = vseq.value_counts().idxmax()
cons = (vseq == let).mean()
mi = max(adjusted_mutual_info_score(vgroup.values, vseq.values), 0)
ser = pd.Series([mi, cons],
index = ['NMI', 'Cons'])
return ser
geo_mni = partial(mni_apply, geo_regions)
col_mni = ltr_cols['Align-ConC'].ix['C'].apply(geo_mni, axis=0).T
# <codecell>
fig, axs = plt.subplots(2,1, figsize = (10,8), sharex=True)
col_mni['NMI-P'] = 100*col_mni['NMI']
col_mni['Cons-P'] = 100*col_mni['Cons']
plot_cols = [('NMI-P', '% Explained Variation'),
('Cons-P', '% Conservation')]
for (col, label), ax in zip(plot_cols, axs.flatten()):
ax.plot(col_mni.index, col_mni[col])
ax.set_ylabel(label)
ax.set_ylim([0,100])
if ax.is_first_row():
ax.set_title('SubC Geo')
elif ax.is_last_row():
ax.set_xlabel('ConC')
ax.set_xlim([0, max(col_mni.index)])
fig.tight_layout()
plt.savefig('/home/will/Dropbox/Wigdahl HIV Lab/SubCAnalysis/subC_geo.png')
# <codecell>
from Bio.Seq import Seq
from Bio import Motif
from StringIO import StringIO
from itertools import groupby
from operator import methodcaller
def yield_motifs():
with open('/home/will/LTRtfAnalysis/Jaspar_PWMs.txt') as handle:
for key, lines in groupby(handle, methodcaller('startswith', '>')):
if key:
name = lines.next().strip().split()[-1].lower()
else:
tmp = ''.join(lines)
mot = Motif.read(StringIO(tmp), 'jaspar-pfm')
yield name, mot
yield name+'-R', mot.reverse_complement()
pwm_dict = {}
for num, (name, mot) in enumerate(yield_motifs()):
if num % 100 == 0:
print num
pwm_dict[name] = mot
tmp = u"""
A 0 0 6 1 0 0 0 4 2 2 0 0 3
C 1 1 1 0 5 6 4 1 0 0 0 3 5 5 4 0
G 0 6 0 1 1 0 0 0 0 7 1 1 0 0 1 0
T 6 0 0 0 1 1 3 5 7 0 0 0 0 2 2 4"""
pwm_dict['coup2'] = Motif.read(StringIO(tmp), 'jaspar-pfm')
pwm_dict['coup2-R'] = Motif.read(StringIO(tmp), 'jaspar-pfm').reverse_complement()
# <codecell>
'Bio.Motif._Motif.Motif' in str(type(pwm_dict['coup2']))
# <codecell>
from Bio.Alphabet import IUPAC
def score_seq(mot, seq):
bseq = Seq(seq, alphabet=IUPAC.unambiguous_dna)
scores = mot.scanPWM(bseq)
for pos, score in enumerate(scores.flatten(),1):
if ~np.isnan(score):
tseq = seq[pos:pos+len(mot)]
yield pos, tseq, score
def get_region(seq, reference, regions = None):
if regions == None:
regions = [(300, 400)]
tmp_seqs = [('conc', reference),
('guess', seq)]
aligned = dict(GeneralSeqTools.call_muscle(tmp_seqs))
out = []
for _, start, stop in regions:
conc_pos = 0
align_start = None
for align_pos, l in enumerate(aligned['conc']):
if l != '-':
conc_pos += 1
if conc_pos == start:
align_start = align_pos
if conc_pos == stop:
align_stop = align_pos
break
yield seq[align_start:align_stop].replace('-', '')
def count_mots(mot, threshes, seq):
check_seq = get_region(seq).next()
if len(check_seq) > 0:
bseq = Seq(check_seq, alphabet=IUPAC.unambiguous_dna)
scores = mot.scanPWM(bseq)
out = []
for name, thresh in threshes:
out.append((name, (scores>=thresh).sum()))
out.append(('300to400Size', len(check_seq)))
else:
out = [(n, np.nan) for n, _ in thresh]
out += [('300to400Size', np.nan)]
return pd.Series(dict(out))
def check_max_scores(mots, regions, reference, seq):
names = []
out_seqs = []
out_scores = []
check_seqs = get_region(seq, reference, regions = regions)
for (name, rstart, rstop), check_seq, mot in zip(regions, check_seqs, mots):
names.append(name)
if len(check_seq) < len(mot):
out_scores.append(np.nan)
out_seqs.append(np.nan)
else:
bseq = Seq(check_seq, alphabet=IUPAC.unambiguous_dna)
scores = np.maximum(mot.scanPWM(bseq),
mot.reverse_complement().scanPWM(bseq))
start_pos = np.argmax(scores)
out_scores.append(np.max(scores))
out_seqs.append(check_seq[start_pos:start_pos+len(mot)])
inds = list(product(['Scores', 'Seqs'],
names))
mi = pd.MultiIndex.from_tuples(inds)
ser = pd.Series(out_scores + out_seqs,
index = mi)
return ser
# <codecell>
conC_regions = [('NFAT-III', 163-5, 181+5),
('NFAT-II', 182-5, 200+5),
('NFAT-I', 240-5, 250+5),
('CEBP', 198-5, 210+5),
('NFKB-IV', 332-10, 332+10),
('NFKB-III', 340-5, 349+5),
('NFKB-II', 353-5, 362+5),
('NFKB-I', 366-5, 375+5),
('SpIII', 379-5, 387+5),
('SPII', 389-5, 398+5),
('SPI', 400-5, 408+5)]
conC_mots = [pwm_dict['nfatc2'],
pwm_dict['nfatc2'],
pwm_dict['nfatc2'],
pwm_dict['cebpa'],
pwm_dict['nf-kappab'],
pwm_dict['nf-kappab'],
pwm_dict['nf-kappab'],
pwm_dict['nf-kappab'],
pwm_dict['sp1'],
pwm_dict['sp1'],
pwm_dict['sp1']
]
conC_tf_checks = partial(check_max_scores,
conC_mots,
conC_regions,
conc_seqs['LTR'])
# <codecell>
subC_scores = {}
for key, seq in pseqdf.ix['C']['ltr'].dropna().to_dict().items():
subC_scores[key] = conC_tf_checks(seq)
subC_scores = pd.DataFrame(subC_scores).T
# <codecell>
conB_regions = [('AP1-IV', 104-5, 104+15),
('AP1-III', 119-5, 119+15),
('AP1-II', 154-5, 154+15),
('AP1-I', 213-5, 213+15),
('CEBP-II', 280-5, 280+15),
('ETS', 304-5, 304+15),
('ATF/Creb', 329-5, 329+15),
('CEBP-I', 329-5, 329+15),
('NFKB-II', 349-5, 349+15),
('NFKB-I', 362-5, 362+15),
('SpIII', 376-5, 376+15),
('SPII', 387-5, 387+15),
('SPI', 398-5, 398+15),]
conB_mots = [pwm_dict['ap1'],
pwm_dict['ap1'],
pwm_dict['ap1'],
pwm_dict['ap1'],
pwm_dict['cebpa'],
pwm_dict['ets1'],
pwm_dict['creb1'],
pwm_dict['cebpa'],
pwm_dict['nf-kappab'],
pwm_dict['nf-kappab'],
pwm_dict['sp1'],
pwm_dict['sp1'],
pwm_dict['sp1']]
conB_tf_checks = partial(check_max_scores,
conB_mots,
conB_regions,
conb_seqs['LTR'])
# <codecell>
subB_scores = {}
for key, seq in pseqdf.ix['B']['ltr'].dropna().to_dict().items():
subB_scores[key] = conB_tf_checks(seq)
subB_scores = pd.DataFrame(subB_scores).T
# <codecell>
ltr_scores = pd.concat([subC_scores, subB_scores], axis=0)
ltr_scores
# <codecell>
weblogolib.LogoData.from_counts?
# <codecell>
import weblogolib
from weblogolib.colorscheme import nucleotide
from corebio.seq import unambiguous_dna_alphabet
def make_logo(fasta_path, png_path, title, start_pos, counts = None):
if counts:
mat_counts = np.array([counts[l] for l in 'ACGT']).transpose()
data = weblogolib.LogoData.from_counts(unambiguous_dna_alphabet, mat_counts)
else:
with open(fasta_path) as handle:
seqs = weblogolib.read_seq_data(handle)
data = weblogolib.LogoData.from_seqs(seqs)
options = weblogolib.LogoOptions()
options.logo_title = title
options.resolution = 500
options.first_index = start_pos
options.number_interval = 1
options.rotate_numbers = True
options.color_scheme = nucleotide
fmt = weblogolib.LogoFormat(data, options)
with open(png_path, 'w') as handle:
weblogolib.png_formatter(data, fmt, handle)
# <codecell>
subtypes = ['C', 'B']
cols = ltr_scores['Seqs'].columns
results = []
for sub, col in product(subtypes, cols):
fix_name = col.replace('/', '-')
start_pos = 0
if sub == 'B':
for (name, start, _), mot in zip(conB_regions, conC_mots):
if col == name:
start_pos = start+5
break
else:
for (name, start, _), mot in zip(conC_regions, conB_mots):
if col == name:
start_pos = start+5
break
pred_counts, mask = ltr_scores.align(x4_pred.ix[sub].dropna(),
join = 'inner',
axis = 0)
pwm_name = '/home/will/SubCData/TFfasta/PWM-%s.png' % fix_name
pwm_name_r = '/home/will/SubCData/TFfasta/PWM-%s-R.png' % fix_name
make_logo(None,
pwm_name,
fix_name,
1, counts = mot.counts)
make_logo(None,
pwm_name_r,
fix_name,
1, counts = mot.reverse_complement().counts)
if mask.mean() > 0.5:
r5mask, x4mask = (mask, ~mask)
else:
r5mask, x4mask = (~mask, mask)
x4_name = '/home/will/SubCData/TFfasta/X4-%s-%s' % (fix_name, sub)
r5_name = '/home/will/SubCData/TFfasta/R5-%s-%s' % (fix_name, sub)
with open(x4_name+'.fasta', 'w') as handle:
x4_seqs = pred_counts['Seqs'][col][x4mask].dropna().to_dict().items()
x4_scores = pred_counts['Scores'][col][x4mask].astype(float).dropna()
GeneralSeqTools.fasta_writer(handle, x4_seqs)
if len(x4_seqs) == 0:
os.remove(x4_name+'.fasta')
continue
make_logo(x4_name+'.fasta',
x4_name+'.png',
'X4-%s-%s' % (sub, col),
start_pos)
with open(r5_name+'.fasta', 'w') as handle:
r5_seqs = pred_counts['Seqs'][col][r5mask].dropna().to_dict().items()
r5_scores = pred_counts['Scores'][col][r5mask].astype(float).dropna()
GeneralSeqTools.fasta_writer(handle, r5_seqs)
make_logo(r5_name+'.fasta',
r5_name+'.png',
'R5-%s-%s' % (sub, col),
start_pos)
#print pred_sp_counts['Scores'][name][mask]
r, pval = ttest_ind(x4_scores, r5_scores)
results.append({
'Subtype': sub,
'X4Binding': x4_scores.mean(),
'R5Binding': r5_scores.mean(),
'NX4': len(x4_seqs),
'NR5': len(r5_seqs),
'pvalue': pval,
'TF': col
})
# <codecell>
pd.DataFrame(results).to_excel('/home/will/Dropbox/Wigdahl HIV Lab/SubCAnalysis/TF_binding_scores.xlsx')
# <codecell>
print pred_sp_counts['Seqs'][name][mask].dropna().head()
print pred_sp_counts['Seqs'][name][~mask].dropna().head()
# <codecell>
threshes = [('FPR-0.01', Motif.Thresholds.ScoreDistribution(nfkb_mot, precision = 50).threshold_fpr(0.01)),
('FPR-0.001', Motif.Thresholds.ScoreDistribution(nfkb_mot, precision = 50).threshold_fpr(0.001)),
('FPR-0.002', Motif.Thresholds.ScoreDistribution(nfkb_mot, precision = 50).threshold_fpr(0.002)),
('FPR-0.005', Motif.Thresholds.ScoreDistribution(nfkb_mot, precision = 50).threshold_fpr(0.005)),
]
# <codecell>
nfkb_count = partial(count_mots, nfkb_mot, threshes)
nf_counts = pseqdf.ix['C']['ltr'].dropna().apply(nfkb_count)
nf_counts['InsertSize'] = nf_counts['300to400Size']-100
#print nf_counts.value_counts()
# <codecell>
pred_nf_counts, pred_x4_nf = nf_counts.align(subc_pred_x4.dropna(), join = 'inner', axis = 0)
pred_nf_counts['IsX4'] = pred_x4_nf
# <codecell>
t.plot?
# <codecell>
fig, ax = plt.subplots(1,1, figsize = (10,5))
edges = np.arange(-10, 30, 5)
x4counts, _ = np.histogram(pred_nf_counts['InsertSize'][mask], bins = edges)
r5counts, _ = np.histogram(pred_nf_counts['InsertSize'][~mask], bins = edges)
t = pd.DataFrame({
'X4':x4counts/x4counts.sum(),
'R5':r5counts/r5counts.sum()
}, index = edges[1:])
(100*t).plot(kind = 'bar', ax=ax, color = 'rb', grid = False, legend = False)
ax.set_ylim([0, 100])
print x4counts.sum(), r5counts.sum()
ax.set_ylabel('% Sequences')
ax.set_xlabel('Indel Size')
fig.savefig('/home/will/Dropbox/Wigdahl HIV Lab/SubCAnalysis/insert_size.png', dpi = 300)
# <codecell>
t.plot?
# <codecell>
fig, ax = plt.subplots(1,1, figsize = (10,5))
edges = sorted(pred_nf_counts['InsertSize'].dropna().unique())
x4counts, _ = np.histogram(pred_nf_counts['InsertSize'][mask], bins = edges)
r5counts, _ = np.histogram(pred_nf_counts['InsertSize'][~mask], bins = edges)
t = pd.DataFrame({
'X4':x4counts/x4counts.sum(),
'R5':r5counts/r5counts.sum()
}, index = edges[1:])
(100*t).plot(ax=ax, color = 'rb', grid = False, legend = False, linewidth = 5, alpha = 0.8)
ax.set_ylim([0, 50])
print x4counts.sum(), r5counts.sum()
ax.set_ylabel('% Sequences')
ax.set_xlabel('Indel Size')
fig.savefig('/home/will/Dropbox/Wigdahl HIV Lab/SubCAnalysis/insert_size_line.png', dpi = 300)
# <codecell>
tcols = ['InsertSize', 'FPR-0.01', 'FPR-0.001', 'FPR-0.002', 'FPR-0.005']
fig, axs = plt.subplots(5, 1, figsize = (10,10))
mask = pred_nf_counts['IsX4']
for col, ax in zip(tcols, axs.flatten()):
nbins = min(10, len(pred_nf_counts[col]))
_, obins, _ = ax.hist([pred_nf_counts[col][mask],
pred_nf_counts[col][~mask]],
bins = nbins,
label = ['X4', 'R5'])
if ax.is_first_row():
ax.legend()
ax.set_title(col)
plt.tight_layout()
# <codecell>
env_seqs = pseqdf.ix['C'][['gp120', 'gp41']].dropna(how = 'all').fillna('-').apply(lambda x: ''.join(x), axis = 1)
ltr_seqs = pseqdf.ix['C']['ltr'].dropna()
vpr_seqs = pseqdf.ix['C']['vpr'].dropna()
tat_seqs = pseqdf.ix['C']['tat'].dropna()
nef_seqs = pseqdf.ix['C']['nef'].dropna()
subc_seqs = pd.DataFrame({
'LTR':ltr_seqs,
'Env':env_seqs,
'Vpr':vpr_seqs,
'Tat':tat_seqs,
'Nef':nef_seqs
})
subc_seqs, subc_pred_x4 = subc_seqs.align(x4_pred.ix['C'], axis = 0, join = 'inner')
# <codecell>
env_seqs = pseqdf.ix['B'][['gp120', 'gp41']].dropna(how = 'all').fillna('-').apply(lambda x: ''.join(x), axis = 1)
ltr_seqs = pseqdf.ix['B']['ltr'].dropna()
vpr_seqs = pseqdf.ix['B']['vpr'].dropna()
tat_seqs = pseqdf.ix['B']['tat'].dropna()
nef_seqs = pseqdf.ix['B']['nef'].dropna()
subb_seqs = pd.DataFrame({
'LTR':ltr_seqs,
'Env':env_seqs,
'Vpr':vpr_seqs,
'Tat':tat_seqs,
'Nef':nef_seqs
})
subb_seqs, subb_pred_x4 = subb_seqs.align(x4_pred.ix['B'], axis = 0, join = 'inner')
# <codecell>
conc_seqs = {}
conc_seqs['LTR'] = """tggaagggttaatttactctaagaaaaggcaagagatccttgatttgtgg
gtctatcacacaCaAGgctactTcCCtGAtTGGCAaaacTacACACCgGG
aCCaGGggtcAgatacCCacTgACctttGGaTGGtgcTtcAAgctaGTaC
CAgTtgacCCaaggGaagtaGAagAggccaacgaaggaGAaaacaaCtGt
tTgcTaCAcCCtatgagcCagCatGGaatgGAggAtgaacacagagAAgt
atTaaagTGGaagtttgacagtcaccTaGcacgcagacacatggcCcGcg
aGctacATCcGGAgTatTAcAaagACTGCTGacACagaaGGgACTtTccg
ctgggactttccactgGGGcgttccaggaggtgtggtctGGGCGGgActG
GGAGTGGtcaaCCCtCaGatGctgCATATAAGCagcTGCTTTtcgcctgt
actgggtctctctaggtagaccagatctgagcctgggagctctctggcta
tctagggaacccactgcttaagcctcaataaagcttgccttgagtgctct
aagtagtgtgtgccctctgttttgactctggtaactagagatccctcaga
cccttttggtagtgaggaaatctctagca""".replace('\n', '').upper()
conc_seqs['Vpr'] = """MEQAPEDQGPQREPYNEWTLELLEELKQEAVRHFPRPWLHSLGQYIYETY
GDTWTGVEAIIRILQQLLFIHFRIGCQHSRIGILRQRRARNGASRS""".replace('\n', '').upper()
conc_seqs['Tat'] = """MEPVDPNLEPWNHPGSQPKTACNKCYCKHCSYHCLVCFQTKGLGISYGRK
KRRQRRSAPPSSEDHQNPISKQPLPQTRGDPTGSEESKKKVESKTETDPFD""".replace('\n', '').upper()
conc_seqs['Nef'] = """MGGKWSKSSIVGWPAVRERIRRTEPAAEGVGAASQDLDKHGAL
TSSNTATNNADCAWLEAQEEEEEVGFPVRPQVPLRPMTYKAAFDLSFFLK
EKGGLEGLIYSKKRQEILDLWVYHTQGYFPDWQNYTPGPGVRYPLTFGWC
FKLVPVDPREVEEANEGENNCLLHPMSQHGMEDEDREVLKWKFDSHLARR
HMARELHPEYYKDC""".replace('\n', '').upper()
conc_seqs['Env'] = """MRVRGILRNCQQWWIWGILGFWMLMICNVVGNLWVTVYYGVPVWKEAKTT
LFCASDAKAYEKEVHNVWATHACVPTDPNPQEIVLENVTENFNMWKNDMV
DQMHEDIISLWDQSLKPCVKLTPLCVTLNCTNATNATNTM
GEIKNCSFNITTELRDKKQKVYALFYRLDIVPLNENNSY
RLINCNTSAITQACPKVSFDPIPIHYCAPAGYAILKCNNKTFNGTGPCNN
VSTVQCTHGIKPVVSTQLLLNGSLAEEEIIIRSENLTNNAKTIIVHLNES
VEIVCTRPNNNTRKSIRIGPGQTFYATGDIIGDIRQAHCNISEDKWNKTL
QKVSKKLKEHFPNKTIKFEPSSGGDLEITTHSFNCRGEFFYCNTSKLFNS
TYNSTNSTITLPCRIKQIINMWQEVGRAMYAPPIAGNIT
CKSNITGLLLTRDGGKNNTETFRPGGGDMRDNWRSELYKYKVVEIKP
LGIAPTKAKRRVVEREKRAVGIGAVFLGFLGAAGSTMGAASITLTVQARQ
LLSGIVQQQSNLLRAIEAQQHMLQLTVWGIKQLQTRVLAIERYLKDQQLL
GIWGCSGKLICTTAVPWNSSWSNKSQEDIWDNMTWMQWDREISNYTDTIY
RLLEDSQNQQEKNEKDLLALDSWKNLWNWFDITNWLWYIKIFIMIVGGLI
GLRIIFAVLSIVNRVRQGYSPLSFQTLTPNPRGPDRLGRIEEEGGEQDR
DRSIRLVSGFLALAWDDLRSLCLFSYHRLRDFILIAARAVELLGRSSLRG
LQRGWEALKYLGSLVQYWGLELKKSAISLLDTIAIAVAEGTDRIIELIQR
ICRAIRNIPRRIRQGFEAALQ""".replace('\n', '').upper()
# <codecell>
conb_seqs = {}
conb_seqs['LTR'] = """tGGAaGGGcTaaTttacTCcCaaaaaAgacAagAtATcCTTGAtcTGTGG
gtctAccAcAcaCAaGGCTacTTCCCtGAtTgGCAgAAcTACACAccAGG
gccaGGgatcAGaTatCCacTgaccTTTGGaTGgTGcTtcAAgcTAGTAC
CAgTtgAgCcAGagaaggTagAagagGccAatgaaggagagaacaacagc
tTGtTaCAcCCtatgagCCtgCATGGgatgGAgGAcccgGAgaaagAAGt
gtTagtgTGGAagTttGACAgccgccTaGcatttcatCAcatggCccgaG
AgctgcATCCggAgTactacaaggActGcTGACatcgagctttctacaaG
GGACTTTCCgCtgGGGACTTTccagggagGcGtggcctGGgcgggaCtgg
GGAgtggCgagCCCtcAGAtgcTgCATATAAGCAGCtGCttTttGccTGT
ACtGGgTCTCTCTggttaGaCCAGATCtGAGCctGGGAGcTCtctggcta
actagggaacccactgcttaagcctcaataaagcttgccttgagtgcttc
aagtagtgtgtgcccgtctgttgtgtgactctggtaactagagatccctc
agacccttttagtcagtgtggaaaatctctagca""".replace('\n', '').upper().replace('-', '')
conb_seqs['Vpr'] = """MEQAPEDQGPQREPYNEWTLELLEELKNEAVRHFPRIWLHGLGQHIYETY
GDTWAGVEAIIRILQQLLFIHFRIGCQHSRIGIT-RQRRARNGASRS""".replace('\n', '').upper().replace('-', '')
conb_seqs['Tat'] = """MEPVDPRLEPWKHPGSQPKTACTNCYCKKCCFHCQVCFITKGLGISYGRK
KRRQRRRAPQDSQTHQVSLSKQPASQ-PRGDPTGPKESKKKVERETETDP
VD""".replace('\n', '').upper().replace('-', '')
conb_seqs['Nef'] = """MGGKWSKRSVVGWPTVRERMR-----RAEPAA--DGVGAVSRDLEKHGAI
TSSNTAANNADCAWLEAQEEE-EVGFPVRPQVPLRPMTYKGALDLSHFLK
EKGGLEGLIYSQKRQDILDLWVYHTQGYFPDWQNYTPGPGIRYPLTFGWC
FKLVPVEPEKVEEANEGENNSLLHPMSLHGMDDPEREVLVWKFDSRLAFH
HMARELHPEYYKDC""".replace('\n', '').upper().replace('-', '')
conb_seqs['Env'] = """MRVMGTQRNYQHLWRWGILILGMLIMCKAT-DLWVTVYYGVPVWKDADTT
LFCASDAKAYDTEVHNVWATHACVPTDPNPQEVNLENVTEDFNMWKNNMV
EQMHEDIISLWDQSLKPCVKLTPLCVTLNCSNA--NTTN--NSTM-----
----EEIKNCSYNITTELRDKTQKVYSLFYKLDVVQLDES--NKSEYY-Y
RLINCNTSAITQACPKVSFEPIPIHYCAPAGFAILKCKDPRFNGTGSCNN
VSSVQCTHGIKPVASTQLLLNGSLAEGKVMIRSENITNNAKNIIVQFNKP
VPITCIRPNNNTRKSIRFGPGQAFYT-NDIIGDIRQAHCNINKTKWNATL
QKVAEQLREHFPNKTIIFTNSSGGDLEITTHSFNCGGEFFYCNTTGLFNS
TWK-NGTT---NNTEQM--ITLPCRIKQIINMWQRVGRAMYAPPIAGVIK
CTSNITGIILTRDGGNNET---ETFRPGGGDMRDNWRSELYKYKVVKIEP
LGVAPTRAKRRVVEREKRAVGMGAVFLGFLGAAGSTMGAASITLTVQARQ
LLSGIVQQQSNLLKAIEAQQHLLKLTVWGIKQLQARVLALERYLQDQQLL
GIWGCSGKLICATTVPWNSSWSNKTQEEIWNNMTWLQWDKEISNYTNIIY
KLLEESQNQQEKNEQDLLALDKWANLWNWFNITNWLWYIRIFIMIVGGLI
GLRIVIAIISVVNRVRQGYSPLSFQIPTP-NPEGLDRPGRIEEGGGEQGR
DRSIRLVSGFLALAWDDLRSLCLFSYHRLRDCILIAARTVELLGHSSLKG
LRLGWEGLKYLWNLLLYWGRELKNSAISLLDTIAVAVAEWTDRVIEIGQR
ACRAILNIPRRIRQGFERALL""".replace('\n', '').upper().replace('-', '')
# <codecell>
aligns = []
for col in subc_seqs.columns:
seqs = subc_seqs[col].dropna().to_dict().items()
for num, (gi, align) in enumerate(GeneralSeqTools.seq_align_to_ref(seqs, conc_seqs[col])):
if (num == 0) or (num == 100) or (num == 10) or (num % 1000 == 0):
print col, num
aligns.append({
'Prot':col,
'ID':gi,
'Align':align
})
# <codecell>
baligns = []
for col in subb_seqs.columns:
seqs = subb_seqs[col].dropna().to_dict().items()
for num, (gi, align) in enumerate(GeneralSeqTools.seq_align_to_ref(seqs, conb_seqs[col])):
if (num == 0) or (num == 100) or (num == 10) or (num % 1000 == 0):
print col, num
baligns.append({
'Prot':col,
'ID':gi,
'Align':align
})
# <codecell>
subc_align = pd.pivot_table(pd.DataFrame(aligns),
rows = 'ID',
cols = 'Prot',
values = 'Align',
aggfunc = 'first')
# <codecell>
subb_align = pd.pivot_table(pd.DataFrame(baligns),
rows = 'ID',
cols = 'Prot',
values = 'Align',
aggfunc = 'first')
# <codecell>
tmp_seqs = []
for col in subc_align.columns:
res = subc_align[col].fillna('-').apply(lambda x: pd.Series(list(x)))
res.columns = pd.MultiIndex.from_tuples([(col, pos+1) for pos in res.columns],
names = ['Prot', 'OCol'])
tmp_seqs.append(res.copy())
subc_cols = pd.concat(tmp_seqs, axis = 1).replace('-', np.nan).replace('X', np.nan)
subc_cols, _ = subc_cols.align(subc_seqs, axis = 0, join = 'right')
# <codecell>
tmp_seqs = []
for col in subb_align.columns:
res = subb_align[col].fillna('-').apply(lambda x: pd.Series(list(x)))
res.columns = pd.MultiIndex.from_tuples([(col, pos+1) for pos in res.columns],
names = ['Prot', 'OCol'])
tmp_seqs.append(res.copy())
subb_cols = pd.concat(tmp_seqs, axis = 1).replace('-', np.nan).replace('X', np.nan)
subb_cols, _ = subb_cols.align(subb_seqs, axis = 0, join = 'right')
# <codecell>
from Bio.Alphabet import generic_dna, generic_protein
from itertools import product, islice, imap
from collections import deque
import os, os.path
import TreeingTools
alpha = generic_dna
def append_seq(ser):
return ''.join(ser.fillna('-'))
def rolling_tree_apply(tup):
group_series, seq_series, kwargs = tup
fname = '/home/will/SubCData/Trees/Tree-%(sub)s-%(Prot)s-%(Start)i-%(WinSize)i.newick' % kwargs
if os.path.exists(fname):
return True
alpha = generic_dna if kwargs['Prot'] == 'LTR' else generic_protein
seq_series = seq_series.dropna(thresh = 5)
vseq, vgroup = seq_series.align(group_series.dropna(), join = 'inner', axis = 0)
nseq_ser = vseq.apply(append_seq, axis = 1)
nseqs = sorted(nseq_ser.to_dict().items())
trop_dict = vgroup.to_dict()
#print nseqs
#try:
# tree, dmat = TreeingTools.phylip_tree_collapse_unique(nseqs, alphabet=alpha, use_fast=True)
#except:
# return False
#print 'treeing', fname
tree = TreeingTools.run_FastTree(nseqs, alphabet=alpha, uniq_seqs=True)
with open(fname, 'w') as handle:
tree.write(handle, schema='newick')
return True
try:
tree, dmat = TreeingTools.phylip_tree_collapse_unique(nseqs, alphabet=alpha, use_fast=True)
benj_res = TreeingTools.check_distance_pvals(dmat, trop_dict, nreps = 50)
except:
return kwargs
benj_res.update(kwargs)
try:
out = TreeingTools.evaluate_association_index(tree, trop_dict)
benj_res['AI'], benj_res['AI-pval'], benj_res['AI-null'] = out
except:
benj_res['AI'], benj_res['AI-pval'], benj_res['AI-null'] = (None, None, None)
return benj_res
def yield_regions(seq_data, trop_data, windows, prots, sub):
for win, prot in product(windows, prots):
print win, prot
tmp_df = seq_data[prot]
for start in range(1, len(tmp_df.columns)-win):
seqs = tmp_df[range(start, start+win)]
tdict = {
'WinSize':win,
'Start':start,
'Prot':prot,
'sub':sub
}