This repository has been archived by the owner on Aug 5, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathintronIC_iaod.py
5323 lines (4596 loc) · 176 KB
/
intronIC_iaod.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/python3
# the above uses specific Python version; allows script name in top
##!/usr/bin/env python3
# the above sources Python from $PATH
"""
usage: intronIC.py [-h] [-g GENOME] [-a ANNOTATION] -n SPECIES_NAME
[-q SEQUENCE_INPUT] [-e] [-s] [-nc] [-i] [-v]
[-m {matrix file}] [-r12 {reference U12 intron sequences}]
[-r2 {reference U2 intron sequences}] [--no_plot]
[--format_info] [-d] [-u] [-na] [-t 0-100] [-ns]
[--five_score_coords start stop]
[--three_score_coords start stop] [-bpc start stop]
[-r {five,bp,three} [{five,bp,three} ...]] [-b]
[--recursive] [--subsample_n SUBSAMPLE_N]
[--parallel_cv PARALLEL_CV]
intronIC (intron Interrogator and Classifier) is a script which collects all
of the annotated introns found in a genome/annotation file pair, and produces
a variety of output files (*.iic) which describe the annotated introns and
(optionally) their similarity to known U12 sequences. Without the '-m' flag,
there MUST exist a matrix file in the 'intronIC_data' subdirectory in the same
parent directory as intronIC.py, with filename 'scoring_matrices.fasta.iic'.
In the same data directory, there must also be a pair of sequence files (see
--format_info) with reference intron sequences named '[u2,
u12]_reference_set.introns.iic'
optional arguments:
-h, --help show this help message and exit
-e, --use_exons Use exon rather than CDS features to define introns
(default: False)
-s, --sequences_only Bypass the scoring system and simply report the intron
sequences present in the annotations (default: False)
-nc, --allow_noncanonical
Do not omit introns with non-canonical splicing
boundaries from scoring (default: False)
-i, --allow_multiple_isoforms
Include non-duplicate introns from isoforms other than
the longest in the scored intron set (default: False)
-v, --allow_intron_overlap
Allow introns with boundaries that overlap other
introns from higher-priority transcripts (longer
coding length, etc.) to be included. This will
include, for instance, introns with alternative 5′/3′
boundaries (default: False)
-m {matrix file}, --custom_matrices {matrix file}
One or more matrices to use in place of the defaults.
Must follow the formatting described by the
--format_info option (default: None)
-r12 {reference U12 intron sequences}, --reference_u12s {reference U12 intron sequences}
introns.iic file with custom reference introns to be
used for setting U12 scoring expectation, including
flanking regions (default: None)
-r2 {reference U2 intron sequences}, --reference_u2s {reference U2 intron sequences}
introns.iic file with custom reference introns to be
used for setting U12 scoring expectation, including
flanking regions (default: None)
--no_plot Do not output illustrations of intron
scores/distributions(plotting requires matplotlib)
(default: False)
--format_info Print information about the system files required by
this script (default: False)
-d, --include_duplicates
Include introns with duplicate coordinates in the
intron seqs file (default: False)
-u, --uninformative_naming
Use a simple naming scheme for introns instead of the
verbose, metadata-laden default format (default:
False)
-na, --no_abbreviation
Use the provided species name in full within the
output files (default: False)
-t 0-100, --threshold 0-100
Threshold value of the SVM-calculated probability of
being a U12 to determine output statistics (default:
90)
-ns, --no_sequence_output
Do not create a file with the full intron sequences of
all annotated introns (default: False)
--five_score_coords start stop
Coordinates describing the 5' sequence to be scored,
relative to the 5' splice site (e.g. position 0 is the
first base of the intron); half-closed interval
[start, stop) (default: (-3, 9))
--three_score_coords start stop
Coordinates describing the 3' sequence to be scored,
relative to the 3' splice site (e.g. position -1 is
the last base of the intron); half-closed interval
[start, stop) (default: (-5, 4))
-bpc start stop, --branch_point_coords start stop
Coordinates describing the region to search for branch
point sequences, relative to the 3' splice site (e.g.
position -1 is the last base of the intron); half-
closed interval [start, stop) (default: (-45, -5))
-r {five,bp,three} [{five,bp,three} ...], --scoring_regions {five,bp,three} [{five,bp,three} ...]
Intron sequence regions to include in intron score
calculations (default: ('five', 'bp'))
-b, --abbreviate_filenames
Use abbreviated species name when creating output
filenames (default: False)
--recursive Generate new scoring matrices and training data using
confident U12s from the first scoring pass. This
option may produce better results in species distantly
related to the species upon which the training
data/matrices are based, though beware accidental
training on false positives. Recommended only in cases
where clear separation between types is seen on the
first pass (default: False)
--subsample_n SUBSAMPLE_N
Number of sub-samples to use to generate SVM
classifiers; 0 uses the entire training set and should
provide the best results; otherwise, higher values
will better approximate the entire set at the expense
of speed (default: 0)
--parallel_cv PARALLEL_CV
Number of parallel processes to use during cross-
validation; increasing this value will reduce runtime
but may result in instability due to outstanding
issues in scikit-learn (default: 1)
required arguments (-g, -a | -q):
-g GENOME, --genome GENOME
Genome file in FASTA format (gzip compatible)
(default: None)
-a ANNOTATION, --annotation ANNOTATION
Annotation file in gff/gff3/gtf format (gzip
compatible) (default: None)
-n SPECIES_NAME, --species_name SPECIES_NAME
Binomial species name, used in output file and intron
label formatting. It is recommended to include at
least the first letter of the species, and the full
genus name since intronIC (by default) abbreviates the
provided name in its output (e.g. Homo_sapiens -->
HomSap) (default: None)
-q SEQUENCE_INPUT, --sequence_input SEQUENCE_INPUT
Provide intron sequences directly, rather than using a
genome/annotation combination. Must follow the
introns.iic format (see README for description)
(default: None)
"""
import argparse
import copy
import logging
import math
import os
import re
import random
import sys
import time
import gzip
import numpy as np
import warnings
# hacky way to ignore annoying sklearn warnings
# (https://stackoverflow.com/a/33616192/3076552)
def warn(*args, **kwargs):
pass
warnings.warn = warn
from scipy import stats as pystats
from bisect import bisect_left, bisect_right
from collections import Counter, defaultdict, deque
from functools import partial
from itertools import islice
from operator import attrgetter
from hashlib import md5
# from sklearn.metrics import roc_curve, roc_auc_score
# from sklearn.cluster import SpectralClustering
from sklearn import svm, preprocessing
from sklearn.base import clone
from sklearn.model_selection import GridSearchCV, train_test_split
from sklearn.metrics import f1_score
# improve sklearn parallel performance/stability
os.environ['JOBLIB_START_METHOD'] = 'forkserver'
# check for the plotting library required to produce
# optionall figures
try:
import matplotlib
matplotlib.use('Agg') # allow to run without X display server
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
CAN_PLOT = True
except ModuleNotFoundError:
CAN_PLOT = False
warnings.filterwarnings(action='ignore')
# Classes ####################################################################
class GFFLineInfo(object):
"""
Takes a gff3/gtf/gff annotation line, and returns available metadata
about it.
"""
def __init__(self, line, line_number):
self.bits = self.__split_on_tabs(line)
try:
self.region = self.bits[0]
try:
self.start = min(map(int, self.bits[3:5]))
self.stop = max(map(int, self.bits[3:5]))
except ValueError:
self.start = None
self.stop = None
self.strand = self.bits[6]
if self.strand not in ('+', '-'):
self.strand = '+'
if self.bits[7] in ['0', '1', '2']:
self.phase = int(self.bits[7])
else:
self.phase = '.'
self.infostring = self.bits[8]
self.feat_type = self.bits[2].lower()
self.parent = self.get_parent()
self.name = self.get_ID()
self.line_number = line_number
except TypeError:
raise
@staticmethod
def __split_on_tabs(l, n=9):
"""
Checks for a valid line (does not start with #).
Splits valid line on tabs, and returns a list of the bits
if the list length is <<n>>. Setting <<n>> to None will return
the split line regardless of length.
"""
if l.startswith('#'):
return None
l = l.strip()
columns = l.split("\t")
if n and len(columns) < n:
return None
return columns
@staticmethod
def __field_match(infostring, tags, delimiter, tag_order=False):
if tag_order:
# check for first match of tags in order
try:
tags = [next(t for t in tags if t.lower() in infostring.lower())]
except StopIteration:
return None
info_bits = infostring.split(delimiter)
try:
match = next(
e for e in info_bits
if any(p.lower() in e.lower() for p in tags))
except StopIteration: # no matches found
return None
if "=" in match:
substring = match.split("=")[1]
else:
substring = match.split()[1]
return substring.strip("\"")
def get_type(self, delimiter=';'):
"""
Classifies annotation lines into type categories,
taking into account edge cases like 'processed transcript'
and 'pseudogenic transcript'.
"""
og_type = self.bits[2].lower()
if og_type == 'mrna':
og_type = 'transcript'
if og_type in ('gene', 'transcript', 'exon', 'cds'):
return og_type
disqualifying = ['utr', 'start', 'stop']
if any(kw in og_type for kw in disqualifying):
return og_type
# Not an obvious type, so search for features of transcripts
# and genes in infostring to try to infer type
# check for explicit mention of transcript in ID
try:
id_string = next(
(f for f in delimiter.split(self.infostring)
if f.startswith("ID")))
if any(tag in id_string for tag in ('transcript', 'mrna')):
return 'transcript'
except StopIteration:
pass
gene_tags = ["gene_id", "geneId"]
transcript_tags = ["transcriptId", "transcript_ID"]
# Transcripts first because genes shouldn't have transcript IDs,
# but transcripts may have gene IDs
for ftype, tags in zip(
['transcript', 'gene'], [transcript_tags, gene_tags]
):
match = self.__field_match(self.infostring, tags, delimiter)
if match:
return ftype
else:
return og_type
def get_ID(self, delimiter=";"):
"""
Finds the ID of a given annotation file line.
"""
# first, do it the easy way
prefix = None
infostring = self.infostring
match = self.__field_match(infostring, ["ID="], delimiter)
if match:
return match
# Constrain feature types to simplify indexing
feat_type = self.feat_type
if feat_type == "mrna":
feat_type = "transcript"
# all get lowercased in the comparison
# if is no 'ID=', should reference self via others
gene_tags = ["ID=", "gene_id", "geneId"]
transcript_tags = ["ID=", "transcriptId", "transcript_ID"]
tag_selector = {
"gene": gene_tags,
"transcript": transcript_tags
}
try:
tags = tag_selector[feat_type]
except KeyError:
# get any ID available, prepended with the feature type
# to keep different features of the same transcript unique
prefix = self.feat_type
tags = ['transcriptID', 'transcript_ID', 'gene_ID', 'geneID']
match = self.__field_match(
infostring, tags, delimiter, tag_order=True)
# if nothing matches, return infostring if there's only
# one tag in it (common for gtf parent features)
if match is None and infostring.count(";") < 2:
match = infostring.split(";")[0]
if prefix:
match = '{}_{}'.format(prefix, match)
return match
def get_parent(self, delimiter=";"):
"""
Retrieves parent information from an annotation line.
"""
# do it the easy way first
infostring = self.infostring
match = self.__field_match(infostring, ["Parent="], delimiter)
if match:
return match
feat_type_converter = {"cds": "exon", "mrna": "transcript"}
feat_type = self.feat_type
if feat_type in feat_type_converter:
feat_type = feat_type_converter[feat_type]
child_tags = [
"Parent=", "transcript_ID",
"transcriptId", "proteinId", "protein_ID"
]
transcript_tags = ["Parent=", "gene_ID", "geneId"]
gene_tags = ["Parent="]
tag_selector = {
"gene": gene_tags,
"transcript": transcript_tags,
"exon": child_tags
}
try:
tags = tag_selector[feat_type]
except KeyError:
# tags = list(set(child_tags + transcript_tags))
tags = child_tags + transcript_tags
match = self.__field_match(infostring, tags, delimiter, tag_order=True)
if not match and feat_type == "transcript":
match = self.get_ID()
return match
class GenomeFeature(object):
"""
Features that all genomic entities should
have.
>start< and >stop< are always relative to positive strand, i.e.
>start< is always less than >stop<.
"""
count = 1
# __slots__ prevents objects from adding new attributes, but it
# significantly reduces the memory footprint of the objects
# in use. Idea from http://tech.oyster.com/save-ram-with-python-slots/
__slots__ = [
'line_number', 'region', 'start', 'stop', 'parent_type',
'strand', 'name', 'parent', 'seq', 'flank', 'feat_type', 'phase',
'upstream_flank', 'downstream_flank', 'family_size', 'unique_num'
]
def __init__(
self, line_number=None, region=None,
start=None, stop=None, parent_type=None,
strand=None, name=None, parent=None,
seq=None, flank=0, feat_type=None,
upstream_flank=None, downstream_flank=None,
family_size=None, phase=None
):
self.region = region
self.start = start
self.stop = stop
self.strand = strand
self.name = name
self.unique_num = self.__class__.count
self.feat_type = feat_type
self.parent = parent
self.parent_type = parent_type
self.family_size = family_size
self.line_number = line_number
self.phase = phase
self.seq = seq
self.flank = flank
self.upstream_flank = upstream_flank
self.downstream_flank = downstream_flank
@property
def length(self):
"""
Returns the length of the object, preferentially
inferring it from the start and stop coordinates,
then from the length of the full sequence.
"""
if not (self.start and self.stop):
if not self.seq:
return None
else:
return len(self.seq)
return abs(self.start - self.stop) + 1
def get_coding_length(self, child_type="cds"):
"""
Returns an integer value of the aggregate
length of all children of type child_type.
If child_type is None, returns aggregate
length of all children
"""
total = 0
while True:
# while children themselves have children, recurse
try:
children = [c for c in self.children if c.children]
for child in children:
total += child.get_coding_length(child_type)
except AttributeError:
try:
children = self.get_children(child_type)
total += sum(c.length for c in children)
except AttributeError: # if was called on exon or cds objects
total += self.length
break
break
return total
def set_family_size(self):
"""
Assigns family_size attribute to all children.
"""
try:
all_children = self.children
except AttributeError:
return
child_types = set([c.feat_type for c in all_children])
for ct in child_types:
siblings = [c for c in all_children if c.feat_type == ct]
sibling_count = len(siblings)
for sib in siblings:
sib.family_size = sibling_count
sib.set_family_size()
def compute_name(self, parent_obj=None, set_attribute=True):
"""
Returns a generated unique ID for the object
in question. Passing a parent object should
be preferred, as the ID is otherwise not
particularly informative (but is unique!)
"""
parent = self.parent
parent_type = self.parent_type
# Make a coord_id relative to parent's contents if possible
try:
# 1-based indexing
unique_num = parent_obj.children.index(self) + 1
# Otherwise, make relative to all made objects of same type
except AttributeError:
# every type should have this
unique_num = "u{}".format(self.unique_num)
coord_id = ("{}:{}_{}:{}".format(parent_type,
parent,
self.feat_type,
unique_num))
if set_attribute:
setattr(self, "name", coord_id)
return coord_id
def update(self, other, attrs=None):
"""
Updates attributes based on another object and
optional attribute filter list
"""
attrs_to_use = vars(other) # use all if not attrs
if attrs:
attrs_to_use = {a: v for a, v in attrs_to_use.items() if a in attrs}
for key, value in attrs_to_use.items():
if hasattr(self, key): # don't make new attributes
setattr(self, key, value)
def get_seq(self, region_seq=None, start=None, stop=None,
flank=0, strand_correct=True):
"""
Retrieves object's sequence from its parent
sequence, with optional flanking sequence.
If >strand_correct<, will return strand-
corrected (e.g. reverse-complemented) sequence.
"""
if region_seq is None:
return self.seq
# Assign class defaults if not values
if start is None:
start = self.start
if stop is None:
stop = self.stop
# Correct for 1-based indexing in start and stop
start -= 1
# avoid negative indices
start = max(start, 0)
# Pull sequence and reverse if necessary
seq = region_seq[start:stop]
if strand_correct and self.strand == '-':
seq = reverse_complement(seq)
if flank > 0:
up_flank = self.upstream_seq(region_seq, flank)
down_flank = self.downstream_seq(region_seq, flank)
seq = [up_flank, seq, down_flank]
return seq
def upstream_seq(self, region_seq, n, strand_correct=True):
"""
Get sequence of n length from upstream of
feature start, relative to coding direction.
"""
if self.strand == "-":
start = self.stop
stop = start + n
else:
stop = self.start - 1
start = max(stop - n, 0) # no negative indices
seq = region_seq[start:stop]
if strand_correct and self.strand == '-':
seq = reverse_complement(seq)
return seq
def downstream_seq(self, region_seq, n, strand_correct=True):
"""
Get sequence of n length from downstream of
feature start, relative to coding direction.
"""
if self.strand == "-":
stop = self.start - 1
start = max(stop - n, 0) # no negative indices
else:
start = self.stop
stop = start + n
seq = region_seq[start:stop]
if strand_correct and self.strand == '-':
seq = reverse_complement(seq)
return seq
class Parent(GenomeFeature):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.children = []
self._intronator = intronator
def get_children(self, child_type=None):
"""
Returns a list of all children of type >child_type<.
If >child_type< not specified, returns all children.
"""
if not child_type:
selected = self.children
else:
selected = [c for c in self.children if c.feat_type == child_type]
return selected
def get_introns(self, child_type):
"""
Returns all introns based on >child_type<,
including any duplicates across children.
"""
introns = []
filtered_children = []
intron_count = 1
try:
filtered_children = [child for child in self.children if
child.feat_type == child_type]
except AttributeError:
return introns
if not filtered_children:
try:
for child in self.children:
introns += child.get_introns(child_type)
return introns
except AttributeError:
return introns
coding_length = self.get_coding_length(child_type)
for indx, intron in enumerate(
self._intronator(filtered_children), start=1):
intron.parent_length = coding_length
intron.index = indx
introns.append(intron)
return introns
class Gene(Parent):
def __init__(self, parent=None, **kwargs):
super().__init__(**kwargs)
self.__class__.count += 1
self.feat_type = "gene"
self.parent = parent
self.parent_type = None
class Transcript(Parent):
def __init__(self, parent=None, **kwargs):
super().__init__(**kwargs)
self.__class__.count += 1
self.feat_type = "transcript"
self.parent_type = "gene"
if not parent:
self.parent = self.name
else:
self.parent = parent
class Exon(GenomeFeature):
def __init__(self, feat_type="exon", parent=None,
grandparent=None, **kwargs):
super().__init__(**kwargs)
self.__class__.count += 1
self.parent_type = "transcript"
self.feat_type = feat_type
self.parent = parent
self.grandparent = grandparent
class Intron(GenomeFeature):
__slots__ = [
'__dict__', 'bp_raw_score', 'bp_region_seq',
'bp_seq', 'bp_start', 'bp_stop', 'bp_z_score', 'corrected',
'downstream_exon', 'downstream_flank', 'duplicate',
'dynamic_tag', 'family_size', 'feat_type',
'five_display_seq', 'five_raw_score',
'five_score_coords', 'five_seq', 'five_start', 'five_stop',
'five_z_score', 'flank', 'fractional_position',
'grandparent', 'index', 'line_number', 'longest_isoform',
'name', 'noncanonical', 'omitted', 'overlap', 'parent',
'parent_type', 'phase', 'region',
'seq', 'start', 'stop', 'strand', 'type_id',
'three_display_seq', 'relative_score',
'three_score_coords', 'three_seq', 'three_z_score',
'three_raw_score', 'u12_matrix', 'u2_matrix', 'unique_num',
'upstream_exon', 'upstream_flank', 'dnts', 'svm_score'
]
def __init__(self, parent=None, grandparent=None, **kwargs):
# Set certain attrs from parent class
super().__init__(**kwargs)
self.__class__.count += 1
# Set other intron-only attrs
# Inherit from transcript
self.feat_type = "intron"
self.parent_type = "transcript"
self.parent = parent
self.grandparent = grandparent
self.five_raw_score = None
self.five_z_score = None
self.bp_raw_score = None
self.bp_z_score = None
self.index = None # in coding orientation
# self.five_seq = None
self.five_seq = None
self.three_seq = None
self.bp_seq = None
self.bp_region_seq = None
self.five_start = None
self.five_stop = None
self.bp_start = None
self.bp_stop = None
self.omitted = False
self.corrected = False
self.duplicate = False
self.overlap = None
self.longest_isoform = None
self.dynamic_tag = set()
self.noncanonical = False
self.upstream_exon = None
self.downstream_exon = None
self.upstream_flank = None
self.downstream_flank = None
# self.phase = None
self.fractional_position = '.'
self.five_score_coords = None
self.three_score_coords = None
self.five_display_seq = None
self.three_display_seq = None
self.u2_matrix = None
self.u12_matrix = None
self.three_raw_score = None
self.three_z_score = None
self.dnts = None
self.svm_score = None
self.relative_score = None
self.type_id = None
@classmethod
def from_exon_pair(cls, up_ex, down_ex):
"""
Takes a pair of Exon objects and builds an intron
based on their information.
"""
# Infer intron coordinates
start = min(up_ex.stop, down_ex.stop) + 1
stop = max(up_ex.start, down_ex.start) - 1
# Get applicable attributes from one of the defining coding objects
strand = up_ex.strand
parent = up_ex.parent
grandparent = up_ex.grandparent
region = up_ex.region
# derive phase from upstream exon (CDS) phase annotation
# (if available)
if up_ex.phase != '.': # default phase value if not present
phase = (up_ex.length - up_ex.phase) % 3
else:
phase = '.'
fam = up_ex.family_size - 1 # intron number is exon number - 1
# average the line numbers of the children that define each intron
# to enable tie-breaking downstream when deciding which duplicates
# to exclude (for those whose parents have equal length)
line_number = sum([x.line_number for x in (up_ex, down_ex)]) / 2
return cls(start=start, stop=stop, strand=strand, family_size=fam,
parent=parent, grandparent=grandparent, region=region,
line_number=line_number, phase=phase)
def get_rel_coords(self, relative_to, relative_range):
"""
Calculates and retrieves a pair of genomic sequence coordinates
based on input relative to the five-prime or three-prime
end of the sequence. Returns a set of adjusted coords.
e.g. get_rel_coords("five", "five", (0, 12)),
get_rel_coords("bp", "three", (-45, -5))
"""
def __upstream(ref, x, strand):
x = abs(x)
if strand == "-":
return ref + x
else:
return ref - x
def __downstream(ref, x, strand):
x = abs(x)
if strand == "-":
return ref - x
else:
return ref + x
start = self.start
stop = self.stop
strand = self.strand
# Begin orientation gymnastics
if strand == "-":
start, stop = stop, start
if relative_to == "five":
ref_point = start
else:
ref_point = stop
new_coords = []
for n in relative_range: # each number can be + or -
if n < 0:
new_coords.append(__upstream(ref_point, n, strand))
else:
new_coords.append(__downstream(ref_point, n, strand))
new_coords = tuple(sorted(new_coords))
# setattr(self, seq_name, new_coords)
return new_coords
def get_name(self, special='?'):
"""
Build a unique name (not including score) from metadata.
"""
if self.name is not None:
return self.name
if self.omitted:
omit_tag = ';[o:{}]'.format(self.omitted)
else:
omit_tag = ''
if self.dynamic_tag:
dyn_tag = ';{}'.format(';'.join(sorted(self.dynamic_tag)))
else:
dyn_tag = ''
if SIMPLE_NAME is True:
return '{}-i_{}{}{}'.format(SPCS, self.unique_num, omit_tag, dyn_tag)
elements = [
self.grandparent, self.parent,
self.index, self.family_size, omit_tag]
tags = [e if e is not None else special for e in elements]
tags.append(dyn_tag) # compatibility with earlier Python 3s
name = "{}-{}@{}-intron_{}({}){}{}".format(SPCS, *tags)
# setattr(self, "name", name)
return name
def get_label(self, special='?'):
"""
Builds a unique intron label from metadata
"""
# if self.omitted:
# setattr(self, 'relative_score', 0)
if self.relative_score is not None:
# clipping prevents rounding from pushing introns over the
# u12 boundary
# *clip* float to 3 places (without rounding)
truncated = math.floor(self.relative_score * 1000) / 1000
score = '{}%'.format(truncated)
# *round* float to 4 places
# rel_score = '{:.4f}%'.format(self.relative_score)
else:
score = None
if not self.name:
self.name = self.get_name()
label = ('{};{}'
.format(*[e if e is not None else special for e in
[self.name, score]]))
return label
def omit_check(
self, min_length, allow_noncanon=False,
allow_overlap=False, longest_only=True):
#TODO make .omitted be a list containing all tags
# instead of just a single string
"""
Checks an intron object for omission criteria, and sets
the >omitted< attribute accordingly.
"""
omit_tags = {
'short': 's',
'ambiguous sequence': 'a',
'noncanonical': 'n',
'coordinate overlap': 'v',
'not in longest isoform': 'i'
}
scoring_regions = ['five_seq', 'three_seq']
omission_reason = None
if self.length < min_length:
omission_reason = 'short'
elif any(valid_chars(getattr(self, region)) is False
for region in scoring_regions):
omission_reason = 'ambiguous sequence'
# check if there is sufficiently long sequence in the
# bp region to score at least one bp motif
elif longest_match(self.bp_region_seq) < BP_MATRIX_LENGTH:
omission_reason = 'short'
elif not allow_noncanon and self.noncanonical:
omission_reason = 'noncanonical'
elif longest_only and self.longest_isoform is False:
omission_reason = 'not in longest isoform'
elif allow_overlap is False and self.overlap:
omission_reason = 'coordinate overlap'
if omission_reason:
setattr(self, 'omitted', omit_tags[omission_reason])
# /Classes ###################################################################
# Functions ##################################################################
def check_thresh_arg(t):
"""
Used in argument parsing to reject malformed threshold values
"""
t = float(t)
if not 0 <= t <= 100:
raise argparse.ArgumentTypeError("'{}' is not within the range 0-100".
format(t))
return t
def reverse_complement(seq):
"""
Returns reverse complement of seq, with
any non-ACTG characters replaced with Ns
"""
transform = {'A': 'T',
'T': 'A',
'C': 'G',
'G': 'C',
'N': 'N'}
try:
comp = [transform[e] for e in seq]
except KeyError: # non-ATCGN characters in seq
seq = [e if e in "ACTGN" else "N" for e in seq]
comp = [transform[e] for e in seq]
rev_comp = comp[::-1]
rev_comp_string = ''.join(rev_comp)
return rev_comp_string
def flex_open(filename):
"""
A generator of lines from a variety of
file types, including compressed files.
"""
magic_dict = {
b'\x1f\x8b\x08': partial(gzip.open, mode='rt')
# "\x42\x5a\x68": "bz2",
# "\x50\x4b\x03\x04": "zip"
}
max_len = max(len(x) for x in magic_dict)
open_func = None
# Try opening the file in binary mode and reading the first
# chunk to see if it matches the signature byte pattern
# expected for each compressed file type
with open(filename, 'rb') as f:
file_start = f.read(max_len)
for magic, func in magic_dict.items():
if file_start.startswith(magic):
open_func = func
if open_func:
return open_func(filename)
else:
return open(filename)
def fasta_parse(fasta, delimiter=">", separator="", trim_header=True):
"""
Iterator which takes FASTA as input. Yields
header/value pairs. Separator will be
used to join the return value; use separator=
None to return a list.
If trim_header, parser will return the
FASTA header up to the first space character.