-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtptools
executable file
·1674 lines (1382 loc) · 63.3 KB
/
tptools
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
# Copyright (C) 2016 Shengwei Hou
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
import sys
import os
import re
import urllib
import argparse
import subprocess
import Bio
from Bio.Seq import Seq
from Bio import SeqIO
from Bio import motifs
from Bio.Alphabet import IUPAC
import numpy as np
from collections import Counter
from sys import stdout, stderr
from grptools import _read_grp, _group_tss, _get_ncol
def main_usage(parser):
""" display usage for main parser
"""
stderr.write(parser.format_help())
def subparser_usage(argv, parser):
""" display usage for subparser
"""
cmd = argv[1]
found = 0
for action in parser._actions:
if isinstance(action, argparse._SubParsersAction):
for choice, subparser in action.choices.items():
if cmd == choice:
stderr.write(subparser.format_help())
found = 1
if not found:
stderr.write("\n\nERROR:%s is not a valid command!!!\n\n"%cmd)
main_usage(parser)
def display_help(argv, parser):
""" display help information
"""
if len(argv) == 1:
main_usage(parser)
sys.exit(1)
elif len(argv) == 2:
subparser_usage(argv, parser)
sys.exit(1)
else:
pass
class BaseGffRecord(object):
""" This is the base class of GFF record, all the other GFF record types should be
inherited from this base GFF Record
"""
id2records = {} # store all the recordID:gffObj
def __init__(self, seqname, source, feature, start, end, score, strand, frame, attribute):
""" Initialize a BaseGffRecord object, use standard GFF format specification.
"""
self.seqname = seqname
self.source = source
self.feature = feature
self.start = int(start)
self.end = int(end)
self.score = str(score)
self.strand = strand
self.frame = str(frame)
self.attribute = attribute
self.attribute_dict = self._get_attribute_dict()
# add this gff record to id2records dict
BaseGffRecord.id2records.update({self.get_subattribute('ID'): self})
def _get_attribute_dict(self):
attribute_dict = {}
attri_list = self.attribute.strip().split(";")
# need to tackle with "note=codon recognized: UUG; tRNA-Leu (CAA);"
last_k, last_v = None, None
for attr in attri_list:
split_list = attr.strip().split("=")
if len(split_list) == 2:
if split_list[1] == '':
split_list[1] = 'None'
k = urllib.unquote(split_list[0])
v = urllib.unquote(split_list[1])
attribute_dict.update({k:v})
last_k, last_v = k, v
else:
assert len(split_list) == 1, "Attribute was not associated with a key, try to rescure!"
if last_k:
attribute_dict[last_k] += ","+urllib.unquote(split_list[0])
else:
raise Exception("No Key was found for this attribute %s!"%split_list[0])
return attribute_dict
def get_subattribute(self, subattribute):
subattr = self.attribute_dict.get(subattribute, None)
return subattr
def set_subattribute(self, subattribute, value):
if self.attribute_dict.has_key(subattribute):
self.attribute_dict[subattribute] = value
else:
self.attribute_dict.update({subattribute:value})
# once set new value, should change self.attribute and self.attribute_dict
self.attribute = ""
self.attribute += "ID="+self.attribute_dict["ID"]+";"
self.attribute += "Name="+self.attribute_dict["Name"]+";"
for k, v in self.attribute_dict.iteritems():
if k in ("ID", "Name"):
continue
else:
self.attribute += k+"="+v+";"
self.attribute = self.attribute.rstrip(";")
# update self.attribute_dict
self.attribute_dict = self._get_attribute_dict()
@staticmethod
def update_hierarchical_relationships():
for ID, gff in BaseGffRecord.id2records.iteritems():
parentID = gff.get_subattribute('Parent')
if parentID:
parent = BaseGffRecord.id2records[parentID]
parent.add_child(gff)
gff.set_parent(parent)
def __str__(self):
return self.seqname+"\t"+self.source+"\t"+self.feature+"\t"+\
str(self.start)+"\t"+str(self.end)+"\t"+self.score+"\t"+\
self.strand+"\t"+self.frame+"\t"+self.attribute+"\n"
class Gene(BaseGffRecord):
"""Gene records have children"""
id2genes = {} # store all the geneID:geneObj
def __init__(self, seqname, source, feature, start, end, score, strand, frame, attribute):
self.children = []
self.Name = None
self.product = None
super(Gene, self).__init__(seqname, source, feature, start, end, score, strand, frame, attribute)
# add this gene to id2genes dict
Gene.id2genes.update({self.get_subattribute('ID'):self})
def add_child(self, child):
if isinstance(child, BaseGffRecord):
self.children.append(child)
else:
print("Child should be GffRecord instance !")
def get_children(self, id2records):
return self.children
def _get_Name(self):
name = self.get_subattribute('Name')
if not name:
name = self.get_subattribute('locus_tag')
return name
def _get_product(self):
"""try to return gene's product first, if failed, then children's product"""
product = self.get_subattribute('product')
if not product and self.children:
product = self.children[0].get_subattribute("product")
return product
def update(self):
self.Name = self._get_Name()
self.product = self._get_product()
class Region(BaseGffRecord):
"""Region records"""
class CDS(BaseGffRecord):
"""CDS records"""
id2cds = {} # store all the cdsID:CDSObj
def __init__(self, seqname, source, feature, start, end, score, strand, frame, attribute):
self.parent = None
super(CDS, self).__init__(seqname, source, feature, start, end, score, strand, frame, attribute)
# add this cds to id2cds dict
CDS.id2cds.update({self.get_subattribute('ID'):self})
def set_parent(self, parent):
if isinstance(parent, Gene):
self.parent = parent
else:
print("Parent of CDS should be Gene instance !")
class RNA(BaseGffRecord):
"""RNA records, super class of tRNA, rRNA, ncRNA, misc_RNA, ..."""
id2rna = {} # store all the rnaID:RNAObject
def __init__(self, seqname, source, feature, start, end, score, strand, frame, attribute):
self.parent = None
self.children = []
super(RNA, self).__init__(seqname, source, feature, start, end, score, strand, frame, attribute)
# add this rna to id2rna dict
RNA.id2rna.update({self.get_subattribute('ID'):self})
def set_parent(self, parent):
if isinstance(parent, Gene):
self.parent = parent
else:
print("Parent of RNA should be Gene instance !")
def add_child(self, child):
if isinstance(child, BaseGffRecord):
self.children.append(child)
else:
print("Child of RNA should be BaseGffRecord instance !")
class tRNA(RNA):
"""tRNA records"""
class rRNA(RNA):
"""rRNA records"""
class tmRNA(RNA):
"""tmRNA records"""
class misc_RNA(RNA):
"""misc_RNA records"""
class ncRNA(RNA):
"""ncRNA"""
class Exon(RNA):
"""exon"""
class Transcript(RNA):
"""transcript"""
class repeat_Region(BaseGffRecord):
"""repeat_region"""
class riboswitch(BaseGffRecord):
"""riboswitch"""
class GffRecordParser(object):
""" This class used to parse gff3 file, to generate BaseGffRecord instances
"""
# constructors to initialize gff instances
constructors = {'region':Region,
'gene':Gene,
'cds':CDS,
'trna':tRNA,
'rrna':rRNA,
'tmrna':tmRNA,
'misc_rna':misc_RNA,
'ncrna':ncRNA,
'srp_rna':ncRNA,
'rnase_p_rna':ncRNA,
'riboswitch':riboswitch,
'repeat_region':repeat_Region,
'transcript':Transcript,
'exon':Exon
}
def __init__(self, handle_or_fileStr):
self.handle = handle_or_fileStr
self.genome_info = None
def _line_parser(self):
# judge file opened or not
if not hasattr(self.handle, "read"):
handle = open(self.handle, "r")
else:
handle = self.handle
while True:
line = handle.readline()
if not line:
# close file handle
try:
handle.close()
except Exception as e:
print(e)
break
else:
if line.startswith("#"):
continue
else:
gff_line_list = line.strip().split("\t")
feature = gff_line_list[2].lower()
constructor = GffRecordParser.constructors.get(feature, None)
if constructor is None:
print("No constructor was found for feature: %s, use BaseGffRecord instead."%feature)
constructor = BaseGffRecord
gff_record = constructor(*gff_line_list)
yield gff_record
def __iter__(self):
return self._line_parser()
class TATA(object):
"""
-8/-4
Pribnow box 5'-TATAAT-3'--TSS Prokayrotic
TATA box 5'-TATAAT-3'--TSS Eukaryotic
-27/-21
-36/-20
"""
scoreMatrix = {"AA":1, "AT":0, "AG":0, "AC":0,
"TA":0, "TT":1, "TG":0, "TC":0,
"GA":0, "GT":0, "GG":1, "GC":0,
"CA":0, "CT":0, "CG":0, "CC":1}
naive_tata_box = []
def __init__(self, tss, seq, strand, genomePos, relativePos):
self.tss = tss
self.seq =seq
self.strand = strand
self.genomePos = genomePos
self.relativePos = relativePos
def __str__(self):
""" here we need to convert the 0-based coordinate to 1-based coordinate
"""
return self.tss.ID +"\t"+self.seq+"\t"+self.strand+"\t"+str(self.genomePos+1)+"\t"+str(self.relativePos+1)+"\n"
@classmethod
def get_genome_gc_content(cls, input_genome_fna):
"""
:param input_genome_fna: the genome fasta file
:return: gc content and gc_dict
"""
GC_dict = {"A": 0, "T": 0, "C": 0, "G": 0}
# if not a open handle, open it for read
if not hasattr(input_genome_fna, 'read'):
input_genome_fna = open(input_genome_fna, "r")
for line in input_genome_fna:
if line.startswith(">"):
continue
for char in line:
char = char.upper()
if char in GC_dict:
GC_dict[char] += 1
# if not closed, close it
if not input_genome_fna.closed:
input_genome_fna.close()
total_chars = sum([v for v in GC_dict.values()])
total_GC = sum([v for k, v in GC_dict.items() if k in {'G', 'C'}])
# calculate normalized gc_dict
nucl_dict = {k: v / float(total_chars) for k, v in GC_dict.iteritems()}
# calculate GC content
gc_cont = float(total_GC) / total_chars
return (gc_cont, nucl_dict)
@classmethod
def get_naive_tata_box_sequences(cls, total_tss, genomeSeq, init_cutoff = 200, startPos=-14, centroid = -10,
querySeq="TATAAT", min_match=3):
for tss in total_tss:
if tss.tss >= init_cutoff:
seq = cls.get_naive_single_TATA_seq(tss, genomeSeq, startPos, querySeq, centroid, min_match)
#print seq
if seq:
tss.set_subattribute('TATA', str(seq.seq).upper())
cls.naive_tata_box.append(seq)
@classmethod
def get_naive_single_TATA_seq(cls, tss, genomeSeq, startPos, querySeq, centroid, min_match):
""" this function will take tss and genomeSeq as input, find the best-matched
querySeq in the region of -15 to 0 upstream of TSS, and return the matched
sequence, with a minimum cutoff that the naive matched score is more than 3.
"""
# get sequence of -15 ~ 0, upstream of TSS
if tss.strand == "+":
targetSeq = genomeSeq[tss.idx+startPos:tss.idx]
else:
assert tss.strand == "-", "tss strand should be -, not %s!"%tss.strand
targetSeq = genomeSeq[tss.idx:tss.idx-startPos].reverse_complement()
targetSeq = targetSeq.upper()
if "N" in targetSeq:
bestMatch = None
return bestMatch
# scan the targetSeq, to find best 6-mer TATA matches
bestScore = -1
bestMatch = None
relativePos = 0
for i in range(0, len(targetSeq)-len(querySeq)):
tmpSeq = targetSeq[i:i+6]
tmpScore = sum(cls.scoreMatrix[item] for item in [x[0]+x[1] for x in zip(tmpSeq, querySeq)])
tmpRelativePos = -1*(len(targetSeq) - i)
# only take at least min_match matched nucleotides as naive TATA sequence
if not tmpScore >=min_match:
continue
if tmpScore > bestScore:
bestScore = tmpScore
bestMatch = tmpSeq
relativePos = tmpRelativePos
elif tmpScore == bestScore:
# when tmpScore is equal to bestScore, then only if it closer to -10.5 will count
if abs(tmpRelativePos) - (-1*centroid) < relativePos -(-1*centroid):
bestScore = tmpScore
bestMatch = tmpSeq
relativePos = tmpRelativePos
else:
continue
return bestMatch
def get_naive_TATA_instances(input_tss, cutoff=200):
"""
:param cutoff: tss cutoff for naive tata sequence
:return: a list of naive tata sequences
"""
tss_dict = {} # {tss_ID:tss_promoterSeq}
# parse TSS file
tss_file = parse_tssFile(input_tss)
for tss in tss_file:
if tss.tss >= cutoff:
naive_TATA = tss.get_subattribute('TATA')
if naive_TATA != "None" and naive_TATA is not None:
naive_TATA = Seq(naive_TATA)
else:
continue
if tss.ID not in tss_dict:
tss_dict.update({tss.ID:naive_TATA})
else:
continue
print("Totally %d naive TATA sequences with cutoff %.2f"%(len(tss_dict), cutoff))
return tss_dict.values()
def create_motif_from_instances(input_instances, background):
"""
:param input_instances: a list of Seq instances with same length
:return:
"""
# create a Motif instance
if len(input_instances) >0 and isinstance(input_instances[0], Bio.SeqRecord.SeqRecord):
input_instances = [str(seq.seq) for seq in input_instances]
m = motifs.create(input_instances)
#print m
#print m.counts
#print m.consensus
# create a position-weight matrix, using background as peuducounts
pwm = m.counts.normalize(pseudocounts=background)
#print pwm
# position-specific scoring matrices
pssm = pwm.log_odds(background)
#print pssm
mean = pssm.mean(background)
std = pssm.std(background)
#print mean, std
return pssm
def get_refined_tata_instances(naive_pssm, total_tss, background, cutoff):
"""
:param pssm: position-specific scoring matrices
:param input_tss: input tss file
:param background: genome atcg content
:return:
"""
# get the naive pssm distribution and threshold, use false-positive rate: fpr=0.05
naive_distribution = naive_pssm.distribution(background=background, precision=10**4)
threshold = naive_distribution.threshold_fpr(0.05)
# get all refined instances
refined_TATA_instances = [] # collect all refined TATA instances
for tss in total_tss:
if tss.tss >= cutoff:
PromoterSeq = tss.get_subattribute('PromoterSeq')
# only cut region -14 to -4 to search refined TATA seq
PromoterSeq = Seq(PromoterSeq[-14:-4].upper(), alphabet=IUPAC.unambiguous_dna)
#print naive_pssm.alphabet
if 'N' not in PromoterSeq:
best_position = -1
best_score = -1
for position, score in naive_pssm.search(PromoterSeq, threshold):
if score > best_score and position > 0:
best_position = position
best_score = score
if best_position > 0:
#print "Best position %d: Best score = %5.3f" % (best_position, best_score)
#print PromoterSeq
refined_TATA = PromoterSeq[best_position:best_position+len(naive_pssm['A'])]
refined_TATA_instances.append(refined_TATA)
return refined_TATA_instances
def scoring_tss_probability(refined_pssm, total_tss, background):
"""
:param refined_pssm: pssm refined from init_cutoff
:param total_tss: all tss in a list
:param background: nucl_dict
:return:
"""
refined_distribution = refined_pssm.distribution(background=background, precision=10**4)
threshold = refined_distribution.threshold_fpr(0.05)
for tss in total_tss:
PromoterSeq = tss.get_subattribute('PromoterSeq')
# only cut region -14 to -4 to search refined TATA seq
PromoterSeq = Seq(PromoterSeq[-14:-4].upper(), alphabet=IUPAC.unambiguous_dna)
#print naive_pssm.alphabet
if 'N' not in PromoterSeq:
best_position = -1
best_score = -1
for position, score in refined_pssm.search(PromoterSeq, threshold=refined_pssm.min):
if score > best_score and position > 0:
best_position = position
best_score = score
if best_position > 0:
#print "Best position %d: Best score = %5.3f" % (best_position, best_score)
#print PromoterSeq
best_TATA = PromoterSeq[best_position:best_position+len(refined_pssm['A'])]
tss.set_subattribute('TATA', str(best_TATA))
tss.set_subattribute('TATA_log_odds', str(best_score))
class TSS():
fwd_pos2tss = {} # {position:TSS}
rev_pos2tss = {} # {position:TSS}
def __init__(self, idx, strand, tss, cov=None):
self.ID = None
self.idx = idx
self.strand = strand
self.tss = float(tss)
self.cov = 0 if cov is None else float(cov)
# here if no cov, then we assume this should not be a tss, set ratio to 0
self.TssCovRatio = 0 if self.cov == 0 else self.tss/self.cov # tss/cov
self.LocalTssEnrichmentScore = None # (upstream+TSS)/(upstream+TSS+downstream), the more sharp in up and down, the more like to be TSS
self.LocalCoverageEnrichmentScore = None # downstream/(upstream+downstream), the more adjacent to 1, the more steep after this TSS, the more likely
self.type = None
self.CurrentGene = None # which gene tss locates in current strand
self.DownstreamGene = None # gene downstream of tss in current strand
self.NearestAntiStrandGene = None # nearest gene in anti strand
self.description = None
self.product = None
self.merged_cov_region = None # a tuple represent the start and end pos of merged coverage region, will be used in gTSS_check
self.attribute=None
self.attribute_dict = None
self.counts = []
# update this TSS instance to pos2tss
if self.strand == "+":
TSS.fwd_pos2tss.update({self.idx:self})
else:
assert self.strand == "-", "TSS strand should be + or - !"
TSS.rev_pos2tss.update(({self.idx:self}))
def _replaceNone(self, item):
if item is None:
return "None"
else:
return str(item)
def _get_Name(self, item):
try:
name = item.Name
except Exception as e:
name = "None"
return name
def _get_Locus_tag(self, item):
try:
locus_tag = item.get_subattribute('locus_tag')
except Exception as e:
locus_tag = "None"
return locus_tag
def set_attribute_dict_from_string(self, attributeString):
self.attribute = attributeString
attribute_dict = {}
attri_list = self.attribute.strip().split(";")
# need to tackle with "note=codon recognized: UUG; tRNA-Leu (CAA);"
last_k, last_v = None, None
for attr in attri_list:
split_list = attr.strip().split("=")
if len(split_list) == 2:
if split_list[1] == '':
split_list[1] = 'None'
k = urllib.unquote(split_list[0])
v = urllib.unquote(split_list[1])
attribute_dict.update({k: v})
last_k, last_v = k, v
else:
assert len(split_list) == 1, "Attribute was not associated with a key, try to rescure!"
if last_k:
attribute_dict[last_k] += "," + urllib.unquote(split_list[0])
else:
raise Exception("No Key was found for this attribute %s!" % split_list[0])
self.attribute_dict = attribute_dict
def update_attribute_dict(self):
# update ID
if self.type is not None:
self.ID = self.type + self.strand + str(self.idx+1)
# update attribute dict
self.attribute_dict = {}
self.attribute_dict.update({'ID':self.ID, 'Name':self.ID,
'LocalTssEnrichmentScore':'%.2f'%float(self.LocalTssEnrichmentScore),
'LocalCoverageEnrichmentScore':'%.2f'%float(self.LocalCoverageEnrichmentScore),
'TssCovRatio':'%.2f'%float(self.TssCovRatio),
'CurrentGene': self._get_Name(self.CurrentGene),
'DownstreamGene':self._get_Name(self.DownstreamGene),
'NearestAntiStrandGene':self._get_Name(self.NearestAntiStrandGene),
'DownstreamGeneLocusTag':self._get_Locus_tag(self.DownstreamGene),
'color':'255+0+0'
})
# update attribute
self.attribute = ""
self.attribute += "ID=" + self.attribute_dict["ID"] + ";"
self.attribute += "Name=" + self.attribute_dict["Name"] + ";"
for k, v in self.attribute_dict.iteritems():
if k in ("ID", "Name"):
continue
else:
self.attribute += k + "=" + v + ";"
self.attribute = self.attribute.rstrip(";")
def get_subattribute(self, subattribute):
subattr = self.attribute_dict.get(subattribute, None)
return subattr
def set_subattribute(self, subattribute, value):
if self.attribute_dict.has_key(subattribute):
self.attribute_dict[subattribute] = value
else:
self.attribute_dict.update({subattribute: value})
# once set new value, should change self.attribute and self.attribute_dict
self.attribute = ""
self.attribute += "ID=" + self.attribute_dict["ID"] + ";"
self.attribute += "Name=" + self.attribute_dict["Name"] + ";"
for k, v in self.attribute_dict.iteritems():
if k in ("ID", "Name"):
continue
else:
self.attribute += k + "=" + v + ";"
self.attribute = self.attribute.rstrip(";")
def __str__(self):
return self.ID + "\t" + str(self.tss) + "\t" + self.type + "\t" + str(self.idx + 1) + "\t" + \
str(self.idx + 1) + "\t" + self._replaceNone(self.description) + "\t" + \
self.strand + "\t" + self._replaceNone(self.product) + "\t" + self.attribute
def _calculate_local_TSS_enrichment_score(idx, strand, tss_arr, length=100):
"""This function used to calculate the local tss enrichment score for a given tss and enrichment length,
the more a TSS obvious, the surrounding tss are more less obvious, in a certain region, like 100nt,
if we assume only one TSS for each genes in this region.
"""
currCount = tss_arr[idx]
if strand == "+":
currCount = idx
sum_upstream = sum(tss_arr[idx-length:idx])
sum_downstream = sum(tss_arr[idx+1:idx+length+1])
#le = (sumleft+currCount)/(sumleft+sumright+currCount) # local enrichment
ltes = currCount/(sum_upstream+sum_downstream+currCount)
else:
currCount = tss_arr[idx]
sum_upstream = sum(tss_arr[idx+1:idx+length+1])
sum_downstream = sum(tss_arr[idx-length:idx])
#le = (sumleft+currCount)/(sumleft+sumright+currCount) # local enrichment
ltes = currCount/(sum_upstream+sum_downstream+currCount)
return ltes
def _calculate_local_cov_enrichment_score(idx, strand, cov_arr, length=10):
"""This function used to calculate the local coverage enrichment score for a given tss and enrichment length,
the more one TSS likely, the slope around this TSS should be more steep, so we can calculate the coverage
after this TSS, devide by coverage around this TSS, to get an coverage enrichment score
"""
if strand == "+":
sum_upstream = sum(cov_arr[idx-length:idx])
sum_downstream = sum(cov_arr[idx:idx+length]) # downstream including the TSS position
else:
strand == "-", "TSS strand should be + or -, not %s"%strand
sum_upstream = sum(cov_arr[idx+1:idx+1+length])
sum_downstream = sum(cov_arr[idx+1-length:idx+1]) # downstream including the TSS position
lces= float(sum_downstream)/(sum_upstream+sum_downstream)
return lces
def update_merged_cov_region(tss, merged_cov):
""" this function will be used to record the coverage > 1 region downstream
of tss, and will get a start and end tuple, recording the coordinate of
coverage region, which will be used in gTSS prediction
"""
# fwd tss, record coverage values after tss
if tss.strand == "+":
# then find all the idx that more than 1, to find the end region
for i, v in enumerate(merged_cov[tss.idx:]):
if v > 1:
continue
else:
tss.merged_cov_region =tuple([tss.idx, tss.idx+i])
break
# rev tss, record coverage values downstream tss
else:
assert tss.strand == "-", "tss strand should be -, not %s"%tss.strand
# then find all the idx that more than 1, append to the rdm_region list
rev_region = merged_cov[0:tss.idx]
for i, v in enumerate(rev_region[::-1]):
if v > 1:
continue
else:
tss.merged_cov_region = tuple([tss.idx-i, tss.idx])
break
def grp2TssTable(args):
"""parse grp file (should be aggregated by grptools), write out TSS table in the following format
#1-based_Pos strand tss cov
82944 + 100 150
82949 + 15 180
...
"""
dRNA_grp = args.dRNA_grp
prefix = args.prefix
if prefix:
outfile = prefix + "_grp2tss.tab"
else:
basename = os.path.basename(dRNA_grp)
filestem = os.path.splitext(basename)[0]
outfile = filestem + "_grp2tss.tab"
headers, arrays = _read_grp(dRNA_grp)
assert len(arrays) == 4, "Input grp file should have coverage and tss info for both strands, please check again!"
with open(outfile, "w") as oh:
oh.write("#1-based_Pos\tstrand\ttss\tcov\tTssCovRatio\tLocalCoverageEnrichmentScore\tLocalTssEnrichmentScore\n")
fwd_cov, fwd_tss, rev_cov, rev_tss = arrays
for i, (cov, tss) in enumerate(zip(fwd_cov, fwd_tss)):
if tss > 0:
idx = i
pos = idx + 1
if cov == 0:
cov = tss
if tss > cov:
tss = cov
TssCovRatio = tss/cov
lces = _calculate_local_cov_enrichment_score(idx,"+", fwd_cov, 10)
ltes = _calculate_local_TSS_enrichment_score(idx, "+", fwd_tss, 100)
oh.write(str(pos) +"\t+"+"\t"+str(tss)+"\t"+str(cov)+"\t%.2f"%TssCovRatio+"\t%.2f"%lces+"\t%.2f"%ltes+"\n")
for i, (cov, tss) in enumerate(zip(rev_cov, rev_tss)):
if tss > 0:
idx = i
pos = idx + 1
if cov == 0:
cov = tss
if tss > cov:
tss = cov
TssCovRatio = tss/cov
lces = _calculate_local_cov_enrichment_score(idx,"-", rev_cov, 10)
ltes = _calculate_local_TSS_enrichment_score(idx, "-", rev_tss, 100)
oh.write(str(pos) +"\t-"+"\t"+str(tss)+"\t"+str(cov)+"\t%.2f"%TssCovRatio+"\t%.2f"%lces+"\t%.2f"%ltes+"\n")
def _get_gene_dict_from_gff(gff_file):
""" this function used to generate fwd_gene_dict and rev_gene_dict from gff
"""
fwd_gene_dict = {} # data format {all_idx: fwd_gene}
rev_gene_dict = {}
fwd_gene_starts_dict = {} # data format {start_idx: fwd_gene}
rev_gene_starts_dict = {}
# read gff file and store gene info
gff_records = GffRecordParser(gff_file)
for gff in gff_records:
if isinstance(gff, Gene):
gene = gff
if gene.strand == "+":
fwd_gene_starts_dict.update({gene.start-1:gene})
for x in xrange(gene.start-1, gene.end):
if not fwd_gene_dict.has_key(x):
fwd_gene_dict.update({x:gene})
else:
# if two fwd gene overlap, assign this idx to latter one
fwd_gene_dict[x] = gene
else:
assert gene.strand == "-", "gene strand should be +/- !"
rev_gene_starts_dict.update({gene.end-1:gene})
# gff is 1-based, python is 0-based
for x in xrange(gene.start-1, gene.end):
if not rev_gene_dict.has_key(x):
rev_gene_dict.update({x:gene})
else:
# if two rev gene overlap, assign this idx to formmer one
continue
# update GFF relationships
BaseGffRecord.update_hierarchical_relationships()
# update Gene's Name and product
for gene in fwd_gene_starts_dict.values():
gene.update()
for gene in rev_gene_starts_dict.values():
gene.update()
return fwd_gene_dict, rev_gene_dict, fwd_gene_starts_dict, rev_gene_starts_dict
######################## find nearest gene ####################################
def getLeft(idx, Dict):
"""Find gene in Dict, at left direction of idx, return gene instance or None"""
left = False
while not left:
idx -= 1
if Dict.has_key(idx):
left=True
return Dict[idx]
if idx < 0:
left=True
return None
def getRight(idx, Dict, genomeLen):
"""Find gene in Dict, at right direction of idx, return gene instance or None"""
right = False
while not right:
idx += 1
if Dict.has_key(idx):
right = True
return Dict[idx]
if idx > genomeLen:
right=True
return None
def find_nearest_gene(tss, fwd_gene_dict, rev_gene_dict, fwd_gene_starts_dict,
rev_gene_starts_dict, genome_length):
""" take tss object and fwd/rev gene dict as inputs, will look for current
gene, upstream gene and downstream gene for this tss.
"""
idx, strand = tss.idx, tss.strand
# fwd tss
if strand == "+":
# update CurrentGene
CurrentGene = fwd_gene_dict.get(idx, None)
tss.CurrentGene = CurrentGene
# check current idx if a start or not
currentStart = fwd_gene_starts_dict.get(idx, None)
# update DownstreamGene
if CurrentGene and not currentStart:
DownstreamGene = getRight(CurrentGene.end, fwd_gene_dict, genome_length)
else:
DownstreamGene = getRight(idx, fwd_gene_dict, genome_length)
tss.DownstreamGene = DownstreamGene
# update NearestAntiStrandGene
antiCurrent = rev_gene_dict.get(idx, None)
if antiCurrent:
NearestAntiStrandGene = antiCurrent
else:
antiLeft = getLeft(idx, rev_gene_dict)
antiRight = getRight(idx, rev_gene_dict, genome_length)
if antiLeft and antiRight:
if idx - (antiLeft.end-1) >= (antiRight.start-1) - idx:
NearestAntiStrandGene = antiRight
else:
NearestAntiStrandGene = antiLeft
else:
if antiLeft:
NearestAntiStrandGene = antiLeft
elif antiRight:
NearestAntiStrandGene = antiRight
else:
NearestAntiStrandGene = None
tss.NearestAntiStrandGene = NearestAntiStrandGene
else:
assert strand == "-", "strand should be +/-, not %s !"%strand
# update CurrentGene
CurrentGene = rev_gene_dict.get(idx, None)
tss.CurrentGene = CurrentGene
# check current idx if a start or not
currentStart = rev_gene_starts_dict.get(idx, None)
# update DownstreamGene
if CurrentGene and not currentStart:
DownstreamGene = getLeft(CurrentGene.start-2, rev_gene_dict)
else:
DownstreamGene = getLeft(idx, rev_gene_dict)
tss.DownstreamGene = DownstreamGene
# update NearestAntiStrandGene
antiCurrent = fwd_gene_dict.get(idx, None)
if antiCurrent:
NearestAntiStrandGene = antiCurrent
else:
antiLeft = getLeft(idx, fwd_gene_dict)
antiRight = getRight(idx, fwd_gene_dict, genome_length)
if antiLeft and antiRight:
if idx - (antiLeft.end-1) >= (antiRight.start-1)-idx:
NearestAntiStrandGene = antiRight
else:
NearestAntiStrandGene = antiLeft
else:
if antiLeft:
NearestAntiStrandGene = antiLeft
elif antiRight:
NearestAntiStrandGene = antiRight
else:
NearestAntiStrandGene = None
tss.NearestAntiStrandGene = NearestAntiStrandGene
def gTSS_check(tss):
""" this function used to check gTSS
"""
DownstreamGene = tss.DownstreamGene