forked from xiezhq/ISEScan
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpred.py
executable file
·2777 lines (2514 loc) · 109 KB
/
pred.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 sys
import argparse
import operator
import time
import random
import os
import datetime
import itertools
import math
import concurrent.futures
import tempfile
# required by clusterIntersect()
import scipy.spatial.distance
import numpy, fastcluster
import scipy.cluster.hierarchy
import tools
import is_analysis
import constants
# cutoff for boundary window when searching for the optimal consensus boundaries of the multi-copy IS element
# boundary window: (boundary-cutoff, boundary+cutoff)
# In our calculations, we require boundary-cutoff >= 1.
#CUTOFF4WINDOW = 0
#CUTOFF4WINDOW = 1
CUTOFF4WINDOW = 3
# re-rank hmmsearch hits by 4 (full sequence E-value, default ranking of hmmsearch results) or 0 (best 1 domain E-value)
SORT_BY = 4
# process_tblout(tblout):
# > Sort hits by ov, best 1 domain E-value and full sequence E-value
# > Remove unsatisfying hits based on ov, best 1 domain E-value and full sequence E-value
#
# Return hits
#
# hits: [hit, ...]
# hit: [best1domainEvalue, line, compoundID, queryName, best1domainEvalue, overlapNumber]
# best1domainEvalue: float, evalue for best 1 domain, refer to hmmsearch manual for details
# line: whole line ending with '\n' in hmmhitsFile created by hmmsearch
# compoundID: the first string ending with space character in protein sequence (.faa) file
# created by FragGeneScan, e.g. 'gi|256374160|ref|NC_013093.1|_6781872_6782144_-',
# 'SRS078176_LANL_scaffold_27612_1219_2391_-', 'C2308936_1_1062_-'
# queryName: name of HMM model in profile HMM model file created by hmmsearch or phmmer,
# e.g. 'IS200_IS605_0.faa', 'IS200/IS605_1|IS200/IS605|IS1341|ISBLO15|'
# overlap: integer, overlap number, how many of envelopes overlap other envelopes;
# be careful when ov > 0refer to hmmsearch manual for details
#
def process_tblout(tblout):
hits = []
fp_tblout = open(tblout, 'r')
for line in fp_tblout:
if line[0] == '#':
continue
item = line.split(None, 14)
# item[0]: string, compound ID, for example, 'gi|256374160|ref|NC_013093.1|_6781872_6782144_-',
# 'SRS078176_LANL_scaffold_27612_1219_2391_-', 'C2308936_1_1062_-'
# item[2]: query name, name of query sequence or profile (IS cluster name), for example,
# 'IS200_IS605_0.faa', 'IS200/IS605_1|IS200/IS605|IS1341|ISBLO15|'
# item[4]: full sequence E-value
# item[7]: best 1 domain E-value
# item[13]: overlap number, how many of envelopes overlap other envelopes;
# be careful when ov > 0
# remove short ORF with length < length of shortest peptide
'''
if '.faa' in item[2]:
familyCluster = item[2].rsplit('.faa', maxsplit=1)[0]
elif '|' in item[2]:
familyCluster = item[2].split('|', maxsplit=1)[0]
else:
e = 'Error, unknown query name in output of Hmmer (hmmsearch/phmmer) in '.format(tblout)
raise RuntimeError(e)
familyCluster = familyCluster.replace('IS200_IS605', 'IS200/IS605')
family, cluster = familyCluster.split('_', maxsplit=1)
minLen4orf4pep = constants.minMax4tpase[family][2]
orfbd = [int(x) for x in item[0].rsplit('_',3)[-3:-1]]
if orfbd[1] - orfbd[0] + 1 < minLen4orf4pep:
continue
'''
#
#hits.append((float(item[7]), line, item[0], item[2].replace('IS200_IS605', 'IS200/IS605'), float(item[4]), int(item[13])))
#
# FORCE PIPELINE TO PREDICT IS BASED ON BEST 1 DOMAIN e-VALUE.
#
hits.append((float(item[7]), line, item[0], item[2].replace('IS200_IS605', 'IS200/IS605'), float(item[7]), int(item[13])))
#
# hits: [hit, ...]
# hit: [best1domainEvalue, line, compoundID, queryName, best1domainEvalue, overlapNumber]
# best1domainEvalue: float, evalue for best 1 domain, refer to hmmsearch manual for details
# line: whole line ending with '\n' in hmmhitsFile created by hmmsearch or phmmer
# compoundID: the first string ending with space character in protein sequence (.faa) file
# created by FragGeneScan, e.g. 'gi|256374160|ref|NC_013093.1|_6781872_6782144_-',
# 'C2308936_1_1062_-', 'SRS078176_LANL_scaffold_9132_3106_4113_+'
# queryName: name of HMM model in profile HMM model file created by hmmsearch or phmmer,
# e.g. 'IS200_IS605_0.faa', 'IS200/IS605_1|IS200/IS605|IS1341|ISBLO15|'
# overlap: integer, overlap number, how many of envelopes overlap other envelopes;
# be careful when ov > 0refer to hmmsearch manual for details
fp_tblout.close()
return hits
'''
# Sort hits
# If sorted type is changed here, please change e_value_type in
# refine_hmm_hits_evalue(tblout_hits_sorted, e_value) immediately
#
# 5 , 0 and 4 correspond to overlap number, best 1 domain E-value and full sequence E-value, respectively
if SORT_BY == 0:
hits_sorted = sorted(hits, key = operator.itemgetter(0))
elif SORT_BY == 4:
# hmmsearch report hits ranked by full sequence E-value for each HMM model.
# We rank hits from all HMM modles in one hmmsearch report file in one sorting.
# Note: mutliple family HMM models exist in each tbl_out file, see any tbl_out file
# refer to ftp://selab.janelia.org/pub/software/hmmer3/3.1b2/Userguide.pdf
hits_sorted = sorted(hits, key = operator.itemgetter(4))
# Do not sort hits, namely, keeping the ranking (by full sequence E-value) reported by hmmsearch
# Note: each HMM model hits have their own ranking in the same tbl_out report file.
#hits_sorted = hits
# hits_sorted: [hit, ..., hit]
# hit[0]: float, best 1 domain E-value
# hit[1]: string, whole line
# hit[2]: string, compound ID, for example, 'gi|256374160|ref|NC_013093.1|_6781872_6782144_-',
# 'C2308936_1_1062_-', 'SRS078176_LANL_scaffold_9132_3106_4113_+'
# hit[3]: string, IS family name
# hit[4]: float, full sequence E-value
# hit[5]: int, overlap number, how many of envelopes overlap other envelopes; be careful when ov > 0
#accid = hits_sorted[0][2].rsplit('|', 2)[-2]
#seqid = hits_sorted[0][2].rsplit('_', 3)[0]
seqids = set()
# seqids: {}, set of sequence identifiers in a dnaFile with multiple sequences included
for hit in hits_sorted:
seqid = hits_sorted[0][2].rsplit('_', 3)[0]
seqids.add(seqid)
return (seqids, hits_sorted)
'''
# refine_hmm_hits() removes the redundant hits (same genome location hitted by different family HMM models)
# and keeps only the best one (sorted by ov and E-values)
# among the hits mapped to the same genome coordinate pair.
# In our hmmsearch results,
# each hit is from a different profile HMM search against the same protein database,
# where each IS family HMM model was used once to search the same protein database.
# Note: two hits are identical or redundant if their coordinates with ignoring strand
# in genome DNA are same. This idea is to coordinate with the definition of IS elements
# where IS element is a genome DNA segment without dependence to the specific DNA strand.
#
# mtblout_hits_sorted: a sorted hits list
def refine_hmm_hits(tblout_hits_sorted):
hits_refined = []
coord_key = []
for hit in tblout_hits_sorted:
# hit[2]: string, compound ID,
# for example, 'gi|15896971|ref|NC_002754.1|_1734599_1736514_+', 'ref|U00096.3|_3720680_3722049_+'
# coord: '_1734599_1736514_+', '_3720680_3722049_+'
#
#coord = (hit[2].rsplit('|', 1))[-1]
coord = (hit[2].rsplit('_', 3))[1:]
# remove strand identifier from IS element candidate
# coord: '_1734599_1736514_', '_3720680_3722049_'
#coord = coord[:-1]
coord = '_'.join(coord[:-1])
if coord not in coord_key:
hits_refined.append(hit)
coord_key.append(coord)
return hits_refined
# Filter hits by the specified E-value cutoff
# mtblout_hits_sorted: a sorted hits list
def refine_hmm_hits_evalue(tblout_hits_sorted, e_value):
# e_value_type: 0 for best_domain_value, 4 for full_sequence_value
e_value_type = SORT_BY
# Option1:
# 1) Keeping hits with either best_domain_value or full_sequence_value <= e_value
if not (tblout_hits_sorted[-1][e_value_type] > e_value):
#
# Option2:
# 1) Keeping hits with both best_domain_value and full_sequence_value <= e_value
# stringent cutoff: hit must be significant with best_domain_value and full_sequence_value
#if not (tblout_hits_sorted[-1][0] > e_value) and not (tblout_hits_sorted[-1][4] > e_value):
#
return tblout_hits_sorted
for i, hit in enumerate(tblout_hits_sorted):
# Option1:
# 1) Keeping hits with either best_domain_value or full_sequence_value <= e_value
if hit[e_value_type] > e_value:
#
# Option2:
# 1) Keeping hits with both best_domain_value and full_sequence_value <= e_value
# stringent cutoff: hit must be significant with best_domain_value and full_sequence_value
#if hit[0] > e_value or hit[4] > e_value:
#
return tblout_hits_sorted[:i]
# remove redundant IS elements with same boundary and same TIR
# The redundant IS elements may be produced by two neighboring ORFs extending to the same TIR boundary.
# For example, ('NC_000913.3', 4518418, 4519014, '+') and ('NC_000913.3', 4519015, 4519224, '+') will
# be extended to the same TIR boundary:
# (45, 22, 25, 0, 4518470, 4518494, 4519217, 4519241, 'TCGGTAATGCTGCCAACTTACTGAT', 'TCGGTAATGACTCCAACTTACTGAT').
# mhits: {seqid: hits, ..., seqid: hits}
# hits: [hit, ..., hit]
# hit: {'orf': orf, 'tirs': tirs, 'hmmhit': hmmhit, 'bd': bd}
# orf: (seqid, begin, end, strand)
# tirs: [tir, ..., tir]
# tir: (score, irId, irLen, nGaps, start1, end1, start2, end2, seq1, seq2)
# hmmhit: (familyName, best_1_domain_E-value, full_sequence_E-value, ncopy4tpase, raworfhits)
# bd: [start, end], boundary of hit (IS element)
#
def removeRedundantIS(mhits):
# hmmhit: (familyName, best_1_domain_E-value, full_sequence_E-value, overlap_number)
if SORT_BY == 4:
sortby = 2
else:
sortby = 1
mhitsNew = {}
for accid, hits in mhits.items():
hitsNew = []
sortedHits = sorted(hits, key=lambda x: x['bd'])
for k, g in itertools.groupby(sortedHits, key=lambda x: x['bd']):
redundantHits = list(g)
if len(redundantHits) > 1:
redundantHits.sort(key = lambda x: x['hmmhit'][sortby])
print('Remove redundant IS elements and keep only one with the least evalue:')
for hit in redundantHits:
print('redundant hit', hit['bd'], hit['occurence']['ncopy4is'],
hit['orf'], hit['hmmhit'])
hitsNew.append(redundantHits[0])
mhitsNew[accid] = hitsNew
return mhitsNew
def clusterIntersect(hits, ids):
# remove the intersected hits
hitsNew = [hit for i, hit in enumerate(hits) if i not in ids]
idsList = sorted(ids)
# create the reduced submatrix of nhits original observations in 2-dimenstional space,
# len(ids) * 2 matrix, where only intersected hits are retained and each row is a hit with
# two features (genome coordinates of a hit).
#
data = []
for id in idsList:
data.append(hits[id]['bd'])
Y = numpy.array(data, int)
#print('data: {}\n{}'.format(Y.shape, Y))
#distMatrix = scipy.spatial.distance.pdist(Y, metric='euclidean')
#distMatrix = scipy.spatial.distance.pdist(Y, tools.distFunction)
distMatrix = scipy.spatial.distance.pdist(Y, tools.distFunctionByoverlap_min)
#print('distMatrix: {}\n{}'.format(distMatrix.shape, distMatrix))
# fastcluster requires the dissimilarity matrix instead of similarity matrix!
hclusters = fastcluster.linkage(distMatrix, method='average', preserve_input='False')
del distMatrix
#cophenet = scipy.cluster.hierarchy.cophenet(hclusters, distMatrix)
#print('cophenetCorrelation = {}'.format(cophenet[0]))
#nids = len(ids)
#print('nids={} timesOfMergingCluster={}'.format(nids, len(hclusters)))
#for i, cluster in enumerate(hclusters):
# print('cluster {:>3} {:>6} {:>6} {:>9.2g} {:>6}'.format(
# i, int(cluster[0]), int(cluster[1]), cluster[2], int(cluster[3])))
#for i, id in enumerate(idsList):
# print('intersected hits', i, hits[id]['bd'], hits[id]['orf'], hits[id]['occurence'], hits[id]['hmmhit'], hits[id]['tirs'])
# dengrogram of hierachical clustering
#scipy.cluster.hierarchy.dendrogram(hclusters)
# form flat clusters from the hierarchical clustering
# Note: t=1.1 instead of 1.0 ensures that the intersected hits with only 1 bp intersect are included in same cluster.
#t = 1.1
#
# When tools.distFunctionByoverlap_min() is used:
# use t=0.5 (50%) to ensure that the orfhits with the overlap of 50% or less will not be included
# in the same cluster.
# Refer to tools.distFunctionByoverlap_min for definition of distance between two vectors.
t = 0.5
clusters = scipy.cluster.hierarchy.fcluster(hclusters, t, criterion='distance')
# determine the representative hit in each cluster
# rules:
# 1) multiple-copy hit has priority over single-copy hit
# 2) and then the hit with lower e-value has priority over hit with higher e-value
clustersDic = {}
for i, clusterid in enumerate(clusters):
if clusterid in clustersDic.keys():
clustersDic[clusterid].append(i)
else:
clustersDic[clusterid] = [i]
# determine the representative hit for each cluster and append the representative hits to hitsNew
for cluster in clustersDic.values():
# sort and group hits into two groups, multiple-copy and single-copy, where multiple-copy hits with
# different copy number are grouped into same group, multiple-copy group.
cluster.sort(key = lambda x: 2 if hits[idsList[x]]['occurence']['ncopy4is']>1 else 1, reverse=True)
gs = itertools.groupby(cluster, key = lambda x: 2 if hits[idsList[x]]['occurence']['ncopy4is']>1 else 1)
# len(gs) == 2 if both multiple- and single-copy groups are available in cluster,
# len(gs) == 1 if either multiple-copy only or single-copy only group is available in cluster.
# sort hits by e-value where gs[0] is groups containing hits with the most of copy number.
k_g = next(gs) # get the first tuple from gs, (k,g)
g = list(k_g[1])
g.sort(key = lambda x: hits[idsList[x]]['hmmhit'][1])
# id of the representative hit with the least e-value, where hit == hits[idsList[id]]
repid = g[0]
hit = hits[idsList[repid]]
hitsNew.append(hit)
#print('representative hit: repid={} hitid={} hitbd={} cluster={}'.format(
# repid, idsList[repid], hit['bd'], cluster))
hitsNew.sort(key = lambda x: x['bd'][0])
return hitsNew
def parallel4overlappedHits(args):
accid, hits = args
ids = set()
for pair in itertools.combinations(range(len(hits)), 2):
#if hits[pair[0]]['orf'][3] != hits[pair[1]]['orf'][3]:
# continue # count hits with orf on different strands as different IS
bd1 = hits[pair[0]]['bd']
bd2 = hits[pair[1]]['bd']
measure, threshold = tools.chooseMeasure(bd1, bd2)
if measure < threshold:
continue
ids.update(pair)
if len(ids) > 0:
print('{}: {} intersected hits found, do clustering to pick the representative hit for each cluster'.format(accid, len(ids)))
hitsNew = clusterIntersect(hits, ids)
else:
print('{}: no intersected hits found'.format(accid))
hitsNew = hits[:]
return hitsNew
def removeOverlappedHits(mhits):
mhitsNew = {}
margs = []
for accid, hits in mhits.items():
args = (accid, hits)
margs.append(args)
for args in margs:
mhitsNew[args[0]] = parallel4overlappedHits(args)
'''
nseq = len(margs)
if nseq > constants.nproc:
nproc = constants.nproc
else:
nproc = nseq
with concurrent.futures.ProcessPoolExecutor(max_workers = nproc) as executor:
future2args = {executor.submit(parallel4overlappedHits, args): args for args in margs}
for future in concurrent.futures.as_completed(future2args):
args = future2args[future]
try:
hitsNew = future.result()
except Exception as e:
print('{} generated an exception: {} in parallel4overlappedHits'.format(args[0], e))
else:
mhitsNew[args[0]] = hitsNew
'''
return mhitsNew
# Write to files the predictions for each genome sequence
#
# mhits: {accid: hits, ..., accid: hits}
# hits: [hit, ..., hit]
# hit: {'orf': orf, 'tirs': tirs, 'hmmhit': hmmhit, 'occurence': occurence, 'isScore': isScore}
# orf: (accid, begin, end, strand)
# tirs: [tir, ..., tir]
# tir: (score, irId, irLen, nGaps, start1, end1, start2, end2, seq1, seq2)
# hmmhit: (clusterName, best_1_domain_E-value, full_sequence_E-value, overlap_number)
# occurence: {'ncopy4orf': ncopy4orf, 'sim4orf': sim4orf, 'ncopy4is': ncopy4is, 'sim4is': sim4is}
# ncopy4orf: copy number of the specific Tpase ORF with sim > constants.sim4iso in same DNA sequence
# ncopy4is: copy number of the specific IS element with sim > constants.sim4iso in same DNA sequence
# sim4orf: Tpase ORF with identicalBases/lengthOfAlignment > sim are regarded as the same Tpase
# sim4is: IS elements with identicalBases/lengthOfAlignment > sim are regarded as the same IS element
# isScore: {'evalue': score4evalue, 'tir': score4tir, 'dr': score4dr, 'occurence': score4occurence,
# 'score': isScore, 'ncopy4orf': ncopy4orf, 'ncopy4is': ncopy4is, 'irSim': irSim}
#
def outputIndividual(mhits, mDNA, proteomes, morfsMerged):
#fmtStrPrediction = '{:<30} # NCBI sequence ID
# {:<11} # family
# {:<59} # subgroup (cluster) ID
# {:>12} {:>12} {:>6} # boundary and length of IS element
# {:>8} # copy number of IS element
# {:>12} {:>12} {:>12} {:>12} # boundary of tir: start1, end1, start2, end2
# {:>5} {:>4} {:>5} {:>5} # characteristics of tir: score, irId, irLen, nGaps
# {:>12} {:>12} {:>6} {:>7} # orf: orfBegin, orfEnd, strand, length
# {:>9.2g} {:>2} # hmmhit
#
# 'seqID', # NCBI sequence ID
# 'family', # family name
# 'cluster', # subgroup, cluster ID created by CD-hit clustering
# 'isBegin', 'isEnd', 'len4is', # boundary and length of IS element
# 'ncopy4is', # copy number of IS element
# 'start1', 'end1', 'start2', 'end2', # boundary of tir
# 'score', 'irId', 'irLen', 'nGaps', # characteristics of tir:
# 'orfBegin', 'orfEnd', 'strand', 'len4orf', # tpase ORF: orfBegin, orfEnd, strand, length
# 'E-value', 'ov', # hmmhit: evalue4best1domain, overlap number output by hmmer
# 'tir', # tir
#
#
fmtStrTitlePredictionNoSeq = '{:<30} {:<11} {:<59} {:>12} {:>12} {:>6} {:>8} {:>12} {:>12} {:>12} {:>12} {:>5} {:>4} {:>5} {:>5} {:>12} {:>12} {:>6} {:>7} {:>9} {:>2} {:<}'
fmtStrPredictionNoSeq = '{:<30} {:<11} {:<59} {:>12} {:>12} {:>6} {:>8} {:>12} {:>12} {:>12} {:>12} {:>5} {:>4} {:>5} {:>5} {:>12} {:>12} {:>6} {:>7} {:>9.2g} {:>2} {:<}'
#print(fmtStrTitlePrediction.format(
# sort keys of dictionary
for seqid in sorted(mhits.keys()):
hits = mhits[seqid]
if len(hits) == 0:
continue
org, fileid, seq = mDNA[seqid]
# proteomes: {seqid: (filename, genes), ..., seqid: (filename, genes)}
# genes: {orfseqid: faa, ..., orfseqid: faa}
# orfseqid: 'seqid_orfid', orfid = 'begin_end_strand'
if seqid not in proteomes.keys():
continue
proteins = proteomes[seqid][1]
if seqid in morfsMerged.keys():
orfsMerged = morfsMerged[seqid]
else:
orfsMerged = set()
dir4output = os.path.join(constants.dir4prediction, org)
tools.makedir(dir4output)
outFile = os.path.join(dir4output, '.'.join([fileid, 'out']))
sumFile = os.path.join(dir4output, '.'.join([fileid, 'sum']))
gffFile = os.path.join(dir4output, '.'.join([fileid, 'gff']))
fp = open(outFile, 'w')
fp4sum = open(sumFile, 'w')
fp4gff = open(gffFile, 'w')
outFile4isfna = os.path.join(dir4output, '.'.join([fileid, 'is', 'fna']))
outFile4orffna = os.path.join(dir4output, '.'.join([fileid, 'orf', 'fna']))
outFile4orffaa = os.path.join(dir4output, '.'.join([fileid, 'orf', 'faa']))
fp4isfna = open(outFile4isfna, 'w')
fp4orffna = open(outFile4orffna, 'w')
fp4orffaa = open(outFile4orffaa, 'w')
# sort by isBegin if tirs exist, else by orfBegin
#hits.sort(key = lambda x: x['tirs'][0][-6] if len(x['tirs'])>0 and len(x['tirs'][0])>0 else x['orf'][1])
# sort by isBegin
hits.sort(key = lambda x: x['bd'][0])
# familySumBySeq: {'family1': nis4family1, ..., 'familyn': nis4familyn}
# bpsBySeq: {'family1': bps, ..., 'familyn': bps}
familySumBySeq = {}
bpsBySeq = {}
print('##gff-version 3', file = fp4gff)
print(fmtStrTitlePredictionNoSeq.format(
'seqID', # NCBI sequence ID
'family', # family name
'cluster', # cluster ID created by CD-hit clustering
'isBegin', 'isEnd', 'len4is', # boundary and length of IS element
'ncopy4is', # copy number of IS element
'start1', 'end1', 'start2', 'end2', # boundary of tir
'score', 'irId', 'irLen', 'nGaps', # characteristics of tir:
'orfBegin', 'orfEnd', 'strand', 'len4orf', # tpase ORF: orfBegin, orfEnd, strand, length
'E-value', 'ov', # hmmhit: best1domain e-value and overlap number output by hmmer
'tir', # tir, seq1:seq2
),
file = fp)
print('#', '-' * 139, file = fp)
IDnum = 0
#for hit in hits:
for hitID, hit in enumerate(hits):
orfBegin, orfEnd, strand = hit['orf'][1:]
len4orf = orfEnd - orfBegin + 1
cluster, best1domE, fullSeqE, ov, = hit['hmmhit']
if 'IS200_IS605_' in cluster:
family = 'IS200/IS605'
else:
family = cluster.split('_',1)[0]
occurence = hit['occurence']
ncopy4is, sim4is, ncopy4orf, sim4orf = occurence['ncopy4is'], occurence['sim4is'], occurence['ncopy4orf'], occurence['sim4orf']
if len(hit['tirs']) > 0:
tirs = hit['tirs']
score, irId, irLen, nGaps, start1, end1, start2, end2, seq1, seq2 = tirs[0]
#isBegin, isEnd = start1, end2
else:
score, irId, irLen, nGaps, start1, end1, start2, end2, seq1, seq2 = (0, 0, 0, 0, 0, 0, 0, 0, '-', '-')
#isBegin, isEnd = orfBegin, orfEnd
isBegin, isEnd = hit['bd']
len4is = isEnd - isBegin + 1
# output .gff file
# gff3 format specifications, refer to
# https://github.com/The-Sequence-Ontology/Specifications/blob/master/gff3.md
#
IDnum += 1
ID = str(IDnum)
# IS element
print('{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}'.format(
seqid, # NCBI sequence ID
'ISEScan',
'insertion_sequence',
isBegin, isEnd,
'.',
#'.', # IS element is DNA transposon and not stranded.
strand, # IS element is DNA transposon and not stranded but usually labeled by strand of Tpase main ORF.
'.',
';'.join(['ID=is'+ID, 'family='+family, 'cluster='+str(cluster)])
), file = fp4gff)
# with TIR
if irLen > 0:
# the first part of TIR
print('{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}'.format(
seqid, # NCBI sequence ID
'ISEScan',
'terminal_inverted_repeat',
start1, end1,
'.',
#'.', # IS element is DNA transposon and not stranded.
strand, # IS element is DNA transposon and not stranded but usually labeled by strand of Tpase main ORF.
'.',
';'.join(['ID=tir'+ID, 'parent=is'+ID])
), file = fp4gff)
# the second part of TIR
print('{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}'.format(
seqid, # NCBI sequence ID
'ISEScan',
'terminal_inverted_repeat',
start2, end2,
'.',
#'.', # IS element is DNA transposon and not stranded.
strand, # IS element is DNA transposon and not stranded but usually labeled by strand of Tpase main ORF.
'.',
';'.join(['ID=tir'+ID, 'parent=is'+ID])
), file = fp4gff)
# output .out file
#print(fmtStrPrediction.format(
print(fmtStrPredictionNoSeq.format(
seqid, # NCBI sequence ID
family, # family name
cluster, # cluster id
isBegin, isEnd, len4is, # boundary and length of IS element
ncopy4is, # copy number of IS element
start1, end1, start2, end2, # tir boundary
score, irId, irLen, nGaps, # characteristics of tir
orfBegin, orfEnd, strand, len4orf, # orf, probably virtual ORF
best1domE, ov, # hmmhit
':'.join([seq1,seq2]), # tir
),
file = fp)
# summarize
if family in familySumBySeq.keys():
familySumBySeq[family] += 1
bpsBySeq[family] += len4is
else:
familySumBySeq[family] = 1
bpsBySeq[family] = len4is
# output sequence of IS element
if strand == '-':
fna4is = tools.complementDNA(seq[isBegin-1: isEnd], '1')[::-1]
else:
fna4is = seq[isBegin-1: isEnd]
head4fna4is = '_'.join([hit['orf'][0], str(isBegin), str(isEnd), strand])
des = cluster
head4fna4is = ' '.join([head4fna4is, des])
fasta4fna4is = tools.fasta_format(head4fna4is, fna4is)
fp4isfna.write(fasta4fna4is)
# ORF
orfStr = '_'.join([str(x) for x in hit['orf'][1:]])
head4fna4orf = '_'.join([hit['orf'][0], orfStr])
orfs4merged = []
for orf in orfsMerged:
# The merged orfs must be located at the same strand.
#if hit['orf'][1] <= orf[1] and hit['orf'][2] >= orf[2] and hit['orf'][3] == orf[3]:
# The merged orfs may be located at the different strands.
if hit['orf'][1] <= orf[1] and hit['orf'][2] >= orf[2]:
orfs4merged.append(orf)
# A hit is created by two merged ORFs.
# At most two ORF hits (ORFs )can be merged into a larger virtual ORF,
# namely, a larger ORF hit. The other ORFs are thrown if there are
# more than two ORFs merged in the current large virtual ORF.
#if len(orfs4merged) == 2:
# break
if len(orfs4merged) > 0:
# sort by start coordinate of ORF
orfs4merged.sort(key = operator.itemgetter(1))
for orf1 in orfs4merged:
orf1str = '_'.join(str(x) for x in orf1[1:])
# amino acid sequence
head4faa4orf1 = '_'.join([orf1[0], orf1str])
faa4orf1 = proteins[head4faa4orf1]
#fasta4faa4orf1 = tools.fasta_format('{} {} merged in virtual ORF {}'.format(
fasta4faa4orf1 = tools.fasta_format('{} {} assinged to {}'.format(
head4faa4orf1, orf1str, orfStr), faa4orf1)
fp4orffaa.write(fasta4faa4orf1)
# nucleic acid sequence
head4fna4orf1 = '_'.join([orf1[0], orf1str])
if orf1[3] == '-':
fna4orf1 = tools.complementDNA(seq[orf1[1]-1: orf1[2]], '1')[::-1]
else:
fna4orf1 = seq[orf1[1]-1: orf1[2]]
#fasta4fna4orf1 = tools.fasta_format('{} {} merged in virtual ORF {}'.format(
fasta4faa4orf1 = tools.fasta_format('{} {} assinged to {}'.format(
head4fna4orf1, orf1str, orfStr), fna4orf1)
fp4orffna.write(fasta4fna4orf1)
elif head4fna4orf in proteins.keys():
# amino acid sequence
faa4orf = proteins[head4fna4orf]
fasta4faa4orf = tools.fasta_format(head4fna4orf, faa4orf)
fp4orffaa.write(fasta4faa4orf)
# nucleic acid sequence
if strand == '-':
fna4orf = tools.complementDNA(seq[orfBegin-1: orfEnd], '1')[::-1]
else:
fna4orf = seq[orfBegin-1: orfEnd]
fasta4fna4orf = tools.fasta_format(head4fna4orf, fna4orf)
fp4orffna.write(fasta4fna4orf)
else:
print('IS element without predicted Tpase ORF is found:', head4fna4orf)
fp4isfna.close()
fp4orffna.close()
fp4orffaa.close()
fp4gff.close()
fp.close()
print('{:<11} {:>6} {:>7} {:>15}'.format('family', 'nIS', '%Genome', 'bps4IS'), file=fp4sum)
#print('-' * 18, file=fp4sum)
nis4seq = 0
bps4seq = 0
len4DNA = len(seq)
for family in sorted(familySumBySeq.keys()):
nis = familySumBySeq[family]
bps4family = bpsBySeq[family]
print('{:<11} {:>6} {:>7.2g} {:>15}'.format(family, nis,
(bps4family/len4DNA)*100, bps4family), file=fp4sum)
nis4seq += nis
bps4seq += bps4family
print('{:<11} {:>6} {:>7.2g} {:>15} {:>15}'.format('total', nis4seq,
(bps4seq/len4DNA)*100, bps4seq, len4DNA), file=fp4sum)
fp4sum.close()
if nis4seq == 0:
print('No valid IS element was found for', seqid)
# Write to files the predictions for each genome sequence
#
# mhits: {accid: hits, ..., accid: hits}
# hits: [hit, ..., hit]
# hit: {'orf': orf, 'tirs': tirs, 'hmmhit': hmmhit, 'occurence': occurence, 'isScore': isScore}
# orf: (accid, begin, end, strand)
# tirs: [tir, ..., tir]
# tir: (score, irId, irLen, nGaps, start1, end1, start2, end2, seq1, seq2)
# hmmhit: (clusterName, best_1_domain_E-value, full_sequence_E-value, ncopy4tpase, raworfhits)
# occurence: {'ncopy4orf': ncopy4orf, 'sim4orf': sim4orf, 'ncopy4is': ncopy4is, 'sim4is': sim4is}
# ncopy4orf: copy number of the specific Tpase ORF with sim > constants.sim4iso in same DNA sequence
# ncopy4is: copy number of the specific IS element with sim > constants.sim4iso in same DNA sequence
# sim4orf: Tpase ORF with identicalBases/lengthOfAlignment > sim are regarded as the same Tpase
# sim4is: IS elements with identicalBases/lengthOfAlignment > sim are regarded as the same IS element
# isScore: {'evalue': score4evalue, 'tir': score4tir, 'dr': score4dr, 'occurence': score4occurence,
# 'score': isScore, 'ncopy4orf': ncopy4orf, 'ncopy4is': ncopy4is, 'irSim': irSim}
# raworfhits: {'orfhits4tpase':orfhits4tpase}
# orfhits4tpase: [], [orfhit4tpase, ...]
# orfhit4tpase: (orf, clusterName, best_1_domain_E-value, full_sequence_E-value, ncopy4tpase)
#
# orgfileid: org/fileid, character string, e.g. HMASM/SRS078176.scaffolds.fa
def outputIS4multipleSeqOneFile(mhits, mDNA, proteomes, morfsMerged, orgfileid):
fmt4seqID = '{:<60}' # NCBI sequence ID
fmt4family = '{:<11}' # family
fmt4cluster = '{:<59}' # subgroup (cluster) ID
fmt4isBegin = '{:>12}' # left boundary of IS
fmt4isEnd = '{:>12}' # right boundary of IS
fmt4isLen = '{:>6}' # length of IS
fmt4ncopy4is = '{:>8}' # copy number of IS element
fmt4start1 = '{:>12}' # boundary of tir: start1
fmt4end1 = '{:>12}' # boundary of tir: end1
fmt4start2 = '{:>12}' # boundary of tir: start2
fmt4end2 = '{:>12}' # boundary of tir: end2
fmt4score4tir = '{:>5}' # characteristics of tir: score
fmt4irId = '{:>4}' # characteristics of tir: irId
fmt4irLen = '{:>5}' # characteristics of tir: irLen
fmt4nGaps4tir = '{:>5}' # characteristics of tir: nGaps
fmt4orfBein = '{:>12}' # orfBegin
fmt4orfEnd = '{:>12}' # orfEnd
fmt4strand = '{:>6}' # strand
fmt4orfLen = '{:>7}' # orf: length of orf
fmt4evalue = '{:>9.2g}' # the best E-value of multiple copies
fmt4evalue4copy = '{:>12.2g}' # E-value of IS copy
fmt4evalue4title = '{:>9}' # format to print E-value in title line
fmt4evalue4copy4title = '{:>12}' # format to print E-value in title line
fmt4ov = '{:>2}' # ov number of hmmsearch
fmt4tir = '{}' # terminal inverted repeat sequences, seq1:seq2
title4seqID = 'seqID' # NCBI sequence ID
title4family = 'family' # family name
title4cluster = 'cluster' # subgroup, cluster ID created by CD-hit clustering
title4isBegin = 'isBegin' # boundary of IS
title4isEnd = 'isEnd' # boundary of IS
title4isLen = 'isLen' # length of IS element
title4ncopy4is = 'ncopy4is' # copy number of IS
title4start1 = 'start1'
title4end1 = 'end1'
title44start2 = 'start2'
title4end2 = 'end2' # boundary of tir
title4score = 'score'
title4irId = 'irId'
title4irLen = 'irLen'
title4nGaps = 'nGaps' # characteristics of tir:
title4orfBegin = 'orfBegin'
title4orfEnd = 'orfEnd'
title4strand = 'strand'
title4orfLen = 'orfLen' # tpase ORF: orfBegin, orfEnd, strand, length
title4evalue = 'E-value' # the best E-value of IS element with multiple copies, namely,
# the E-value of the IS copy with the best E-vluae among all copies of the same IS element in a genome sequence
title4evalue4copy = 'E-value4copy' # E-value of the IS copy
title4ov = 'ov' # hmmhit: evalue, overlap number output by hmmer
title4tir = 'tir' # tir, seq1:seq2
titleLine = [
title4seqID , # NCBI sequence ID
title4family , # family name
title4cluster , # subgroup, cluster ID created by CD-hit clustering
title4isBegin , # boundary of IS
title4isEnd , # boundary of IS
title4isLen , # length of IS element
title4ncopy4is , # copy number of IS
title4start1 ,
title4end1 ,
title44start2 ,
title4end2 , # boundary of tir
title4score ,
title4irId ,
title4irLen ,
title4nGaps , # characteristics of tir:
title4orfBegin ,
title4orfEnd ,
title4strand ,
title4orfLen , # tpase ORF: orfBegin, orfEnd, strand, length
title4evalue ,
title4ov , # hmmhit: evalue, overlap number output by hmmer
title4tir # tir, seq1:seq2
]
titleLine4raw = titleLine[:len(titleLine)-2]
titleLine4raw.append(title4evalue4copy)
titleLine4raw.extend(titleLine[-2:])
fmtTitlePrediction = [
fmt4seqID , # NCBI sequence ID
fmt4family , # family
fmt4cluster , # subgroup (cluster) ID
fmt4isBegin , # left boundary of IS
fmt4isEnd , # right boundary of IS
fmt4isLen , # length of IS
fmt4ncopy4is , # copy number of IS element
fmt4start1 , # boundary of tir: start1
fmt4end1 , # boundary of tir: end1
fmt4start2 , # boundary of tir: start2
fmt4end2 , # boundary of tir: end2
fmt4score4tir , # characteristics of tir: score
fmt4irId , # characteristics of tir: irId
fmt4irLen , # characteristics of tir: irLen
fmt4nGaps4tir , # characteristics of tir: nGaps
fmt4orfBein , # orfBegin
fmt4orfEnd , # orfEnd
fmt4strand , # strand
fmt4orfLen , # orf: length of orf
fmt4evalue4title , # format to print E-value of hmmsearch in title line
fmt4ov , # ov number of hmmsearch
fmt4tir , # terminal inverted repeat sequences, seq1:seq2
]
fmtTitlePrediction4raw = fmtTitlePrediction[:len(fmtTitlePrediction)-2]
fmtTitlePrediction4raw.append(fmt4evalue4copy4title)
fmtTitlePrediction4raw.extend(fmtTitlePrediction[-2:])
fmtStrTitlePrediction = ' '.join(fmtTitlePrediction)
fmtStrTitlePrediction4raw = ' '.join(fmtTitlePrediction4raw)
fmtPrediction = [
fmt4seqID , # NCBI sequence ID
fmt4family , # family
fmt4cluster , # subgroup (cluster) ID
fmt4isBegin , # left boundary of IS
fmt4isEnd , # right boundary of IS
fmt4isLen , # length of IS
fmt4ncopy4is , # copy number of IS element
fmt4start1 , # boundary of tir: start1
fmt4end1 , # boundary of tir: end1
fmt4start2 , # boundary of tir: start2
fmt4end2 , # boundary of tir: end2
fmt4score4tir , # characteristics of tir: score
fmt4irId , # characteristics of tir: irId
fmt4irLen , # characteristics of tir: irLen
fmt4nGaps4tir , # characteristics of tir: nGaps
fmt4orfBein , # orfBegin
fmt4orfEnd , # orfEnd
fmt4strand , # strand
fmt4orfLen , # orf: length of orf
fmt4evalue , # format to print E-value of hmmsearch
fmt4ov , # ov number of hmmsearch
fmt4tir , # terminal inverted repeat sequences, seq1:seq2
]
fmtPrediction4raw = fmtPrediction[:len(fmtPrediction)-2]
fmtPrediction4raw.append(fmt4evalue4copy)
fmtPrediction4raw.extend(fmtPrediction[-2:])
fmtStrPrediction = ' '.join(fmtPrediction)
fmtStrPrediction4raw = ' '.join(fmtPrediction4raw)
#fmtStrTitlePrediction = '{:<60} {:<11} {:<59} {:>12} {:>12} {:>6} {:>8} {:>12} {:>12} {:>12} {:>12} {:>5} {:>4} {:>5} {:>5} {:>12} {:>12} {:>6} {:>7} {:>9} {:>2} {:<}'
#fmtStrPrediction = '{:<60} {:<11} {:<59} {:>12} {:>12} {:>6} {:>8} {:>12} {:>12} {:>12} {:>12} {:>5} {:>4} {:>5} {:>5} {:>12} {:>12} {:>6} {:>7} {:>9.2g} {:>2} {:<}'
fmtStrTitleSum = '{:<60} {:<11} {:>6} {:>7} {:>15} {:>15}'
fmtStrSum = '{:<60} {:<11} {:>6} {:>7.2f} {:>15} {:>15}'
common4output = os.path.join(constants.dir4prediction, orgfileid)
outFile = '.'.join([common4output, 'out'])
outFile4raw = '.'.join([common4output, 'raw'])
sumFile = '.'.join([common4output, 'sum'])
gffFile = '.'.join([common4output, 'gff'])
tools.makedir(os.path.dirname(outFile))
fp = open(outFile, 'w')
fp4raw = open(outFile4raw, 'w')
print(fmtStrTitlePrediction.format(*titleLine), file = fp)
print(fmtStrTitlePrediction4raw.format(*titleLine4raw), file = fp4raw)
print('#', '-' * 139, file = fp)
print('#', '-' * 139, file = fp4raw)
# character string to hold the content of csv file with the same content as raw file except
# one 'sn' collumn is inserted and becomes the first collumn and the last 'tir' collumn in
# raw file is splitted into two collumns, 'seq1' and 'seq2' and the last second collumn 'ov'
# in raw file is removed in csv file. The 'sn' collumn is the sequential
# number of the specific IS copy in the sequences in a fasta file, starting from 1 to n which is
# the total number of the IS copies in all sequecnes in a fasta file.
#
# orgfileid: org/fileid, examples:
# Shigella_dysenteriae_Sd197_uid58213/NC_007606.fna, NGT10/final.contigs.fa
sn = 0
islist4csv = []
titleLine4csv = ['sn']
titleLine4csv.extend(titleLine4raw[:len(titleLine4raw)-2])
titleLine4csv.extend(['seq1', 'seq2'])
islist4csv.append(titleLine4csv)
fp4sum = open(sumFile, 'w')
print(fmtStrTitleSum.format(
'# seqid', 'family', 'nIS', '%Genome', 'bps4IS', 'dnaLen'), file=fp4sum)
nis4seqTotal = 0
bps4seqTotal = 0
len4DNATotal = 0
fp4gff = open(gffFile, 'w')
print('##gff-version 3', file = fp4gff)
outFile4isfna = '.'.join([common4output, 'is', 'fna'])
outFile4orffna = '.'.join([common4output, 'orf', 'fna'])
outFile4orffaa = '.'.join([common4output, 'orf', 'faa'])
fp4isfna = open(outFile4isfna, 'w')
fp4orffna = open(outFile4orffna, 'w')
fp4orffaa = open(outFile4orffaa, 'w')
# sort keys of dictionary
for seqid in sorted(mhits.keys()):
hits = mhits[seqid]
if len(hits) == 0:
continue
org, fileid, seq = mDNA[seqid]
# proteomes: {seqid: (filename, genes), ..., seqid: (filename, genes)}
# genes: {orfseqid: faa, ..., orfseqid: faa}
# orfseqid: 'seqid_orfid', orfid = 'begin_end_strand'
if seqid not in proteomes.keys():
continue
proteins = proteomes[seqid][1]
if seqid in morfsMerged.keys():
orfsMerged = morfsMerged[seqid]
else:
orfsMerged = set()
# sort by isBegin if tirs exist, else by orfBegin
#hits.sort(key = lambda x: x['tirs'][0][-6] if len(x['tirs'])>0 and len(x['tirs'][0])>0 else x['orf'][1])
# sort by isBegin
hits.sort(key = lambda x: x['bd'][0])
# familySumBySeq: {'family1': nis4family1, ..., 'familyn': nis4familyn}
# bpsBySeq: {'family1': bps, ..., 'familyn': bps}
familySumBySeq = {}
bpsBySeq = {}
IDnum = 0
#for hit in hits:
for hitID, hit in enumerate(hits):
# The value of ov was replaced by ncopy4tpase in previous steps.
cluster, best1domE, fullSeqE, ov, raworfhits = hit['hmmhit'][:5]
evalue = fullSeqE
orfhits4tpase = raworfhits['orfhits4tpase']
# for IS with Tpase
if len(orfhits4tpase) > 0:
# orfhits4tpase: [orfhit4tpase, ...]
# orfhit4tpase: (orf, ..., ov)
# We simply use the first Tpase orf with the best e-value in orfhits4tpase.
orfhit4tpase = orfhits4tpase[0]
evalue4copy = orfhit4tpase[3]
orf4tpase = orfhit4tpase[0]
orfBegin, orfEnd, strand = orf4tpase[1:]
# for IS without Tpase identified
else:
evalue4copy = -1
orf4tpase = ()
orfBegin, orfEnd, strand = 0, 0, ''
len4orf = orfEnd - orfBegin + 1
if 'IS200_IS605_' in cluster:
family = 'IS200/IS605'
else:
family = cluster.split('_',1)[0]
occurence = hit['occurence']
ncopy4is, sim4is, ncopy4orf, sim4orf = occurence['ncopy4is'], occurence['sim4is'], occurence['ncopy4orf'], occurence['sim4orf']
if len(hit['tirs']) > 0:
tirs = hit['tirs']
score, irId, irLen, nGaps, start1, end1, start2, end2, seq1, seq2 = tirs[0]
#isBegin, isEnd = start1, end2
else:
score, irId, irLen, nGaps, start1, end1, start2, end2, seq1, seq2 = (0, 0, 0, 0, 0, 0, 0, 0, '-', '-')
#isBegin, isEnd = orfBegin, orfEnd
isBegin, isEnd = hit['bd']
len4is = isEnd - isBegin + 1
# output .gff file
# gff3 format specifications, refer to
# https://github.com/The-Sequence-Ontology/Specifications/blob/master/gff3.md
#
IDnum += 1
ID = str(IDnum)
# IS element
isid = '_'.join([seqid, 'IS', ID])
print('{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}'.format(
seqid, # sequence ID
'ISEScan',
'insertion_sequence',
isBegin, isEnd,
'.',
#'.', # IS element is DNA transposon and not stranded.
strand, # IS element is DNA transposon and not stranded but usually labeled by strand of Tpase main ORF.
'.',
';'.join(['ID='+isid, 'family='+family, 'cluster='+str(cluster)])
), file = fp4gff)
# with TIR
tirid = '_'.join([isid,'TIR'])
parentid = isid
if irLen > 0:
# the first part of TIR
print('{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}'.format(
seqid, # NCBI sequence ID
'ISEScan',
'terminal_inverted_repeat',
start1, end1,
'.',
#'.', # IS element is DNA transposon and not stranded.
strand, # IS element is DNA transposon and not stranded but usually labeled by strand of Tpase main ORF.
'.',
';'.join(['ID='+tirid, 'parent='+isid])
), file = fp4gff)
# the second part of TIR
print('{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}\t{}'.format(
seqid, # NCBI sequence ID
'ISEScan',
'terminal_inverted_repeat',
start2, end2,
'.',
#'.', # IS element is DNA transposon and not stranded.
strand, # IS element is DNA transposon and not stranded but usually labeled by strand of Tpase main ORF.
'.',
';'.join(['ID='+tirid, 'parent='+isid])