-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathdetect_splicing_events.py
More file actions
2274 lines (1862 loc) · 78.5 KB
/
Copy pathdetect_splicing_events.py
File metadata and controls
2274 lines (1862 loc) · 78.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import argparse
import bisect
import multiprocessing
import os
import os.path
from rmats_long import rmats_long_utils
def parse_args():
parser = argparse.ArgumentParser(
description=('Detect alternative splicing events from'
' a set of isoforms'))
parser.add_argument(
'--gtf-dir',
required=True,
help='The output directory from organize_gene_info_by_chr.py')
parser.add_argument('--align-dir',
help=('The output directory from'
' organize_alignment_info_by_gene_and_chr.py'))
parser.add_argument(
'--out-dir',
required=True,
help='The directory to create and where chr files will be written')
parser.add_argument(
'--max-nodes-in-event',
default=50,
type=int,
help=('Only look for events between nodes (splice sites) in the'
' splice graph that are at most --max-nodes-in-event apart.'
' Default: %(default)s'))
parser.add_argument(
'--max-paths-in-event',
default=50,
type=int,
help=('Only output events with at most --max-paths-in-event.'
' Default: %(default)s'))
parser.add_argument('--num-threads',
default=1,
type=int,
help='how many threads to use. Default: %(default)s')
parser.add_argument(
'--min-reads-per-edge',
default=5,
type=int,
help=('Only include an edge in the splice graph if there are at least'
' this many supporting reads. Default: %(default)s'))
parser.add_argument('--output-full-gene-asm',
action='store_true',
help=('Output only ASMs that cover the entire gene'
' (from transcript start to end)'))
parser.add_argument('--output-basic-events',
action='store_true',
help=('Output only ASMs for basic events'
' (SE, A5SS, A3SS, MXE, RI)'))
parser.add_argument('--simplify-gene-isoform-endpoints',
action='store_true',
help=('Combine gene isoforms where the only difference'
' is the transcripts start and/or end'))
parser.add_argument(
'--filter-gene-isoforms-by-edge',
action='store_true',
help=('With --output-full-gene-asm, require each isoform to have'
' --min-reads-per-edge for each splice junction'))
parser.add_argument('--output-strict-only',
action='store_true',
help='Only output events where is_strict is True')
parser.add_argument(
'--novel-junctions',
action='store_true',
help=('Consider splice junctions found in --align-dir but'
' not --gtf-dir'))
args = parser.parse_args()
# Without the align_dir the edges cannot be filtered by read count
if not args.align_dir:
args.min_reads_per_edge = 0
if args.output_full_gene_asm and args.output_basic_events:
parser.error('At most one of'
' [--output-full-gene-asm, --output-basic-events]'
' can be used')
return args
def parse_gtf_line(line):
parsed = dict()
columns = rmats_long_utils.read_tsv_line(line)
num_columns = len(columns)
if num_columns == 4:
gene_id = columns[2]
parsed['gene'] = gene_id
return parsed
start_str = columns[0]
transcript_start = int(start_str)
end_str = columns[1]
transcript_end = int(end_str)
sjs_string = columns[2]
sjs = rmats_long_utils.parse_sjs_string(sjs_string)
strand = columns[3]
transcript_id = columns[4]
parsed['transcript_id'] = transcript_id
parsed['strand'] = strand
exons = list()
exons.append([transcript_start, None])
for sj_start, sj_end in sjs:
exons[-1][1] = sj_start
exons.append([sj_end, None])
exons[-1][1] = transcript_end
parsed['exons'] = exons
return parsed
class Node:
'''
A Node in the splice graph is one of:
* supersource (^): All transcripts start here
* supersink ($): All transcripts end here
* exon start: The start coordinate of an exon
* exon end: The end coordinate of an exon
Example:
* Transcripts
+ (^)->(a,b)->(c,d)->(e,f)-> (g,h)->(i,j)->($)
+ (^)->(a,b)-> (e,f)-> (g,h)->(i,j)->($)
+ (^)->(a,b)->(c,d)->(e,f)->(g*,h)->(i,j)->($)
+ (g*,h) is like exon (g,h) but with an earlier start coordinate
+ a, c, e, g, i are exon start nodes
+ b, d, f, h, j are exon end nodes
* Final splice graph:
^ -> a -> b ------> e -> f -> g*
\ / \ \
c -> d g -> h -> i -> j -> $
The implementations of hash and equality do not include self.edges.
This allows keeping the edges within the Node as a dictionary.
This node has a directed edge to node_b if node_b in self.edges
The value in the dictionary is the edge weight which defaults to
zero and can be assigned later.
'''
def __init__(self, coordinate, node_type):
self.edges = dict()
self.from_nodes = set()
self.coordinate = coordinate
self.node_type = node_type
self.removed = dict()
self.num_edges_from_source = 0
self.num_edges_from_non_source = 0
def _compare_key(self):
return (self.coordinate, self.node_type)
def __hash__(self):
return hash(self._compare_key())
def __eq__(self, other):
return self._compare_key() == other._compare_key()
def __lt__(self, other):
if self == other:
return False
if (self.node_type == 'source') or (other.node_type == 'sink'):
return True
if (self.node_type == 'sink') or (other.node_type == 'source'):
return False
if self.coordinate is None and other.coordinate is None:
return self.node_type < other.node_type
if self.coordinate is None:
return True
if other.coordinate is None:
return False
return self._compare_key() < other._compare_key()
def __str__(self):
return str(self._compare_key())
def __repr__(self):
return repr({
'edges': [str(x) for x in self.edges],
'coordinate': self.coordinate,
'node_type': self.node_type
})
def reverse_minus_strand_exons(exons):
reversed_exons = list()
for exon in reversed(exons):
end, start = exon
reversed_exons.append((start, end))
return reversed_exons
def add_node_edge(from_node, to_node):
from_node.edges[to_node] = 0
if from_node.node_type == 'source':
to_node.num_edges_from_source += 1
else:
to_node.num_edges_from_non_source += 1
to_node.from_nodes.add(from_node)
def remove_node_edge(from_node, to_node):
del from_node.edges[to_node]
if from_node.node_type == 'source':
to_node.num_edges_from_source -= 1
else:
to_node.num_edges_from_non_source -= 1
to_node.from_nodes.remove(from_node)
def update_if_closer(container, key_node, new_node):
old_node = container.get(key_node, None)
if old_node is None or old_node.coordinate is None:
container[key_node] = new_node
return
if new_node.coordinate is None or key_node.coordinate is None:
return
old_diff = abs(old_node.coordinate - key_node.coordinate)
new_diff = abs(new_node.coordinate - key_node.coordinate)
if new_diff < old_diff:
container[key_node] = new_node
# closest_downstream_by_node: stores one outgoing edge for each node
# closest_upstream_by_node: stores one incoming edge for each node
# The extra closest_downstream_by_node and closest_upstream_by_node are used
# to provide missing exon start/end coordinates for splicing events
# that don't depend on the full exon
def set_closest_up_and_down(graph_results):
closest_downstream_by_node = dict()
closest_upstream_by_node = dict()
graph_results['closest_down'] = closest_downstream_by_node
graph_results['closest_up'] = closest_upstream_by_node
all_nodes = graph_results['all_nodes']
for node in all_nodes:
for down_node in node.edges:
update_if_closer(closest_downstream_by_node, node, down_node)
for up_node in node.from_nodes:
update_if_closer(closest_upstream_by_node, node, up_node)
# build_splice_graph returns:
# splice_graph: the source node of the graph
# sink: the sink node of the graph
# all_nodes: a dict containing all nodes in the graph
def build_splice_graph(transcripts, strand):
all_nodes = dict()
splice_graph = Node(None, 'source')
all_nodes[splice_graph] = splice_graph
sink_node = Node(None, 'sink')
all_nodes[sink_node] = sink_node
for transcript_details in transcripts:
exons = transcript_details['exons']
if strand == '-':
exons = reverse_minus_strand_exons(exons)
node = splice_graph
for exon in exons:
start, end = exon
start_node = Node(start, 'start')
existing_start = all_nodes.get(start_node)
if existing_start:
start_node = existing_start
else:
all_nodes[start_node] = start_node
add_node_edge(node, start_node)
# move to exon start node
node = start_node
end_node = Node(end, 'end')
existing_end = all_nodes.get(end_node)
if existing_end:
end_node = existing_end
else:
all_nodes[end_node] = end_node
add_node_edge(node, end_node)
# move to exon end node
node = end_node
# add sink node at end of every transcript
add_node_edge(node, sink_node)
results = dict()
results['graph'] = splice_graph
results['sink'] = sink_node
results['all_nodes'] = all_nodes
return results
def filter_running_paths(paths, cutoff_node, strand):
if cutoff_node is None or cutoff_node.coordinate is None:
return paths
cutoff = cutoff_node.coordinate
new_paths_set = set()
new_paths = list()
for path in paths:
for node_i, node in enumerate(path):
if (node.coordinate is not None
and ((strand == '+') and (node.coordinate >= cutoff) or
(strand == '-') and (node.coordinate <= cutoff))):
new_path = path[node_i:]
new_path_tuple = tuple(new_path)
if new_path_tuple not in new_paths_set:
new_paths_set.add(new_path_tuple)
new_paths.append(new_path)
break
return new_paths
def detect_bubbles_visit_node(node, nodes_to_visit, running_paths_by_node,
cutoff_node, strand, max_paths_in_event,
bubbles):
if node.node_type == 'source':
running_path = [node]
running_paths_by_node[node] = [running_path]
paths_by_start = dict()
# Stop tracking paths that end at this node
running_paths = running_paths_by_node.pop(node)
running_paths = filter_running_paths(running_paths, cutoff_node, strand)
for running_path in running_paths:
# Add all start-to-node paths that could be part of a bubble.
# If a start node does not have multiple outgoing edges then it
# cannot be the start of a bubble.
for start_node_i in range(len(running_path) - 1):
start_node = running_path[start_node_i]
if len(start_node.edges) < 2:
continue
paths_for_start_end = paths_by_start.get(start_node)
if not paths_for_start_end:
paths_for_start_end = set()
paths_by_start[start_node] = paths_for_start_end
paths_for_start_end.add(tuple(running_path[start_node_i:]))
detect_bubbles_from_paths(paths_by_start, max_paths_in_event, bubbles)
if len(running_paths_by_node) == 0:
# All currently tracked paths end at this node.
# Reset to a single path with this node.
running_path = [node]
running_paths = [running_path]
for other in node.edges:
nodes_to_visit.add(other)
paths_to_other = running_paths_by_node.get(other)
if not paths_to_other:
paths_to_other = list()
running_paths_by_node[other] = paths_to_other
for running_path in running_paths:
extended = running_path + [other]
paths_to_other.append(extended)
def choose_next_node(nodes_to_visit, strand):
next_node = None
for node in nodes_to_visit:
if next_node is None:
next_node = node
continue
if node.coordinate is None:
continue
if next_node.coordinate is None:
next_node = node
continue
# It's possible for a coordinate to be both a start and end of an exon
if (((node.coordinate == next_node.coordinate)
and (node.node_type == 'start'))):
next_node = node
continue
if (strand == '+') and (node.coordinate < next_node.coordinate):
next_node = node
continue
if (strand == '-') and (node.coordinate > next_node.coordinate):
next_node = node
continue
nodes_to_visit.remove(next_node)
return next_node
def detect_bubbles_from_paths(by_start, max_paths_in_event, bubbles):
for paths in by_start.values():
num_paths = len(paths)
if (num_paths < 2) or (num_paths > max_paths_in_event):
continue
shared_nodes = None
for path in paths:
if shared_nodes is None:
shared_nodes = set(path)
else:
shared_nodes.intersection_update(set(path))
# A bubble is multiple paths between two nodes.
# If all the paths share a node other than the
# start and end nodes then there is a smaller bubble to find
if len(shared_nodes) == 2:
bubble = {'paths': paths, 'path_to_id': dict()}
bubbles.append(bubble)
def detect_bubbles(splice_graph, strand, max_nodes_in_event,
max_paths_in_event):
# Start at the source node and traverse the graph.
# When choosing the next node prefer nodes with lower coordinates, but
# if the graph is for the minus strand then prefer higher coordinates.
# That way, when a node is visited all nodes that link to it will already
# have been visited.
# This assumes no loops and that strand information is correct.
# While doing the traversal keep track of "running paths".
# If at any time all running paths share a node then stop tracking
# those paths. This is because any bubble would end at the shared node.
# To limit the search and ensure reasonable running time and memory usage,
# store the order of nodes_visited. If a running path contains a node that
# is more than max_nodes_in_event back in nodes_visited then remove that
# node from the running path and simplify the remaining running paths.
nodes_to_visit = {splice_graph}
running_paths_by_node = dict()
nodes_visited = list()
bubbles = list()
while nodes_to_visit:
next_node = choose_next_node(nodes_to_visit, strand)
nodes_visited.append(next_node)
cutoff_node = None
if len(nodes_visited) > max_nodes_in_event:
cutoff_node = nodes_visited[-max_nodes_in_event]
detect_bubbles_visit_node(next_node, nodes_to_visit,
running_paths_by_node, cutoff_node, strand,
max_paths_in_event, bubbles)
return bubbles
def sort_bubbles_by_coord_key_func(reverse, bubble):
key = list()
paths = bubble['paths']
for path in paths:
coords = [node.coordinate for node in path]
coords.sort(reverse=reverse)
key.append(coords)
key.sort(reverse=reverse)
return key
def sort_bubbles_by_coord_plus_key_func(bubble):
reverse = False
return sort_bubbles_by_coord_key_func(reverse, bubble)
def sort_bubbles_by_coord_minus_key_func(bubble):
reverse = True
return sort_bubbles_by_coord_key_func(reverse, bubble)
def sort_bubbles_by_coord(is_minus_strand, bubbles):
if is_minus_strand:
key_func = sort_bubbles_by_coord_minus_key_func
bubbles.sort(key=key_func, reverse=True)
else:
key_func = sort_bubbles_by_coord_plus_key_func
bubbles.sort(key=key_func)
def append_se_bubble(upstream_end, exon_start, exon_end, downstream_start,
bubbles):
paths = {
(upstream_end, exon_start, exon_end, downstream_start),
(upstream_end, downstream_start),
}
bubble = {
'paths': paths,
'path_to_id': dict(),
}
bubbles.append(bubble)
def detect_se_events_with_targets(upstream_end, exon_start, targets,
is_minus_strand, bubbles):
new_bubbles = list()
for exon_end in exon_start.edges:
if exon_end.node_type != 'end':
continue
for downstream_start in exon_end.edges:
if downstream_start.node_type != 'start':
continue
if downstream_start in targets:
append_se_bubble(upstream_end, exon_start, exon_end,
downstream_start, new_bubbles)
sort_bubbles_by_coord(is_minus_strand, new_bubbles)
bubbles.extend(new_bubbles)
def detect_se_events_with_up_end(upstream_end, is_minus_strand, bubbles):
connected_starts = list()
for other in upstream_end.edges:
if other.node_type == 'start':
connected_starts.append(other)
connected_starts.sort(reverse=is_minus_strand)
targets = set(connected_starts)
for exon_start in connected_starts:
targets.remove(exon_start)
detect_se_events_with_targets(upstream_end, exon_start, targets,
is_minus_strand, bubbles)
def append_a5ss_bubble(upstream_start, up_end, other_up_end, shared_down_start,
bubbles):
paths = {
(upstream_start, up_end, shared_down_start),
(upstream_start, other_up_end, shared_down_start),
}
bubble = {
'paths': paths,
'path_to_id': dict(),
}
bubbles.append(bubble)
def detect_a5ss_events_with_up_start(upstream_start, is_minus_strand, bubbles):
new_bubbles = list()
up_ends_by_down_start = dict()
for up_end in upstream_start.edges:
if up_end.node_type != 'end':
continue
for down_start in up_end.edges:
if down_start.node_type != 'start':
continue
for_down_start = up_ends_by_down_start.get(down_start)
if not for_down_start:
for_down_start = list()
up_ends_by_down_start[down_start] = for_down_start
for_down_start.append(up_end)
for down_start, up_ends in up_ends_by_down_start.items():
num_ends = len(up_ends)
for end_i, up_end in enumerate(up_ends):
for other_i in range(end_i + 1, num_ends):
other_up_end = up_ends[other_i]
append_a5ss_bubble(upstream_start, up_end, other_up_end,
down_start, new_bubbles)
sort_bubbles_by_coord(is_minus_strand, new_bubbles)
bubbles.extend(new_bubbles)
def append_a3ss_bubble(upstream_end, down_start, other_down_start,
shared_down_end, bubbles):
paths = {
(upstream_end, down_start, shared_down_end),
(upstream_end, other_down_start, shared_down_end),
}
bubble = {
'paths': paths,
'path_to_id': dict(),
}
bubbles.append(bubble)
def detect_a3ss_events_with_up_end(upstream_end, is_minus_strand, bubbles):
new_bubbles = list()
down_starts_by_down_end = dict()
for down_start in upstream_end.edges:
if down_start.node_type != 'start':
continue
for down_end in down_start.edges:
if down_end.node_type != 'end':
continue
for_down_end = down_starts_by_down_end.get(down_end)
if not for_down_end:
for_down_end = list()
down_starts_by_down_end[down_end] = for_down_end
for_down_end.append(down_start)
for down_end, down_starts in down_starts_by_down_end.items():
num_starts = len(down_starts)
for start_i, down_start in enumerate(down_starts):
for other_i in range(start_i + 1, num_starts):
other_down_start = down_starts[other_i]
append_a3ss_bubble(upstream_end, down_start, other_down_start,
down_end, new_bubbles)
sort_bubbles_by_coord(is_minus_strand, new_bubbles)
bubbles.extend(new_bubbles)
def append_mxe_bubble(upstream_end, first_start, first_end, second_start,
second_end, down_start, bubbles):
paths = {
(upstream_end, first_start, first_end, down_start),
(upstream_end, second_start, second_end, down_start),
}
bubble = {
'paths': paths,
'path_to_id': dict(),
}
bubbles.append(bubble)
def detect_mxe_events_with_up_end(upstream_end, is_minus_strand, bubbles):
new_bubbles = list()
mid_by_down_start = dict()
for mid_start in upstream_end.edges:
if mid_start.node_type != 'start':
continue
for mid_end in mid_start.edges:
if mid_end.node_type != 'end':
continue
for down_start in mid_end.edges:
if down_start.node_type != 'start':
continue
for_down_start = mid_by_down_start.get(down_start)
if not for_down_start:
for_down_start = list()
mid_by_down_start[down_start] = for_down_start
for_down_start.append((mid_start, mid_end))
for down_start, mid_exons in mid_by_down_start.items():
num_mids = len(mid_exons)
for first_i, first_exon in enumerate(mid_exons):
first_start, first_end = first_exon
for second_i in range(first_i + 1, num_mids):
second_exon = mid_exons[second_i]
second_start, second_end = second_exon
if is_minus_strand:
max_lower = max(first_end.coordinate,
second_end.coordinate)
min_upper = min(first_start.coordinate,
second_start.coordinate)
else:
max_lower = max(first_start.coordinate,
second_start.coordinate)
min_upper = min(first_end.coordinate,
second_end.coordinate)
has_overlap = max_lower <= min_upper
if has_overlap:
continue
append_mxe_bubble(upstream_end, first_start, first_end,
second_start, second_end, down_start,
new_bubbles)
sort_bubbles_by_coord(is_minus_strand, new_bubbles)
bubbles.extend(new_bubbles)
def append_ri_bubble(upstream_start, upstream_end, downstream_start,
downstream_end, bubbles):
paths = {
(upstream_start, upstream_end, downstream_start, downstream_end),
(upstream_start, downstream_end),
}
bubble = {
'paths': paths,
'path_to_id': dict(),
}
bubbles.append(bubble)
def detect_ri_events_with_up_start(upstream_start, is_minus_strand, bubbles):
new_bubbles = list()
either_ends = set()
for an_end in upstream_start.edges:
if an_end.node_type != 'end':
continue
either_ends.add(an_end)
for up_end in either_ends:
for down_start in up_end.edges:
if down_start.node_type != 'start':
continue
for down_end in down_start.edges:
if down_end.node_type != 'end':
continue
if down_end in either_ends:
append_ri_bubble(upstream_start, up_end, down_start,
down_end, new_bubbles)
sort_bubbles_by_coord(is_minus_strand, new_bubbles)
bubbles.extend(new_bubbles)
def detect_basic_events_at_node(node, strand, nodes_to_visit, bubbles):
for other in node.edges:
nodes_to_visit.add(other)
if node.node_type in ['source', 'sink']:
return
is_minus_strand = strand == '-'
if node.node_type == 'end':
upstream_end = node
detect_se_events_with_up_end(upstream_end, is_minus_strand, bubbles)
detect_mxe_events_with_up_end(upstream_end, is_minus_strand, bubbles)
detect_a3ss_events_with_up_end(upstream_end, is_minus_strand, bubbles)
if node.node_type == 'start':
upstream_start = node
detect_a5ss_events_with_up_start(upstream_start, is_minus_strand,
bubbles)
detect_ri_events_with_up_start(upstream_start, is_minus_strand,
bubbles)
def detect_basic_events(splice_graph, strand):
bubbles = list()
nodes_to_visit = {splice_graph}
while nodes_to_visit:
next_node = choose_next_node(nodes_to_visit, strand)
detect_basic_events_at_node(next_node, strand, nodes_to_visit, bubbles)
return bubbles
def get_isoform_exons(path, closest_downstream_by_node,
closest_upstream_by_node, output_full_gene_asm):
exons = list()
for node in path:
if node.node_type in ['source', 'sink']:
continue
if node.node_type == 'start':
if output_full_gene_asm:
exons.append([node.coordinate, None])
else:
default_end = closest_downstream_by_node[node]
exons.append([node.coordinate, default_end.coordinate])
elif node.node_type == 'end':
if exons:
exons[-1][-1] = node.coordinate
else:
default_start = closest_upstream_by_node[node]
exons.append([default_start.coordinate, node.coordinate])
return [tuple(exon) for exon in exons]
def is_exon_skipping(paths):
if len(paths) != 2:
return False
include_path = None
skip_path = None
for path in paths:
if len(path) == 2:
skip_path = path
if len(path) == 4:
include_path = path
if include_path is None or skip_path is None:
return False
return ((include_path[0] == skip_path[0])
and (include_path[3] == skip_path[1])
and (include_path[0].node_type == 'end')
and (include_path[1].node_type == 'start')
and (include_path[2].node_type == 'end')
and (include_path[3].node_type == 'start'))
def is_alt_3_splice_site(paths):
if len(paths) != 2:
return False
path_list = list()
for path in paths:
if len(path) != 3:
return False
path_list.append(path)
path_a = path_list[0]
path_b = path_list[1]
return ((path_a[0] == path_b[0]) and (path_a[2] == path_b[2])
and (path_a[1].node_type == path_b[1].node_type)
and (path_a[1].coordinate != path_b[1].coordinate)
and (path_a[0].node_type == 'end')
and (path_a[1].node_type == 'start')
and (path_a[2].node_type == 'end'))
def is_alt_5_splice_site(paths):
if len(paths) != 2:
return False
path_list = list()
for path in paths:
if len(path) != 3:
return False
path_list.append(path)
path_a = path_list[0]
path_b = path_list[1]
return ((path_a[0] == path_b[0]) and (path_a[2] == path_b[2])
and (path_a[1].node_type == path_b[1].node_type)
and (path_a[1].coordinate != path_b[1].coordinate)
and (path_a[0].node_type == 'start')
and (path_a[1].node_type == 'end')
and (path_a[2].node_type == 'start'))
def is_alt_first_exon(paths):
if len(paths) != 2:
return False
path_list = list()
for path in paths:
if len(path) != 4:
return False
path_list.append(path)
path_a = path_list[0]
path_b = path_list[1]
return ((path_a[0] == path_b[0]) and (path_a[3] == path_b[3])
and (path_a[1].node_type == path_b[1].node_type)
and (path_a[1].coordinate != path_b[1].coordinate)
and (path_a[2].node_type == path_b[2].node_type)
and (path_a[2].coordinate != path_b[2].coordinate)
and (path_a[0].node_type == 'source')
and (path_a[1].node_type == 'start')
and (path_a[2].node_type == 'end')
and (path_a[3].node_type == 'start'))
def is_alt_last_exon(paths):
if len(paths) != 2:
return False
path_list = list()
for path in paths:
if len(path) != 4:
return False
path_list.append(path)
path_a = path_list[0]
path_b = path_list[1]
return ((path_a[0] == path_b[0]) and (path_a[3] == path_b[3])
and (path_a[1].node_type == path_b[1].node_type)
and (path_a[1].coordinate != path_b[1].coordinate)
and (path_a[2].node_type == path_b[2].node_type)
and (path_a[2].coordinate != path_b[2].coordinate)
and (path_a[0].node_type == 'end')
and (path_a[1].node_type == 'start')
and (path_a[2].node_type == 'end')
and (path_a[3].node_type == 'sink'))
def is_intron_retention(paths):
if len(paths) != 2:
return False
retained_path = None
spliced_path = None
for path in paths:
if len(path) == 4:
spliced_path = path
elif len(path) == 2:
retained_path = path
else:
return False
return ((retained_path is not None) and (spliced_path is not None)
and (spliced_path[0] == retained_path[0])
and (spliced_path[3] == retained_path[1])
and (spliced_path[0].node_type == 'start')
and (spliced_path[1].node_type == 'end')
and (spliced_path[2].node_type == 'start')
and (spliced_path[3].node_type == 'end'))
def is_mutually_exclusive_exons(paths):
if len(paths) != 2:
return False
path_list = list()
for path in paths:
if len(path) != 4:
return False
path_list.append(path)
path_a = path_list[0]
path_b = path_list[1]
could_be_mxe = ((path_a[0] == path_b[0]) and (path_a[3] == path_b[3])
and (path_a[1].node_type == path_b[1].node_type)
and (path_a[1].coordinate != path_b[1].coordinate)
and (path_a[2].node_type == path_b[2].node_type)
and (path_a[2].coordinate != path_b[2].coordinate)
and (path_a[0].node_type == 'end')
and (path_a[1].node_type == 'start')
and (path_a[2].node_type == 'end')
and (path_a[3].node_type == 'start'))
if not could_be_mxe:
return False
exon_a = [path_a[1].coordinate, path_a[2].coordinate]
exon_b = [path_b[1].coordinate, path_b[2].coordinate]
exon_a.sort()
exon_b.sort()
max_start = max(exon_a[0], exon_b[0])
min_end = min(exon_a[1], exon_b[1])
has_overlap = max_start <= min_end
return not has_overlap
def group_path_info_by_internal_nodes(paths, path_to_id):
paths_by_internal = dict()
result = {'any_alt': False, 'paths_by_internal': paths_by_internal}
for path_i, path in enumerate(paths):
# All paths share the first and last node. Just check on 1st path
if path_i == 0:
has_start = path[0].node_type == 'source'
has_end = path[-1].node_type == 'sink'
# Only simplify if the paths include the source or sink node.
if not (has_start or has_end):
return result
internal_start_offset = 1
internal_end_offset = 1
if has_start:
internal_start_offset += 1
if has_end:
internal_end_offset += 1
# The ends of the paths are always the same for paths in an event.
# Also transcript start and end sites are not "internal"
internal_list = list()
for i in range(internal_start_offset, len(path) - internal_end_offset):
internal_list.append(path[i].coordinate)
internal = tuple(internal_list)
details = paths_by_internal.get(internal)
if not details:
details = {
'paths': list(),
'starts': set(),
'ends': set(),
'starts_by_coord': dict(),
'ends_by_coord': dict(),
'ids_by_start': dict(),
'ids_by_end': dict()
}
paths_by_internal[internal] = details
else:
result['any_alt'] = True
# convert from a tuple to a list to allow modifying
details['paths'].append(list(path))
path_id = path_to_id.get(path)
if has_start:
start_coord = path[1].coordinate