-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathalibaseqPy3.py
1960 lines (1870 loc) · 96.3 KB
/
alibaseqPy3.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
from Bio import SeqIO
from Bio.Seq import Seq
from Bio.SeqRecord import SeqRecord
from decimal import Decimal
import glob
import os
import shutil
import csv
import sys
import argparse
import math
parser = argparse.ArgumentParser(description='ALiBaSeq (Alignment-Based Sequence extraction)',formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser._action_groups.pop()
required = parser.add_argument_group('required arguments')
optional = parser.add_argument_group('optional arguments')
required.add_argument('-b', metavar='table', help='alignment table file',dest="blastfilearg",required=True)
required.add_argument('-f', choices=['S','M','SM'], help='file / folder mode',dest="filefolder", required=True)
required.add_argument('-x', choices=['n','s','a','b'], help='extraction type: n (whole contig), s (only best hit region), a (extract all hit regions and join them), b (extract region between two outmost hit regions)',dest="extractiontype",required=True)
optional.add_argument('-t', metavar='assembly', help='assembly file',dest="targetf")
optional.add_argument('-q', metavar='query', help='query file(s) to which extracted results are to be appended; if not specified, sequences are extracted into blank files',dest="queryf")
optional.add_argument('-o', metavar='output', help='output folder for modified files with extracted sequences',dest="output", default="alibaseq_out")
optional.add_argument('-s', metavar='logsuffix', help='output log suffix',dest="logsuffix", default="default")
optional.add_argument('--om', choices=['query','target', 'combined'], help='output mode: group in files per bait [query], per sample [target], or combine in a single file [combined]',dest="outM", default="query")
optional.add_argument('-e', metavar='N', help='evalue cutoff',dest="evalue", type=float, default=0.01)
optional.add_argument('-i', metavar='N', help='identity cutoff',dest="identity", type=float, default=0.0)
optional.add_argument('-B', metavar='N', help='bitscore cutoff',dest="bitscore", type=float, default=0.0)
optional.add_argument('-c', metavar='N', help='number of contigs to extract; if set to 0, then extract all contigs; if set to -1, then extract the best and all close matches',dest="contignum", type=int, default=1)
optional.add_argument('--fl', metavar='N', help='flanks on each side in bp',dest="flanks", type=int, default=0)
optional.add_argument('--lr', dest='local_rec', choices=['none','actual','range'], help='local reciprocator setting', default='range')
optional.add_argument('--is', dest='interstitch', action='store_true', help='perform contig stitching', default=False)
# optional.add_argument('--translate', dest='trans_out', action='store_true', help='translate output (for -x s or -x a)', default=False)
optional.add_argument('--hit-ovlp', metavar='N', help='allowed hit overlap on query, >= 1 in bp, or relative 0 < N < 1',dest="hit_ovlp", type=float, default=0.1)
optional.add_argument('--ctg-ovlp', metavar='N', help='allowed contig overlap on query, >= 1 in bp, or relative 0 < N < 1',dest="ctg_ovlp", type=float, default=0.2)
optional.add_argument('--recip-ovlp', metavar='N', help='contig overlap on query for reciprocator selection, >= 1 in bp, or relative 0 < N < 1',dest="recip_ovlp", type=float, default=10)
optional.add_argument('--bt', choices=['blast','hmmer22', 'hmmer18', 'hmmer15', "lastz", "sam", "bam"], help='alignment table type',dest="bt", default="blast")
optional.add_argument('--btR', choices=['blast','bed'], help='reference alignment table type',dest="btR", default="blast")
optional.add_argument('--ac', choices=['dna-dna', 'tdna-aa', 'aa-tdna', 'aa-aa', 'tdna-tdna'], help='alignment coordinate type',dest="ac", default="dna-dna")
optional.add_argument('--acr', choices=['dna-dna', 'tdna-aa', 'aa-tdna', 'aa-aa', 'tdna-tdna'], help='reciprocal alignment coordinate type',dest="acr", default="dna-dna")
optional.add_argument('--acR', choices=['dna-dna', 'tdna-aa', 'aa-tdna', 'aa-aa', 'tdna-tdna'], help='reference alignment coordinate type',dest="acR", default="dna-dna")
optional.add_argument('-r', metavar='file/folder', help='reciprocal search output file or folder',dest="rec_search")
optional.add_argument('-R', metavar='file', help='bait to reference contig correspondence file',dest="target_ref_file")
optional.add_argument('-m', choices=['e/b-i','e-b-i','b-e-i','i-b-e','i-e-b','b-i-e','e-i-b'], help='order of metrics to use to select best matches (e - evalue, b - bitscore, i - identity)',dest="metric", default="e/b-i")
optional.add_argument('--rescale-metric', dest='metricR', action='store_true', help='divide metric value by length of hit region', default=False)
optional.add_argument('--metric-merge-corr', metavar='N', help='modify combined metric by this value',dest="metricC", type=float, default=1.0)
optional.add_argument('--no-hs', dest='no_hs', action='store_true', help='do not run hit stitcher', default=False)
optional.add_argument('--ref-hs', dest='ref_hs', action='store_true', help='run hit stitcher on reciprocal table (slow)', default=False)
optional.add_argument('--keep-strand', dest='keep_strand', action='store_true', help='keep original contig direction', default=False)
optional.add_argument('--rm-rec-not-found', dest='rmrecnf', action='store_true', help='remove hits without matches in reciprocal search', default=False)
optional.add_argument('--hmmer-global', dest='hmmerg', action='store_true', help='use HMMER contig score instead of domain score', default=False)
optional.add_argument('--amalgamate-hits', dest='amlghitscore', action='store_true', help='combine score for different hits of the same contig', default=False)
optional.add_argument('--max-gap', metavar='N', help='max gap between HSP regions in either query or hit, use 0 for no filtering',dest="max_gap", type=int, default=0)
optional.add_argument('--cname', dest='cname', action='store_true', help='append original contig name to output sequence name', default=False)
optional.add_argument('--both-strands', dest='bstrands', choices=['1','0'], help='allow both strands of the same contig region to be considered', default='1')
optional.add_argument('--srt', metavar='N', help='score ratio threshold, greater which the hits considered be close matches',dest="srt", type=float, default=0.9)
optional.add_argument('--samScore', metavar='metric', help='metric to use for scoring matches',dest="samscore", default="MAPQ")
optional.add_argument('--dd', dest='dd', choices=['all','none','random'], help='in case hit matches several query with exactly equal score, assign such hit to [all queries / none of the queries / at random to only one]', default='none')
optional.add_argument('--log-header', dest='loghead', action='store_true', help='add a header to the table-like log files', default=False)
optional.add_argument('--synteny', dest='syntcheck', choices=['1','0'], help='only stitch hits that are in synteny to query', default='1')
optional.add_argument('-d', metavar='namedelim', help='sample/contigID delimiter, should be a character not encountered in contig or sample names',dest="namedelim", default="|")
if len(sys.argv) == 1:
parser.print_help()
sys.exit()
else:
args = parser.parse_args()
blastfilearg = vars(args)["blastfilearg"]
filefolder = vars(args)["filefolder"]
bt = vars(args)["bt"]
hmmerg = vars(args)["hmmerg"]
if bt == "hmmer18":
if vars(args)["extractiontype"] != "n":
print ("only whole contig extraction is supported for hmmer18 tables, option -x ignored")
if vars(args)["ac"] != "aa-aa":
print ("hmmer18 tables are only for AA vs AA search, option --ac ignored")
extractiontype = "n"
ac = "aa-aa"
elif bt == "hmmer15":
if vars(args)["ac"] != "dna-dna":
print ("hmmer15 tables are only for DNA vs DNA search, option --ac ignored")
ac = "dna-dna"
extractiontype = vars(args)["extractiontype"]
elif bt == "sam" or bt == "bam":
print ("SAM / BAM input, importing Pysam")
import pysam
samscore = vars(args)["samscore"]
if vars(args)["ac"] != "dna-dna":
print ("SAM / BAM files are only for DNA vs DNA search, option --ac ignored")
ac = "dna-dna"
extractiontype = vars(args)["extractiontype"]
else:
ac = vars(args)["ac"]
extractiontype = vars(args)["extractiontype"]
if vars(args)["no_hs"] or extractiontype == "n" or extractiontype == "s":
print ("without hit stitcher, contig stitching is disabled, option --is ignored")
run_hs = False
interstitch = False
else:
run_hs = True
interstitch = vars(args)["interstitch"]
if extractiontype == "n" and vars(args)["keep_strand"]:
keep_strand = True
else:
keep_strand = False
# if vars(args)["trans_out"]:
# if extractiontype == "s" or extractiontype == "a":
# if ac == "aa-aa" or ac == "tdna-aa":
# print ("should not attempt to translate AA sequence, option --translate ignored")
# trans_out = False
# else:
# trans_out = True
# else:
# print ("will only translate exact matches (options -x s or -x a), option --translate ignored")
# trans_out = False
# else:
# trans_out = False
trans_out = False
outM = vars(args)["outM"]
if vars(args)["targetf"] == None:
dry_run = True
noq = True
print ("option -q ignored")
else:
targetf = vars(args)["targetf"]
dry_run = False
if outM == "query":
if vars(args)["queryf"] == None:
noq = True
else:
queryf = vars(args)["queryf"]
noq = False
else:
noq = True
evalue = vars(args)["evalue"]
bitscore = vars(args)["bitscore"]
identity = vars(args)["identity"]
contignum = vars(args)["contignum"]
if contignum == 1 and outM == "query":
cname = vars(args)["cname"]
else:
cname = True
local_rec = vars(args)["local_rec"]
if vars(args)["rec_search"] == None:
rec_search = None
else:
rec_search = vars(args)["rec_search"]
if vars(args)["target_ref_file"] == None:
print ("please specify -R")
sys.exit()
else:
target_ref_file = vars(args)["target_ref_file"]
acr = vars(args)["acr"]
acR = vars(args)["acR"]
btR = vars(args)["btR"]
rmrecnf = vars(args)["rmrecnf"]
hit_ovlp = vars(args)["hit_ovlp"]
if hit_ovlp < 0:
print ("overlap value must be 0 or positive")
sys.exit()
ctg_ovlp = vars(args)["ctg_ovlp"]
if ctg_ovlp < 0:
print ("overlap value must be 0 or positive")
sys.exit()
recip_ovlp = vars(args)["recip_ovlp"]
if recip_ovlp < 0:
print ("overlap value must be 0 or positive")
sys.exit()
flanks = vars(args)["flanks"]
output_dir = vars(args)["output"]
logsuffix = vars(args)["logsuffix"]
if bt == "sam" or bt == "bam":
metric = [1,0,2]
else:
if vars(args)["metric"] == "e/b-i":
metric = "e/b-i"
else:
metric = [int(x) for x in vars(args)["metric"].replace("e","0").replace("b","1").replace("i","2").split("-")]
metricR = vars(args)["metricR"]
metricC = vars(args)["metricC"]
ref_hs = vars(args)["ref_hs"]
max_gap = vars(args)["max_gap"]
amlghitscore = vars(args)["amlghitscore"]
if vars(args)["bstrands"] == '1':
if trans_out or contignum == 1:
bstrands = True
else:
bstrands = False
else:
bstrands = False
srt = vars(args)["srt"]
dd = vars(args)["dd"]
loghead = vars(args)["loghead"]
syntcheck = vars(args)["syntcheck"]
namedelim = vars(args)["namedelim"]
if namedelim == "@":
print ("@ is reserved, please use other delimiter")
sys.exit()
elif len(namedelim) != 1:
print ("delimiter should be a single character")
sys.exit()
dashb = "#"*75
dash = "-"*50
warninglist = []
#function to display messages and write them into the debugfile
def messagefunc(msg, columns, f, fl=True):
if fl:
sys.stdout.write((" "*columns)+"\r")
sys.stdout.write(msg[:columns]+"\r")
sys.stdout.flush()
else:
sys.stdout.write((" "*columns)+"\r")
print (msg)
print (msg, file=f)
#function for creating an output folder. old stuff will be deleted
def mkdirfunc(dir1):
if not os.path.exists (dir1):
os.makedirs(dir1) #creating folder if necessary
else:
shutil.rmtree(dir1) #removing old files
os.makedirs(dir1)
#function for copying alignment files before changing them
#all alignments are copied regardless of whether they will be modified or not
def copyfunc(dir1, cols, debugfile):
messagefunc("copying files *.fa*", cols, debugfile, False)
copyfunc_c = 0
for x in glob.glob(queryf+"/*.fa*"):
locusfname = x.split("/")[-1]
if not os.path.exists (dir1+"/"+locusfname):
prog = "copying "+str(locusfname)+"..."
messagefunc(prog, cols, debugfile)
shutil.copy2(queryf+"/"+locusfname, dir1)
copyfunc_c += 1
messagefunc("copied "+str(copyfunc_c)+" files", cols, debugfile, False)
#function for parsing a blast output file
def readblastfilefunc(b, evalue1, bitscore1, identity1, as_target, ac3, recstats, cols, debugfile):
messagefunc("processing "+b, cols, debugfile, False)
returndict = {}
blastfile = open(b, "rU")
reader = csv.reader(blastfile, delimiter='\t')
linecounter = 0
ignorecount = 0
for row in reader:
if evalue1:
if float(row[10]) <= evalue1 and float(row[11]) >= bitscore1 and float(row[2]) >= identity1:
qname = row[0].split("/")[-1]
if qname[-4::] == ".fas":
qname = qname[:-4:]
tname = row[1]
if recstats:
init_queries.add(qname)
init_targets.add(tname)
if as_target:
#populate target table
if tname in returndict:
if qname in returndict[tname]:
returndict[tname][qname][linecounter] = rowfunc(row, ac3)
else:
returndict[tname][qname] = {linecounter: rowfunc(row, ac3)}
else:
returndict[tname] = {qname: {linecounter: rowfunc(row, ac3)}}
else:
#populate query table
if qname in returndict:
if tname in returndict[qname]:
returndict[qname][tname][linecounter] = rowfunc(row, ac3)
else:
returndict[qname][tname] = {linecounter: rowfunc(row, ac3)}
else:
returndict[qname] = {tname: {linecounter: rowfunc(row, ac3)}}
else:
ignorecount += 1
linecounter += 1
else:
qname = row[0].split("/")[-1]
if qname[-4::] == ".fas":
qname = qname[:-4:]
tname = row[1]
if as_target:
#populate target table
if tname in returndict:
if qname in returndict[tname]:
returndict[tname][qname][linecounter] = rowfunc(row, ac3)
else:
returndict[tname][qname] = {linecounter: rowfunc(row, ac3)}
else:
returndict[tname] = {qname: {linecounter: rowfunc(row, ac3)}}
else:
#populate query table
if qname in returndict:
if tname in returndict[qname]:
returndict[qname][tname][linecounter] = rowfunc(row, ac3)
else:
returndict[qname][tname] = {linecounter: rowfunc(row, ac3)}
else:
returndict[qname] = {tname: {linecounter: rowfunc(row, ac3)}}
linecounter += 1
blastfile.close()
return returndict, ignorecount
#function for the blast parser to return a list for dict like this:
#dict[query] = [target_f, target_r, target_b, query_f, query_r, query_b, eval, bitscore, identity]
#query - query name, target_f - target start pos, target_r - target end, target_b - forward or reverse target direction
#query_f - query start, query_r - query end, query_b - query direction
def rowfunc(row, aligntype):
if int(row[8]) < int(row[9]):
target_b = True
else:
target_b = False
if aligntype == "tdna-aa":
if target_b:
target_f = int(row[8])*3-2
target_r = int(row[9])*3
else:
target_f = int(row[8])*3
target_r = int(row[9])*3-2
else:
target_f = int(row[8])
target_r = int(row[9])
#check query
if int(row[6]) < int(row[7]):
query_b = True
else:
query_b = False
if aligntype == "aa-tdna":
if query_b:
query_f = int(row[6])*3-2
query_r = int(row[7])*3
else:
query_f = int(row[6])*3
query_r = int(row[7])*3-2
else:
query_f = int(row[6])
query_r = int(row[7])
return [target_f, target_r, target_b, query_f, query_r, query_b, float(row[10]), float(row[11]),float(row[2])]
#function for parsing hmmer output tables
def readhmmerfilefunc(b, evalue1, bitscore1, bt1, ac1, hmmerg1, cols, debugfile):
messagefunc("processing "+b, cols, debugfile, False)
targetdict = {}
hmmfile = open(b, "rU")
linecounter = 0
recordcounter = 0
ignorecount = 0
if bt1 == "hmmer18":
qname1 = 2
tname1 = 0
eval1 = 4
bit1 = 5
elif bt1 == "hmmer15":
qname1 = 2
query1 = 4
query2 = 5
tname1 = 0
target1 = 6
target2 = 7
eval1 = 12
bit1 = 13
elif bt1 == "hmmer22":
qname1 = 3
query1 = 15
query2 = 16
tname1 = 0
target1 = 17
target2 = 18
eval1 = 12
bit1 = 13
for row in hmmfile:
if row[0] != "#":
line = row.strip().split()
if float(line[eval1]) <= evalue1 and float(line[bit1]) >= bitscore1:
qname = line[qname1]
if ac1 == "aa-tdna":
tname = "_".join(line[tname1].split("_")[:-1])
strand = line[tname1].split("_")[-1][0]
frame = int(line[tname1].split("_")[-1][1])
ctg_length = int(line[tname1].split("_")[-1][3:])
else:
tname = line[tname1]
init_queries.add(qname)
init_targets.add(tname)
if bt1 != "hmmer18":
if int(line[target1]) < int(line[target2]):
target_b = True
else:
target_b = False
if int(line[query1]) < int(line[query2]):
query_b = True
else:
query_b = False
target_f = int(line[target1])
target_r = int(line[target2])
query_f = int(line[query1])
query_r = int(line[query2])
else:
target_f = 0
target_r = 1
target_b = True
query_f = 0
query_r = 1
query_b = True
#no identity is reported, so it is set to 0.0 and does not interfere with scoring system
if ac1 == "aa-tdna":
query_f = int(line[query1])*3-2
query_r = int(line[query2])*3
if strand == "f":
target_b = True
else:
target_b = False
if target_b:
target_f = int(line[target1])*3-2+frame
target_r = int(line[target2])*3+frame
if target_r > ctg_length:
target_r = ctg_length
else:
target_f = ctg_length-int(line[target1])*3+frame
if target_f < 0:
target_f = 0
target_r = ctg_length-int(line[target2])*3-2+frame
if bt1 == "hmmer22" and hmmerg1:
outrow = [target_f, target_r, target_b, query_f, query_r, query_b, float(line[6]), float(line[7]), 0.0]
else:
outrow = [target_f, target_r, target_b, query_f, query_r, query_b, float(line[eval1]), float(line[bit1]), 0.0]
#populate target table
if tname in targetdict:
if qname in targetdict[tname]:
targetdict[tname][qname][linecounter] = outrow
else:
targetdict[tname][qname] = {linecounter: outrow}
else:
targetdict[tname] = {qname: {linecounter: outrow}}
else:
ignorecount += 1
linecounter += 1
hmmfile.close()
return targetdict, ignorecount
#function for parsing a bed file (bait regions)
def readbedfilefunc(b, cols, debugfile):
messagefunc("processing "+b, cols, debugfile, False)
returndict = {}
bedfile = open(b, "rU")
reader = csv.reader(bedfile, delimiter='\t')
linecounter = 0
for row in reader:
qname = row[3] # name field of BED
tname = row[0] # chrom field of BED
target_f = int(row[1]) # chromStart field of BED
target_r = int(row[2]) # chromEnd field of BED
query_f = 1
query_r = (target_r - target_f)+1
query_b = True
#score field is ignored
if row[5] == "+":
target_b = True
else:
target_b = False
returndict[qname] = {tname : {linecounter : [target_f, target_r, target_b, query_f, query_r, query_b, 0, 1, 100.0]}}
print (returndict, file = debugfile)
bedfile.close()
return returndict
#function for parsing a lastz output file
def readlastzfilefunc(b, bitscore1, identity1, as_target, recstats, cols, debugfile):
messagefunc("processing "+b, cols, debugfile, False)
returndict = {}
lastzfile = open(b, "rU")
reader = csv.reader(lastzfile, delimiter='\t')
linecounter = 0
ignorecount = 0
for row in reader:
if float(row[0]) >= bitscore1 and float(row[14]) >= identity1:
qname = row[6].split("/")[-1]
if qname[-4::] == ".fas":
qname = qname[:-4:]
tname = row[1]
if recstats:
init_queries.add(qname)
init_targets.add(tname)
if as_target:
#populate target table
if tname in returndict:
if qname in returndict[tname]:
returndict[tname][qname][linecounter] = rowfunclastz(row)
else:
returndict[tname][qname] = {linecounter: rowfunclastz(row)}
else:
returndict[tname] = {qname: {linecounter: rowfunclastz(row)}}
else:
#populate query table
if qname in returndict:
if tname in returndict[qname]:
returndict[qname][tname][linecounter] = rowfunclastz(row)
else:
returndict[qname][tname] = {linecounter: rowfunclastz(row)}
else:
returndict[qname] = {tname: {linecounter: rowfunclastz(row)}}
else:
ignorecount += 1
linecounter += 1
lastzfile.close()
return returndict, ignorecount
#row function for lastz parser
def rowfunclastz(row):
target_f = int(row[3])+1
target_r = int(row[4])
if row[2] == "+":
target_b = True
else:
target_b = False
query_f = int(row[8])+1
query_r = int(row[9])
if row[7] == "+":
query_b = True
else:
query_b = False
return [target_f, target_r, target_b, query_f, query_r, query_b, 0, float(row[0]), float(row[14])]
#function for parsing SAM / BAM formats
def readsamformat(b, isbinary, bitscore1, samscore1, cols, debugfile):
if isbinary:
rmode = 'rb'
else:
rmode = 'r'
messagefunc("processing "+b, cols, debugfile, False)
returndict = {}
linecounter = 0
ignorecount = 0
samfile = pysam.AlignmentFile(b, rmode)
for read in samfile.fetch():
if read.is_unmapped is False:
qname = read.query_name.split(" ")[0]
tname = read.reference_name.split(" ")[0]
query_b = not read.is_reverse
query_f = read.query_alignment_start+1
query_r = read.query_alignment_end
target_f = read.reference_start+1
target_r = read.reference_end
cigar_stats = read.get_cigar_stats()
if cigar_stats[0][7] > 0:
ident = float(cigar_stats[0][7]) / (cigar_stats[0][7]+cigar_stats[0][8])*100
else:
ident = 100.0
if samscore1 == "MAPQ":
quality = read.mapping_quality
else:
tags = dict(read.get_tags())
if samscore1 in tags:
quality = tags[samscore1]
else:
messagefunc("SAM / BAM quality metric specified is not found", cols, debugfile, False)
sys.exit()
rowval = [target_f, target_r, True, query_f, query_r, query_b, 0, float(quality), ident]
if tname in returndict:
if qname in returndict[tname]:
returndict[tname][qname][linecounter] = rowval
else:
returndict[tname][qname] = {linecounter: rowval}
else:
returndict[tname] = {qname: {linecounter: rowval}}
else:
ignorecount += 1
linecounter += 1
samfile.close()
return returndict, ignorecount
#first main function
def target_processor(inpdict, local_rec, metric, metricR, hit_overlap, recip_overlap, ac1, run_hs1, max_gap1, amlghitscore, metricC,bstrands1, filtration_table1, cols, debugfile):
messagefunc(dashb, cols, debugfile)
messagefunc("running target processor...", cols, debugfile)
outdict = {}
filtration_table1["synteny"] = 0
filtration_table1["actual"] = 0
filtration_table1["range"] = 0
for targetkey, targetval in inpdict.items():
messagefunc(dash, cols, debugfile)
messagefunc("target processor on hit "+targetkey, cols, debugfile)
#run local actual reciprocal check (check each hit of target only matches one query)
if local_rec == "actual":
if len(targetval) > 1 or len(list(targetval[x] for x in targetval)[0]) > 1:
messagefunc("running actual (per HSP) reciprocity check", cols, debugfile)
targetval = actual_reciprocator(targetval,recip_overlap, bstrands1, filtration_table1, metric, metricR)
else:
messagefunc("only one HSP for this hit, no reciprocity check", cols, debugfile)
#run hit overlapper and stitcher
messagefunc("running hit processor", cols, debugfile)
if run_hs1:
tgt_proc_out = hit_stitcher(targetval, metric, metricR, hit_overlap, ac1, max_gap1, amlghitscore, metricC, filtration_table1, cols, debugfile) #stitched subcontigs per query
else:
tgt_proc_out = reformat_hits(targetval, metric, metricR, cols, debugfile)
#run local range reciprocal check
if local_rec == "range":
if len(tgt_proc_out) > 1:
messagefunc("running range reciprocity check", cols, debugfile)
tgt_proc_out = range_reciprocator(targetkey, tgt_proc_out, metric, metricR, recip_overlap, bstrands1, filtration_table1, cols, debugfile) #check that each subcontig matches only 1 Q
else:
messagefunc("only one query for this hit, no reciprocity check", cols, debugfile)
outdict[targetkey] = tgt_proc_out
return outdict
#function to split hits by 'relative' strand (same vs opposite)
#input is dictionary {linecounter: [target_f, target_r, target_b, query_f, query_r, query_b, float(row[10]), float(row[11]),float(row[2])]}
#return list of dictionaries
def strand_selector(inpdict):
#split into things per direction
clusterF = {}
clusterR = {}
for hitkey, hitval in inpdict.items():
if hitval[2] == hitval[5]:
clusterF[hitkey] = hitval
else:
clusterR[hitkey] = hitval
return [clusterF, clusterR]
#function to check that each target hit region matches to only one query
def actual_reciprocator(inpdict, recip_overlap, bstrands2, filtration_table2, metric, metricR):
returndict = inpdict
blacklisted = set()
for refquerykey, refqueryval in inpdict.items():
#hits with same target and query - check per strand
clusters = strand_selector(refqueryval)
cluster_scoring = []
for cluster in clusters:
for refhit in list(x for x in refqueryval):
refhit_t_range = refqueryval[refhit][0:2]
refhit_score = refqueryval[refhit][6:9]
for testhit in list(x for x in cluster):
if testhit != refhit and (refquerykey, testhit) not in blacklisted:
testhit_t_range = refqueryval[testhit][0:2]
testhit_score = refqueryval[testhit][6:9]
if getOverlap(refhit_t_range, testhit_t_range, recip_overlap) > recip_overlap:
comp1 = compare_scores(refhit_t_range, refhit_score, testhit_t_range, testhit_score, metric, metricR)
if comp1 == 0:
blacklisted.add((refquerykey, testhit))
strand_best_hit = []
for hitkey, hitval in cluster.items():
if (refquerykey, hitkey) not in blacklisted:
if len(strand_best_hit) == 0:
strand_best_hit = hitval
else:
comp1 = compare_scores(strand_best_hit[0:2], strand_best_hit[6:9], hitval[0:2], hitval[6:9], metric, metricR)
if comp1 == 1:
strand_best_hit = hitval
cluster_scoring.append(strand_best_hit)
if not bstrands2 and len(cluster_scoring[0]) > 0 and len(cluster_scoring[1]) > 0:
comp2 = compare_scores(cluster_scoring[0][0:2], cluster_scoring[0][6:9], cluster_scoring[1][0:2], cluster_scoring[1][6:9], metric, metricR)
if comp2 == 1:
for hitkey in clusters[0]:
blacklisted.add((refquerykey, hitkey))
else:
for hitkey in clusters[1]:
blacklisted.add((refquerykey, hitkey))
#hits with same target but different queries - check against all strands
for refhit in list(x for x in refqueryval):
if (refquerykey, refhit) not in blacklisted:
for testquerykey, testqueryval in inpdict.items():
if testquerykey != refquerykey:
for testhit in list(x for x in testqueryval):
if testhit != refhit and (testquerykey, testhit) not in blacklisted:
testhit_t_range = testqueryval[testhit][0:2]
testhit_score = testqueryval[testhit][6:9]
if getOverlap(refhit_t_range, testhit_t_range, recip_overlap) > recip_overlap:
comp1 = compare_scores(refhit_t_range, refhit_score, testhit_t_range, testhit_score, metric, metricR)
if comp1 == 0:
blacklisted.add((testquerykey, testhit))
messagefunc("filtered out HSPs: "+str(len(blacklisted))+", listed below:", cols, debugfile)
for bad_element in blacklisted:
print (bad_element[0],returndict[bad_element[0]][bad_element[1]], file = debugfile)
del returndict[bad_element[0]][bad_element[1]]
filtration_table2["actual"] += len(blacklisted)
return returndict
#function to reformat the hit tables in case hit stitcher is not run
def reformat_hits(inpdict, metric, metricR, cols, debugfile):
returnlist = {} #all queries for the target go here
for querykey, queryval in inpdict.items():
clusters = strand_selector(queryval)
directions = [True, False]
best_index1 = None
best_dir1 = None
best_range1 = None
best_score1 = None
best_data1 = None
for cluster_index in range(2):
direct = directions[cluster_index]
hits1 = list(clusters[cluster_index][x] for x in clusters[cluster_index])
for hit_index in range(len(hits1)):
if best_index1 == None:
best_index1 = hit_index
best_dir1 = [direct]
best_range1 = [min(hits1[hit_index][0:2]),max(hits1[hit_index][0:2]),min(hits1[hit_index][3:5]),max(hits1[hit_index][3:5])]
best_score1 = hits1[hit_index][6:9]
best_data1 = best_range1+best_score1
else:
hit_scores = hits1[hit_index][6:9]
hit_ranges = [min(hits1[hit_index][0:2]),max(hits1[hit_index][0:2]), min(hits1[hit_index][3:5]), max(hits1[hit_index][3:5])]
hit_data = hit_ranges+hit_scores
comp1 = compare_scores(best_range1, best_score1, hit_ranges, hit_scores, metric, metricR)
if comp1 == 1:
best_index1 = hit_index
best_dir1 = [direct]
best_range1 = [min(hits1[hit_index][0:2]),max(hits1[hit_index][0:2]), min(hits1[hit_index][3:5]), max(hits1[hit_index][3:5])]
best_score1 = hits1[hit_index][6:9]
best_data1 = best_range1+best_score1
returnlist[indexer_function(querykey,str(0))] = [best_dir1, best_score1, best_range1, best_data1]
print (querykey, ", selected best hit:", returnlist[indexer_function(querykey,str(0))], file = debugfile)
return returnlist
#function to split hits by 'absolute' strand
def trans_selector(inpdict):
#split into things per direction
cluster1 = {}
cluster2 = {}
for hitkey, hitval in inpdict.items():
if hitval[2] == True:
cluster1[hitkey] = hitval
else:
cluster2[hitkey] = hitval
return [cluster1, cluster2]
#function to process hit of the same target (remove redundant, order and stitch hits, make subcontigs)
def hit_stitcher(inpdict, metric, metricR, hit_overlap, ac2, max_gap2, amlghitscore, metricC, filtration_table2, cols, debugfile):
returnlist = {} #all queries for the target go here
for querykey, queryval in inpdict.items():
clusters = strand_selector(queryval)
directions = [True, False]
stitched_subcontigs = [] #stitched subcontigs for a query go here
for cluster_index in range(2):
direct = directions[cluster_index]
#add condition for no hits?
if len(clusters[cluster_index]) > 1:
messagefunc("running hit overlapper...", cols, debugfile)
#this is a hitlist {hit index: [hit val]}
hitdict = clusters[cluster_index]
messagefunc("direction: "+str(direct)+", number of HSPs: "+str(len(clusters[cluster_index])), cols, debugfile)
subcontigs = []
if ac2 == "tdna-aa" or ac2 == "tdna-tdna" or ac2 == "aa-tdna":
hitdicts = trans_selector(hitdict)
else:
hitdicts = [hitdict]
for trans_dict in hitdicts:
startpoints = {}
endpoints = {}
for hitkey, hitval in trans_dict.items():
startpoints[hitkey] = min(hitval[3], hitval[4])
endpoints[hitkey] = max(hitval[3], hitval[4])
sorted_startpoints = sorted(startpoints, key=lambda x: startpoints[x])
sorted_endpoints = sorted(endpoints, key=lambda x: endpoints[x])
currently_processing = []
ovlp_processed = []
cur_number = 0
for i in range(len(sorted_startpoints)):
if i == 0:
currently_processing.append(trans_dict[sorted_startpoints[i]])
ovlp_processed.append([])
else:
maxtovlp = []
maxqovlp = []
maxqovlpD = []
combovlp = []
for cp in range(len(currently_processing)):
tovlp = getOverlap(trans_dict[sorted_startpoints[i]][0:2],currently_processing[cp][0:2], 1)
qovlp = getOverlap(trans_dict[sorted_startpoints[i]][3:5],currently_processing[cp][3:5], 1)
qovlpD = getOverlap(trans_dict[sorted_startpoints[i]][3:5],currently_processing[cp][3:5], hit_overlap)
maxtovlp.append(tovlp)
maxqovlp.append(qovlp)
maxqovlpD.append(qovlpD)
combovlp.append(tovlp+qovlp)
best_ind = combovlp.index(max(combovlp))
#if closest hit overlaps on query
if maxqovlpD[best_ind] > hit_overlap:
#if also overlaps on target - extend proper layer
if maxtovlp[best_ind] > 0:
if ac2 == "tdna-aa" or ac2 == "tdna-tdna" or ac2 == "aa-tdna":
if maxqovlp[best_ind] % 3 == 0:
currently_processing[best_ind] = extend_hit(currently_processing[best_ind], trans_dict[sorted_startpoints[i]])
else:
comp0 = compare_scores(currently_processing[best_ind][0:2],currently_processing[best_ind][6:9], trans_dict[sorted_startpoints[i]][0:2],trans_dict[sorted_startpoints[i]][6:9], metric, metricR)
#if current is better, do nothing, else replace current with i
if comp0 == 1:
currently_processing[best_ind] = trans_dict[sorted_startpoints[i]]
else:
currently_processing[best_ind] = extend_hit(currently_processing[best_ind], trans_dict[sorted_startpoints[i]])
#else overlaps on query but not target - add separate layer, keep current in the current layer
else:
currently_processing.append(trans_dict[sorted_startpoints[i]])
ovlp_processed.append([])
#if non overlapping on query - add current to the layer, make it the new current
else:
#first check synteny and gap
if synteny_check(currently_processing[best_ind], trans_dict[sorted_startpoints[i]], direct, max_gap2, cols, debugfile):
ovlp_processed[best_ind].append(currently_processing[best_ind])
currently_processing[best_ind] = trans_dict[sorted_startpoints[i]]
#otherwise, add as separate layer
else:
currently_processing.append(trans_dict[sorted_startpoints[i]])
ovlp_processed.append([])
filtration_table2["synteny"] += 1
#finalize current
for cp in range(len(currently_processing)):
ovlp_processed[cp].append(currently_processing[cp])
for sbctg in ovlp_processed:
subcontigs.append(sbctg)
messagefunc(str(len(subcontigs))+" pseudocontigs survived", cols, debugfile)
#this part will stitch hits of subcontigs
messagefunc("running hit stitcher...", cols, debugfile)
for sbctg in subcontigs:
stitched_subcontig = join_chunks(sbctg, direct, amlghitscore, metricC)
stitched_subcontigs.append(stitched_subcontig)
#if only one hit
if len(clusters[cluster_index]) == 1:
sbctg = list(clusters[cluster_index][x] for x in clusters[cluster_index])
stitched_subcontig = join_chunks(sbctg, direct, amlghitscore, metricC)
stitched_subcontigs.append(stitched_subcontig)
for subcont_index in range(len(stitched_subcontigs)):
returnlist[indexer_function(querykey,str(subcont_index))] = stitched_subcontigs[subcont_index]
return returnlist
#checks syntheny and gap between hits
def synteny_check(item1, item2, direct1, max_gap3, cols1, debugfile1):
cond = True
item1medT = median([item1[0],item1[1]])
item1medQ = median([item1[3],item1[4]])
item2medT = median([item2[0],item2[1]])
item2medQ = median([item2[3],item2[4]])
deltaT = item2medT - item1medT
deltaQ = item2medQ - item1medQ
if syntcheck:
if direct1:
if deltaQ > 0 and deltaT < 0:
cond = False
elif deltaQ < 0 and deltaT > 0:
cond = False
else:
if deltaQ > 0 and deltaT > 0:
cond = False
elif deltaQ < 0 and deltaT < 0:
cond = False
if not cond:
messagefunc("synteny check: direction "+str(direct1)+", dQ "+str(deltaQ)+", dT "+str(deltaT), cols1, debugfile1)
if max_gap3 > 0:
if abs(deltaT) > max_gap3 or abs(deltaQ) > max_gap3:
cond = False
messagefunc("gap check: direction "+str(direct1)+", min dQ "+str(deltaQ)+", min dT "+str(deltaT), cols1, debugfile1)
return cond
#join chunks in correct order
#all coordinates are returned in forward orientation, direction maintained by [direct]
def join_chunks(sbctg1, direct1, amlghitscore1, metricC1):
median_query = {}
start_query = {}
end_query = {}
start_target = {}
end_target = {}
eval_hit = {}
bit_hit = {}
ident_hit = {}
scores_sbctg1 = []
for chunk in range(len(sbctg1)):
median_query[chunk] = median([sbctg1[chunk][3],sbctg1[chunk][4]])
start_query[chunk] = min(sbctg1[chunk][3],sbctg1[chunk][4])
end_query[chunk] = max(sbctg1[chunk][3],sbctg1[chunk][4])
start_target[chunk] = min(sbctg1[chunk][0],sbctg1[chunk][1])
end_target[chunk] = max(sbctg1[chunk][0],sbctg1[chunk][1])
eval_hit[chunk] = sbctg1[chunk][6]
bit_hit[chunk] = sbctg1[chunk][7]
ident_hit[chunk] = sbctg1[chunk][8]
if chunk == 0:
scores_sbctg1 = [eval_hit[chunk], bit_hit[chunk], ident_hit[chunk]]
else:
if amlghitscore1:
scores_sbctg1 = amalgamate_scores(scores_sbctg1, [eval_hit[chunk], bit_hit[chunk], ident_hit[chunk]], metricC1)
else:
scores_sbctg1 = [min(scores_sbctg1[0], eval_hit[chunk]), max(scores_sbctg1[1], bit_hit[chunk]), max(scores_sbctg1[2], ident_hit[chunk])]
#ranges
start_target_subctg = min(list(start_target[x] for x in start_target))
end_target_subctg = max(list(end_target[x] for x in end_target))
start_query_subctg = min(list(start_query[x] for x in start_query))
end_query_subctg = max(list(end_query[x] for x in end_query))
gapstart = 0
# stitched_subcontigs = [[direct],[scores],[ranges],[hits: [range, score], gap, [range, score], gap ...]]
stitched_sbctg1 = []
stitched_sbctg1.append([direct1]) #add direction
stitched_sbctg1.append(scores_sbctg1) #add scores
stitched_sbctg1.append([start_target_subctg, end_target_subctg, start_query_subctg, end_query_subctg]) #add ranges
#add per hit information
stitched_hits = []
for key in sorted(median_query, key=lambda x: median_query[x]):
if gapstart > 0:
stitched_hits.append(start_query[key]-1-gapstart)
stitched_hits.append([start_target[key], end_target[key], start_query[key], end_query[key], eval_hit[key], bit_hit[key], ident_hit[key]])
gapstart = end_query[key]
stitched_sbctg1.append(stitched_hits)
return stitched_sbctg1
#function to join contigs in correct order
def join_contigs(inplist):
median_query = {}
start_query = {}
end_query = {}
target_dict = {}
for target in inplist:
median_query[target[0]] = median([min(target[1][2][2],target[1][2][3]),max(target[1][2][2],target[1][2][3])])
start_query[target[0]] = min(target[1][2][2],target[1][2][3])
end_query[target[0]] = max(target[1][2][2],target[1][2][3])
target_dict[target[0]] = target[1]
gapstart = 0
returnlist = []
start_query_superctg = min(list(start_query[x] for x in start_query))
end_query_superctg = max(list(end_query[x] for x in end_query))
for key in sorted(median_query, key=lambda x: median_query[x]):
if gapstart > 0:
returnlist.append(start_query[key]-1-gapstart)
returnlist.append([key,target_dict[key]])
gapstart = end_query[key]
return [start_query_superctg, end_query_superctg], returnlist
#function to merge overlapping hits. resulting hit gets highest score
def extend_hit(item1, item2):
outlist = []
scores = (min(item1[6], item2[6]), max(item1[7], item2[7]), max(item1[8], item2[8]))
#using item1 as benchmark for resulting direction
direction1 = item1[2]
direction2 = item1[5]
#if ref item is True
if direction1:
outlist.append(min(item1[0], item2[0],item1[1], item2[1])) #min coord first
outlist.append(max(item1[0], item2[0],item1[1], item2[1])) #max coord second
else:
outlist.append(max(item1[0], item2[0],item1[1], item2[1])) #max coord first
outlist.append(min(item1[0], item2[0],item1[1], item2[1])) #min coord second
outlist.append(direction1)
#if query is true
if direction2:
outlist.append(min(item1[3], item1[4], item2[3], item2[4])) #min coord first
outlist.append(max(item1[3], item1[4], item2[3], item2[4])) #max coord second
else:
outlist.append(max(item1[3], item1[4], item2[3], item2[4])) #max coord first
outlist.append(min(item1[3], item1[4], item2[3], item2[4])) #min coord second
outlist.append(direction2)
for score in scores:
outlist.append(score)
return outlist
#function to combine scores (used for hit (only if --amalgamate-hits) and contig (always) stitching)
def amalgamate_scores(item1, item2, metricC):
neweval = item1[0] * item2[0] #probability product
if neweval != 0.0:
(sign, digits, exponent) = Decimal(neweval).as_tuple()
neweval = 1*(10**int(round((exponent+len(digits))*metricC)))
newbit = (item1[1] + item2[1])*metricC #sum of bits
newident = (item1[2] + item2[2]) / 2 #average of identities
return [neweval, newbit, newident]
#function to compare scores of two items, takes ranges and scores
#return 0 if first is better
#return 1 if second is better
#return 2 if they are equal
#metric [0,1,2] or [2,1,0] or "e/b-i"
def compare_scores(item1ranges, item1scores, item2ranges, item2scores, metric, metricR):
len1 = float(max(item1ranges[0], item1ranges[1]) - min(item1ranges[0], item1ranges[1]))
len2 = float(max(item2ranges[0], item2ranges[1]) - min(item2ranges[0], item2ranges[1]))
if metricR:
eval1 = item1scores[0] / len1
bit1 = item1scores[1] / len1
ident1 = item1scores[2] / len1
eval2 = item2scores[0] / len2
bit2 = item2scores[1] / len2
ident2 = item2scores[2] / len2
else:
eval1 = item1scores[0]
bit1 = item1scores[1]
ident1 = item1scores[2]
eval2 = item2scores[0]
bit2 = item2scores[1]
ident2 = item2scores[2]
metricL = [[eval1,eval2],[bit1,bit2],[ident1,ident2]]