-
Notifications
You must be signed in to change notification settings - Fork 9
/
PhyLTR.py
executable file
·8891 lines (8591 loc) · 465 KB
/
PhyLTR.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 python3
import sys
import re
import os
import time
import os.path
import subprocess
import random
from shutil import copyfile, copytree, rmtree
from datetime import datetime
from math import ceil
from Bio import SeqIO, AlignIO
from multiprocessing import Pool, Manager
from copy import copy, deepcopy
from inspect import currentframe, getframeinfo
class GFF3_line:
"""A class to represet GFF3 lines and allow modification of the
values of its fields.
Attributes:
------------
field0, ..., field8 strings containing the values of each field
in a GFF3 line
attributes a dictionary containing the key-value pairs
in the GFF3 line 9th field
Methods:
------------
str() Outputs GFF3 line
repr() Outputs GFF3 line
addAttr() Adds new GFF3 attribute
delAttr() Delete a GFF3 attribute
refreshAttrStr() This needs to be called if changes were made to
any of the attributes. It refreshes
"""
def __init__(self, line=None, **kwargs):
"""GFF3_line is initialized to contain the fields of the GFF3
line provided as attributes. The attributes are kept in a
dictionary and a the keys are ordered in a list to preserve
the order of attributes upon getting the sring representation
of the line from the GFF3_line object.
"""
if line == None:
(self.seqid,
self.source,
self.type,
self.start,
self.end,
self.score,
self.strand,
self.phase,
self.attributes_str) = [None]*9
self.attributes_order = []
self.attributes = {}
else:
(self.seqid,
self.source,
self.type,
self.start,
self.end,
self.score,
self.strand,
self.phase,
self.attributes_str) = line.strip().split('\t')
self.start = int(self.start)
self.end = int(self.end)
assert self.start <= self.end
self.coords = (self.start, self.end)
self.length = self.end - self.start + 1
attributes_list = self.attributes_str.split(';')
self.attributes_order = [attr.split('=')[0] for attr in
attributes_list]
self.attributes = {attr.split('=')[0]:attr.split('=')[1] for
attr in attributes_list}
self.line_number = None
if 'line_number' in kwargs:
self.line_number = kwargs['line_number']
# rename the name attribute so it conforms to GFF3 specifications,
# where Name is a reserved attribute key. The version of LTRDigest
# makes attribute key name
if 'name' in self.attributes:
self.attributes['Name'] = self.attributes.pop('name')
self.attributes_order[self.attributes_order.index('name')] = 'Name'
def __repr__(self):
"""Output for overloaded functions str() and repr()"""
return '\t'.join([str(self.seqid),
str(self.source),
str(self.type),
str(self.start),
str(self.end),
str(self.score),
str(self.strand),
str(self.phase),
str(self.attributes_str)])
def refreshAttrStr(self):
"""If the attributes dictionary or attributes_order has been
altered this should be called to update attributes_str.
"""
self.attributes_str = ';'.join(['='.join(
[attr, self.attributes[attr]]) for attr in self.attributes_order])
def addAttr(self, attr_key, attr_val, replace=False, attr_pos=0):
"""ds attribute, default is at the start of the list.
Default behavior is to add attr_val to a growing
comma-sep list if attr_key exists. Set replace=True to
replace existing attr_val.
"""
if attr_key in self.attributes:
if replace:
delAttr(attr_key)
self.attributes[attr_key] = attr_val
self.attributes_order.insert(attr_pos, attr_key)
self.refreshAttrStr()
# grow list
else:
self.attributes[attr_key] = '{0},{1}'.format(
self.attributes[attr_key], attr_val)
self.refreshAttrStr()
else:
self.attributes[attr_key] = attr_val
self.attributes_order.insert(attr_pos, attr_key)
self.refreshAttrStr()
def delAttr(self, attr_key):
"""Deletes attribute."""
del self.attributes[attr_key]
self.attributes_order.pop(self.attributes_order.index(attr_key))
self.refreshAttrStr()
def rename_fasta_seq_headers(in_flpath,
in_header_pattern,
header_to_name_map,
out_flpath):
"""in_fasta_filepath - the fasta file with headers to be renamed.
in_header_pattern - a regex that will match the part of the header
that corresponds to keys in header_to_name_map
header_to_name_map - a dict with keys as part of in_fasta_filepath
seq headers that match in_header_pattern and
values as the abbreviated LTR-RT ID (e.g. 24_1,
which corresponds to LTR_retrotransposon24)
This function depends on the re and Bio.SeqIO modules
"""
fasta_file = list(SeqIO.parse(in_flpath, 'fasta'))
in_header_pattern = re.compile(in_header_pattern)
for seq in fasta_file:
seq_id = re.search(in_header_pattern, seq.id).group(1)
seq.id = header_to_name_map[seq_id]
seq.description = ''
SeqIO.write(fasta_file, out_flpath, 'fasta')
def write_ltrs_gff3(data):
"""Writes items from a list data to a file (intended to be a GFF3 file
in PhyLTR.py). For use with -ltrs option in PhyLTR.py
"""
if len(data) < 3:
print('Less than 2 LTRs...? ...GFF3 not written. DATA:\n{0}'.format(
'\n'.join(data)), file=sys.stderr)
elif len(data) > 3:
print('More than 2 LTRs...? ...GFF3 not written. DATA:\n{0}'.format(
'\n'.join(data)), file=sys.stderr)
else:
# data[-1] should have the output filepath while data[0:2] are
# the GFF3 lines
with open(data[-1], 'w') as out_fl:
out_fl.write(''.join(data[0:2]))
def call_process(call_str):
"""Just runs subprocess.call. For simplifying parallel execution of
PhyLTR.py using the multiprocessing module.
"""
subprocess.call(call_str, shell=True)
def count_end_gaps(aln):
"""Input is a two-element list of seqs of identical length
(a pairwise alignment).
Returns the number of bases to subtract from the alignment length.
The reason being that since this is meant for alignments between
two LTRs, LTR boundaries may be off and part of LTR may have been
left in the genome. If LTR boundaries were accurate it's possible
there would be no end gaps. The length is used in PhyLTR.py for
estimating sequence divergence.
The number of gaps from the left end in the seq with the most
gaps on the left end plus the number from the right end
Algorithm: walk inward from each seq end one char at a time and
count how many gaps. Stop a walk when the char is not the gap char.
When all walks are non-gap chars, return the sum of the highest
left and highest right count.
"""
# make sure input seqs are the same length
if len(aln[0]) != len(aln[1]):
raise ValueError('Sequences in alignment have different length')
# Keys are all same in these dicts. The number from the key can be
# stripped and used as the index with which to access the sequence.
# keeps track of how many gaps on each end of each sequence
end_gaps = {'L0':0, 'L1':0, 'R0':0, 'R1':0}
# keeps track of the current character in each walk
chars = {'L0':'-', 'L1':'-', 'R0':'-', 'R1':'-'}
# keeps track of the current position of each walk
pos = {'L0':0, 'L1':0, 'R0':-1, 'R1':-1}
while chars['L0'] == ('-'
or chars['L1'] == '-'
or chars['R0'] == '-'
or chars['R1'] == '-'):
for k in end_gaps:
if chars[k] == '-':
# Strip num from key k to get index of sequence
seq = int(k[1])
# get next position in current walk
chars[k] = aln[seq][pos[k]]
# add one to count if this char is a gap char
if chars[k] == '-':
end_gaps[k] += 1
# get next index to continue walk from left side
if 'L' in k:
pos[k] += 1
# get next indext to continue walk from right side
if 'R' in k:
pos[k] -= 1
# return gap count
return ( max([end_gaps['L0'],end_gaps['L1']])
+ max([end_gaps['R0'],end_gaps['R1']]) )
def fastas2supermatrix(**kwargs):
"""Needs biopython installed
kwargs expected:
input_dir='path to dir containing fasta files to be concatenated'
input_dir is expected to have only fasta files to be concatenated
1. Check that lengths of all seqs in each input fasta alignment are
the same, report seq lengths and quit if they're different.
2. For each fasta file input, add each sequence identifier as a key
in a dictionary with the value of the key a dictionary with the
name of the fasta file the key and the value the sequence.
3. Make a set of unique sequence ids.
4. Build a new dicitonary with keys as sequence identifiers and
values are concatenated sequences, with Ns or gaps if no
sequence is available for that identifier for a given fasta file
input.
5. Write new fasta of concatenated sequences.
"""
# get names of input files. dir with input files passed to this
# function as kwarg input_dir.
input_fastas = [fl for fl in os.listdir(kwargs['input_dir'])
if not fl.startswith('.')]
# will become a nested dict holding sequences from each fasta file
# for each sequence header
seqs_dct = {}
# will hold the length of each alignment
seq_lengths = {}
# process each fasta seq
for fasta in input_fastas:
# read in alignment
fasta_contents = list(SeqIO.parse('{0}/{1}'.format(
kwargs['input_dir'],
fasta), 'fasta'))
# make sure seqs in the alignment are the same length. If they
# aren't then print seq ids and lengths to stderr and quit
all_seqs_lengths = {seq.id:len(seq) for seq in fasta_contents}
if len(set(all_seqs_lengths.values())) != 1:
print('Sequences in file: {0} not all of equal length'.format(
fasta),
file=sys.stderr)
print('\n'.join(
['sequence\tlength']
+ ['{0}\t{1}'.format(seq, all_seqs_lengths[seq])
for seq in all_seqs_lengths]), file=sys.stderr)
sys.exit()
seq_lengths[fasta] = len(fasta_contents[0])
# Add sequences to seqs_dct
for seq in fasta_contents:
if seq.id in seqs_dct:
# check for duplicate seq id and stop program if any
# duplicates are found
if fasta in seqs_dct[seq.id]:
print('Duplicate sequence identifier in {0}: {1}'.format(
fasta, seq.id),
file=sys.stderr)
sys.exit()
# if no duplicate add sequence to nested dict with key
# as fasta file name
seqs_dct[seq.id][fasta] = str(seq.seq)
else:
# add sequence to nested dict with key as fasta file
# name
seqs_dct[seq.id] = { fasta:str(seq.seq) }
# print concatenated fasta supermatrix
if 'output_fl' in kwargs:
out_fl = open(kwargs['output_fl'], 'a')
for seq in seqs_dct:
output_seq = ''
for fasta in input_fastas:
if fasta not in seqs_dct[seq]:
output_seq += 'N' * seq_lengths[fasta]
else:
output_seq += seqs_dct[seq][fasta]
if 'output_fl' in kwargs:
out_fl.write('>{0}\n'.format(seq))
out_fl.write('{0}\n'.format(output_seq))
else:
print('>{0}'.format(seq))
print(output_seq)
if 'output_fl' in kwargs:
out_fl.close()
def bedtoolsid2attr(gff_flpath,
attr='ID',
strand=False,
lstrip=None):
"""This takes a GFF and creates a map of the current attribute
specified by attr, to the expected names that will be output by
bedtools getfasta (a tool for extracting sequences from a FASTA
which correspond to features in a GFF3.
Also as a standalone script:
bedtoolsid2attr.py -gff <gff> [-attr <str>] [-strand]
"""
STRAND = strand
attr_pat = re.compile('{0}=(.+?)(;|$)'.format(attr))
map_dct = {}
with open(gff_flpath) as in_fl:
for line in in_fl:
if not line.startswith('#'):
fields = line.strip().split('\t')
seqid = fields[0]
start = str(int(fields[3]) - 1)
end = fields[4]
strand = fields[6]
attr_value = re.search(attr_pat, fields[8]).group(1)
if not lstrip == None:
attr_value = attr_value.lstrip(lstrip)
if STRAND:
map_dct['{0}:{1}-{2}({3})'.format(seqid,
start,
end,
strand)
] = attr_value
else:
map_dct['{0}:{1}-{2}'.format(seqid,
start,
end)
] = attr_value
return map_dct
def rename_fasta_seq_headers(in_flpath,
in_header_pattern,
header_to_name_map,
out_flpath):
"""I/O for changing fasta sequence headers. Uses regex matching and
dictionary associating current with new name.
in_fasta_filepath - the fasta file with headers to be renamed.
in_header_pattern - a regex that will match the part of the header
that corresponds to keys in header_to_name_map
header_to_name_map - a dict with keys as part of in_fasta_filepath
seq headers that match in_header_pattern and
values as the abbreviated LTR-RT ID (e.g. 24_1,
which corresponds to LTR_retrotransposon24)
This function depends on the re and Bio.SeqIO modules
"""
fasta_file = list(SeqIO.parse(in_flpath, 'fasta'))
in_header_pattern = re.compile(in_header_pattern)
for seq in fasta_file:
seq_id = re.search(in_header_pattern, seq.id).group(1)
seq.id = header_to_name_map[seq_id]
seq.description = ''
SeqIO.write(fasta_file, out_flpath, 'fasta')
def ChangeFastaHeaders(inputFastaPath, inputGFFpath, attribute='ID'):
"""Creates map of bedtools getfasta-style features, reads in
inputFasta, writes newFasta, deletes inpuFasta, renames newFasta
as inputFasta
"""
bedtoolsIDmap = bedtoolsid2attr(inputGFFpath, attr=attribute)
newFasta = '{0}.new.tmp'.format(inputFastaPath)
header_pattern='(.+?:\d+?-\d+?)(?:$|\D)'
rename_fasta_seq_headers(inputFastaPath,
header_pattern,
bedtoolsIDmap,
newFasta)
os.replace(newFasta, inputFastaPath)
def ChangeFastaHeadersMultiprocessing(bundle):
"""Creates map of bedtools getfasta-style features, reads in
inputFasta, writes newFasta, deletes inpuFasta, renames
newFasta as inputFasta
"""
inputFastaPath = bundle[0]
inputGFFpath = bundle[1]
attribute=bundle[2]
bedtoolsIDmap = bedtoolsid2attr(inputGFFpath, attr=attribute)
newFasta = '{0}.new.tmp'.format(inputFastaPath)
header_pattern='(.+?:\d+?-\d+?)(?:$|\D)'
rename_fasta_seq_headers(inputFastaPath,
header_pattern,
bedtoolsIDmap,
newFasta)
os.replace(newFasta, inputFastaPath)
def mergeCoords(A,B):
"""
Takes two tuples and outputs two tuples, which will be identical
if the original overlap otherwise will be the originals
A = (a1, a2), B = (b1, b2) and a1<=b1, a1<=a2, b1<=b2
case 1: a2<=b1 ---> output originals
case 2: b1<a2 && b2>a2 ---> output (a1, b2)
case 3: b2<=a2 ---> output A
"""
assert (min(A) <= min(B)), (
'tuples given to mergeCoords in wrong order: A={0}, B={1}').format(A,B)
if min(B) >= max(A):
return ((A,B), 0)
elif min(B) < max(A) and max(B) > max(A):
output = (min(A),max(B))
return ((output, output), 1)
elif max(B) <= max(A):
return ((A,A), 2)
else:
raise Exception(
'Unexpected result from mergeCoords(A,B) using A={0}, B={1}'.format(
A,B))
def append2logfile(directory, logfilename, content):
"""Appends string 'content' to directory/logfilename"""
with open('{0}/{1}'.format(directory, logfilename), 'a') as logfile:
logtime = datetime.now().strftime('%Y-%m-%d_%H:%M:%S')
logfile.write('{0}\n'.format(logtime))
logfile.write('{0}\n\n'.format(content))
def write2summary(text):
"""Write text to a hardcoded summary file at output_dir/summary"""
scriptpath = os.path.realpath(__file__)
lineno = getframeinfo(currentframe()).lineno + 1
append2logfile(paths['output_top_dir'],
mainlogfile,
'line {1} in {2}\nWriting to summary file at {0}'.format(
'{0}/summary'.format(
paths['output_top_dir']),
lineno,
scriptpath))
with open('{0}/summary'.format(paths['output_top_dir']), 'a') as summaryFl:
summaryFl.write('{0}\n'.format(text))
def makecall(call, stdout = None, stderr = None, stdin = None):
"""Handles running subprocess.call. Used when making calls without
multiprocessing
"""
if stdout == None and stderr == None and stdin == None:
subprocess.call(call)
elif stdout != None:
with open(stdout, 'w') as outfl:
if stderr != None:
with open(stderr, 'w') as errfl:
if stdin == None:
subprocess.call(call, stdout=outfl, stderr=errfl)
else:
with open(stdin, 'r') as inFl:
subprocess.call(call,
stdin=inFl,
stdout=outfl,
stderr=errfl)
elif stderr == None:
if stdin == None:
subprocess.call(call, stdout=outfl)
else:
with open(stdin, 'r') as inFl:
subprocess.call(call, stdin=inFl, stdout=outfl)
elif stderr != None and stdout == None:
with open(stderr, 'w') as errfl:
if stdin == None:
subprocess.call(call, stderr=errfl)
else:
with open(stdin, 'r') as inFl:
subprocess.call(call, stdin=inFl, stderr=errfl)
elif stdin != None and stderr == None and stdout == None:
with open(stdin, 'r') as inFl:
subprocess.call(call, stdin=inFl)
def makecallMultiprocessing(callBundle):
"""Handles running subprocess.call when using multiprocessing.
Used to iterate over calls with Pool().map
"""
call = callBundle[0]
stdout = callBundle[1]
stderr = callBundle[2]
stdin = callBundle[3]
if stdout == None and stderr == None and stdin == None:
subprocess.call(call)
elif stdout != None:
with open(stdout, 'w') as outfl:
if stderr != None:
with open(stderr, 'w') as errfl:
if stdin == None:
subprocess.call(call, stdout=outfl, stderr=errfl)
else:
with open(stdin, 'r') as inFl:
subprocess.call(call,
stdin=inFl,
stdout=outfl,
stderr=errfl)
elif stderr == None:
if stdin == None:
subprocess.call(call, stdout=outfl)
else:
with open(stdin, 'r') as inFl:
subprocess.call(call, stdin=inFl, stdout=outfl)
elif stderr != None and stdout == None:
with open(stderr, 'w') as errfl:
if stdin == None:
subprocess.call(call, stderr=errfl)
else:
with open(stdin, 'r') as inFl:
subprocess.call(call, stdin=inFl, stderr=errfl)
elif stdin != None and stderr == None and stdout == None:
with open(stdin, 'r') as inFl:
subprocess.call(call, stdin=inFl)
def MakeDir(pathsname, path):
"""Makes a directory path and stores it in the global dict paths
under the key pathsname and writes to logfile.
"""
global paths
paths[pathsname] = path
if not os.path.exists(path):
os.makedirs(path)
scriptpath = os.path.realpath(__file__)
lineno = getframeinfo(currentframe()).lineno + 1
append2logfile(paths['output_top_dir'],
mainlogfile, (
'line {2} in {3}\nCreated dir for {0}:\n{1}').format(pathsname,
path,
lineno,
scriptpath))
def addStrandToGFF(strandDct, GFFpth):
"""Updates strand field for element with ? as strand based on Dfam
and Repbase results. Provide a dictionary with LTR RT # (e.g. 4 for
LTR_retrotransposon4) as keys and strand as values. A new GFF will
be written, and the old one removed.
"""
newgff = '{0}.updatingstrandinprocess'.format(GFFpth)
if os.path.exists(newgff):
os.remove(newgff)
with open(GFFpth) as inFl:
for line in inFl:
if not line.startswith('#'):
try:
gffLine = GFF3_line(line)
except:
print(line)
sys.exit()
if gffLine.strand == '?':
if 'Parent' in gffLine.attributes:
elNum = re.search('\d*$',
gffLine.attributes['Parent']
).group(0)
elif 'ID' in gffLine.attributes:
elNum = re.search('\d*$',
gffLine.attributes['ID']
).group(0)
else:
print(('WARNING:\taddStrandToGFF() found the following '
'GFF file to contain the following line where '
'strand is unknown and the attributes lack ID or '
'Parent keys\n{0}\n{1}').format(GFFpth,
line.strip()),
file=sys.stderr)
if elNum in strandDct:
if elNum == '?':
continue
gffLine.strand = strandDct[elNum]
with open(newgff, 'a') as outGFFfl:
outGFFfl.write(str(gffLine)+'\n')
else:
with open(newgff, 'a') as outGFFfl:
outGFFfl.write(line)
else:
with open(newgff, 'a') as outGFFfl:
outGFFfl.write(line)
else:
with open(newgff, 'a') as outGFFfl:
outGFFfl.write(line)
os.rename(newgff, GFFpth)
def RemoveNonLTRretrotransposons(LTRdigestGFFfl,
annotAttr2DbDict,
outputFlName,
REPORTCONFLICTS=True,
KEEPCONFLICTS=False,
KEEPNOCLASSIFICATION=False,
logFilePth='conflictingAnnotations.log'):
"""Removes non-LTR retrotransposons from LTRdigest GFF3 input based
on classifications from e.g. Repbase or Dfam
Parses LTRdigestGFFfl and checks attributes specified in
annotAttr2DbDict for annotations and looks for them in the Db
specified in annotAttr2DbDict. If found, that element is output.
If conflicting annotations are found, REPORTCONFLICTS=True writes
conflicts to logfile at logFilePth; if KEEPCONFLICTS=True,
the element is retained in the output GFF.
Structure of annotAttr2DbDict should be:
{ attr1:DbFlName1, ... }
where attr are keys in the attributes field of the input GFF3 that
contain classification information derived from the database of
which DbFlName should be the subset of classifications in the
database that are LTR retrotransposons.
If an attribute's value is "None", it is treated as "no
information". If all attributes specified in annotAttr2DbDict are
"None" and KEEPNOCLASSIFICATION=True, that element is output.
"""
LTR_retrotransposon_GFF_lines = {}
FOUNDNONLTR = False
Db_LTR_retrotransposon_features = {}
Db_files = list(annotAttr2DbDict.values())
for dbFlPth in Db_files:
with open(dbFlPth) as dbFl:
for line in dbFl:
flName = dbFlPth.split('/')[-1]
if flName in Db_LTR_retrotransposon_features:
Db_LTR_retrotransposon_features[flName].add(line.strip())
else:
Db_LTR_retrotransposon_features[flName] = set(
[line.strip()])
logfile = open(logFilePth, 'a')
logfile.write(('#Conflicting annotations (e.g. Dfam->Copia Repbase->Gypsy) '
'are reported. If an annotation is Unknown it does not count '
'as a conflict\n'))
with open(LTRdigestGFFfl) as gffFl:
for line in gffFl:
if line.startswith('#'):
continue
gffLine = GFF3_line(line)
# First line in LTR retrotransposon block in LTRdigest GFF3
if gffLine.type == 'repeat_region':
FOUNDNONLTR = False
if gffLine.type in LTR_retrotransposon_GFF_lines:
sys.exit('Line\n{0}\nout of order'.format(line.strip()))
# add repeat_region line to output ('true positive') set
LTR_retrotransposon_GFF_lines[
gffLine.attributes['ID']] = [ line.strip() ]
continue
elif gffLine.type == 'LTR_retrotransposon':
## Check if LTR
NoClassification = []
LTRmatching = {}
# Check database true positives list# Check database
# true positives list
for attr in annotAttr2DbDict:
db = annotAttr2DbDict[attr].split('/')[-1]
annot = gffLine.attributes[attr]
if not annot == 'None':
if (annot in Db_LTR_retrotransposon_features[db]
or annot == 'Unknown'):
# is homologous to LTR retrotransposon in
# given db
LTRmatching[attr] = True
else:
# homologous to a non-LTR retrotransposon
# in given db. Flag for removal as 'false
# positive'
LTRmatching[attr] = False
else:
# not homologous to a known LTR RT in given db.
NoClassification.append('None')
LTRmatching_values = list(LTRmatching.values())
if True in LTRmatching_values and False in LTRmatching_values:
# Found conflicting annotations: LTR and Non-LTR
if REPORTCONFLICTS:
logfile.write(
'{0}\thas conflicting annotations LTR and Non-LTR\t{1}\n'.format(
gffLine.attributes['Parent'],
'\t'.join(['{0}={1}'.format(
attr, gffLine.attributes[attr])
for attr in LTRmatching]
)))
if KEEPCONFLICTS:
LTR_retrotransposon_GFF_lines[
gffLine.attributes['Parent']].append(line.strip())
else:
FOUNDNONLTR = True
del(LTR_retrotransposon_GFF_lines[
gffLine.attributes['Parent']])
continue
# no demonstrated homology to LTR RT in any db
elif 'None' in NoClassification and LTRmatching_values == []:
if KEEPNOCLASSIFICATION:
LTR_retrotransposon_GFF_lines[
gffLine.attributes['Parent']].append(line.strip())
continue
del(LTR_retrotransposon_GFF_lines[
gffLine.attributes['Parent']])
FOUNDNONLTR = True
continue
# no demonstratd homology to LTR RT in any db
elif NoClassification == [] and LTRmatching_values == []:
logfile.write('{0}\thas no classification\n'.format(
gffLine.attributes['Parent']))
FOUNDNONLTR = True
del(LTR_retrotransposon_GFF_lines[
gffLine.attributes['Parent']])
continue
# homology to non-LTR retrotransposon in a db
elif False in LTRmatching_values:
del(LTR_retrotransposon_GFF_lines[
gffLine.attributes['Parent']])
FOUNDNONLTR = True
continue
else:
LTR_retrotransposon_GFF_lines[
gffLine.attributes['Parent']].append(line.strip())
continue
else:
if FOUNDNONLTR:
continue
parent = gffLine.attributes['Parent']
if 'LTR_retrotransposon' in parent:
parent = 'repeat_region{0}'.format(parent.lstrip(
'LTR_retrotransposon'))
if not parent in LTR_retrotransposon_GFF_lines:
sys.exit(('Line\n{0}\nParent attribute not in LTR '
'retrotransposon dictionary').format(line.strip()))
LTR_retrotransposon_GFF_lines[parent].append(line.strip())
with open(outputFlName, 'w') as outFl:
for element in sorted(list(LTR_retrotransposon_GFF_lines.keys())):
if LTR_retrotransposon_GFF_lines[element] != []:
for line in LTR_retrotransposon_GFF_lines[element]:
outFl.write(line.strip()+'\n')
outFl.write('###\n')
logfile.close()
def writeLTRretrotransposonInternalRegions(inputGFFpth,
outputGFFpth,
elementSet = None,
truncateParent = False):
"""Requires Class GFF3_line
Writes GFF3 for region between two LTRs from a LTRharvest-type file
Only for elements in elementSet if provided, if elementSet == None,
all elements are written. if truncateParent=True, Parent attribute
has 'LTR_retrotranspson' trimmed from it
"""
with open(inputGFFpth, 'r') as inGFF:
currentNewElement = GFF3_line()
for line in inGFF:
if '\tlong_terminal_repeat\t' in line:
gffLine = GFF3_line(line)
if elementSet == None or (elementSet != None
and gffLine.attributes[
'Parent']
in elementSet):
if not currentNewElement.start == None:
if truncateParent == True:
gffLine.attributes[
'Parent'] = gffLine.attributes[
'Parent'].lstrip(
'LTR_retrotransposon')
currentNewElement.end = gffLine.start
if (currentNewElement.end
- currentNewElement.start
+ 1) <= 0:
currentNewElement = GFF3_line()
continue
assert currentNewElement.attributes['Parent'] == gffLine.attributes['Parent'], (
'GFF long_terminal_repeats may be out of '
'order. Check near {0} or {1} in {2}').format(
currentNewElement.attributes['Parent'],
gffLine.attributes['Parent'],
inputGFFpth)
currentNewElement.seqid = gffLine.seqid
currentNewElement.source = 'PhyLTR'
currentNewElement.type = \
'LTR_retrotransposon_InternalRegion'
currentNewElement.score = '.'
currentNewElement.strand = gffLine.strand
currentNewElement.phase = '.'
with open(outputGFFpth, 'a') as outGFFfl:
outGFFfl.write('{0}\n'.format(
str(currentNewElement)))
currentNewElement = GFF3_line()
else:
currentNewElement.start = gffLine.end
if truncateParent == True:
currentNewElement.attributes[
'Parent'] = gffLine.attributes[
'Parent'].lstrip(
'LTR_retrotransposon')
else:
currentNewElement.attributes[
'Parent'] = gffLine.attributes['Parent']
currentNewElement.attributes_order.append('Parent')
currentNewElement.refreshAttrStr()
def writeLTRretrotransposonGFF(inputGFFpth,
outputGFFpth,
elementSet = None,
REPEATREGION = False,
truncateParent = True):
"""Requires Class GFF3_line
Writes GFF3 for LTR_retrotransposon type features from a
LTRharvest-type file. Only for elements in elementSet if provided,
if elementSet == None, all elements are written. If
truncateParent=True, Parent attribute has 'LTR_retrotranspson'
trimmed from it. If REPEATREGION==True, extract entire repeat region
"""
global paths
if os.path.isfile(outputGFFpth):
os.remove(outputGFFpth)
scriptpath = os.path.realpath(__file__)
lineno = getframeinfo(currentframe()).lineno + 1
if not elementSet == None:
append2logfile(paths['output_top_dir'],
mainlogfile,
(('line {3} in {4}\n '
'Writing LTR_retrotransposon features:\n '
'{0}\nfrom:\n{1}\nto:\n{2}')).format(
','.join(sorted(list(elementSet))),
inputGFFpth,
outputGFFpth,
lineno,
scriptpath))
else:
append2logfile(paths['output_top_dir'],
mainlogfile,
('line {2} in {3}\nWriting LTR_retrotransposon features:\n '
'all elements\nfrom:\n{0}\nto:\n{1}').format(inputGFFpth,
outputGFFpth,
lineno,
scriptpath))
if REPEATREGION:
feat = '\trepeat_region\t'
else:
feat = '\tLTR_retrotransposon\t'
with open(inputGFFpth, 'r') as inGFF:
currentNewElement = GFF3_line()
for line in inGFF:
if feat in line:
gffLine = GFF3_line(line)
if elementSet == None or (elementSet != None
and gffLine.attributes[
'ID'] in elementSet):
with open(outputGFFpth, 'a') as outFl:
if truncateParent:
gffLine.attributes['ID'] = gffLine.attributes[
'ID'][19:]
gffLine.refreshAttrStr()
outFl.write(str(gffLine)+'\n')
def writeLTRsGFF(inputGFFpth, outputGFFpth, elementSet=None):
"""Requires Class GFF3_line
Writes one GFF3 for each pair of LTRs from a LTRharvest-type file.
Only for elements in elementSet if provided, if elementSet == None,
all elements are written. If truncateParent=True, Parent attribute
has 'LTR_retrotranspson' trimmed from it
"""
global paths
if os.path.isfile(outputGFFpth):
os.remove(outputGFFpth)
scriptpath = os.path.realpath(__file__)
lineno = getframeinfo(currentframe()).lineno + 1
append2logfile(paths['output_top_dir'],
mainlogfile,
('line {3} in {4}\nWriting long_terminal_repeat features:\n '
'{0}\nfrom:\n{1}\nto:\n{2}').format(
','.join(sorted(list(elementSet))),
inputGFFpth,
outputGFFpth,
lineno,
scriptpath))
with open(inputGFFpth, 'r') as inGFF:
currentNewElement = GFF3_line()
LTR_counts = {}
for line in inGFF:
if '\tlong_terminal_repeat\t' in line:
gffLine = GFF3_line(line)
if elementSet == None or (elementSet != None
and gffLine.attributes['Parent']
in elementSet):
with open(outputGFFpth, 'a') as outFl:
if gffLine.attributes['Parent'] in LTR_counts:
if LTR_counts[gffLine.attributes['Parent']] > 2:
sys.exit(('writeLTRsGFF found element {0} to '
'contain more that 2 LTRs in\n{1}').format(
gffLine.attributes['Parent'],
inputGFFpth))
gffLine.attributes['ID'] = gffLine.attributes[
'Parent'] + '_R'
LTR_counts[gffLine.attributes['Parent']] += 1
else:
gffLine.attributes['ID'] = gffLine.attributes[
'Parent'] + '_L'
LTR_counts[gffLine.attributes['Parent']] = 1
gffLine.attributes_order = ['ID', 'Parent']
gffLine.refreshAttrStr()
outFl.write(str(gffLine)+'\n')
def ltrharvest():
"""Runs LTRharvest. LTRharvest options can be specified on the
command line. See phyltr -h for defaults and phyltr -help for explanation.
"""
global paths
global filenames
if LTRHARVEST:
# If this is in paths this step has been completed. Skip
if not 'inputFastaSuffixArray' in paths:
MakeDir('suffixerator_dir', '{0}/suffixerator'.format(
paths['output_top_dir']))
paths['inputFastaSuffixArray'] = '{0}/{1}.index'.format(
paths['suffixerator_dir'],
paths['inputFasta'])
gt_suffixerator_call_string = ('gt suffixerator -db {1} '
'-indexname {0} '
'-dna -tis -suf -lcp '
'-des -ssp '
'1>suffixerator.stdout '
'2>suffixerator.stderr').format(
paths['inputFastaSuffixArray'],
paths['inputFasta'])
gt_suffixerator_call = [ executables['genometools'],
'suffixerator',
'-db',
paths['inputFasta'],
'-indexname',
paths['inputFastaSuffixArray'],
'-dna',
'-tis',
'-suf',
'-lcp',
'-des',
'-ssp' ]
scriptpath = os.path.realpath(__file__)
lineno = getframeinfo(currentframe()).lineno + 1
append2logfile(paths['output_top_dir'],
mainlogfile,
('line {2} in {3}\nBegan creating suffix array for '
'{0} using the call:\n{1}').format(
paths['inputFasta'],
gt_suffixerator_call_string,
lineno, scriptpath))
# Run suffixerator
makecall(gt_suffixerator_call,
'{0}/suffixerator.stdout'.format(
paths['suffixerator_dir']),
'{0}/suffixerator.stderr'.format(
paths['suffixerator_dir']))
scriptpath = os.path.realpath(__file__)
lineno = getframeinfo(currentframe()).lineno + 1
append2logfile(paths['output_top_dir'],
mainlogfile, ('line {0} in {1}\n '
'Finished gt suffixerator').format(lineno,
scriptpath) )
paths['suffixeratorInputFastaCopy'] = '{0}/{1}'.format(
paths['suffixerator_dir'],
filenames['inputFasta'])
copyfile(paths['inputFasta'], paths['suffixeratorInputFastaCopy'])
# Add suffix array path to status file (for resuming later)
with open('{0}/status'.format(
paths['output_top_dir']), 'a') as statusFlAppend:
statusFlAppend.write('inputFastaSuffixArray\t{0}\n'.format(
paths['inputFastaSuffixArray']))
# If this is in paths this step has been completed, skip