-
Notifications
You must be signed in to change notification settings - Fork 0
/
pyGTF.py
executable file
·1143 lines (1016 loc) · 38.1 KB
/
pyGTF.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding:utf-8 -*-
import bz2
import sys
import gzip
import logging
import argparse
from io import open
logging.basicConfig(
level=logging.INFO,
format='%(levelname)-5s @ %(filename)s:%(lineno)s, %(asctime)s, %(message)s',
stream=sys.stderr
)
logger = logging.getLogger(__name__)
# stdlog = logging.StreamHandler(sys.stdout)
# stdlog.setLevel(logging.INFO)
# formatter = logging.Formatter('%(asctime)-12s: %(levelname)-8s\n %(message)s')
# stdlog.setFormatter(formatter)
# logger.addHandler(stdlog)
class Files(object):
'''
open file as file handle for iterator
'''
def __init__(self, File):
self._fos = File
def __iter__(self):
if self._fos.lower().endswith(('.gz', '.gzip')):
fp = gzip.open(self._fos)
elif self._fos.lower().endswith('.bz2'):
fp = bz2.BZ2File(self._fos)
else:
fp = open(self._fos, encoding='utf-8')
for index, line in enumerate(fp):
if index % 50000 == 0 and index != 0:
logger.info('working on line NO. of {}: {:,}'.format(self._fos, index))
try:
# if isinstance(line, bytes):
line = line.decode('utf-8')
except:
pass
yield line
fp.close()
class Sequence(object):
'''
nucleic acid sequence object, contain seq, name and seq description
'''
def __init__(self, name, seq, descr=''):
self._id = name
self._seq = seq.strip()
self._descr = descr
@property
def name(self):
return self._id
@property
def seq(self):
return self._seq
@property
def descr(self):
return self._descr
@property
def length(self):
return len(self._seq)
@property
def is_empty(self):
return False if self._seq else True
def reverse_complement(self):
paired_rc = {
'A': 'T',
'T': 'A',
'C': 'G',
'G': 'C',
'N': 'N',
'a': 't',
't': 'a',
'c': 'g',
'g': 'c',
'n': 'n',
}
seq = ''.join([paired_rc[i] for i in self._seq[::-1]])
return Sequence(self._id, seq, self._descr)
def write_to_fasta_file(self, fp, chara=80):
if self._descr:
fp.write('>{} {}\n'.format(self._id, self._descr).decode('utf-8'))
else:
fp.write('>{}\n'.format(self._id).decode('utf-8'))
fp.write('{}'.format(self.__class__._seq_formater(self._seq, chara)).decode('utf-8'))
def write_to_tab_file(self, fp):
fp.write('{}\t{}\n'.format(self._id, self._seq).decode('utf-8'))
@classmethod
def _seq_formater(cls, seq, length):
tmp = ''
for i in range(0, len(seq), length):
tmp += seq[i : (i + length)] + '\n'
return tmp
class SequenceWithQual(Sequence):
'''
nucleic acid sequence object, contain seq, name and qual
'''
def __init__(self, name, seq, qual):
if len(seq) != len(qual):
raise Exception('length is Inconsistent seq and qual string')
self._id = name
self._seq = seq
# super().__init__(name, seq)
# Sequence.__init__(self, name, seq)
self._qual = qual
@property
def name(self):
return self._id
@property
def seq(self):
return self._seq
@property
def qual(self):
return [ord(i) for i in self._qual]
@property
def qualstr(self):
return self._qual
@property
def length(self):
return len(self._seq)
def write_to_fastq_file(self, fp):
fp.write('@{}\n'.format(self._id).decode('utf-8'))
fp.write('{}\n'.format(self._seq).decode('utf-8'))
fp.write('+\n{}\n'.format(self._qual).decode('utf-8'))
def write_to_fasta_file(self, fp):
fp.write('>{}\n'.format(self._id).decode('utf-8'))
fp.write('{}\n'.format(self._seq).decode('utf-8'))
class Fasta_Reader(Files):
'''
File parser for fasta file of nucleic acid
'''
def __init__(self, fasta):
Files.__init__(self, fasta)
def __iter__(self):
seq = None
for line in Files.__iter__(self):
if line.startswith('>'):
if seq:
yield Sequence(seqid, seq, descr)
seqid, _, descr = line.strip('>\t \n').partition(' ')
seq = ''
else:
assert seq is not None, 'FASTA file does not start with \'>\'.'
seq += line.strip()
yield Sequence(seqid, seq, descr)
class FastqFileError(Exception):
'''
'''
pass
class Fastq_Reader(Files):
'''
File parser for fastq file of nucleic acid
'''
def __init__(self, fastq):
self._fastq = fastq
Files.__init__(self, fastq)
def __iter__(self):
iter = Files.__iter__(self)
while True:
try:
seqid = next(iter)
except StopIteration:
break # end of file
try:
seq, _, qual = next(iter), next(iter), next(iter)
except StopIteration:
raise FastqFileError(
'incompelete Fastq file: {}\n'.format(self._fastq)
)
seqid, seq, qual = [i.strip('\t \n') for i in [seqid[1:], seq, qual]]
yield SequenceWithQual(seqid, seq, qual)
def phred_judge(self):
iter = Files.__iter__(self)
_, _, _, qual = next(iter), next(iter), next(iter), next(iter)
phred = min([ord(i) for i in qual.strip()])
# phred = fromstring(qual, dtype=byte)
return 'phred+64' if phred > 64 else 'phred+33'
class Transcript(object):
'''
Transcript structure annotation information
Parameter
---------
Tid: sring
Transcript IDs
chro: sting
chromesome ID
start, end: int
0-based location
strand: string
choices from {-, +}
exon: list
[(exonstart1, exonend1), (exonstart2, exonend2), ]
cds: tuple
(cds start site, cds end site)
infor: dict
transcript_name, transcript_type: string
gene_id, gene_name, gene_type: string
'''
def __init__(self, Tid, chro, start, end, strand, exon, cds=None, infor=None):
self._id = Tid
self._chro = chro
self._start = start
self._end = end
self._strand = strand
self._exon = tuple([
(x, y) for x, y in sorted(set(exon), key=lambda x: x[0], reverse=False)
])
self._codingregion = cds
self._attributes = infor if infor else {}
self.__structure_data_validation()
self._utr5, self._cds, self._utr3 = self.__transcriptional_region_group()
def __structure_data_validation(self):
assert self._strand in ['-', '+'], 'unsupported strand Symbol, {-, +}'
for each in self._exon:
msg = '{}: Exon region Over range of the transcriptional region.'.format(self._id)
assert self._start <= each[0] < each[1] <= self._end, msg
if self._codingregion:
msg = 'Error CDS postion, support format: (start, end)'
assert len(self._codingregion) == 2, msg
start, end = self._codingregion
msg = '{}: CDS region Over range of the transcriptional region.'.format(self._id)
assert self._start <= start < end <= self._end, msg
def __transcriptional_region_group(self):
if self._codingregion:
cstart, cend = self._codingregion
if cstart == cend:
return (), (), ()
utr5 = [(x, y) for x, y in self._exon if x < cstart]
if utr5:
start, end = utr5.pop(); utr5.append((start, cstart))
cds = [(x, y) for x, y in self._exon if (cstart < y <= cend) or (cstart <= x < cend)]
if cds:
start, end = cds.pop(); cds.append((start, cend))
start, end = cds.pop(0); cds.insert(0, (cstart, end))
utr3 = [(x, y) for x, y in self._exon if y > cend]
if utr3:
start, end = utr3.pop(0); utr3.insert(0, (cend, end))
if self._strand == '-':
utr5, utr3 = utr3, utr5
return map(tuple, [utr5, cds, utr3])
else:
return (), (), ()
@property
def id(self):
return self._id
@property
def chro(self):
return self._chro
@property
def start(self):
'''
1-based
'''
return self._start + 1
@property
def end(self):
return self._end
@property
def strand(self):
return self._strand
@property
def bed(self):
'''
basic bed:
chro, start, end, name, score, strand
'''
return (self._chro, self._start, self._end, self._id, 0, self._strand)
@property
def exon(self):
return self._exon
@property
def exon_count(self):
return len(self._exon)
@property
def length(self):
return sum([(y - x) for x, y in self._exon])
@property
def cds(self):
return self._cds
@property
def length_cds(self):
return sum([(y - x) for x, y in self._cds])
@property
def name(self):
return self._attributes.get('transcript_name', self._id)
@property
def type(self):
return self._attributes.get('transcript_type', "")
@property
def gene_id(self):
return self._attributes.get('gene_id', self._id)
@property
def gene_name(self):
return self._attributes.get('gene_name', "")
@property
def gene_type(self):
return self._attributes.get('gene_type', "")
def del_version(self, sep='.'):
'''
remove version infor of transcript id, default version infor at '.' after
'''
tid = self._id
if sep in tid:
self._id = tid[:tid.rindex(sep)]
gid = self._attributes.get('gene_id', None)
if sep in gid:
self._attributes['gene_id'] = gid[:gid.rindex(sep)]
def id_modifer(self, func):
'''
modify transcript_id, gene_id
parameter
---------
func: function, recommend use lambda
'''
self._id = func(self._id)
self._attributes['gene_id'] = func(self.gene_id)
def to_gtf(self, fp):
'''
parameter
---------
fp: file handle for output standrand GTF file
'''
attr = self.__attri_of_gtfline()
RecordTranscript = (
self._chro, '.', 'transcript', self._start + 1, self._end, '.', self._strand, '.', attr,
)
tmp = zip(
('exon', 'CDS', '5UTR', '3UTR'),
(self._exon, self._cds, self._utr5, self._utr3)
)
RecordDetails = []
for label, region in tmp:
for start, end in region:
RecordDetails.append(
(self._chro, '.', label, start + 1, end, '.', self._strand, '.', attr)
)
order = False if self._strand == '+' else True
RecordDetails = sorted(RecordDetails, key=lambda x: x[3], reverse=order)
fp.write(self.__class__.__list2str(RecordTranscript))
for feature in RecordDetails:
fp.write(self.__class__.__list2str(feature))
def __attri_of_gtfline(self):
skipkeys = {
'gene_id', 'gene_name', 'gene_type', 'gene_biotype',
'transcript_id', 'transcript_name', 'transcript_type',
'transcript_biotype', 'Parent', 'ID', 'gene', 'gbkey', 'Name',
}
keepkeys = set(self._attributes.keys()) - skipkeys
attr = ['transcript_id "{}"; gene_id "{}"; '.format(self.id, self.gene_id), ]
keys = ['transcript_name', 'gene_name', 'transcript_type', 'gene_type']
for key in keys:
value = self._attributes.get(key, None)
if value:
attr.append('{} "{}"; '.format(key, value))
attr += ['{} "{}"; '.format(i, self._attributes[i]) for i in keepkeys]
return ''.join(attr)
@classmethod
def __list2str(cls, lst):
return '{}\n'.format('\t'.join([str(i) for i in lst])).decode('utf-8')
def to_bed(self, fp):
'''
parameter
---------
fp: file handle for output 12 columns bed file
'''
cstart, cend = self._codingregion if self._cds else (self._end, self._end)
exon_num = self.exon_count
exon_len = ''.join(['{},'.format(x[1] - x[0]) for x in self._exon])
exon_start = ''.join(['{},'.format(x[0] - self._start) for x in self._exon])
Record = (
self._chro,
self._start,
self._end,
self.name,
0,
self._strand,
cstart,
cend,
0,
exon_num,
exon_len,
exon_start,
)
fp.write(self.__class__.__list2str(Record))
def to_genePred(self, fp, refFlat=False):
'''
parameter
---------
fp: file handle for output GenePred file,
refFlat: bool
whether create refFlat style genePred, {True, False}
reference
---------
url: https://genome.ucsc.edu/FAQ/FAQformat#format9
'''
if self._codingregion:
cstart, cend = self._codingregion
else:
cstart, cend = self._end, self._end
exon_num = self.exon_count
estart = ''.join(['{},'.format(i[0]) for i in self._exon])
eend = ''.join(['{},'.format(i[1]) for i in self._exon])
Record = [
self.name,
self._chro,
self._strand,
self._start,
self._end,
cstart,
cend,
exon_num,
estart,
eend,
]
if refFlat:
Record.insert(0, self.gene_id)
fp.write(self.__class__.__list2str(Record))
def overlap_with(self, transcript):
'''
'''
flag = False
if self.chro == transcript.chro:
if (self.start <= transcript.start < self.end) or (self.start < transcript.end <= self.end):
flag = True
return flag
def __extract_seq(self, faidx, chro, start, end):
try:
seq = faidx[chro][start:end]
except KeyError:
seq = ''
logger.error('Chromesome("{}") does not exist in fasta file, Skip...'.format(chro))
return seq
def extract_genomic_seq(self, seqfp):
'''
parameter
---------
seqfp: dict
{chro: seq, }
'''
seq = self.__extract_seq(seqfp, self._chro, self._start, self._end)
obj = Sequence(
'{}'.format(self._id),
seq,
'genomic sequence, gene_id:{}'.format(self.gene_id)
)
if self._strand == '-':
obj = obj.reverse_complement()
return (obj, )
def extract_isoform_seq(self, seqfp):
'''
'''
seq = ''.join([self.__extract_seq(seqfp, self._chro, x, y) for x, y in self._exon])
obj = Sequence(
self._id, seq, 'transcript sequence, gene_id:{}'.format(self.gene_id)
)
if self._strand == '-':
obj = obj.reverse_complement()
return (obj, )
def extract_cds_seq(self, seqfp):
'''
'''
seq = ''.join([self.__extract_seq(seqfp, self._chro, x, y) for x, y in self._cds])
obj = Sequence(
self._id, seq, 'coding sequence, gene_id:{}'.format(self.gene_id)
)
if self._strand == '-':
obj = obj.reverse_complement()
return (obj, )
def extract_exon_seq(self, seqfp):
'''
'''
objlst = []
exon_num = self.exon_count
for index, (x, y) in enumerate(self._exon):
order = index + 1 if self._strand == '+' else exon_num - index
obj = Sequence(
'{}_exon{}'.format(self._id, order),
self.__extract_seq(seqfp, self._chro, x, y),
'exonic sequence, gene_id:{}'.format(self.gene_id),
)
if self._strand == '-':
obj = obj.reverse_complement()
objlst.append(obj)
return tuple(objlst)
def extract_intron_seq(self, seqfp):
'''
'''
objlst = []
intron_num = self.exon_count - 1
if intron_num >= 1:
for index in range(intron_num):
_, x = self._exon[index]
y, _ = self._exon[index + 1]
order = index + 1 if self._strand == '+' else intron_num - index
obj = Sequence(
'{}_intron{}'.format(self._id, order),
self.__extract_seq(seqfp, self._chro, x, y),
'intronic sequence, gene_id:{}'.format(self.gene_id),
)
if self._strand == '-':
obj = obj.reverse_complement()
objlst.append(obj)
return tuple(objlst)
def extract_utr5_seq(self, seqfp):
'''
'''
seq = ''.join([self.__extract_seq(seqfp, self._chro, x, y) for x, y in self._utr5])
obj = Sequence(
'{}_utr5'.format(self._id),
seq,
'5\' untranslated region sequence, gene_id:{}'.format(self.gene_id)
)
if self._strand == '-':
obj = obj.reverse_complement()
return (obj, )
def extract_utr3_seq(self, seqfp):
'''
'''
seq = ''.join([self.__extract_seq(seqfp, self._chro, x, y) for x, y in self._utr3])
obj = Sequence(
'{}_utr3'.format(self._id),
seq,
'3\' untranslated region sequence, gene_id:{}'.format(self.gene_id)
)
if self._strand == '-':
obj = obj.reverse_complement()
return (obj, )
def extract_utr_seq(self, seqfp):
'''
'''
utr5, = self.extract_utr5_seq(seqfp)
utr3, = self.extract_utr3_seq(seqfp)
return (utr5, utr3)
class GTF_Reader(Files):
'''
File parser for GTF/GFF file of gene annotation
'''
def __init__(self, gtf):
self._transcript_feature = {'mRNA', 'transcript'}
self._keep_feature = {
'CDS',
'exon',
'transcript',
'mRNA'
}
self._skip_feature = {
'Selenocysteine',
'start_codon',
'stop_codon',
'UTR',
'gene',
'five_prime_UTR',
'three_prime_UTR',
'five_prime_utr',
'three_prime_utr',
'3UTR',
'5UTR',
}
Files.__init__(self, gtf)
def __iter__(self):
t_id, t_chro = None, None
t_exon, t_cds, t_info = [], [], {}
for line in self.__read_gtf():
chro, _, feature, start, end, _, strand, _, attr, line_id = line
if t_id and ((t_id != line_id) or ((t_id == line_id) and (t_chro != chro))):
t_cds = sorted(t_cds, key=lambda x: x[0], reverse=False)
t_cds = (t_cds[0][0], t_cds[-1][-1])
logger.debug(t_cds)
yield Transcript(t_id, t_chro, t_start, t_end, t_strand, t_exon, t_cds, t_info)
t_exon, t_cds, t_info = [], [], {}
if feature in self._transcript_feature:
t_id = line_id
t_chro, t_start, t_end, t_strand = chro, start, end, strand
try:
t_info['gene_id'] = attr.pop('gene_id')
t_info['gene_name'] = attr.pop('gene_name')
except KeyError:
t_info['gene_id'] = attr.pop('Parent')
t_info['transcript_name'] = attr.pop('Name')
t_info.update(attr)
elif feature == 'exon':
t_exon.append((start, end))
elif feature == 'CDS':
t_cds.append((start, end))
t_cds = sorted(t_cds, key=lambda x: x[0], reverse=False)
t_cds = (t_cds[0][0], t_cds[-1][-1])
logger.debug(t_cds)
yield Transcript(t_id, t_chro, t_start, t_end, t_strand, t_exon, t_cds, t_info)
def safe_mode(self):
'''
parse structure data of GTF/GFF file as python object to memory,
safe_mode methods is Applicable to unsorted files,
the same transcript annotation line is no longer in the same block
'''
logger.info('Start Read gff file to python object...')
transcriptlst, annot = [], {}
for line in self.__read_gtf():
chro, _, feature, start, end, _, strand, _, attr, t_id = line
transcriptlst.append((chro, t_id))
if feature in self._transcript_feature:
annot.setdefault((chro, t_id), {})['pos'] = [chro, start, end, strand]
try:
geneid = attr.pop('gene_id')
except KeyError:
geneid = attr.pop('Parent')
t_info = {'gene_id': geneid}
t_info.update(attr)
annot[(chro, t_id)]['attri'] = t_info
elif feature == 'exon':
annot.setdefault((chro, t_id), {}).setdefault('exon', []).append((start, end))
elif feature == 'CDS':
annot.setdefault((chro, t_id), {}).setdefault('cds', []).append((start, end))
logger.info('Done of parse gff, sort transcript list...')
transcriptlst = sorted(
set(transcriptlst),
key=lambda x: transcriptlst.index(x),
reverse=False
)
logger.info('Done of sort transcript list.')
for CHR, iso in transcriptlst:
chro, start, end, strand = annot[(CHR, iso)]['pos']
assert CHR == chro, ''
exon = annot[(CHR, iso)].get('exon', None)
cds = annot[(CHR, iso)].get('cds', None)
t_info = annot[(CHR, iso)].get('attri', None)
if not any([exon, cds]):
exon = [(start, end)]
elif not exon:
exon = cds.copy()
if cds:
cds = sorted(cds, key=lambda x: x[0], reverse=False)
cds = (cds[0][0], cds[-1][-1])
yield Transcript(iso, chro, start, end, strand, exon, cds, t_info)
def __read_gtf(self):
logger.info((
'Skip known annotation feature: \n'
' ({})'.format(', '.join(self._skip_feature))
))
for line in Files.__iter__(self):
if line.startswith('#') or not line.strip():
continue
# logger.debug(line)
chro, source, feature, start, end, score, strand, frame, attr = line.strip().split('\t')
if feature not in self._keep_feature:
if feature not in self._skip_feature:
logger.warning('skip novel annotation feature: {}'.format(feature))
continue
start, end = int(start) - 1, int(end)
if '=' in attr:
attr = [i.strip().partition('=') for i in attr.split(';') if i.strip()]
attr = {i[0]: i[2].strip('\'\t\n\r"') for i in attr}
line_id = attr['ID'] if feature in self._transcript_feature else attr['Parent']
else:
attr = [i.strip().partition(' ') for i in attr.split(';') if i.strip()]
attr = {i[0]: i[2].strip('\'\t\n\r"') for i in attr}
line_id = attr['transcript_id']
yield chro, source, feature, start, end, score, strand, frame, attr, line_id
class RefSeq_GFF_Reader(Files):
'''
File parser for GFF file of gene annotation from NCBI RefSeq or Genome database
'''
def __init__(self, gtf, chrom=None):
Files.__init__(self, gtf)
self._chrom = self.__convert_chrom_id(chrom) if chrom else {}
def __convert_chrom_id(self, tab):
with open(tab, encoding='utf-8') as f:
tab = [i.strip().split()[:2] for i in f if not i.startswith('#')]
return {i[0]: i[1] for i in tab}
def __iter__(self):
genelst, annot = self.__parse_gff()
for CHR, gene in genelst:
for iso in annot[(CHR, gene)]:
chro, start, end, strand = annot[(CHR, gene)][iso]['infor']
assert CHR == chro, ''
chro = self._chrom.get(chro, chro)
exon = annot[(CHR, gene)][iso].get('exon', None)
cds = annot[(CHR, gene)][iso].get('cds', None)
attri = annot[(CHR, gene)][iso].get('attri', None)
if not any([exon, cds]):
exon = [(start, end)]
elif not exon:
exon = cds.copy()
if cds:
cds = sorted(cds, key=lambda x: x[0], reverse=False)
cds = (cds[0][0], cds[-1][-1])
yield Transcript(iso, chro, start, end, strand, exon, cds, attri)
def __parse_gff(self):
RegulateRegion = {
'DNAseI_hypersensitive_site',
'enhancer',
'enhancer_blocking_element',
'insulator',
'promoter',
'protein_binding_site',
'replication_regulatory_region',
'transcriptional_cis_regulatory_region',
}
logger.info((
'skip annotation feature as Regulating region: \n'
' ({})'.format(', '.join(RegulateRegion))
))
MotifRegion = {
'centromere',
'direct_repeat',
'microsatellite',
'tandem_repeat',
'mobile_genetic_element',
'nucleotide_motif',
'repeat_instability_region',
}
logger.info((
'skip annotation feature as Motif sequence region: \n'
' ({})'.format(', '.join(MotifRegion))
))
UnknownRegion = {
'cDNA_match',
'repeat_region',
'D_loop',
'match',
'region',
'origin_of_replication',
'sequence_feature',
'biological_region', # Igl
'sequence_alteration',
'CAGE_cluster',
'meiotic_recombination_region',
'mitotic_recombination_region',
}
logger.info((
'skip annotation feature of unknown: \n'
' ({})'.format(', '.join(UnknownRegion))
))
SkipRegion = UnknownRegion | MotifRegion | RegulateRegion
TRANSCRIPT = {
'mRNA',
'lnc_RNA',
'ncRNA',
'antisense_RNA',
'transcript', # non coding
'RNase_MRP_RNA',
'RNase_P_RNA',
'Y_RNA',
'tRNA',
'rRNA',
'snoRNA',
'snRNA',
'primary_transcript', # miRNA precursor seq
'miRNA',
'C_gene_segment',
'D_gene_segment',
'V_gene_segment',
'J_gene_segment',
'SRP_RNA',
'telomerase_RNA',
'vault_RNA',
'guide_RNA',
'scRNA',
}
logger.info((
'the following annotation feature as transcript: \n'
' ({})'.format(', '.join(TRANSCRIPT))
))
logger.info('Start Read gff file to python object...')
Gidlst, GAnnot, TAnnot, Tstructure = [], {}, {}, {}
for line in Files.__iter__(self):
if line.startswith('#') or not line.strip():
continue
chro, _, feature, start, end, _, strand, _, attr = line.strip().split('\t')
if feature in SkipRegion:
continue
start, end = int(start) - 1, int(end)
attr = [i.strip().partition('=') for i in attr.split(';') if i.strip()]
attr = {i[0]: i[2].strip('\'\t\n\r"') for i in attr}
Dbxref = [i.partition(':') for i in attr.pop('Dbxref', '').split(',')]
Dbxref = {i[0]: i[2].strip('\'\t\n\r"') for i in Dbxref}
attr.update(Dbxref)
if feature == 'gene' or feature == 'pseudogene':
line_id = attr.pop('ID')
Gidlst.append((chro, line_id))
GAnnot.setdefault((chro, line_id), {})['infor'] = [chro, start, end, strand]
attr['gene_name'] = attr.pop('Name')
attr['gene_type'] = attr.pop('gene_biotype')
GAnnot[(chro, line_id)]['attri'] = attr
elif feature in TRANSCRIPT:
g_id = attr.pop('Parent')
t_id = attr.pop('ID')
Gidlst.append((chro, g_id))
TAnnot.setdefault((chro, g_id), {}).setdefault(t_id, {})['infor'] = [chro, start, end, strand]
if feature == 'miRNA':
attr['transcript_id'] = attr.pop('product')
attr['transcript_name'] = attr.pop('gene')
attr['transcript_type'] = 'miRNA'
elif feature == 'tRNA':
attr['transcript_id'] = t_id
attr['transcript_name'] = t_id
attr['transcript_type'] = 'tRNA'
else:
attr['transcript_id'] = attr.get('transcript_id', t_id)
attr['transcript_name'] = attr.get('Name', t_id)
tmp = attr['gbkey']
attr['transcript_type'] = 'protein_coding' if tmp == 'mRNA' else tmp
TAnnot[(chro, g_id)][t_id]['attri'] = attr
elif feature == 'exon':
t_id = attr.pop('Parent')
Tstructure.setdefault((chro, t_id), {}).setdefault('exon', []).append((start, end))
elif feature == 'CDS':
t_id = attr.pop('Parent')
Tstructure.setdefault((chro, t_id), {}).setdefault('cds', []).append((start, end))
else:
logger.warning('skip novel annotation feature: {}'.format(feature))
logger.info('Done of Read gff, sort transcript list...')
Gidlst = sorted(
set(Gidlst), key=lambda x: Gidlst.index(x), reverse=False
)
logger.info((
'Done of sort transcript list, convert raw annot infor to '
'appropriate transcript structure annotation...'
))
annot = {}
for index, (CHR, gene) in enumerate(Gidlst):
if index % 5000 == 0 and index != 0:
logger.info('Already processed gene NO. : {}'.format(index))
infor_gene = GAnnot.get((CHR, gene), None)
infor_transcript = TAnnot.get((CHR, gene), None)
if infor_transcript is None:
logger.debug('Missing transcript feature line of gene: {}'.format(gene))
annot.setdefault((CHR, gene), {}).setdefault(gene, {})['infor'] = infor_gene['infor']
annot[(CHR, gene)][gene]['attri'] = infor_gene['attri']
annot[(CHR, gene)][gene]['exon'] = Tstructure.get((CHR, gene), {}).get('exon', None)
annot[(CHR, gene)][gene]['cds'] = Tstructure.get((CHR, gene), {}).get('cds', None)
else:
for iso in infor_transcript:
chro, start, end, strand = infor_transcript[iso]['infor']
attri = infor_transcript[iso]['attri']
if infor_gene:
G_chro, G_start, G_end, G_strand = infor_gene['infor']
msg = 'transcript({}) region over range of gene({}) region'.format(iso, gene)
assert G_start <= start < end <= G_end, msg
msg = 'chro is inconsistent of transcript({}) and gene({})'.format(iso, gene)
assert chro == G_chro, msg
msg = ('Transcription direction(strand) is inconsistent of '
'transcript({}) and gene({})').format(iso, gene)
assert strand == G_strand, msg
Gattr = infor_gene['attri']
attri.update(Gattr)
annot.setdefault((chro, gene), {}).setdefault(iso, {})['infor'] = infor_transcript[iso]['infor']
if attri.get('gene_type', '') == 'other':
attri['gene_type'] = attri['transcript_type']
annot[(chro, gene)][iso]['attri'] = attri
structure = Tstructure.get((chro, iso), Tstructure.get((chro, gene), {}))
annot[(chro, gene)][iso]['exon'] = structure.get('exon', None)
annot[(chro, gene)][iso]['cds'] = structure.get('cds', None)
logger.info('Done of parse gff.')
return Gidlst, annot
class Bed_Reader(Files):
'''
'''
def __init__(self, bed):
Files.__init__(self, bed)
def __iter__(self):
for line in Files.__iter__(self):
chro, start, end, name, _, strand, cstart, cend, _, _, elen, estart = line.strip().split('\t')
start, end, cstart, cend = map(int, [start, end, cstart, cend])
elen = [int(i) for i in elen.split(',') if i]
estart = [int(i) + start for i in estart.split(',') if i]
assert len(estart)==len(elen), 'Error line: {}'.format(line)
eend = [estart[i] + elen[i] for i, j in enumerate(elen)]
EXON = [(estart[i], eend[i]) for i, j in enumerate(estart)]
if cstart == cend:
CDS = []
attri = {'transcript_type': 'noncoding'}
else:
CDS = (cstart, cend)
attri = {'transcript_type': 'protein_coding'}
yield Transcript(name, chro, start, end, strand, EXON, CDS, attri)
class genePred_Reader(Files):
'''
'''
def __init__(self, refFlat):
Files.__init__(self, refFlat)