-
Notifications
You must be signed in to change notification settings - Fork 6
/
VizUtil.py
1764 lines (1450 loc) · 69.6 KB
/
VizUtil.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
import bisect
from collections import defaultdict
import copy
import os
import sys
from intervaltree import IntervalTree
import matplotlib
from matplotlib import pyplot as plt
import numpy as np
import yaml
matplotlib.use('Agg')
contig_spacing = 1. / 100
unaligned_cutoff_frac = 1. / 60
def cart2pol(x, y):
rho = np.sqrt(x ** 2 + y ** 2)
phi = np.arctan2(y, x) / (2. * np.pi) * 360
return rho, phi
def pol2cart(rho, phi):
x = rho * np.cos(phi)
y = rho * np.sin(phi)
return x, y
# arguments: thetas, rhos, however rad_vect can be a single rho, and will get turned into a list of same length as theta
def polar_series_to_cartesians(line_points, rad_vect):
if len(line_points) == 0:
return [], []
if not isinstance(rad_vect, list):
rad_vect = [rad_vect,] * len(line_points)
return zip(*[pol2cart(r, i) for r, i in zip(rad_vect, line_points)])
def round_to_1_sig(x):
if x == 0:
return 0.
return round(x, -int(np.floor(np.log10(abs(x)))))
def convert_gpos_to_ropos(cgpos, ro_start, ro_end, g_start, cdir):
if cdir == "+":
return (cgpos - g_start) + ro_start
else:
return ro_end - (cgpos - g_start)
def reverse_cycle(cycle):
rcycle = []
for s, d in cycle[::-1]:
nd = "-" if d == "+" else "+"
rcycle.append((s, nd))
return rcycle
class CycleVizElemObj(object):
def __init__(self, m_id, chrom, ref_start, ref_end, direction, s, t, seg_count, padj, nadj, cmap_vect=None):
if cmap_vect is None: cmap_vect = []
self.id = m_id
self.chrom = chrom
self.ref_start = ref_start
self.ref_end = ref_end
self.direction = direction
self.abs_start_pos = s
self.abs_end_pos = t
self.scaling_factor = 1
self.seg_count = seg_count
self.cmap_vect = cmap_vect
self.aln_lab_ends = (None, None)
self.aln_bound_posns = (None, None)
self.label_posns = []
self.track_height_shift = 0
self.start_trim = False
self.end_trim = False
self.feature_tracks = []
self.prev_is_adjacent = padj
self.next_is_adjacent = nadj
self.custom_face_color = None
self.custom_edge_color = 'k'
self.custom_bh = None
def compute_label_posns(self):
if self.direction == "+":
if self.abs_start_pos is None:
self.abs_start_pos = self.aln_bound_posns[0] - self.scaling_factor * self.cmap_vect[
self.aln_lab_ends[0] - 1]
if self.abs_end_pos is None:
self.abs_end_pos = self.aln_bound_posns[1] + self.scaling_factor * (
self.cmap_vect[-1] - self.cmap_vect[self.aln_lab_ends[1] - 1])
for i in self.cmap_vect[:-1]:
self.label_posns.append(self.scaling_factor * i + self.abs_start_pos)
else:
if self.abs_start_pos is None:
self.abs_start_pos = self.aln_bound_posns[0] - self.scaling_factor * (
self.cmap_vect[-1] - self.cmap_vect[self.aln_lab_ends[1] - 1])
if self.abs_end_pos is None:
self.abs_end_pos = self.aln_bound_posns[1] + self.scaling_factor * self.cmap_vect[
self.aln_lab_ends[0] - 1]
rev_cmap_vect = [self.cmap_vect[-1] - x for x in self.cmap_vect[::-1][1:]] # does not include length value
for i in rev_cmap_vect:
self.label_posns.append(self.scaling_factor * i + self.abs_start_pos)
self.label_posns = self.label_posns[::-1]
def to_string(self):
return "{}{} | GenomePos: {}:{}-{} | Circle Start: {} | Circle End: {} | scaling {}".format(self.id, self.direction, self.chrom,
str(self.ref_start), str(self.ref_end), str(self.abs_start_pos), str(self.abs_end_pos), str(self.scaling_factor))
# trim visualized contig if it's long and unaligned
def trim_obj_ends(self, total_length):
# use the .end_trim,.start_trim to chop off.
# overhang should go to 1/3 of the unaligned cutoff threshold
if self.start_trim:
p_abs_start = self.abs_start_pos
print("DOING s TRIM on " + self.id)
self.abs_start_pos = self.aln_bound_posns[0] - unaligned_cutoff_frac * total_length / 4.
if self.direction == "-":
self.update_label_posns(p_abs_start - self.abs_start_pos)
print("now", self.abs_start_pos)
if self.end_trim:
p_abs_end = self.abs_end_pos
print("DOING e TRIM on " + self.id)
print(self.aln_bound_posns)
self.abs_end_pos = self.aln_bound_posns[-1] + unaligned_cutoff_frac * total_length / 4.
if self.direction == "-":
self.update_label_posns(p_abs_end - self.abs_end_pos)
print("now", self.abs_end_pos)
# update label positions after trimming contigs
def update_label_posns(self, s_diff):
print("Trimmed by", s_diff)
for ind in range(len(self.label_posns)):
self.label_posns[ind] -= s_diff
# this stores the local properties of each gene's visualization
class gene_viz_instance(object):
def __init__(self, gParent, normStart, normEnd, total_length, seg_dir, currStart, currEnd, hasStart, hasEnd, seg_ind, pTup):
self.gParent = gParent
self.normStart = normStart
self.normEnd = normEnd
self.total_length = total_length
self.seg_dir = seg_dir
self.currStart = currStart
self.currEnd = currEnd
self.hasStart = hasStart
self.hasEnd = hasEnd
self.seg_ind = seg_ind
self.pTup = pTup
def get_angles(self):
tm = "X"
start_angle = self.normStart / self.total_length * 360
end_angle = self.normEnd / self.total_length * 360
if self.seg_dir == "+" and self.gParent.strand == "+":
s_ang = start_angle
e_ang = end_angle
sm = "<"
em = "s"
elif self.seg_dir == "+" and self.gParent.strand == "-":
s_ang = end_angle
e_ang = start_angle
sm = ">"
em = "s"
elif self.seg_dir == "-" and self.gParent.strand == "+":
s_ang = end_angle
e_ang = start_angle
sm = ">"
em = "s"
else:
s_ang = start_angle
e_ang = end_angle
sm = "<"
em = "s"
return s_ang, e_ang, sm, em, tm
def draw_marker_ends(self, gbh):
# iterate over gdrops and see how many times the gene appears.
# self.gdrops = sorted(self.gdrops, key=lambda x: x[-1])
if self.hasStart or self.hasEnd:
s_ang, e_ang, sm, em, tm = self.get_angles()
me_color = 'red' if self.gParent.highlight_name else 'silver'
if self.hasStart:
x_m, y_m = pol2cart(gbh, (s_ang / 360 * 2 * np.pi))
t = matplotlib.markers.MarkerStyle(marker=sm)
t._transform = t.get_transform().rotate_deg(s_ang - 89)
plt.scatter(x_m, y_m, marker=t, s=15, color=me_color, zorder=3, alpha=0.8)
if self.hasEnd:
x_m, y_m = pol2cart(gbh, (e_ang / 360 * 2 * np.pi))
t = matplotlib.markers.MarkerStyle(marker=em)
t._transform = t.get_transform().rotate_deg(e_ang - 91)
plt.scatter(x_m, y_m, marker=t, s=5, color=me_color, zorder=3, alpha=0.8)
# makes a gene object from parsed refGene data
# this stores global properties for the gene
class gene(object):
def __init__(self, gchrom, gstart, gend, gdata, highlight_name):
self.gchrom = gchrom
self.gstart = gstart
self.gend = gend
self.gname = gdata[-4]
self.strand = gdata[3]
self.highlight_name = highlight_name
estarts = [int(x) for x in gdata[9].rsplit(",") if x]
eends = [int(x) for x in gdata[10].rsplit(",") if x]
self.eposns = list(zip(estarts, eends))
self.gdrops = []
self.gdrops_go_to_link = set()
class feature_track(object):
def __init__(self, index, primary_data, secondary_data, dd, dv_min, dv_max):
self.index = index
self.primary_data = primary_data
self.secondary_data = secondary_data
self.track_props = dd
self.track_min = dv_min
self.track_max = dv_max
self.sec_rsf = 1
self.sec_rss = 0
self.minsec = 0
self.base = 0
self.top = 0
self.primary_links = []
self.secondary_links = []
class Link(object):
def __init__(self, chromA, chromB, data_tup):
self.chromA = chromA
self.chromB = chromB
self.startA, self.endA = data_tup[0], data_tup[1]
self.startB, self.endB = data_tup[2], data_tup[3]
self.score = data_tup[4][0]
self.link_color = data_tup[4][1]
self.posA_hits = []
self.posB_hits = []
# Set colors for chromosomes
def get_chr_colors():
to_add = plt.cm.get_cmap(None, 4).colors[1:]
# color_vect = ["#ffe8ed","indianred","salmon","burlywood",'#d5b60a',"xkcd:algae",to_add[0],"darkslateblue",
# to_add[2],"#017374","#734a65","#bffe28","xkcd:darkgreen","#910951","xkcd:stone",
# "xkcd:purpley","xkcd:brown","lavender","darkseagreen","powderblue","#ff073a",to_add[1],
# "magenta","plum"]
color_vect = ["aqua", "rosybrown", "salmon", "bisque", 'goldenrod', "xkcd:algae", to_add[0], "darkslateblue",
"yellow", "sienna", "purple", "#bffe28", "xkcd:darkgreen", "#910951", "xkcd:stone",
"xkcd:purpley", "xkcd:brown", "lavender", "darkseagreen", "powderblue", "crimson", to_add[1],
"fuchsia", "pink"]
chrnames = [str(i) for i in (list(range(1, 23)))] + ["X", "Y"]
chromosome_colors = dict(zip(["chr" + i for i in chrnames], color_vect))
for i in range(len(chrnames)):
chromosome_colors[chrnames[i]] = color_vect[i]
return chromosome_colors
# rotate text to be legible on both sides of circle
def correct_text_angle(text_angle):
if 90 < abs(text_angle) < 270:
text_angle -= 180
ha = "right"
else:
ha = "left"
return text_angle, ha
def pair_is_edge(a_id, b_id, a_dir, b_dir, bpg_dict, seg_end_pos_d):
rObj1_end = seg_end_pos_d[a_id][-1] if a_dir == "+" else seg_end_pos_d[a_id][0]
rObj2_start = seg_end_pos_d[b_id][0] if b_dir == "+" else seg_end_pos_d[b_id][-1]
return rObj1_end in bpg_dict[rObj2_start]
# parse the breakpoint graph to indicate for two endpoints if there is an edge.
def parse_BPG(BPG_file):
bidirectional_edge_dict = defaultdict(set)
seg_end_pos_d = {}
seqnum = 0
with open(BPG_file) as infile:
for line in infile:
fields = line.rstrip().rsplit()
if not fields:
continue
if fields[0] in ["concordant", "discordant"]:
e_rep = fields[1].rsplit("->")
start = e_rep[0][:-1]
end = e_rep[1][:-1]
bidirectional_edge_dict[start].add(end)
bidirectional_edge_dict[end].add(start)
elif fields[0] == "sequence":
seqnum += 1
seg_end_pos_d[str(seqnum)] = (fields[1][:-1], fields[2][:-1])
return bidirectional_edge_dict, seg_end_pos_d
# Read an AA-formatted cycles file
def parse_cycles_file(cycles_file):
cycles = {}
segSeqD = {}
circular_D = {}
with open(cycles_file) as infile:
for line in infile:
if line.startswith("Segment"):
fields = line.rstrip().split()
lowerBound = int(fields[3])
upperBound = int(fields[4])
chrom = fields[2]
segNum = fields[1]
segSeqD[segNum] = (chrom, lowerBound, upperBound)
elif "Cycle=" in line:
isCycle = True
curr_cycle = []
fields = line.rstrip().rsplit(";")
lineD = {x.rsplit("=")[0]: x.rsplit("=")[1] for x in fields}
lineD["Cycle"] = int(lineD["Cycle"])
segs = lineD["Segments"].rsplit(",")
for i in segs:
seg = i[:-1]
if seg != "0" and i:
strand = i[-1]
curr_cycle.append((seg, strand))
else:
isCycle = False
cycles[lineD["Cycle"]] = curr_cycle
circular_D[lineD["Cycle"]] = isCycle
return cycles, segSeqD, circular_D
def handle_struct_bed_data(struct_data):
#sort by the index
flatvals = [[chrom] + list(x) for chrom, cl in struct_data.items() for x in cl]
flatvals.sort(key=lambda x: x[3][0])
segSeqD = {}
rev_segSeqD = {}
seg_end_pos_d = {}
bidirectional_edge_dict = defaultdict(set)
cycle = []
connections = []
isCycle = True
uind = 0
for ind, i in enumerate(flatvals):
# print(i)
# 0 is chrom, 1 is index, 2 is start, 3 is end, 4 is tuple of datastuff
# datastuff is strand, connected
pt = (i[0], i[1], i[2])
if pt not in segSeqD.values():
uind += 1
segSeqD[uind] = pt
rev_segSeqD[pt] = uind
cind = rev_segSeqD[pt]
cycle.append((cind, i[3][1]))
seg_end_pos_d[cind] = (pt[0] + ':' + str(pt[1]), pt[0] + ':' + str(pt[2]))
connections.append(i[3][2] == 'True') # expecting 'True' or 'False' string in this column from the file
# if non-cyclic path, put zeros on it
if not all(connections):
# put zeros on it -- no, those are ordinarily stripped!
# cycle = [(0, '+')] + cycle + [(0, '+')]
isCycle = False
# make the bpg dict
# print(cycle)
for a, b, conn in zip(cycle, cycle[1:] + [cycle[0]], connections):
# print(a,b,conn)
if conn:
ae = seg_end_pos_d[a[0]][1] if a[1] == '+' else seg_end_pos_d[a[0]][0]
bs = seg_end_pos_d[b[0]][0] if b[1] == '+' else seg_end_pos_d[b[0]][1]
bidirectional_edge_dict[ae].add(bs)
bidirectional_edge_dict[bs].add(ae)
# print(bidirectional_edge_dict)
return cycle, isCycle, segSeqD, seg_end_pos_d, bidirectional_edge_dict
# return list of relevant genes sorted by starting position
def rel_genes(chrIntTree, pTup, gene_set=None):
if gene_set is None:
gene_set = set()
currGenes = {}
chrom = pTup[0]
overlappingT = chrIntTree[chrom][pTup[1]:pTup[2]]
gene_set_only = (len(gene_set) == 0)
for i in overlappingT:
gObj = i.data
gname = gObj.gname
is_other_feature = (gname.startswith("LOC") or gname.startswith("LINC") or gname.startswith("MIR"))
if gene_set_only:
gene_set.add(gname)
if not is_other_feature and gname in gene_set:
if gname not in currGenes:
currGenes[gname] = gObj
# gene appears in file twice, if one is larger, use it. else just use the widest endpoints
else:
oldTStart = currGenes[gname].gstart
oldTEnd = currGenes[gname].gend
if gObj.gend - gObj.gstart > oldTEnd - oldTStart:
currGenes[gname] = copy.deepcopy(gObj)
else:
if gObj.gstart < oldTStart:
currGenes[gname].gstart = gObj.gstart
if gObj.gend > oldTEnd:
currGenes[gname].gend = gObj.gend
relGenes = sorted(currGenes.values(), key=lambda x: (x.gstart, x.gend))
return relGenes
# extract oncogenes from a file.
# Assumes refseq genome name in last column, or get the refseq name from a gff file
def parse_gene_subset_file(gene_list_file, gff=False):
gene_set = set()
with open(gene_list_file) as infile:
for line in infile:
fields = line.rstrip().split()
if not fields:
continue
if not gff:
gene_set.add(fields[-1].strip("\""))
else:
# parse the line and get the name
propFields = {x.split("=")[0]: x.split("=")[1] for x in fields[-1].rstrip(";").split(";")}
gene_set.add(propFields["Name"])
return gene_set
def parse_genes(ref, gene_highlight_list):
t = defaultdict(IntervalTree)
__location__ = os.path.realpath(os.path.join(os.getcwd(), os.path.dirname(__file__)))
if ref == "GRCh37" or ref == "hg19":
refGene_name = "refGene_hg19.txt"
elif ref == "GRCm38" or ref == "mm10":
refGene_name = "refGene_mm10.txt"
else:
refGene_name = "refGene_" + ref + ".txt"
seenNames = set()
with open(os.path.join(__location__, "resources", refGene_name)) as infile:
for line in infile:
fields = line.rsplit("\t")
currChrom = fields[2]
if (ref == "GRCh37" or ref == "GRCm38") and not currChrom.startswith("hpv"):
currChrom = currChrom[3:]
tstart = int(fields[4])
tend = int(fields[5])
gname = fields[-4]
if gname not in seenNames:
seenNames.add(gname)
currGene = gene(currChrom, tstart, tend, fields, gname in gene_highlight_list)
t[currChrom][tstart:tend] = currGene
return t
def parse_bed(bedfile, store_all_additional_fields=False):
data_dict = defaultdict(list)
with open(bedfile) as infile:
if bedfile.endswith(".bedpe"):
for line in infile:
line = line.rstrip()
if not line.startswith("#") and line:
fields = line.rsplit("\t")
chromA = fields[0]
startA, endA = float(fields[1]), float(fields[2])
chromB = fields[3]
startB, endB = float(fields[4]), float(fields[5])
if len(fields) > 6:
score = float(fields[6])
else:
score = 1.0
if len(fields) > 7:
color = fields[7]
else:
color = 'red'
data = (score, color)
data_dict[(chromA, chromB)].append((startA, endA, startB, endB, data))
else:
for entry_index, line in enumerate(infile):
line = line.rstrip("\n")
if not line.startswith("#") and len(line) > 0:
fields = line.rsplit()
chrom = fields[0]
begin, end = float(fields[1]), float(fields[2])
if not store_all_additional_fields:
if len(fields) > 3:
data = float(fields[3])
# if np.isinf(data):
# data = None
else:
data = None
else:
data = tuple([entry_index] + fields[3:])
if data:
data_dict[chrom].append((begin, end, data))
return data_dict
def rescale_by_secondary(primary_dset, secondary_dset, chrom, mode):
# put secondary data into an intervaltree
if mode == True:
mode = "mean"
if mode != "mean" and mode != "each":
print("Incorrect norm by secondary mode selected, must be 'mean' or 'each'... using 'mean'")
if len(secondary_dset) == 0:
print("No secondary data! skipping normalization")
return primary_dset, secondary_dset
sit = IntervalTree()
normed_primary = defaultdict(list)
normed_secondary = defaultdict(list)
if mode == "each":
for point in secondary_dset[chrom]:
sit.addi(point[0], point[1], point[2])
normed_secondary[chrom].append([point[0], point[1], 2])
elif mode == "mean":
print("Normalizing 'mean' for secondary will update secondary")
lscale = 100000.0
runl = 0.
runs = 0.
c = 0
#for everything in secondary, compute a mean
for ival in secondary_dset.values():
for point in ival:
c+=1
l = (point[1] - point[0])/lscale
runl+=l
runs+=(l*point[2])
if c > 0:
allmean = runs/runl
else:
print("no secondary data, setting scale to 1")
allmean = 1.0
#replace everything in secondary with that mean
for point in secondary_dset[chrom]:
sit.addi(point[0], point[1], allmean)
normed_secondary[chrom].append([point[0], point[1], 2.0])
for point in primary_dset[chrom]:
hit_sec = list(sit[point[0]:point[1]])
if not hit_sec:
print("could not normalize " + str(point))
elif len(hit_sec) > 1:
print(str(point) + ": multiple secondary track hits for normalization, using first hit " + "(" + str(hit_sec[0]) + ")")
else:
normed_primary[chrom].append([point[0], point[1], point[2]/float(hit_sec[0].data)])
return normed_primary, normed_secondary
# take the feature data (cfc) and extract only the regions overlapping the reference segment in question (obj)
# append the coordinate restricted feature (restricted_cfc) to a list of features kept by the reference object (obj)
def store_bed_data(cfc, ref_placements, primary_end_trim=0, secondary_end_trim=0):
if cfc.track_props['tracktype'] == 'standard' or cfc.track_props['tracktype'] == 'rects':
# print("extracting features, ET", primary_end_trim)
for obj in ref_placements.values():
primeTrim = primary_end_trim
if obj.ref_end - obj.ref_start <= primary_end_trim*2:
primeTrim = max(0,(obj.ref_end - obj.ref_start)/2 - 2)
# print("reset ET ", primeTrim)
secTrim = secondary_end_trim
if obj.ref_end - obj.ref_start <= primary_end_trim * 2:
secTrim = max(0, (obj.ref_end - obj.ref_start) / 2 - 2)
# print("reset ET ", secTrim)
local_primary_data = defaultdict(list)
local_secondary_data = defaultdict(list)
#store primary data
for dstore, currdata, currTrim, uc, lc, in zip([local_primary_data, local_secondary_data],
[cfc.primary_data[obj.chrom], cfc.secondary_data[obj.chrom]],
[primeTrim, secTrim], [cfc.track_props['primary_upper_cap'],
cfc.track_props['secondary_upper_cap']],
[cfc.track_props['primary_lower_cap'],
cfc.track_props['secondary_lower_cap']]):
for init_point in currdata:
#open the interval by 1
point = [init_point[0], init_point[1]+1, init_point[2]]
if obj.ref_start+currTrim <= point[0] <= obj.ref_end-currTrim or \
obj.ref_start+currTrim <= point[1] <= obj.ref_end-currTrim:
if uc and point[2] > uc:
point[2] = uc
if lc and point[2] < lc:
point[2] = lc
dstore[obj.chrom].append(point)
elif point[0] < obj.ref_start+currTrim and point[1] > obj.ref_end-currTrim:
dstore[obj.chrom].append(point)
restricted_cfc = copy.copy(cfc)
if cfc.track_props['rescale_by_secondary']:
print(obj.to_string(), "normalizing by secondary")
normed_primary, normed_secondary = rescale_by_secondary(local_primary_data, local_secondary_data,
obj.chrom, cfc.track_props['rescale_by_secondary'])
restricted_cfc.primary_data = normed_primary
restricted_cfc.secondary_data = normed_secondary
elif cfc.track_props['rescale_by_count']:
print(obj.to_string(), "rescaling by count")
normed_primary = defaultdict(list)
for point in local_primary_data[obj.chrom]:
normed_primary[obj.chrom].append([point[0], point[1], point[2] / float(obj.seg_count)])
restricted_cfc.primary_data = normed_primary
restricted_cfc.secondary_data = local_secondary_data
else:
restricted_cfc.primary_data = local_primary_data
restricted_cfc.secondary_data = local_secondary_data
obj.feature_tracks.append(restricted_cfc)
print(obj.to_string(),"now has",len(obj.feature_tracks),"tracks")
elif cfc.track_props['tracktype'] == 'links':
for cdat, c_link_store in zip([cfc.primary_data, cfc.secondary_data], [cfc.primary_links, cfc.secondary_links]):
for cp, data_tup_list in cdat.items():
for data_tup in data_tup_list:
cLink = cfc.Link(cp[0], cp[1], data_tup)
# hitA, hitB = False, False
for obj in ref_placements.values():
seg_len = obj.ref_end - obj.ref_start
# check if it's chromA
if obj.chrom == cLink.chromA:
# check if overlap coord
if obj.ref_start <= cLink.startA <= obj.ref_end or \
obj.ref_start <= cLink.endA <= obj.ref_end:
# compute the normpos
# print("matched", cp, data_tup, "A")
if obj.direction == "+":
normStart_A = obj.abs_start_pos + max(0, cLink.startA - obj.ref_start)
normEnd_A = obj.abs_start_pos + min(seg_len, cLink.endA - obj.ref_start)
else:
normEnd_A = obj.abs_start_pos + min(seg_len, obj.ref_end - cLink.startA)
normStart_A = obj.abs_start_pos + max(0, obj.ref_end - cLink.endA)
cLink.posA_hits.append((normStart_A, normEnd_A))
# hitA = True
# check if it's chromB
if obj.chrom == cLink.chromB:
# check if overlap coord
if obj.ref_start <= cLink.startB <= obj.ref_end or \
obj.ref_start <= cLink.endB <= obj.ref_end:
# print("matched", cp, data_tup, "B")
# compute the normpos
if obj.direction == "+":
normStart_B = obj.abs_start_pos + max(0, cLink.startB - obj.ref_start)
normEnd_B = obj.abs_start_pos + min(seg_len, cLink.endB - obj.ref_start)
else:
normEnd_B = obj.abs_start_pos + min(seg_len, obj.ref_end - cLink.startB)
normStart_B = obj.abs_start_pos + max(0, obj.ref_end - cLink.endB)
cLink.posB_hits.append((normStart_B, normEnd_B))
# hitB = True
# if cfc.track_props['link_single_match'] and hitA and hitB:
# break
c_link_store.append(cLink)
# holds the place of the feature
for obj in ref_placements.values():
obj.feature_tracks.append(cfc)
# print(obj.to_string(), "now has", len(obj.feature_tracks), "tracks")
# Assign interior track data to a location(s) in a refobj, and create a new refobj for that overlapping region,
# to represent the interior track data
# TODO: What if the segments in the inside track are scrambled w.r.t the reference track?
def handle_IS_data_relaxed(ref_placements, interior_cycle, interior_segSeqD, IS_isCircular, IS_bh, cycleColor='lightskyblue'):
cycle_seg_counts = get_seg_amplicon_count(interior_cycle)
prev_seg_index_is_adj, next_seg_index_is_adj = adjacent_segs(interior_cycle, interior_segSeqD, IS_isCircular)
# need to match to the ref_placements
valid_link_pairs = set(zip(interior_cycle[:-1],interior_cycle[1:]))
if IS_isCircular:
valid_link_pairs.add((interior_cycle[-1],interior_cycle[0]))
new_interior_cycle = []
new_IS_links = []
# lastIndHit = -1
IS_rObj_placements = {}
u_ind = 0
for obj in ref_placements.values():
s_to_add = []
c_to_add = []
seg_len = obj.ref_end - obj.ref_start
for ind, (segID, segdir) in enumerate(interior_cycle):
padj, nadj = prev_seg_index_is_adj[ind], next_seg_index_is_adj[ind]
seg_id_count = cycle_seg_counts[segID]
c, s, e = interior_segSeqD[segID]
if c != obj.chrom:
continue
# overlaps the ref seg
if obj.ref_start <= s <= obj.ref_end or obj.ref_start <= e <= obj.ref_end:
# compute the normpos
if obj.direction == "+":
normStart = obj.abs_start_pos + max(0, s - obj.ref_start)
normEnd = obj.abs_start_pos + min(seg_len, e - obj.ref_start)
else:
normStart = obj.abs_start_pos + min(0, obj.ref_end - e)
normEnd = obj.abs_start_pos + max(seg_len, obj.ref_end - s)
# make a refobj
currObj = CycleVizElemObj(segID, c, s, e, obj.direction, normStart, normEnd, seg_id_count, padj, nadj)
currObj.custom_face_color = cycleColor
currObj.custom_bh = IS_bh
s_to_add.append(currObj)
c_to_add.append((segID, segdir))
if not s_to_add:
continue
ssta, scta = zip(*sorted(zip(s_to_add, c_to_add), key=lambda x: x[0].abs_start_pos))
new_interior_cycle.extend(scta)
for rObj, ct in zip(ssta, scta):
IS_rObj_placements[u_ind] = rObj
u_ind+=1
print(new_interior_cycle)
for a, b in zip(new_interior_cycle[:-1], new_interior_cycle[1:]):
if (a,b) in valid_link_pairs or (b,a) in valid_link_pairs:
new_IS_links.append(True)
else:
new_IS_links.append(False)
if (new_interior_cycle[-1], new_interior_cycle[0]) in valid_link_pairs or (new_interior_cycle[0], new_interior_cycle[-1]) in valid_link_pairs:
new_IS_links.append(True)
else:
new_IS_links.append(False)
# print(new_IS_links)
# print(new_interior_cycle)
return IS_rObj_placements, new_interior_cycle, new_IS_links
def cycles_match(ref_placements, cycle, isCycle, start_ref_ind, interior_cycle, interior_segSeqD, IS_isCircular):
ref_start_seg = start_ref_ind
start_offset = 0
ref_end_seg = None
end_offset = 0
interior_cumulative_bounds = [0, ]
prev_seg_index_is_adj, next_seg_index_is_adj = adjacent_segs(interior_cycle, interior_segSeqD, IS_isCircular)
# print(prev_seg_index_is_adj)
# print(next_seg_index_is_adj)
for ind, (segID, intdir) in enumerate(interior_cycle):
c, s, e = interior_segSeqD[segID]
cumulative_pos = interior_cumulative_bounds[-1] + e - s
interior_cumulative_bounds.append(cumulative_pos)
# print(interior_cumulative_bounds)
left_interior_cycle_index = 0
segID, intdir = interior_cycle[left_interior_cycle_index]
c, s, e = interior_segSeqD[segID]
rObj = ref_placements[start_ref_ind]
if rObj.chrom != c or rObj.direction != intdir or not (rObj.ref_start <= s <= rObj.ref_end):
return False, ref_start_seg, ref_end_seg, start_offset, end_offset
print("found initial matching seg: ", rObj.to_string())
if intdir == "+":
curr_interior_offset = s - rObj.ref_start
else:
curr_interior_offset = rObj.ref_end - e
start_offset = curr_interior_offset
print(start_offset, "start offset")
ref_ind = start_ref_ind
while left_interior_cycle_index < len(interior_cumulative_bounds) - 1:
tb = False
print("RID", ref_ind, ref_placements[ref_ind].to_string())
if ref_ind >= len(cycle) - 1 and isCycle:
ref_ind = -1
right_interior_cycle_index_hit = bisect.bisect(interior_cumulative_bounds, curr_interior_offset) - 1
# print("Right index", right_interior_cycle_index_hit, curr_interior_offset, interior_cumulative_bounds)
ref_end_seg = ref_ind
segID, intdir = interior_cycle[left_interior_cycle_index]
c, s, e = interior_segSeqD[segID]
if rObj.direction == "+":
end_offset = e - rObj.ref_start
else:
end_offset = e - rObj.ref_start
interior_contains_ref = s <= rObj.ref_start <= rObj.ref_end <= e
overlaps = (rObj.ref_start <= s <= rObj.ref_end or rObj.ref_start <= e <= rObj.ref_end)
# print(c, rObj.chrom, intdir, rObj.direction, overlaps)
if c != rObj.chrom or intdir != rObj.direction or not any([interior_contains_ref, overlaps]):
print("different chrom, dir or bounds")
return False, ref_start_seg, ref_end_seg, start_offset, end_offset
# print(right_interior_cycle_index_hit, left_interior_cycle_index)
if right_interior_cycle_index_hit != left_interior_cycle_index:
# print(right_interior_cycle_index_hit, len(interior_cumulative_bounds) - 1)
if right_interior_cycle_index_hit == len(interior_cumulative_bounds) - 1:
for x in range(left_interior_cycle_index, right_interior_cycle_index_hit-1):
if not next_seg_index_is_adj[x]:
print(x, "was not adjacent")
return False, ref_start_seg, ref_end_seg, start_offset, end_offset
if rObj.direction == "+":
# print(s,e, rObj.ref_start, rObj.ref_end)
end_offset = e - rObj.ref_start
print(end_offset, "+ end offset")
else:
# print(s,e, rObj.ref_start, rObj.ref_end)
end_offset = e - rObj.ref_start
print(end_offset, "- end offset")
print("Reached end of interior cycle")
return True, ref_start_seg, ref_end_seg, start_offset, end_offset
else:
# print("not hitting end yet")
if rObj.direction == "+" and abs(rObj.ref_end - e) < 2:
print("both uptick positive")
left_interior_cycle_index+=1
curr_interior_offset += (rObj.ref_end - rObj.ref_start)
ref_ind += 1
rObj = ref_placements[ref_ind]
elif rObj.direction == "-" and abs(rObj.ref_start - s) < 2:
print("both uptick negative")
left_interior_cycle_index+=1
curr_interior_offset += (rObj.ref_end - rObj.ref_start)
ref_ind += 1
rObj = ref_placements[ref_ind]
else:
for x in range(left_interior_cycle_index, right_interior_cycle_index_hit):
if not next_seg_index_is_adj[x]:
print(x, "was not adjacent")
return False, ref_start_seg, ref_end_seg, start_offset, end_offset
print("ends were not aligned")
left_interior_cycle_index = right_interior_cycle_index_hit
else:
# it was the same interior seg
print("same interior segment")
# print(c,s,e)
#
# print(rObj.direction, s, e, rObj.ref_start, rObj.ref_end)
if rObj.direction == "+" and abs(rObj.ref_end - e) < 2:
print("uptick both positive")
left_interior_cycle_index += 1
tb = True
elif rObj.direction == "-" and abs(rObj.ref_start - s) < 2:
print("uptick both negative")
left_interior_cycle_index += 1
tb = True
curr_interior_offset += (rObj.ref_end - rObj.ref_start)
ref_ind += 1
rObj = ref_placements[ref_ind]
# if ref_ind == start_ref_ind:
# print("went full circle")
# return False, ref_start_seg, ref_end_seg, start_offset, end_offset
# print(right_interior_cycle_index_hit, len(interior_cumulative_bounds)-1, tb)
if right_interior_cycle_index_hit == len(interior_cumulative_bounds) - 2 and tb:
print("Finished matching")
return True, ref_start_seg, ref_end_seg, start_offset, end_offset
def handle_IS_data(ref_placements, cycle, isCycle, interior_cycle, interior_segSeqD, IS_isCircular, IS_bh, cycleColor='lightskyblue'):
# find all the locations where the IS matches the ref perfectly
# cycle_seg_counts = get_seg_amplicon_count(interior_cycle)
# prev_seg_index_is_adj, next_seg_index_is_adj = adjacent_segs(interior_cycle, interior_segSeqD, IS_isCircular)
# need to match to the ref_placements
# valid_link_pairs = set(zip(interior_cycle[:-1], interior_cycle[1:]))
# if IS_isCircular:
# valid_link_pairs.add((interior_cycle[-1], interior_cycle[0]))
# covered_to = 0
for ind, obj in ref_placements.items():
s_to_add = []
c_to_add = []
# seg_len = obj.ref_end - obj.ref_start
segID, segdir = interior_cycle[0]
c, s, e = interior_segSeqD[segID]
if segdir == "+":
spoint = s
else:
spoint = e
# print(segID, c, obj.chrom, segdir, obj.direction, obj.ref_start, spoint, obj.ref_end, obj.to_string())
if c == obj.chrom and obj.direction == segdir and obj.ref_start <= spoint <= obj.ref_end:
# launch a matching search
matched, ref_start_ind, ref_end_ind, ref_start_offset, ref_end_offset = cycles_match(ref_placements, cycle,
isCycle, ind, interior_cycle, interior_segSeqD, IS_isCircular)
print(matched, ref_start_ind, ref_end_ind, ref_start_offset, ref_end_offset)
print("")
if not matched:
continue
if ref_end_ind < ref_start_ind:
ref_inds_hit = list(range(ref_start_ind, len(cycle))) + list(range(0, ref_end_ind+1))
else:
ref_inds_hit = range(ref_start_ind, ref_end_ind+1)
# print("RIH", ref_inds_hit)
for matched_ref_ind in ref_inds_hit:
curr_rObj = ref_placements[matched_ref_ind]
if matched_ref_ind == ref_start_ind:
if curr_rObj.direction == "+":
normStart = curr_rObj.abs_start_pos + ref_start_offset
else:
normStart = curr_rObj.abs_start_pos + ref_start_offset
if ref_start_ind == ref_end_ind:
normEnd = curr_rObj.abs_start_pos + ref_end_offset
else:
normEnd = curr_rObj.abs_end_pos
seg_chrom, seg_s, seg_e = interior_segSeqD[interior_cycle[0][0]]
# else:
# normStart = curr_rObj.abs_start_pos
# seg_chrom, seg_s, seg_e = curr_rObj.chrom, curr_rObj.ref_start, curr_rObj.ref_end
elif matched_ref_ind == ref_end_ind:
normStart = curr_rObj.abs_start_pos
normEnd = curr_rObj.abs_start_pos + ref_end_offset
if curr_rObj.direction == "+":
normEnd = curr_rObj.abs_start_pos + ref_end_offset
else:
normStart = curr_rObj.abs_start_pos + ref_end_offset
seg_chrom, seg_s, seg_e = interior_segSeqD[interior_cycle[-1][0]]
else:
normStart = curr_rObj.abs_start_pos
normEnd = curr_rObj.abs_end_pos