-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathRUN_BSA1.02.py
1395 lines (1322 loc) · 59.1 KB
/
RUN_BSA1.02.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
"""This program performs BSA and associated statistics"""
import sys
import re
import argparse
import math
import multiprocessing
import os
import random
import subprocess
from decimal import Decimal
from itertools import permutations
from numpy import percentile
import matplotlib
matplotlib.use('Agg')
from matplotlib import rcParams
from matplotlib import pyplot as plt
N_CPU = multiprocessing.cpu_count()
rcParams['font.sans-serif'] = 'Arial'
rcParams['pdf.fonttype'] = 42
rcParams['ps.fonttype'] = 42
PARSER = argparse.ArgumentParser(formatter_class=argparse.RawDescriptionHelpFormatter)
# vcf file and out-directory
PARSER.add_argument("-v", "--vcf", required=False,
help="VCF file with BSA parents and offspring")
PARSER.add_argument("-o", "--outdir", required=True,
help="Directory where output files will be written")
# parent and offspring linermation and individual variant filters
PARSER.add_argument("-psel", "--selected_parent", required=False,
help="Parent with trait of interest "
"if several crosses, insert them in order, commas,no_spaces")
PARSER.add_argument("-pcon", "--control_parent", required=False,
help="Parent without trait of interest "
"if several crosses, insert them in order, commas,no_spaces")
PARSER.add_argument("-pmaj", "--major_parent", required=False,
help="Known parent when the other's genotype is not known "
"if several crosses, insert them in order, commas,no_spaces")
PARSER.add_argument("-hpd", "--haplodiploid", required=False, default=None,
help="Haplodiploid male parent")
PARSER.add_argument("-osel", "--selected_offspring", required=False,
help="Offspring with trait of interest "
"if several crosses, insert them in order, commas,no_spaces")
PARSER.add_argument("-ocon", "--control_offspring", required=False,
help="Offspring without trait of interest "
"if several crosses, insert them in order, commas,no_spaces")
PARSER.add_argument("-mac", "--mac", required=False, default=0.95,
help="Major allele cutoff; "
"locus will not be considered segregating if higher")
PARSER.add_argument("-over", "--coverage_over", required=False, default=1.50,
help="Maximum coverage depth as a multiple of genome-wide average")
PARSER.add_argument("-under", "--coverage_under", required=False, default=0.25,
help="Minimum coverage depth as a multiple of genome-wide average")
PARSER.add_argument("-qds", "--qds", required=False, default=2,
help="Mininum variant score")
PARSER.add_argument("-sor", "--sor", required=False, default=3,
help="Maximum strand bias score")
PARSER.add_argument("-mq", "--mps", required=False, default=50,
help="Minimum mean mapping quality score")
PARSER.add_argument("-mqrs", "--mqrs", required=False, default=-8,
help="Minimum mean quality rank sum score")
PARSER.add_argument("-rprs", "--rprs", required=False, default=-8,
help="Minimum read pos rank sum")
# General options for parsing the VCF file and for sliding window analysis
PARSER.add_argument("-b", "--binsize", required=False, default=100000,
help="Genomic size of bins for storing VCF linermation")
PARSER.add_argument("-w", "--window", required=False, default=75000,
help="Genomic length of sliding windows")
PARSER.add_argument("-s", "--slide", required=False, default=5000,
help="Genomic length by which windows slide across the genome")
PARSER.add_argument("-m", "--min_allele", required=False,
help="Minimum number of variants in a window")
PARSER.add_argument("-f", "--min_scaffold", required=False, default=500000,
help="Minimum chromsome/scaffold length")
#stuff for plotting
PARSER.add_argument("-xstep", "--xstep", required=False, default=0,
help="Distance between x-marks")
PARSER.add_argument("-ystep", "--ystep", required=False, default=0.1,
help="Distance between y-marks")
PARSER.add_argument("-xticks", "--xticks", required=False, default=17,
help="Number of ticks on x-axis")
PARSER.add_argument("-yticks", "--yticks", required=False, default=0,
help="Number of ticks on y-axis")
PARSER.add_argument("-xminor", "--xminor", required=False, default=5,
help="Number of minor x-ticks related to spacing of major ticks")
PARSER.add_argument("-yminor", "--yminor", required=False, default=2,
help="Number of minor y-ticks related to spacing of major ticks")
PARSER.add_argument("-col", "--colors", required=False,
default='jet',
help="Colors for plot")
PARSER.add_argument("-plot", "--plot", required=False, default=None,
help="Combined sel-control files separated by comma")
PARSER.add_argument("-permplot", "--permplot", required=False, default=None,
help="Permutation files separated by comma")
# this is for permutations
PARSER.add_argument("-perm", "--perm", required=False, default=0,
help="The number of permutations to perform")
PARSER.add_argument("-sig", "--significance", required=False, default=0.05,
help="Significance cutoff for permutation test")
PARSER.add_argument("-sigcol", "--sigcolor", required=False, default="red",
help="Color of line denoting significance on plot")
PARSER.add_argument("-u", "--unpaired", required=False, action="store_true",
help="Use if experimental and control groups unpaired; "
"by default the are paired")
PARSER.add_argument("-n", "--n_threads", required=False, default=N_CPU,
help="Number of threads; "
"only used when data are unpaired; "
"defaults to the number of processing core")
PARSER.add_argument("-comb", "--combinations", required=False, default=1,
help="Number of exp-control combinations "
"that will be permuted "
"the default stays 1 if paired"
"and factorial(ngroups) if not"
"if unpaired and any number above 1"
"it will use that number")
# additional options
PARSER.add_argument("-mask", "--masking_file", required=False, default=None,
help="File with genomic regions to mask"
"Chrom\tbeg\tend\n for masking")
PARSER.add_argument("-zoom", "--zoom_file", required=False, default=None,
help="File with regions where you want a zoomed in plot"
"Chrom\tbeg\tend\n for zoomed in plotting")
PARSER.add_argument("-vb", "--verbose", required=False, action="store_true",
help="Prints additional files")
########################## VARIABLES ############################
ARGDICT = {}
ARGIES = PARSER.parse_args()
ARGDICT["vcf"] = ARGIES.vcf
ARGDICT["outdir"] = ARGIES.outdir
ARGDICT["outdir1"] = ARGDICT["outdir"]+"/info_files"
ARGDICT["outdir2"] = ARGDICT["outdir"]+"/BSA_output"
ARGDICT["outdir3"] = ARGDICT["outdir"]+"/BSA_plots"
ALL_POPS = set()
if ARGIES.selected_parent:
ARGDICT["selected_parent"] = ARGIES.selected_parent.split(",")
ALL_POPS = ALL_POPS | set(ARGDICT["selected_parent"])
if ARGIES.control_parent:
ARGDICT["control_parent"] = ARGIES.control_parent.split(",")
ALL_POPS = ALL_POPS | set(ARGDICT["control_parent"])
if ARGIES.haplodiploid:
ARGDICT["haplodiploid"] = ARGIES.haplodiploid
if ARGIES.major_parent:
ARGDICT["major_parent"] = ARGIES.major_parent.split(",")
ALL_POPS = ALL_POPS | set(ARGDICT["major_parent"])
if ARGIES.selected_offspring:
ARGDICT["selected_offspring"] = ARGIES.selected_offspring.split(",")
ALL_POPS = ALL_POPS | set(ARGDICT["selected_offspring"])
if ARGIES.control_offspring:
ARGDICT["control_offspring"] = ARGIES.control_offspring.split(",")
ALL_POPS = ALL_POPS | set(ARGDICT["control_offspring"])
ARGDICT["mac"] = float(ARGIES.mac)
ARGDICT["coverage_over"] = float(ARGIES.coverage_over)
ARGDICT["coverage_under"] = float(ARGIES.coverage_under)
ARGDICT["binsize"] = int(ARGIES.binsize)
ARGDICT["window"] = int(ARGIES.window)
ARGDICT["slide"] = int(ARGIES.slide)
if ARGIES.min_allele:
ARGDICT["min_allele"] = int(ARGIES.min_allele)
else:
ARGDICT["min_allele"] = ARGDICT["window"]*0.00050
ARGDICT["min_scaffold"] = int(ARGIES.min_scaffold)
ARGDICT["qds"] = float(ARGIES.qds)
ARGDICT["mps"] = float(ARGIES.mps)
ARGDICT["sor"] = float(ARGIES.sor)
ARGDICT["mqrs"] = float(ARGIES.mqrs)
ARGDICT["rprs"] = float(ARGIES.rprs)
ARGDICT["xstep"] = float(ARGIES.xstep)
ARGDICT["ystep"] = float(ARGIES.ystep)
ARGDICT["xticks"] = int(ARGIES.xticks)
ARGDICT["yticks"] = int(ARGIES.yticks)
ARGDICT["xminor"] = float(ARGIES.xminor)
ARGDICT["yminor"] = float(ARGIES.yminor)
if ARGIES.plot:
ARGDICT["plot"] = ARGIES.plot.split(",")
if ARGIES.permplot:
ARGDICT["permplot"] = ARGIES.permplot.split(",")
ARGDICT["color"] = ARGIES.colors.split(",")
if len(ARGDICT["color"]) == 1:
ARGDICT["color"] = ARGDICT["color"][0]
else:
ALL_COLORS_NAME = set([])
for collie in matplotlib.colors.cnames.items():
ALL_COLORS_NAME.add(str(collie[0]))
INVALID_COLORS = []
for col in ARGDICT["color"][1:]:
if col[0] == "#":
match_color = re.search(r'^#(?:[0-9a-fA-F]{3}){1,2}$', col)
if not match_color:
INVALID_COLORS.append(col)
else:
if col not in ALL_COLORS_NAME:
INVALID_COLORS.append(col)
if INVALID_COLORS:
INVALID_STRING = ",".join(INVALID_COLORS)
print("THE FOLLOWING COLORS ARE INVALID: %s"%(INVALID_STRING))
sys.exit()
if "selected_offspring" in ARGDICT:
if len(ARGDICT["color"])-3 != len(ARGDICT["selected_offspring"]):
print("INVALID NUMBER OF COLORS! NEED TO PROVIDE COLORS FOR: "
"SELECTED, UNSELECTED, AND ALL THE REPLICATES")
sys.exit()
if "plot" in ARGDICT:
if len(ARGDICT["color"])-1 != len(ARGDICT["plot"]):
print("INVALID NUMBER OF COLORS!")
sys.exit()
ARGDICT["perm"] = int(ARGIES.perm)
ARGDICT["sig"] = float(ARGIES.significance)
ARGDICT["sigcolor"] = ARGIES.sigcolor
if ARGIES.unpaired:
ARGDICT["unpaired"] = ARGIES.unpaired
ARGDICT["n_threads"] = int(ARGIES.n_threads)
if int(ARGIES.combinations) > 1:
ARGDICT["combinations"] = int(ARGIES.combinations)
else:
ARGDICT["combinations"] = math.factorial(len(ARGDICT["control_offspring"]))
else:
ARGDICT["n_threads"] = 1
ARGDICT["combinations"] = 1
if ARGIES.masking_file:
ARGDICT["masking_file"] = ARGIES.masking_file
if ARGIES.verbose:
ARGDICT["verbose"] = ARGIES.verbose
if ARGIES.zoom_file:
ARGDICT["zoom_file"] = ARGIES.zoom_file
PREFIX = {0:'bp',
1:'kb', # kilo
2:'Mb', # mega
3:'Gb', # giga
4:'Tb', # tera
5:'Pb', # peta
6:'Eb', # exa
7:'Zb', # zetta
8:'Yb' # yotta
}
########################## FUNCTIONS ############################
def mean(vector):
"""Calculates mean"""
list_vector = list(vector)
sum_vector = sum(list_vector)
len_vector = float(len(list_vector))
mean_final = sum_vector/len_vector
return(mean_final)
def error(message):
"""Prints error messages"""
sys.exit(message)
def arange(start, end, step):
"""A range function that works for floats"""
split_start = str(start).split(".")
if len(split_start) > 1:
dec_start = len(split_start[1])
else:
dec_start = 0
split_step = str(step).split(".")
if len(split_step) > 1:
dec_step = len(split_step[1])
else:
dec_step = 0
if dec_step > dec_start:
decider = str(step)
else:
decider = str(start)
final_list = []
current = float(start)
while current < end:
current = int(current) if float(current) == int(current) else current
final_list.append(current)
current = current + step
current = float(Decimal(current).quantize(Decimal(decider)))
return(final_list)
def afill(start, end, ntries):
"""A function that fill evenly spaced values between two numbers"""
step = (end-start)/float(ntries+1) if ntries > 0 else 0
final_list = [float(start) + (i+1)*step for i in range(ntries)]
return(final_list)
# this function processes scaffold linermation
def scale_dict(line_file):
"""Creates a dict with cumulative positions for each chromosome"""
line_read = open(line_file, "r")
line_dict = {}
final_lenny = 0
lenny = 0
scaffolds = []
for line in line_read:
linetab = (line.rstrip()).split("\t")
scaffy = linetab[0]
scaffolds.append(scaffy)
final_lenny = final_lenny + lenny
lenny = int(linetab[1])
line_dict[scaffy] = final_lenny
line_read.close()
return(line_dict, scaffolds)
# this function processes scaffold linermation
def length_dict(line_file):
"""Creates a dict with chromosome lengths"""
line_read = open(line_file, "r")
line_dict = {}
for line in line_read:
linetab = (line.rstrip()).split("\t")
scaffy = linetab[0]
lenny = int(linetab[1])
line_dict[scaffy] = lenny
line_read.close()
return(line_dict)
def scale_ends(line_file):
"""Creates a dict with ends for each chromosome"""
try:
line_read = open(line_file, "r")
except IOError:
error("FILE NOT FOUND, LIKELY BECAUSE YOU ARE RUNNING "
"THE PLOTTING CODE. MOVE THE info_files DIRECTORY "
"INTO YOUR OUTDIR FOR THIS TO WORK")
line_dict = {}
final_lenny = 0
lenny = 0
scaffolds = []
for line in line_read:
linetab = (line.rstrip()).split("\t")
scaffy = linetab[0]
scaffolds.append(scaffy)
lenny = int(linetab[1])
final_lenny = final_lenny + lenny
line_dict[scaffy] = final_lenny
line_read.close()
return(line_dict, scaffolds)
def masker():
"""Specifies regions of genome to mask"""
maskdict = {}
if "masking_file" in ARGDICT:
maskfile = open(ARGDICT["masking_file"])
for line in maskfile:
line = line.split("\t")
try:
int(line[1]) and int(line[2])
except ValueError:
error("CANNOT CONVERT MASKING COORDS TO INTEREGRS. "
"EXITING PROGRAM.")
if line[0] not in maskdict:
maskdict[line[0]] = set(range(int(line[1]), int(line[2])+1))
maskdict[line[0]] = maskdict[line[0]] | set(range(int(line[1]), int(line[2])+1))
scaffs = scale_dict(ARGDICT["outdir1"] + "/chrom_file.txt")[1]
for scaff in scaffs:
if scaff not in maskdict:
maskdict[scaff] = set([-1])
return(maskdict)
def verbosy(indict, contigs, outkeys):
"""Outputs all the variant/allele info"""
for outkey in outkeys:
outfile = open(ARGDICT["outdir1"] + "/%s.txt"%(outkey), "w")
outfile.close()
for contig in contigs:
binnies = indict[contig]
for binny in sorted(binnies):
positions = indict[contig][binny]
for position in sorted(positions):
strains = indict[contig][binny][position]
for strain in strains:
value = indict[contig][binny][position][strain]
outfile = open(ARGDICT["outdir1"] + "/%s.txt"%(strain), "a")
# should remove binny once i test this
outfile.write("%s\t%s\t%s\t%s\n"%(contig, position, binny, value))
outfile.close()
# COVERAGE
def coverage():
"""Calculates average coverage per strain/individual"""
print("ITERATING OVER VCF FILE TO GET COVERAGE INFORMATION")
cov = {}
if not os.path.isdir("%s"%ARGDICT["outdir1"]):
subprocess.call("mkdir %s"%(ARGDICT["outdir1"]), shell=True)
outcov = open(ARGDICT["outdir1"]+"/coverageinfo.txt", "w")
line_file_handle = open(ARGDICT["outdir1"]+"/chrom_file.txt", "w")
the_right_stuff = set()
openvcf = open(ARGDICT["vcf"])
for line in openvcf:
if line[0] == "#":
if line.split("=")[0] == "##contig":
line = line.split("=")
vcf_scaff = line[2].split(",")[0]
vcf_scaff_len = (line[3].split(">")[0])
if int(vcf_scaff_len) > ARGDICT["min_scaffold"]:
the_right_stuff.add(vcf_scaff)
line_file_handle.write("%s\t%s\n"%(vcf_scaff, vcf_scaff_len))
elif line[0:6] == "#CHROM":
header_strains = line.strip().split("\t")[9:]
not_in_vcf = ALL_POPS - set(header_strains)
if len(not_in_vcf) > 0:
not_in_vcf_string = ",".join(not_in_vcf)
print("INVALID STRAIN NAMES: %s. EXITING PROGRAM"%(not_in_vcf_string))
sys.exit()
right_strains = [st for st in header_strains if st in ALL_POPS]
indexed_strains = [header_strains.index(st) for st in right_strains]
for strain in right_strains:
cov[strain] = {}
cov[strain]["cov"] = 0.0
cov[strain]["total"] = 0.0
else:
line = line.replace("|", "/")
line = line.strip().split("\t")
info = line[9:]
if (line[0] in the_right_stuff
and len(line[3]) == 1
and len(line[4].split(",")) == 1):
for ix_strain in zip(indexed_strains, right_strains):
if "./" not in info[ix_strain[0]]:
reads = info[ix_strain[0]].split(":")[1].split(",")
parent_cov = sum([int(i) for i in reads])
cov[ix_strain[1]]["cov"] = cov[ix_strain[1]]["cov"] + parent_cov
cov[ix_strain[1]]["total"] = cov[ix_strain[1]]["total"] + 1
openvcf.close()
line_file_handle.close()
for strain in right_strains:
avecov = cov[strain]["cov"]/cov[strain]["total"]
outcov.write("%s\t%s\n"%(strain, avecov))
outcov.close()
def spt_vcfcov(stringy):
"""Parses string with coverage info in VCF and gets total coverage"""
return(sum([float(i) for i in
stringy.split(":")[1].split(",")]))
def round_sig(xxx, sig):
"""Determines the number of sig figs"""
if xxx:
output = (round(xxx, sig-int(math.floor(
math.log10(abs(xxx))))-1))
else:
output = 0
return(output)
def inferred(indv):
"""Process offspring information when information only from a single parent"""
exp_genosplito = set(indv[2].split(":")[0].split("/"))
sample_scores = []
if len(exp_genosplito) == 1:
exp_allele = list(exp_genosplito)[0]
#### now let's get the selected
for ns in range(2):
sample_ix = list(set([call for call in indv[ns].split(":")[0].split("/")
if call == exp_allele]))
if sample_ix:
sample_ix = int(sample_ix[0])
sample_score = float(indv[ns].split(":")[1].split(",")
[sample_ix])/spt_vcfcov(indv[ns])
else:
sample_score = 0.0
sample_scores.append(sample_score)
high_scores = [i for i in sample_scores if i >= ARGDICT["mac"]]
if len(high_scores) < len(sample_scores):
return(sample_scores)
def haplodiploid(indv):
"""Process offspring information when one of parents is haplodiploid"""
exp_genosplito = set(indv[2].split(":")[0].split("/"))
cont_genosplito = set(indv[3].split(":")[0].split("/"))
if (len(exp_genosplito | cont_genosplito) == 2
and exp_genosplito != cont_genosplito
and (len(exp_genosplito) == 1
or len(cont_genosplito) == 1)):
if len(exp_genosplito) == 1 and len(cont_genosplito) == 1:
bothdiff = True
exp_allele = list(exp_genosplito)[0]
reverse = False
else:
bothdiff = False
if (len(exp_genosplito) == 1
and ARGDICT["haplodiploid"] in ARGDICT["control_parent"]):
exp_allele = list(exp_genosplito)[0]
reverse = False
elif (len(cont_genosplito) == 1
and ARGDICT["haplodiploid"] in ARGDICT["selected_parent"]):
exp_allele = list(cont_genosplito)[0]
reverse = True
else:
return(None)
#### now let's get the offspring
sample_scores = []
for ns in range(2):
sample_ix = list(set([call for call in indv[ns].split(":")[0].split("/")
if call == exp_allele]))
if sample_ix:
sample_ix = int(sample_ix[0])
sample_score = float(indv[ns].split(":")[1].split(",")
[sample_ix])/spt_vcfcov(indv[ns])
else:
sample_score = 0.0
sample_scores.append(sample_score)
high_scores = [i for i in sample_scores if i >= ARGDICT["mac"]]
if (bothdiff or
(not bothdiff
and len(high_scores) < len(sample_scores))):
if reverse:
sample_scores = [1-i for i in sample_scores]
return(sample_scores)
def both_fixed(indv):
"""Process offspring information when both parents fixed"""
exp_genosplito = set(indv[1].split(":")[0].split("/"))
cont_genosplito = set(indv[2].split(":")[0].split("/"))
if (len(exp_genosplito | cont_genosplito) == 2
and exp_genosplito != cont_genosplito
and (len(exp_genosplito) == 1
and len(cont_genosplito) == 1)):
exp_allele = list(exp_genosplito)[0]
sample_ix = list(set([call for call in indv[0].split(":")[0].split("/")
if call == exp_allele]))
if sample_ix:
sample_ix = int(sample_ix[0])
sample_score = float(indv[0].split(":")[1].split(",")
[sample_ix])/spt_vcfcov(indv[0])
else:
sample_score = 0.0
return(sample_score)
def process_noparents(line, vcfline, cov):
"""Processes each line of a VCF file when parents are not specified"""
# now let's parse it for each replicate:
outdict = {}
info = line[9:]
for sample in zip(ARGDICT["selected_offspring"], ARGDICT["control_offspring"]):
scores = []
indv = [info[vcfline.index(sample[0])],
info[vcfline.index(sample[1])]]
if (len([call for call in indv if "." not in call]) == len(indv) and
(cov[sample[0]]*ARGDICT["coverage_under"]
<= spt_vcfcov(indv[0]) <= cov[sample[0]]*ARGDICT["coverage_over"]
and cov[sample[1]]*ARGDICT["coverage_under"]
<= spt_vcfcov(indv[1]) <= cov[sample[1]]*ARGDICT["coverage_over"])):
########### NOW ONTO THE ACTUAL CALLS
for call in indv:
sample_score = float(call.split(":")[1].split(",")[0])/spt_vcfcov(call)
scores.append(sample_score)
high_scores = [i for i in scores if i >= ARGDICT["mac"]]
low_scores = [i for i in scores if i <= 1-ARGDICT["mac"]]
if (len(high_scores) < len(scores)
and len(low_scores) < len(scores)):
outdict[sample[0]] = abs(scores[0] - scores[1])
outdict[sample[1]] = 0
return(outdict)
def process_infer(line, vcfline, cov):
"""Processes each line of a VCF file when only one parent is specified"""
# now let's parse it for each replicate:
outdict = {}
info = line[9:]
for sample in zip(ARGDICT["selected_offspring"],
ARGDICT["control_offspring"],
ARGDICT["major_parent"]):
indv = [info[vcfline.index(sample[0])],
info[vcfline.index(sample[1])],
info[vcfline.index(sample[2])]]
if (len([call for call in indv if "." not in call]) == len(indv) and
(cov[sample[0]]*ARGDICT["coverage_under"]
<= spt_vcfcov(indv[0]) <= cov[sample[0]]*ARGDICT["coverage_over"]
and cov[sample[1]]*ARGDICT["coverage_under"]
<= spt_vcfcov(indv[1]) <= cov[sample[1]]*ARGDICT["coverage_over"]
and cov[sample[2]]*ARGDICT["coverage_under"]
<= spt_vcfcov(indv[2]) <= cov[sample[2]]*ARGDICT["coverage_over"])):
########### NOW ONTO THE ACTUAL CALLS
sample_scores = inferred(indv)
if sample_scores:
outdict[sample[0]] = sample_scores[0]
outdict[sample[1]] = sample_scores[1]
return(outdict)
def process_hpd(line, vcfline, cov):
"""Processes each line of a VCF file when parents are not specified"""
# now let's parse it for each replicate:
outdict = {}
info = line[9:]
for sample in zip(ARGDICT["selected_offspring"],
ARGDICT["control_offspring"],
ARGDICT["selected_parent"],
ARGDICT["control_parent"]):
indv = [info[vcfline.index(sample[0])],
info[vcfline.index(sample[1])],
info[vcfline.index(sample[2])],
info[vcfline.index(sample[3])]]
if (len([call for call in indv if "." not in call]) == len(indv) and
(cov[sample[0]]*ARGDICT["coverage_under"]
<= spt_vcfcov(indv[0]) <= cov[sample[0]]*ARGDICT["coverage_over"]
and cov[sample[1]]*ARGDICT["coverage_under"]
<= spt_vcfcov(indv[1]) <= cov[sample[1]]*ARGDICT["coverage_over"]
and cov[sample[2]]*ARGDICT["coverage_under"]
<= spt_vcfcov(indv[2]) <= cov[sample[2]]*ARGDICT["coverage_over"]
and cov[sample[3]]*ARGDICT["coverage_under"]
<= spt_vcfcov(indv[3]) <= cov[sample[3]]*ARGDICT["coverage_over"])):
########### NOW ONTO THE ACTUAL CALLS
sample_scores = haplodiploid(indv)
if sample_scores:
outdict[sample[0]] = sample_scores[0]
outdict[sample[1]] = sample_scores[1]
return(outdict)
def process_samples(line, vcfline, cov):
"""Processes each line of a VCF file"""
# now let's parse it for each replicate:
outdict = {}
info = line[9:]
for sample in zip(ARGDICT["selected_offspring"]+ARGDICT["control_offspring"],
ARGDICT["selected_parent"]*2,
ARGDICT["control_parent"]*2):
indv = [info[vcfline.index(sample[0])],
info[vcfline.index(sample[1])],
info[vcfline.index(sample[2])]]
if (len([call for call in indv if "." not in call]) == len(indv) and
(cov[sample[0]]*ARGDICT["coverage_under"]
<= spt_vcfcov(indv[0]) <= cov[sample[0]]*ARGDICT["coverage_over"]
and cov[sample[1]]*ARGDICT["coverage_under"]
<= spt_vcfcov(indv[1]) <= cov[sample[1]]*ARGDICT["coverage_over"]
and cov[sample[2]]*ARGDICT["coverage_under"]
<= spt_vcfcov(indv[2]) <= cov[sample[2]]*ARGDICT["coverage_over"])):
########### NOW ONTO THE ACTUAL CALLS
sample_score = both_fixed(indv)
if sample_score is not None:
outdict[sample[0]] = sample_score
return(outdict)
def line_parser(line):
"""Parses VCF string to get mapping quality info"""
linedict = {}
line = line.split(";")
for keyval in line:
keyval = keyval.split("=")
try:
linedict[keyval[0]] = float(keyval[1])
except ValueError:
linedict[keyval[0]] = str(keyval[1])
return(linedict)
def get_vcftuple():
"""Parses the VCF file, filters SNPs, and extracts relevant information"""
print("PARSING VCF TO ANALYZE VARIANTS")
chrom_tuple = scale_ends(ARGDICT["outdir1"] + "/chrom_file.txt")
chrom_dict = chrom_tuple[0]
chroms = chrom_tuple[1]
number_total_snps = 0
number_qc_snps = 0
number_passed_snps = 0
cov = {}
with open(ARGDICT["outdir1"] + "/coverageinfo.txt", "r") as opencov:
for line in opencov:
line = (line.rstrip()).split("\t")
strain = line[0]
cov[strain] = float(line[1])
masking = masker()
openvcf = open(ARGDICT["vcf"], "r") # feeds the file line by line (see below)
vcfdict = {}
contigs = []
vcfline = None
outkeys = [i for i in ARGDICT["selected_offspring"]+ARGDICT["control_offspring"]]
for line in openvcf: # let's go over each line
line = line.replace("|", "/")
line = line.rstrip().split("\t")
chrom = line[0]
vcfline = line[9:] if chrom == "#CHROM" else vcfline
if (chrom in chroms
and len(line[3]) == 1 and len(line[4]) == 1):
pos = int(line[1])
quals = line_parser(line[7])
number_total_snps += 1
if ("QD" in quals and "MQ" in quals and "SOR" in quals
and "MQRankSum" in quals and "ReadPosRankSum" in quals):
if chrom not in contigs:
vcfdict[chrom] = {}
for binny in range(1, chrom_dict[chrom], ARGDICT["binsize"]):
vcfdict[chrom][binny] = {}
contigs.append(chrom)
current_bin = 1
if pos >= current_bin + ARGDICT["binsize"]:
while pos >= current_bin + ARGDICT["binsize"]:
current_bin = current_bin + ARGDICT["binsize"]
if (pos not in masking[chrom]
and quals["QD"] >= ARGDICT["qds"]
and quals["MQ"] >= ARGDICT["mps"]
and quals["SOR"] < ARGDICT["sor"]
and quals["MQRankSum"] >= ARGDICT["mqrs"]
and quals["ReadPosRankSum"] >= ARGDICT["rprs"]):
vcfdict[chrom][current_bin][pos] = {}
number_qc_snps += 1
if ("selected_parent" and "control_parent" in ARGDICT
and "haplodiploid" not in ARGDICT):
outdict = process_samples(line, vcfline, cov)
elif ("selected_parent" and "control_parent" in ARGDICT
and "haplodiploid" in ARGDICT):
outdict = process_hpd(line, vcfline, cov)
elif "major_parent" in ARGDICT:
outdict = process_infer(line, vcfline, cov)
else:
outdict = process_noparents(line, vcfline, cov)
if outdict:
number_passed_snps += 1
for sample in outdict:
vcfdict[chrom][current_bin][pos][sample] = outdict[sample]
if "verbose" in ARGDICT:
verbosy(vcfdict, contigs, outkeys)
print("the total number of SNPs considered is %s"%(number_total_snps))
print("the total number of SNPs that passed QC is %s"%(number_qc_snps))
print("the total number of SNPs that passed QC and BSA cutoffs is %s"%(number_passed_snps))
return(vcfdict, contigs, outkeys)
def process_segment(vcf_tuple, scaffy, beg):
"""Retrives allele counts within a genomic window"""
relevant_keys = [i for i in vcf_tuple[0][scaffy] if i <= beg < i+ARGDICT["binsize"]
or beg <= i <= beg + ARGDICT["window"]
or i <= beg + ARGDICT["window"] < i+ARGDICT["binsize"]]
segment_spls = {}
for spl in vcf_tuple[2]:
segment_spls[spl] = {}
segment_spls[spl]["count"] = 0.0
segment_spls[spl]["averages"] = 0.0
for relevant_key in relevant_keys:
section = sorted(vcf_tuple[0][scaffy][relevant_key])
for snppy in section:
if beg <= snppy <= beg + ARGDICT["window"]:
snppy_spls = vcf_tuple[0][scaffy][relevant_key][snppy]
for spl in snppy_spls:
spl_value = vcf_tuple[0][scaffy][relevant_key][snppy][spl]
segment_spls[spl]["count"] += 1
segment_spls[spl]["averages"] += spl_value
return(segment_spls)
def slider(vcf_tuple):
"""Performs a sliding window analysis"""
print("RUNNING SLIDING WINDOW ANALYSIS")
shader = scale_dict(ARGDICT["outdir1"] + "/chrom_file.txt")[0]
lennies = length_dict(ARGDICT["outdir1"] + "/chrom_file.txt")
outdict = {}
for spl in vcf_tuple[2]:
outdict[spl] = {}
outdict[spl]["val"] = []
outdict[spl]["pos"] = []
outdict[spl]["nvr"] = []
for scaffy in vcf_tuple[1]:
beg = 0
medpos = mean([beg, beg+ARGDICT["window"]])+shader[scaffy]
while (beg+ARGDICT["window"]) <= (lennies[scaffy] + ARGDICT["slide"]):
segment_spls = process_segment(vcf_tuple, scaffy, beg)
for spl in segment_spls:
if segment_spls[spl]["count"] >= ARGDICT["min_allele"]:
outdict[spl]["val"].append(segment_spls[spl]["averages"]
/segment_spls[spl]["count"])
outdict[spl]["pos"].append(medpos)
outdict[spl]["nvr"].append(int(segment_spls[spl]["count"]))
beg = beg + ARGDICT["slide"]
medpos = mean([beg, beg + ARGDICT["window"]]) + shader[scaffy]
outdir2 = ARGDICT["outdir2"]
if not os.path.isdir("%s"%ARGDICT["outdir2"]):
subprocess.call("mkdir %s"%(outdir2), shell=True)
if "verbose" in ARGDICT:
for spl in vcf_tuple[2]:
bsa_out = open(ARGDICT["outdir2"]+"/%s.txt"%(spl), "w")
positions = outdict[spl]["pos"]
for possa in positions:
where = positions.index(possa)
bsa_out.write(
"%s\t%s\t%s\n" %
(possa, outdict[spl]["val"][where],
outdict[spl]["nvr"][where]))
bsa_out.close()
return(outdict)
def shade_grid(axes, maxx):
"""Shades chromosomes in alternating gray and white"""
shader_file = ARGDICT["outdir1"] + "/chrom_file.txt"
shade_scaff_line = scale_dict(shader_file)
shader = shade_scaff_line[0]
scaffolds = shade_scaff_line[1]
# here comes the shading of scaffolds/chroms
old = None
shade = False
# here comes the shading
for contig in scaffolds:
val = shader[contig]
if old and shade:
axes.axvspan(old, val, color='0.87', alpha=0.5)
shade = False
else:
if old != None:
shade = True
old = val
# the last one
if shade:
axes.axvspan(old, maxx, color='0.87', alpha=0.5)
axes.grid(True, axis="y", ls="dotted", color="0.85",lw=1.5)
def inducer(beg, end, number):
"""Spaces ticks on plot when spacing defined"""
count = 0
while number > 1e3:
number = number/1e3
count += 1
ticklocator = arange(beg, end+number, number*math.pow(1e3, count))[1:]
xminorlocator = None
yminorlocator = None
if ARGDICT["xminor"] > 0:
xminorlocator = arange(beg, end+number, number*math.pow(1e3, count)/ARGDICT["xminor"])[1:]
if ARGDICT["yminor"] > 0:
yminorlocator = arange(beg, end+number, number*math.pow(1e3, count)/ARGDICT["yminor"])[1:]
beglab = beg*math.pow(1e3, -count)
endlab = end*math.pow(1e3, -count)
ticklabels = arange(beglab, endlab+number, number)
sigfigs = max([len(set(str(i))-set(["."])) for i in ticklabels])
ticklabels = [round_sig(i, sigfigs) for i in ticklabels][1:]
if ticklabels[-1] > 1e3:
newbeg = beglab
newend = endlab
while ticklabels[-1] > 1e3:
newbeg = newbeg/1e3
newend = newend/1e3
number = number/1e3
count += 1
ticklabels = arange(newbeg, newend+number, number)
final_ticklabels = []
for tickl in ticklabels:
if int(tickl) == float(tickl):
final_ticklabels.append(str(int(tickl)))
else:
final_ticklabels.append(str(tickl))
return(ticklocator, final_ticklabels, xminorlocator, yminorlocator, count)
def process_coords(coord, number, count):
"""Processes coordinates for plotting"""
if number < 1:
number = "%f"%(number)
number = number.rstrip("0")
zeros = str(number).split(".")[1].count("0")
number = float(number)
newcoord = str(coord).split(".")
newcoord[1] = newcoord[1][:zeros+1]
newcoord = float(".".join(newcoord))
else:
newcoord = coord*math.pow(1e3, -count)
newcoord = math.floor(newcoord)
newcoord = newcoord*math.pow(1e3, count)
return(newcoord, number)
def reducer(beg, end, nticks):
"""Helps determine tick spacing based on optimal number of ticks"""
count = 0
number = end - beg
number = number/float(nticks)
while number > 1e3:
number = number/1e3
count += 1
number = float("%0.1g"%(number)) # math.floor(number) if number >= 1 else
if number < 1:
newbeg = process_coords(beg, number, count)[0]
newend = process_coords(end, number, count)[0]
number = process_coords(end, number, count)[1]
else:
newbeg = process_coords(beg, number, count)[0]
newend = process_coords(end, number, count)[0]
ticklocator = arange(newbeg, newend+number, number*math.pow(1e3, count))
ticklocator = [i for i in ticklocator if beg < i < end]
xminorlocator = None
yminorlocator = None
if ARGDICT["xminor"] > 0:
xminorlocator = arange(newbeg, newend+number, number*math.pow(1e3, count)/ARGDICT["xminor"])
if ARGDICT["yminor"] > 0:
yminorlocator = arange(newbeg, newend+number, number*math.pow(1e3, count)/ARGDICT["yminor"])
beglab = newbeg*math.pow(1e3, -count)
endlab = newend*math.pow(1e3, -count)
ticklabels = arange(beglab, endlab+number, number)
if ticklabels[-1] > 1e3:
newbeg = beglab
newend = endlab
while ticklabels[-1] > 1e3:
newbeg = newbeg/1e3
newend = newend/1e3
number = number/1e3
count += 1
ticklabels = arange(newbeg, newend+number, number)
ticklabels = [i for i in ticklabels if beg < int(i*math.pow(1e3, count)) < end]
final_ticklabels = []
for tickl in ticklabels:
if int(tickl) == float(tickl):
final_ticklabels.append(str(int(tickl)))
else:
final_ticklabels.append(str(tickl))
return(ticklocator, final_ticklabels, xminorlocator, yminorlocator, count)
def ticks(axes, x_min, x_max, y_min, y_max):
"""Specifies ticks for the plot"""
# x-axis
if ARGDICT["xstep"]:
scaled_ticks = arange(0, x_max+ARGDICT["xstep"], ARGDICT["xstep"])
scaled_ticks = [i for i in scaled_ticks
if x_min <= i <= x_max+ARGDICT["xstep"]]
tick_def = inducer(min(scaled_ticks), max(scaled_ticks), ARGDICT["xstep"])
else:
try:
tick_def = reducer(x_min, x_max, ARGDICT["xticks"])
except KeyError:
error("YOU MUST PROVIDE EITHER TICK SPACING OR THE PREFERRED NUMBER OF TICKS")
axes.set_xticks(tick_def[0])
axes.set_xticklabels(tick_def[1], size=17.24)
axes.set_xlabel("Genomic Position (%s)" %(PREFIX[tick_def[4]]), size=17.24)
if ARGDICT["xminor"] > 0:
axes.set_xticks(tick_def[2], minor=True)
if ARGDICT["ystep"]:
scaled_ticks = arange(-1.1, 1.1, ARGDICT["ystep"])
scaled_ticks = [i for i in scaled_ticks if
y_min-ARGDICT["ystep"] <= i <= y_max+ARGDICT["ystep"]]
tick_def = inducer(min(scaled_ticks),
max(scaled_ticks), ARGDICT["ystep"])
else:
try:
tick_def = reducer(y_min, y_max, ARGDICT["yticks"])
except KeyError:
error("YOU MUST PROVIDE EITHER TICK SPACING OR THE PREFERRED NUMBER OF TICKS")
axes.set_yticks(tick_def[0])
if ARGDICT["yminor"] > 0:
axes.set_yticks(tick_def[3], minor=True)
axes.set_yticklabels(tick_def[1], size=17.24)
axes.tick_params(axis="both", which="both", top=True, right=True)
def finish_plot(axes, indict, fig, commas):
"""Adds the option to zoom in on parts of plot"""
all_spls = sorted(indict)
if "nvr" in indict[all_spls[0]]:
plot_file = ARGDICT["outdir3"] + "/BSA_sep_plot.pdf"
axes.set_ylabel("Selected parent allele frequency", size=17.24)
elif commas:
plot_file = ARGDICT["outdir3"] + "/BSA_comb_plot.pdf"
axes.set_ylabel("Difference in allele frequency", size=17.24)
else:
plot_file = ARGDICT["outdir3"] + "/BSA_average_plot.pdf"
axes.set_ylabel("Difference in allele frequency", size=17.24)
print("Saving plot to %s"%(plot_file))
print("***********************")
fig.savefig(plot_file, bbox_inches='tight')
if "zoom_file" in ARGDICT:
converta = scale_dict(ARGDICT["outdir1"] + "/chrom_file.txt")[0]
zoomy = open(ARGDICT["zoom_file"])
for line in zoomy:
line = line.rstrip().split("\t")
chrom = line[0]
beg = int(line[1])+converta[chrom]
end = int(line[2])+converta[chrom]
y_min = 1
y_max = 0
for spl in all_spls:
posses = [p for p in indict[spl]["pos"] if beg <= p <= end]
where_beg = indict[spl]["pos"].index(posses[0])
where_end = indict[spl]["pos"].index(posses[-1])
values = indict[spl]["val"][where_beg:where_end]
y_max = max(values) if max(values) > y_max else y_max
y_min = min(values) if min(values) < y_min else y_min
if "stat_cutoff" in ARGDICT:
axes.axhline(y=ARGDICT["stat_cutoff"],
ls="dashed", lw=1, color=ARGDICT["sigcolor"])
axes.axhline(y=-ARGDICT["stat_cutoff"],
ls="dashed", lw=1, color=ARGDICT["sigcolor"])
y_max = ARGDICT["stat_cutoff"] if ARGDICT["stat_cutoff"] > y_max else y_max
y_min = -ARGDICT["stat_cutoff"] if -ARGDICT["stat_cutoff"] < y_min else y_min
new_extremes = (y_min-abs(y_max-y_min)*0.05, y_max+abs(y_max-y_min)*0.05)
if "nvr" in indict[all_spls[0]]:
y_min = 0
y_max = 1
else:
y_min = new_extremes[0]
y_max = new_extremes[1]
ticks(axes, beg, end, y_min, y_max)
if "nvr" not in indict[all_spls[0]]:
axes.set_ylim(y_min, y_max)
else:
axes.set_ylim(-0.02, 1.02)
axes.set_xlim(beg, end)
new_plotfile = ARGDICT["outdir3"]+"/%s_%s_%s_%s.pdf"%(
plot_file.split("/")[-1].split(".")[0], chrom, beg, end)
print("Saving plot to %s"%(new_plotfile))
print("***********************")