-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy patheVNTR_plots.py
1628 lines (1431 loc) · 64.7 KB
/
eVNTR_plots.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
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
import seaborn.apionly as sns
import statsmodels.api as sm
import numpy as np
import pandas as pd
from math import log10
import operator
import os
import glob
from advntr.models import load_unique_vntrs_data
from run_regression import load_individual_genotypes
vntr_models_dir = '/home/mehrdad/workspace/adVNTR/vntr_data/hg38_selected_VNTRs_Illumina.db.bck'
ref_vntrs = load_unique_vntrs_data(vntr_models_dir)
reference_vntrs = {}
for ref_vntr in ref_vntrs:
reference_vntrs[ref_vntr.id] = ref_vntr
def plot_expression_genotype_correlation(vntr_id, tissue_name):
gene_name = reference_vntrs[vntr_id].gene_name
if vntr_id == 450457:
gene_name = 'RPA2'
data_file = 'genotype_expression_correlation/%s/%s/correlation.txt' % (tissue_name, vntr_id)
if not os.path.exists(data_file):
return
with open(data_file) as infile:
lines = infile.readlines()
data = []
labels = []
overall = []
normalize_labels = []
for line in lines:
print(line.strip())
line = line.strip().split(' ')
if len(line[1].split(',')) < 5:
print('skip')
continue
labels.append(str(line[0]))
data.append([float(e) for e in line[1].split(',')])
overall += data[-1]
normalize_labels += [len(labels)-1 for _ in range(len(data[-1]))]
from sklearn.preprocessing import quantile_transform
overall = [[e] for e in overall]
overall = quantile_transform(np.array(overall), n_quantiles=10, random_state=0, copy=True)
for i in range(len(data)):
data[i] = [overall[j][0] for j in range(len(overall)) if normalize_labels[j] == i]
print('points', sum([len(data[i]) for i in range(len(data))]))
import seaborn as sns
sns.set()
sns.set_style("whitegrid")
sns.set_context("paper")
pvalue = 1
pvalue_file = 'pvalues/%s/%s/pvalues.txt' % (tissue_name, vntr_id)
with open(pvalue_file) as infile:
lines = infile.readlines()
lines = [line.strip() for line in lines if line.strip() != '']
for line in lines:
snp, p = line.split()
if '%s' % vntr_id in snp:
pvalue = float(p)
break
print(tissue_name, pvalue)
# return
fig = plt.figure(figsize=(6, 4))
ax = fig.add_subplot(111)
# data = np.array(data).transpose()
if len(labels) < 4:
sns.set_palette(sns.color_palette([sns.xkcd_rgb["denim blue"], sns.xkcd_rgb['medium green'], sns.xkcd_rgb['pale red']]))
sns.boxplot(data=data, ax=ax, showfliers=False, width=0.3, linewidth=1)
sns.swarmplot(data=data, ax=ax, color=".2")
if vntr_id == 331737:
ax.set_xticklabels(['Normal Count', 'Expanded'], size=12)
ax.set_xlabel('VNTR Genotype')
else:
ax.set_xticklabels([float(item) for item in labels], size=12)
ax.set_xlabel('Average Number of Repeats')
ax.set_ylabel('Normalized Gene Expression')
ax.set_title('Expression of %s Gene' % (gene_name,))
#ax.set_ylim(0)
plt.tight_layout()
COLOR = 'black'
plt.rcParams['text.color'] = COLOR
plt.rcParams['axes.labelcolor'] = COLOR
plt.rcParams['xtick.color'] = COLOR
plt.rcParams['ytick.color'] = COLOR
plt.gca().spines['bottom'].set_color('black')
plt.gca().spines['left'].set_color('black')
plt.gca().spines['top'].set_color('black')
plt.gca().spines['right'].set_color('black')
fig.savefig('expression_%s_%s.pdf' % (gene_name, tissue_name))
plt.cla()
plt.clf()
plt.close()
def plot_dose_dependence_of_correlation(use_beta=True):
import seaborn as sns
sns.set()
sns.set_style("whitegrid")
sns.set_context("paper")
significant_vntrs = set([])
tissue_data_dir = glob.glob('pvalues/*')
for tissue_dir in tissue_data_dir:
vntrs_data = glob.glob(tissue_dir + '/*')
tissue_name = os.path.basename(tissue_dir)
for vntr_pvalue_dir in vntrs_data:
vntr_id = int(os.path.basename(vntr_pvalue_dir))
significant_vntrs.add((tissue_name.replace(' ', '-'), vntr_id))
# significant_vntrs.add(vntr_id)
print(len(significant_vntrs))
increasing = 0
decreasing = 0
hist_data = []
tissue_data_dir = glob.glob('caviar_inputs/*')
print(tissue_data_dir)
for tissue_dir in tissue_data_dir:
vntr_dirs = glob.glob(tissue_dir + '/*')
tissue_name = os.path.basename(tissue_dir)
for vntr_dir in vntr_dirs:
vntr_id = int(os.path.basename(vntr_dir))
effect_size_file = 'caviar_inputs/%s/%s/%s_Z' % (tissue_name, vntr_id, tissue_name)
with open(effect_size_file) as infile:
lines = infile.readlines()
effect_size = float(lines[0].strip().split()[1])
hist_data.append(effect_size)
if effect_size > 0:
increasing += 1
else:
decreasing += 1
if use_beta:
hist_data = []
increasing = 0
decreasing = 0
tissue_data_dir = glob.glob('regression_results/*')
print(tissue_data_dir)
for tissue_dir in tissue_data_dir:
print(tissue_dir)
tissue_name = os.path.basename(tissue_dir)
vntr_files = glob.glob(tissue_dir + '/*')
for vntr_file in vntr_files:
vntr_id = int(os.path.basename(vntr_file[:-4]))
if (tissue_name, vntr_id) not in significant_vntrs:
continue
with open(vntr_file) as infile:
lines = infile.readlines()
effect_size = float(lines[0].strip().split('\t')[3])
hist_data.append(effect_size)
if effect_size > 0:
increasing += 1
elif effect_size < -0:
decreasing += 1
print(increasing, decreasing)
from pylab import rcParams
# rcParams['figure.figsize'] = 8, 5
# plt.bar([0, 1], [increasing, decreasing], width=0.5)
# plt.xticks((0, 1), ['Increasing', 'Decreasing'], size=12)
data = {}
print(data)
for h in hist_data:
h = round(10 * h) / 10.0
if h not in data.keys():
data[h] = 0
data[h] += 1
print(data)
# plt.bar(data.keys(), data.values(), width=0.10)
# plt.hist(hist_data, bins=100, histtype='step')
sns.set_palette(sns.hls_palette(8, l=.3, s=.8))
sns.set_palette(sns.color_palette("dark", 40))
sns.distplot(hist_data, bins=100)
plt.xlabel('Dose Dependence', size=14)
plt.ylabel('Significant associations', size=14)
# plt.xlim(-0.6, 1.6)
plt.tight_layout()
plt.gca().spines['bottom'].set_color('black')
plt.gca().spines['left'].set_color('black')
plt.gca().spines['top'].set_color('black')
plt.gca().spines['right'].set_color('black')
plt.savefig('dose_dependence.png', dpi=300)
plt.cla()
plt.clf()
plt.close()
def plot_variant_caviar_scores(vntr_id, tissue_name, xlim=None):
caviar_post_file = 'caviar_inputs/%s/%s/caviar_post' % (tissue_name.replace(' ', '-'), vntr_id)
post = pd.read_csv(caviar_post_file, sep="\t", header=0)
post = post.sort_values(post.columns[2], ascending=False)
post = post.reset_index(drop=True)
vntr_x = reference_vntrs[vntr_id].start_point
# vntr_x = 0
vntr_y = 0
x = []
y = []
for row in range(0,len(post.index)):
if '%s' % vntr_id in post.values[row][0]:
vntr_y = float(post.values[row][2])
else:
x.append(int(post.values[row][0].split('_')[1]))
y.append(post.values[row][2])
# vntr_x = get_vntr_x(vntr_id, x)
print(vntr_x)
gene_name = reference_vntrs[vntr_id].gene_name
fig = plt.figure(figsize=(6, 1.8))
ax = fig.add_subplot(111)
ax.scatter(x, y, marker='.', c='gray')
ax.scatter(vntr_x, vntr_y, marker='*', c='r')
ax.set_ylabel('Causality probability')
if xlim:
ax.set_xlim(xlim[0], xlim[1])
plt.tight_layout()
COLOR = 'black'
plt.rcParams['text.color'] = COLOR
plt.rcParams['axes.labelcolor'] = COLOR
plt.rcParams['xtick.color'] = COLOR
plt.rcParams['ytick.color'] = COLOR
plt.gca().spines['bottom'].set_color('black')
plt.gca().spines['left'].set_color('black')
plt.gca().spines['top'].set_color('black')
plt.gca().spines['right'].set_color('black')
fig.savefig('caviar_%s_%s.png' % (gene_name, tissue_name), dpi=300)
# fig.savefig('caviar_%s_%s.pdf' % (gene_name, tissue_name))
plt.cla()
plt.clf()
plt.close()
def plot_variant_pvalues(vntr_id, tissue_name):
pvalue_file = 'pvalues/%s/%s/pvalues.txt' % (tissue_name, vntr_id)
with open(pvalue_file) as infile:
lines = infile.readlines()
lines = [line.strip() for line in lines if line.strip() != '']
y = []
x = []
vntr_x = reference_vntrs[vntr_id].start_point
# vntr_x = 0
vntr_y = 0
for line in lines:
snp, p = line.split()
if '%s' % vntr_id in snp:
vntr_y = -log10(float(p))
else:
y.append(-log10(float(p)))
x.append(float(snp.split('_')[1]))
# vntr_x = get_vntr_x(vntr_id, x)
gene_name = reference_vntrs[vntr_id].gene_name
# import seaborn as sns
# sns.set()
# sns.set_style("whitegrid")
# sns.set_context("talk")
fig = plt.figure(figsize=(6, 1.8))
ax = fig.add_subplot(111)
ax.scatter(x, y, marker='.', c='gray')
ax.scatter(vntr_x, vntr_y, marker='*', c='r')
# ax.set_xlabel('Genomic location')
ax.set_ylabel('-log10 P-value')
plt.tight_layout()
xlim = plt.xlim()
COLOR = 'black'
plt.rcParams['text.color'] = COLOR
plt.rcParams['axes.labelcolor'] = COLOR
plt.rcParams['xtick.color'] = COLOR
plt.rcParams['ytick.color'] = COLOR
plt.gca().spines['bottom'].set_color('black')
plt.gca().spines['left'].set_color('black')
plt.gca().spines['top'].set_color('black')
plt.gca().spines['right'].set_color('black')
fig.savefig('pvalues_%s_%s.png' % (gene_name, tissue_name), dpi=300)
#fig.savefig('pvalues_%s_%s.pdf' % (gene_name, tissue_name))
plt.cla()
plt.clf()
plt.close()
return xlim
def plot_pvalue_and_caviar(vntr_id, tissue_name):
xlim = plot_variant_pvalues(vntr_id, tissue_name)
plot_variant_caviar_scores(vntr_id, tissue_name, xlim=xlim)
def plot_allele_count_distribution():
# **** replace avg_length by two integer RU counts
genotypes = load_individual_genotypes(reference_vntrs)
genotyped_vntr_ids = {_id: set() for _id in range(1000000)}
for individual_id, result_map in genotypes.items():
for genotyped_vntr, avg_length in result_map.items():
if avg_length == 'None' or avg_length is None:
continue
genotyped_vntr_ids[genotyped_vntr].add(avg_length)
# print(genotyped_vntr_ids)
vntr_genotypes = {_vntr_id: len(lengths) for _vntr_id, lengths in genotyped_vntr_ids.items() if len(lengths) != 0}
data = {}
for vntr_id, number_of_genotypes in vntr_genotypes.items():
number_of_genotypes = min(number_of_genotypes, 15)
annotation = reference_vntrs[vntr_id].annotation
if annotation not in ['UTR', 'Coding', 'Promoter']:
continue
if annotation not in data.keys():
data[annotation] = {}
if number_of_genotypes not in data[annotation].keys():
data[annotation][number_of_genotypes] = 0
data[annotation][number_of_genotypes] += 1
offset = -0.2
for key in data.keys():
print(data[key].values())
values = np.array(data[key].values()) / float(sum(data[key].values())) * 100
print(values)
plt.bar(np.array(data[key].keys()) + offset, values, label=key, width=0.2)
offset += 0.2
plt.legend()
plt.xlabel('Number of alleles')
plt.ylabel('Percentage of VNTRs')
plt.savefig('VNTR_genotype_allele_count.png', dpi=200)
plt.cla()
plt.clf()
plt.close()
def plot_vntr_polymorphic_rate_based_on_cohort_size():
import seaborn as sns
sns.set()
sns.set_style("whitegrid")
sns.set_context("poster")
res = {}
cohort_size = []
prev_points = {'UTR':0, 'Coding':0, 'Promoter':0}
for i in [i for i in range(651, 652, 10)]:# + [None]:
# if i is not None:
# continue
print(i)
genotypes = load_individual_genotypes(reference_vntrs, True, i)
genotyped_vntr_ids = {_id: set() for _id in range(1000000)}
vntr_genotypes_map = {_id: [] for _id in range(1000000)}
for individual_id, result_map in genotypes.items():
for genotyped_vntr, avg_length in result_map.items():
if avg_length == 'None' or avg_length is None:
continue
vntr_genotypes_map[genotyped_vntr].append(avg_length)
genotyped_vntr_ids[genotyped_vntr].add(avg_length)
# print(genotyped_vntr_ids)
vntr_genotypes = {_vntr_id: len(lengths) for _vntr_id, lengths in genotyped_vntr_ids.items() if len(lengths) != 0}
poly = {}
total = {}
for vntr_id, number_of_genotypes in vntr_genotypes.items():
annotation = reference_vntrs[vntr_id].annotation
if annotation not in ['UTR', 'Coding', 'Promoter']:
continue
if annotation not in total.keys():
total[annotation] = 0
poly[annotation] = 0
from collections import Counter
g_dict = Counter(vntr_genotypes_map[vntr_id])
count_of_second_frequent = sorted(g_dict.values(), reverse=True)[1] if len(g_dict) > 1 else 0
# if number_of_genotypes > 1:
count_of_most_frequent = vntr_genotypes_map[vntr_id].count(max(set(vntr_genotypes_map[vntr_id]), key = vntr_genotypes_map[vntr_id].count))
# if count_of_most_frequent < i*0.95:
if i - count_of_most_frequent > 5:
# if count_of_second_frequent > 5:
poly[annotation] += 1
total[annotation] += 1
rate = {key: float(poly[key]) / total[key] for key in poly.keys()}
print(poly)
for key in poly.keys():
if key not in res.keys():
res[key] = []
res[key].append(max(rate[key], prev_points[key]))
# prev_points[key] = max(rate[key], prev_points[key]*101/100)
cohort_size.append(i if i != None else 652)
for key in res.keys():
plt.plot(cohort_size, res[key], label=key)
plt.legend()
plt.xlabel('Cohort Size')
plt.ylabel('Rate of polymorphic VNTRs')
plt.tight_layout()
plt.savefig('polymorphic_vntrs_cohort_size_l5.png', dpi=300)
plt.cla()
plt.clf()
plt.close()
def plot_vntr_polymorphic_rate_based_on_annotation():
genotypes = load_individual_genotypes(reference_vntrs)
genotyped_vntr_ids = {_id: set() for _id in range(1000000)}
for individual_id, result_map in genotypes.items():
for genotyped_vntr, avg_length in result_map.items():
if avg_length == 'None' or avg_length is None:
continue
genotyped_vntr_ids[genotyped_vntr].add(avg_length)
# print(genotyped_vntr_ids)
vntr_genotypes = {_vntr_id: len(lengths) for _vntr_id, lengths in genotyped_vntr_ids.items() if len(lengths) != 0}
poly = {}
total = {}
for vntr_id, number_of_genotypes in vntr_genotypes.items():
annotation = reference_vntrs[vntr_id].annotation
if annotation not in ['UTR', 'Coding', 'Promoter']:
continue
if annotation not in total.keys():
total[annotation] = 0
poly[annotation] = 0
if number_of_genotypes > 1:
poly[annotation] += 1
total[annotation] += 1
rate = {key: float(poly[key]) / total[key] for key in poly.keys()}
plt.bar([0, 1, 2], rate.values(), width=0.5)
plt.xticks((0, 1, 2), [item for item in rate.keys()], size=12)
plt.xlabel('Annotation')
plt.ylabel('Rate of polymorphic VNTRs')
plt.savefig('polymorphic_vntrs.png', dpi=100)
plt.cla()
plt.clf()
plt.close()
def plot_evntrs_and_number_of_tissues():
data = {}
tissue_data_dir = glob.glob('pvalues/*')
for tissue_dir in tissue_data_dir:
vntrs_data = glob.glob(tissue_dir + '/*')
tissue_name = os.path.basename(tissue_dir)
for vntr_pvalue_dir in vntrs_data:
vntr_id = int(os.path.basename(vntr_pvalue_dir))
if vntr_id not in data.keys():
data[vntr_id] = set([])
data[vntr_id].add(tissue_name)
pvalue_file = vntr_pvalue_dir + '/pvalues.txt'
with open(pvalue_file) as infile:
lines = infile.readlines()
lines = [line.strip() for line in lines if line.strip() != '']
data = {key: len(value) for key, value in data.items()}
bar_data = {}
for n_tissue in set(data.values()):
res = 0
for key in data.keys():
if data[key] == n_tissue:
res += 1
bar_data[n_tissue] = res
plt.bar(bar_data.keys(), bar_data.values())
plt.xlabel('Shared across number of tissues')
plt.ylabel('Number of VNTR-eQTLs')
plt.savefig('eVNTR_uniqueness.png', dpi=300)
plt.cla()
plt.clf()
plt.close()
def plot_effect_per_allele_frequency():
import matplotlib.pyplot as plt
# plt.style.use('ggplot')
# plt.rcParams['axes.facecolor'] = '#FFFFFF'
import seaborn as sns
sns.set()
sns.set_style("whitegrid")
sns.set_context("paper")
plt.gca().spines['bottom'].set_color('black')
plt.gca().spines['left'].set_color('black')
plt.gca().spines['top'].set_color('black')
plt.gca().spines['right'].set_color('black')
genotypes = load_individual_genotypes(reference_vntrs, False)
genotyped_vntr_ids = {_id: set() for _id in range(1000000)}
vntr_genotypes_map = {_id: [] for _id in range(1000000)}
for individual_id, result_map in genotypes.items():
for genotyped_vntr, alleles in result_map.items():
if alleles == 'None' or alleles is None or None in alleles:
continue
vntr_genotypes_map[genotyped_vntr] += alleles
for allele in alleles:
genotyped_vntr_ids[genotyped_vntr].add(allele)
vntr_genotypes = {_vntr_id: len(lengths) for _vntr_id, lengths in genotyped_vntr_ids.items() if len(lengths) != 0}
maf = {}
for vntr_id, number_of_genotypes in vntr_genotypes.items():
from collections import Counter
g_dict = Counter(vntr_genotypes_map[vntr_id])
count_of_second_frequent = sorted(g_dict.values(), reverse=True)[1] if len(g_dict) > 1 else 0
count_of_most_frequent = vntr_genotypes_map[vntr_id].count(
max(set(vntr_genotypes_map[vntr_id]), key=vntr_genotypes_map[vntr_id].count))
maf[vntr_id] = count_of_second_frequent / float(len(vntr_genotypes_map[vntr_id]))
import math
print('computed minor allele frequencies')
thresholds = {}
with open('thresholds.txt') as infile:
lines = infile.readlines()
for l in lines:
thresholds[l.split('\t')[0].replace(' ', '-')] = float(l.split('\t')[1])
x = []
y = []
xpvalue = []
ypvalue = []
gene_names = []
vntr_bestpvalue = {}
vntr_bestbeta = {}
tissue_data_dir = glob.glob('regression_results/*')
for tissue_dir in tissue_data_dir:
vntrs_data = glob.glob(tissue_dir + '/*')
tissue_name = os.path.basename(tissue_dir).split('---')[0]
if len(os.path.basename(tissue_dir).split('---')) > 1:
tissue_name += ' - ' + os.path.basename(tissue_dir).split('---')[1][:5]
for vntr_pvalue_dir in vntrs_data:
vntr_id = int(os.path.basename(vntr_pvalue_dir)[:-4])
if maf[vntr_id] not in vntr_bestpvalue.keys():
vntr_bestpvalue[maf[vntr_id]] = 0
if maf[vntr_id] not in vntr_bestbeta.keys():
vntr_bestbeta[maf[vntr_id]] = 0
pvalue_file = vntr_pvalue_dir
with open(pvalue_file) as infile:
line = infile.readlines()[0].strip()
effect_size = float(line.split()[3])
pvalue = float(line.split()[4])
gene_names.append(reference_vntrs[vntr_id].gene_name)
x.append(maf[vntr_id])
y.append(abs(effect_size))
vntr_bestbeta[maf[vntr_id]] = max(vntr_bestbeta[maf[vntr_id]], abs(effect_size))
xpvalue.append(maf[vntr_id])
ypvalue.append(-math.log(pvalue, 10))
vntr_bestpvalue[maf[vntr_id]] = max(vntr_bestpvalue[maf[vntr_id]], -math.log(pvalue, 10))
plt.ylabel('Effect Size')
plt.xlabel('MAF: minor allele frequency (second most common allele)')
# x = []
# y = []
# for key, value in vntr_bestbeta.items():
# x.append(maf[key])
# y.append(value)
def is_peak(maf, beta):
# beta = vntr_bestbeta[maf]
peaks = []
for _maf, _beta in vntr_bestbeta.items():
if _maf == maf:
continue
if maf - 0.05 < _maf < maf + 0.05:
peaks.append(_beta)
return beta > 2.0 * sum(peaks) / float(len(peaks))
# colors = []
# for i in range(len(x)):
# if x[i] > 0.05 and is_peak(x[i], y[i]):
# colors.append('tab:red')
# else:
# colors.append('tab:blue')
plt.scatter(x, y, marker='.', alpha=0.4)
for i in range(len(x)):
if x[i] > 0.05 and y[i] == vntr_bestbeta[x[i]] and (y[i] > 0.45 or (y[i] > 0.29 and x[i] > 0.1)):
if x[i] > 0.17 or y[i] > 0.48 or gene_names[i] in ['FAM71E2', 'EPS8L2', 'SRRD', 'RAET1G', 'ANKRD30BL']:
plt.text(x[i], y[i], gene_names[i], {'ha': 'left', 'va': 'bottom'}, rotation=45, fontsize=6)
else:
print(x[i], y[i], gene_names[i])
#if gene_names[i] == 'FAM71E2':
# text_pos = (x[i] + 0.05, y[i] + 0.07)
# arrow_end = (x[i] - text_pos[0] + 0.003, y[i] - text_pos[1] + 0.005)
if gene_names[i] == 'ZNF232':
text_pos = (x[i], y[i] + 0.1)
arrow_end = (x[i] - text_pos[0], y[i] - text_pos[1] + 0.01)
elif gene_names[i] == 'CRYBB2P1':
text_pos = (x[i] + 0.03, y[i]+0.08)
arrow_end = (x[i] - text_pos[0] + 0.001, y[i] - text_pos[1] + 0.008)
# plt.annotate(gene_names[i], xy=(x[i], y[i]), xytext=text_pos, fontsize=6, arrowprops=dict(facecolor='black', shrink=0.05))
arrow_color = 'k'
plt.arrow(text_pos[0], text_pos[1], arrow_end[0], arrow_end[1], fc=arrow_color, ec=arrow_color, width=0.001, lw=0.5)
plt.text(text_pos[0], text_pos[1], gene_names[i], {'ha': 'left', 'va': 'bottom'}, rotation=45, fontsize=6)
# sns.distplot(x)
# sns.kdeplot(x)
plt.tight_layout(pad=2, w_pad=0, h_pad=2)
plt.savefig('maf_effect_size.png', dpi=300)
plt.cla()
plt.clf()
plt.close()
plt.ylabel('$\\mathdefault{-log_{10}(Pvalue)}$', fontsize=12)
plt.xlabel('MAF: minor allele frequency (second most common allele)', fontsize=12)
# xpvalue = []
# ypvalue = []
# for key, value in vntr_bestpvalue.items():
# xpvalue.append(maf[key])
# ypvalue.append(value)
plt.scatter(xpvalue, ypvalue, marker='.', alpha=0.4)
for i in range(len(xpvalue)):
if xpvalue[i] > 0.05 and ypvalue[i] == vntr_bestpvalue[xpvalue[i]] and ypvalue[i] > 10:
print(gene_names[i])
if gene_names[i] not in ['RMDN1', 'CADM1', 'COLQ', 'SNHG16', 'ANKEF1', 'ZNF736', 'CCDC57', 'PTTG1', 'EPDR1', 'ALKBH5', 'BAIAP2L2']:
plt.text(xpvalue[i], ypvalue[i], gene_names[i], {'ha': 'left', 'va': 'bottom'}, rotation=45, fontsize=6)
else:
print(xpvalue[i], ypvalue[i], gene_names[i])
if gene_names[i] == 'RMDN1':
text_pos = (x[i], ypvalue[i] + 3)
arrow_end = (x[i] - text_pos[0], ypvalue[i] - text_pos[1] + 1)
plt.text(xpvalue[i]-0.005, ypvalue[i]+0.04, gene_names[i], {'ha': 'left', 'va': 'bottom'}, rotation=45,
fontsize=6)
continue
elif gene_names[i] == 'CADM1':
plt.text(xpvalue[i] + 0.0003, ypvalue[i] - 1, gene_names[i], {'ha': 'left', 'va': 'bottom'},
rotation=45, fontsize=6)
continue
elif gene_names[i] == 'COLQ':
plt.text(xpvalue[i] - 0.003, ypvalue[i] - 0.5, gene_names[i], {'ha': 'left', 'va': 'bottom'},
rotation=45, fontsize=6)
continue
elif gene_names[i] == 'BAIAP2L2' and xpvalue[i] < 0.37:
plt.text(xpvalue[i], ypvalue[i], gene_names[i], {'ha': 'left', 'va': 'bottom'}, rotation=45,
fontsize=6)
continue
elif gene_names[i] == 'BAIAP2L2':
text_pos = (x[i] + 0.020, ypvalue[i]+8)
arrow_end = (x[i] + 0.0020, ypvalue[i]+0.6)
elif gene_names[i] == 'SNHG16':
text_pos = (x[i], ypvalue[i] + 8)
arrow_end = (x[i], ypvalue[i] + 0.7)
elif gene_names[i] == 'ANKEF1':
text_pos = (x[i] + 0.022, ypvalue[i]+4)
arrow_end = (x[i] + 0.0025, ypvalue[i]+0.03)
elif gene_names[i] == 'ZNF736':
text_pos = (x[i] + 0.02, ypvalue[i] - 1.5)
arrow_end = (x[i] + 0.0025, ypvalue[i]-0.02)
elif gene_names[i] == 'CCDC57':
text_pos = (x[i] + 0.013, ypvalue[i] + 2)
arrow_end = (x[i] + 0.0025, ypvalue[i]+0.02)
elif gene_names[i] == 'PTTG1':
text_pos = (x[i], ypvalue[i] + 4)
arrow_end = (x[i], ypvalue[i] + 0.7)
elif gene_names[i] == 'EPDR1':
text_pos = (x[i], ypvalue[i] + 12)
arrow_end = (x[i], ypvalue[i] + 0.7)
elif gene_names[i] == 'ALKBH5':
text_pos = (x[i] + 0.02, ypvalue[i])
arrow_end = (x[i] + 0.0025, ypvalue[i])
else:
continue
# plt.annotate(gene_names[i], xy=(x[i], y[i]), xytext=text_pos, fontsize=6, arrowprops=dict(facecolor='black', shrink=0.05))
arrow_color = 'k'
plt.annotate(gene_names[i], xy=arrow_end, xytext=text_pos, va='bottom', bbox=dict(fc='none', ec='none', pad=0), rotation=45,
arrowprops=dict(facecolor='black', shrink=0, width=1.5, headlength=5, headwidth=4.5), fontsize=6)
#plt.arrow(text_pos[0], text_pos[1], arrow_end[0], arrow_end[1], fc=arrow_color, ec=arrow_color, width=0.002)
#plt.text(text_pos[0], text_pos[1], gene_names[i], {'ha': 'left', 'va': 'bottom'}, rotation=45, fontsize=6)
#plt.plot([0, 0.5], [-math.log(0.0005, 10), -math.log(0.0005, 10)], '--', color='tab:red')
lower = -math.log(0.00101531415963, 10)
upper = -math.log(3.79592740513e-05, 10)
# plt.axhspan(lower, upper, facecolor='tab:red', alpha=0.4, xmin=0, xmax=0.5)
plt.fill([0,0.5,0.5,0], [lower,lower,upper,upper], 'tab:red', alpha=0.3, edgecolor='red')
plt.tight_layout(pad=2, w_pad=0, h_pad=2)
plt.savefig('maf_pvalue.pdf')
def plot_evntrs_per_tissue():
import matplotlib.pyplot as plt
# plt.style.use('ggplot')
plt.rcParams['axes.facecolor'] = '#FFFFFF'
plt.gca().spines['bottom'].set_color('black')
plt.gca().spines['left'].set_color('black')
plt.gca().spines['top'].set_color('black')
plt.gca().spines['right'].set_color('black')
import seaborn as sns
sns.set()
sns.set_style("whitegrid")
sns.set_context("paper")
thresholds = {}
with open('thresholds.txt') as infile:
lines = infile.readlines()
for l in lines:
thresholds[l.split('\t')[0].replace(' ', '-')] = float(l.split('\t')[1])
data = {}
tissue_data_dir = glob.glob('regression_results/*')
for tissue_dir in tissue_data_dir:
vntrs_data = glob.glob(tissue_dir + '/*')
threshold = thresholds[os.path.basename(tissue_dir)]
tissue_name = os.path.basename(tissue_dir).split('---')[0].replace('-', ' ')
if len(os.path.basename(tissue_dir).split('---')) > 1:
tissue_name += ' - ' + os.path.basename(tissue_dir).split('---')[1].replace('-', ' ')
if tissue_name not in data.keys():
data[tissue_name] = set([])
for vntr_pvalue_dir in vntrs_data:
vntr_id = int(os.path.basename(vntr_pvalue_dir)[:-4])
# data[tissue_name].add(vntr_id)
# pvalue_file = vntr_pvalue_dir + '/pvalues.txt'
pvalue_file = vntr_pvalue_dir
with open(pvalue_file) as infile:
line = infile.readlines()[0].strip()
if float(line.split()[4]) <= threshold:
data[tissue_name].add(vntr_id)
data_count = {key: len(value) for key, value in data.items()}
sorted_data = sorted(data_count.items(), key=operator.itemgetter(1), reverse=True)
unique_counts = {}
shared_by_tissues = {}
tissue_order = []
bottoms = []
def autolabel(rects, offset):
"""
Attach a text label above each bar displaying its height
"""
for i, rect in enumerate(rects):
# height = rect.get_height()
plt.text(rect.get_x() + rect.get_width() / 2., 1.01 * (offset[i]),
'%d' % int(offset[i]),
ha='center', va='bottom', color='gray', size=5)
for shared_counter in range(0, 2):#len(sorted_data)):
shared_by_tissues[shared_counter] = []
for key, value in sorted_data:
value=data[key]
res = 0
for v in value:
found = 0
for other_tissue, vntrs in data.items():
if other_tissue == key:
continue
if v in vntrs:
found += 1
if found == shared_counter or (shared_counter == 1 and found >= 1):
res += 1
unique_counts[key] = res
shared_by_tissues[shared_counter].append(res)
if shared_counter == 0:
tissue_order.append(key)
bottoms.append(0)
label = None
red_color = '#d62728'
blue_color = "#1f77b4"
if shared_counter == 0:
label = 'Tissue Specific VNTR-eQTLs'
color = red_color
if shared_counter == 1:
label = 'Shared VNTR-eQTLs'
color = blue_color
bar = plt.bar(np.array([i for i in range(len(shared_by_tissues[shared_counter]))]), shared_by_tissues[shared_counter], label=label, width=0.6, bottom=bottoms, color=color)
bottoms = [bottoms[i] + shared_by_tissues[shared_counter][i] for i in range(len(bottoms))]
print(bottoms)
print(sum(bottoms))
autolabel(bar, bottoms)
print(shared_by_tissues)
for i in range(len(tissue_order)):
tissue_order[i] = tissue_order[i].replace('Gastroesophageal Junction', 'GE Junction')
tissue_order[i] = tissue_order[i].replace('Cells - ', '')
p = tissue_order[i].find('(')
if p != -1:
tissue_order[i] = tissue_order[i][:p].strip()
plt.xticks(np.array([i for i in range(len(tissue_order))]), tissue_order, rotation=90, fontsize=6)
plt.legend()
plt.ylim(0, 45)
plt.xlabel('Tissue name')
plt.ylabel('Number of VNTR-eQTLs')
plt.tight_layout(pad=2, w_pad=0, h_pad=2)
plt.savefig('eVNTR_per_tissue.png', dpi=300)
plt.cla()
plt.clf()
plt.close()
def plot_affected_bp_per_individual():
# import matplotlib.pyplot as plt
import seaborn as sns
sns.set()
sns.set_style("whitegrid")
sns.set_context("paper")
plt.gca().spines['bottom'].set_color('black')
plt.gca().spines['left'].set_color('black')
plt.gca().spines['top'].set_color('black')
plt.gca().spines['right'].set_color('black')
genotypes = load_individual_genotypes(reference_vntrs, False)
genotyped_vntr_ids = {_id: set() for _id in range(1000000)}
reference_repeats = {_id: [] for _id in range(1000000)}
hist_data = []
cp_diff = []
for individual_id, result_map in genotypes.items():
affected = 0
different_sites = 0
for genotyped_vntr, genotype in result_map.items():
if genotype == 'None' or genotype is None or None in genotype or 'None' in genotype:
continue
ref_vntr_length = reference_vntrs[genotyped_vntr].get_length()
vntr_pattern_length = len(reference_vntrs[genotyped_vntr].pattern)
ref_copy_number = len(reference_vntrs[genotyped_vntr].get_repeat_segments())
affected += sum([abs(ref_vntr_length - allele * vntr_pattern_length) for allele in genotype if allele != ref_copy_number])
different_sites += sum([1 for allele in genotype if allele != ref_copy_number] + [0])
reference_repeats[genotyped_vntr] += genotype
hist_data.append(affected)
cp_diff.append(different_sites)
# data = {point: 0 for point in range(min(hist_data), max(hist_data) + 1)}
# for h in hist_data:
# data[h] += 1
# del data[0]
#
# plt.bar(data.keys(), data.values(), width=0.8)
print('different sites')
print(sum(cp_diff) / float(len(cp_diff)))
print(min(cp_diff))
print(cp_diff)
hist_mean = sum(hist_data) / float(len(hist_data))
print(hist_mean)
plt.hist(hist_data, 100)
plt.axvline(hist_mean, color='k', linestyle='dashed', linewidth=1)
# plt.xlabel('Base-pairs difference from reference')
plt.xlabel('Total BP affected by VNTR variation')
plt.ylabel('Number of individuals')
plt.xscale('log')
ax = plt.gca()
ax.xaxis.grid(False)
plt.savefig('affected_bp_per_individual.pdf')
plt.cla()
plt.clf()
plt.close()
def plot_most_common_allele_difference_from_reference():
from brokenaxes import brokenaxes
genotypes = load_individual_genotypes(reference_vntrs, False)
genotyped_vntrs = set([])
most_common_allele = {_id: [] for _id in range(1000000)}
for individual_id, result_map in genotypes.items():
for genotyped_vntr, alleles in result_map.items():
if alleles == 'None' or alleles is None or alleles[0] is None:
continue
genotyped_vntrs.add(genotyped_vntr)
most_common_allele[genotyped_vntr] += alleles
for key, value in most_common_allele.items():
if most_common_allele[key] == []:
most_common_allele[key].append(0)
most_common_allele = {key: most_common(value) for key, value in most_common_allele.items() if key in genotyped_vntrs}
hist_data = []
for vntr_id, major_allele in most_common_allele.items():
hist_data.append(major_allele - len(reference_vntrs[vntr_id].get_repeat_segments()))
bar_ranges = 6
print('avg:', sum([abs(e) for e in hist_data if abs(e) > 0]) / float(len([abs(e) for e in hist_data if abs(e) > 0])))
print('avg:', sum([abs(e) for e in hist_data]) / float(len(hist_data)))
print(len([1 for e in hist_data if abs(e) > 3]), len([1 for e in hist_data if abs(e) > 0]), len(hist_data))
data = {point: 0 for point in range(-bar_ranges, bar_ranges + 1)}
for h in hist_data:
h = min(bar_ranges, h)
h = max(h, -bar_ranges)
data[h] += 1
# del data[0]
print(data)
second_peak = max([data[i] for i in data.keys() if i !=0 ])
bax = brokenaxes(ylims=((-1, second_peak + second_peak * 0.4), (data[0]-second_peak*0.3, data[0]+second_peak*0.2)), hspace=.09)
bax.bar(data.keys(), data.values(), width=0.8)
# plt.hist(hist_data, 40)
bax.set_ylabel('Number of VNTR Loci', labelpad=40)
# bax.canvas.draw()
# print(bax.get_xticklabels())
# print(bax.get_xticklabels()[0])
# labels = [item.get_text() for item in bax.get_xticklabels()[1]]
# labels[0] = '<=6'
# labels[-1] = '>=6'
bax.set_xticklabels(['', u'<=6', u'-4', u'-2', u'0', u'2', u'4', u'>=6', ''])
bax.set_xlabel('Most common allele repeat difference from GRCh38', labelpad=20)
plt.savefig('common_allele_difference_from_reference.pdf')
plt.cla()
plt.clf()
plt.close()
def plot_bp_difference_from_reference():
from brokenaxes import brokenaxes
genotypes = load_individual_genotypes(reference_vntrs, False)
hist_data = []
for individual_id, result_map in genotypes.items():
for genotyped_vntr, alleles in result_map.items():
if alleles == 'None' or alleles is None or alleles[0] is None:
continue
ref_repeats = len(reference_vntrs[genotyped_vntr].get_repeat_segments())
pattern_len = len(reference_vntrs[genotyped_vntr].pattern)
for allele in alleles:
# if allele != ref_repeats:
hist_data.append(int(round(allele * pattern_len - ref_repeats * pattern_len))) # bp difference
# hist_data.append(int(round(allele - ref_repeats))) # copy number difference
bar_ranges = 10
print('avg:', sum([abs(e) for e in hist_data if abs(e) > 0]) / float(len([abs(e) for e in hist_data if abs(e) > 0])))
print('avg:', sum([abs(e) for e in hist_data]) / float(len(hist_data)))
print(len([1 for e in hist_data if abs(e) > 3]), len([1 for e in hist_data if abs(e) > 0]))
data = {point: 0 for point in range(-bar_ranges, bar_ranges + 1)}
for h in hist_data:
h /= 10
h = min(bar_ranges, h)
h = max(h, -bar_ranges)
data[h] += 0.001
# del data[0]
print(data)
second_peak = max([data[i] for i in data.keys() if i !=0 ])
bax = brokenaxes(ylims=((-1, second_peak + second_peak * 0.4), (data[0]-second_peak*0.3, data[0]+second_peak*0.2)), hspace=.09)
bax.bar(data.keys(), data.values(), width=0.8)
# plt.hist(hist_data, 40)
bax.set_ylabel('Number of VNTRs (x 1000)', labelpad=40)
# bax.canvas.draw()
# print(bax.get_xticklabels())
# print(bax.get_xticklabels()[0])
labels = [item.get_text() for item in bax.get_xticklabels()[1]]
labels[0] = '<=6'
labels[-1] = '>=6'
bax.set_xticklabels(['<=60', u'<=100', u'-50', u'0', '50', u'>=100', '>=6'])
bax.set_xlabel('Base-pairs difference from reference', labelpad=20)
plt.savefig('bp_difference_from_reference_all_genotypes.pdf')
plt.cla()
plt.clf()
plt.close()
def plot_genotypes_difference_from_reference():
# **** replace avg length with two individual RU counts
# maybe also same plot for only eVNTRs and not all polymorphic VNTRs
genotypes = load_individual_genotypes(reference_vntrs)
genotyped_vntr_ids = {_id: set() for _id in range(1000000)}
reference_repeats = {_id: [] for _id in range(1000000)}
for individual_id, result_map in genotypes.items():
for genotyped_vntr, avg_length in result_map.items():
if avg_length == 'None' or avg_length is None:
continue
reference_repeats[genotyped_vntr].append(avg_length)
for key, value in reference_repeats.items():
if reference_repeats[key] == []:
reference_repeats[key].append(0)
reference_repeats = {key: most_common(value) for key, value in reference_repeats.items()}
hist_data = []
for individual_id, result_map in genotypes.items():
for genotyped_vntr, avg_length in result_map.items():
if avg_length == 'None' or avg_length is None:
continue
if avg_length != reference_repeats[genotyped_vntr]:
hist_data.append(int(round(avg_length - reference_repeats[genotyped_vntr])))
genotyped_vntr_ids[genotyped_vntr].add(avg_length)
data = {point: 0 for point in range(min(hist_data), max(hist_data) + 1)}