-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy patharcPlot.py
executable file
·1272 lines (846 loc) · 40.5 KB
/
arcPlot.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/python
# ---------------------------------------------------------------------------------------
# Flexible Arc Plotting code
# Anthony Mustoe
# Weeks lab, UNC
# 2016, 2017, 2018
#
# Modifications
# Version 2.1 with plot profile option
#
# ---------------------------------------------------------------------------------------
import sys, os, math, argparse
import RNAtools2 as RNAtools
import matplotlib
#matplotlib.use('Agg')
matplotlib.rcParams['xtick.major.size'] = 8
matplotlib.rcParams['xtick.major.width'] = 2.5
matplotlib.rcParams['xtick.direction'] = 'out'
matplotlib.rcParams['xtick.minor.size'] = 4
matplotlib.rcParams['xtick.minor.width'] = 1
matplotlib.rcParams['pdf.fonttype'] = 42
matplotlib.rcParams['font.sans-serif'] = 'Arial'
import matplotlib.pyplot as plot
import matplotlib.patches as patches
import matplotlib.gridspec as gridspec
from matplotlib.path import Path
from matplotlib.ticker import MultipleLocator, FormatStrFormatter
import numpy as np
class ArcLegend(object):
"""Container for Legend for arc plot"""
def __init__(self, title=None, colors=[], labels=[], msg=None):
assert len(colors)==len(labels), "colors and labels must be the same size"
self.title=title
self.colors = colors
self.labels = labels
self.msg = msg
def append(self, t, colors, labels):
if self.title is not None and t is not None:
self.title+=' & '+t
elif self.title is None:
self.title = t
self.colors.extend(colors)
self.labels.extend(labels)
def drawLegend(self, ax, xbound, ybound):
"""Draw legend on axes, computing location based on axes bounds
ax = axes object to draw on
xbound = xboundary of axis
ybound = yboundary of axis
"""
spacing = 3
# determine bounding box
nlines = len(self.colors) + int(self.title is not None) + 1
height = spacing*nlines
width = 15
if self.title is not None and len(self.title) > width:
width = len(self.title)
#xloc = xbound-width
#if xloc < 0:
# xloc = 0
#if ybound < 0:
# yloc = ybound+height+2
# ax.add_patch(patches.Rectangle( (xloc-2, yloc-height+4), width, height, fc='white', lw=1.0))
#else:
# yloc = ybound-height+2
# ax.add_patch(patches.Rectangle( (xloc-2, yloc+4), width, height, fc='white', lw=1.0))
xloc = xbound
yloc = ybound
# write the title
if self.title is not None:
ax.text(xloc, yloc, self.title, horizontalalignment='left',
size="11",weight="medium", color="black")
yloc -= spacing
for i, c in enumerate(self.colors):
# self.colors is a list of dict patch specifications, so c is a dict
ax.add_patch(patches.Rectangle( (xloc, yloc), 1.5, 1.5, color=c, clip_on=False ) )
# now add label
ax.text(xloc+2.5, yloc, self.labels[i], horizontalalignment='left',
size="8",weight="normal", color="black")
yloc -= spacing
if self.msg:
ax.text(xloc, yloc, self.msg, horizontalalignment='left',
size="8",weight="normal", color="black")
class ArcPlot(object):
def __init__(self, title='', fasta=None):
self.title = title
self.seq = ''
if fasta:
self.addFasta(fasta)
self.seqcolors = ['black']
self.drawseq = True
self.grid = False
self.handleLength = 4*(math.sqrt(2)-1)/3
self.adjust = 1.4
self.topPatches = []
self.botPatches = []
self.height = [0, 0] # the figure height
self.intdistance = None
self.reactprofile = None
self.reactprofileType = 'SHAPE'
self.toplegend = None
self.botlegend = None
def addFasta(self, fastafile):
read = False
with open(fastafile) as inp:
for line in inp:
if line[0]=='>':
read = True
continue
line = line.strip()
if read and len(line) > 0:
self.seq += line
def addArcPath(self, outerPair, innerPair=None, panel=1, color = 'black', alpha=0.5, window=1):
""" add the arPath object for a given set of parameters
If only outerPair is passed, innerPair is computed from window
If both outerPair and innerPair are passed, window is not used
"""
if innerPair is None:
innerPair = [outerPair[0]+0.5 + window-1, outerPair[1]-0.5]
outerPair = [outerPair[0]-0.5, outerPair[1]+0.5 + window-1]
else:
innerPair = [innerPair[0]+0.5, innerPair[1]-0.5]
outerPair = [outerPair[0]-0.5, outerPair[1]+0.5]
innerRadius = (innerPair[1] - innerPair[0])/2.0
outerRadius = (outerPair[1] - outerPair[0])/2.0
verts = []
codes = []
# outer left
verts.append( (outerPair[0], 0) )
codes.append( Path.MOVETO )
# outer left control 1
verts.append( (outerPair[0], panel*self.handleLength*outerRadius) )
codes.append( Path.CURVE4 )
# outer left control 2
verts.append( (outerPair[0]+outerRadius*(1-self.handleLength), panel*outerRadius) )
codes.append( Path.CURVE4 )
# outer center
verts.append( (outerPair[0]+outerRadius, panel*outerRadius) )
codes.append( Path.CURVE4 )
# outer right control 1
verts.append( (outerPair[0]+outerRadius*(1+self.handleLength), panel*outerRadius) )
codes.append( Path.CURVE4 )
# outer right control 2
verts.append( (outerPair[1], panel*self.handleLength*outerRadius) )
codes.append( Path.LINETO )
# outer right
verts.append( (outerPair[1], 0) )
codes.append( Path.LINETO )
# inner right
verts.append( (innerPair[1], 0) )
codes.append( Path.LINETO )
# inner right control 1
verts.append( (innerPair[1], panel*self.handleLength*innerRadius) )
codes.append( Path.CURVE4 )
# inner right control 2
verts.append( (innerPair[0]+innerRadius*(1+self.handleLength), panel*innerRadius) )
codes.append( Path.CURVE4 )
# inner center
verts.append( (innerPair[0]+innerRadius, panel*innerRadius) )
codes.append( Path.CURVE4 )
# inner left control 1
verts.append( (innerPair[0]+innerRadius*(1-self.handleLength), panel*innerRadius) )
codes.append( Path.CURVE4 )
# inner left control 2
verts.append( (innerPair[0], panel*self.handleLength*innerRadius) )
codes.append( Path.LINETO )
# inner left
verts.append( (innerPair[0], 0) )
codes.append( Path.LINETO )
# outer left duplicate
verts.append( (outerPair[0], 0) )
codes.append( Path.CLOSEPOLY )
# rescale verts
if panel == 1:
adval = self.adjust
else:
adval = -(self.adjust-1)
# move arcs away from x-axis
verts = [ (x,y+adval) for x,y in verts ]
indpath = Path(verts, codes)
patch = patches.PathPatch(indpath, facecolor=color, alpha=alpha,
linewidth=0, edgecolor='none')
if panel == 1:
self.topPatches.append(patch)
if outerRadius > self.height[1]:
self.height[1] = outerRadius
else:
self.botPatches.append(patch)
if outerRadius > self.height[0]:
self.height[0] = outerRadius
def plotProfile(self, ax, bounds=None, colthresh = (-10, 0.4, 0.85, 3), heightscale=None):
"""Add a reactivity profile to the axes (self.reactprofile needs to be set)
ax = axes object to add plot. Expected to be top axis
colthresh = thresholds to bin reactivity data.
First element indicates "No-data lower bound"
Last element indicates "Max reactivity" -- values are trucated above this
heightscale = scaling to control height of bars
"""
if self.reactprofile is None:
return
# check to see if DMS and colthresh defaults not overridden
if self.reactprofileType == 'DMS' and colthresh == (-10,0.4,0.85,3):
colthresh = (-10, 0.15, 0.4, 1)
xvals = [ [] for i in range(4) ]
yvals = [ [] for i in range(4) ]
if heightscale is None:
heightscale = max(4, min(10, len(self.reactprofile)/50.))
heightscale = min(max(self.height)/4., heightscale)
if self.reactprofileType == 'DMS': # adjust for compressed ploting range
heightscale *= 2
for x,y in enumerate(self.reactprofile):
if bounds is not None and x<bounds[0] or x>bounds[1]:
continue
if y is None or y != y or y<colthresh[0]:
xvals[0].append(x+1)
yvals[0].append(0.6*heightscale+self.adjust)
elif y < colthresh[1]:
xvals[1].append(x+1)
yvals[1].append(y*heightscale)
elif y < colthresh[2]:
xvals[2].append(x+1)
yvals[2].append(y*heightscale)
else:
xvals[3].append(x+1)
if y > colthresh[3]:
yvals[3].append(colthresh[3]*heightscale)
else:
yvals[3].append(y*heightscale)
ax.bar(xvals[0], yvals[0], alpha=0.7, linewidth=0, color=(179./255, 171./255, 148./255),
align='center', clip_on=False, bottom=-0.3*heightscale)
ax.bar(xvals[1], yvals[1], alpha=0.7, linewidth=0, color='black',
align='center', clip_on=False, bottom=self.adjust)
ax.bar(xvals[2], yvals[2], alpha=0.7, linewidth=0, color='orange',
align='center', clip_on=False, bottom=self.adjust)
ax.bar(xvals[3], yvals[3], alpha=0.7, linewidth=0, color='red',
align='center', clip_on=False, bottom=self.adjust)
# deal with the axis
ax.axes.get_yaxis().set_visible(True)
ax.tick_params(axis='y', direction='out', labelsize=6, left=True, right=False)
ax.set_yticks( np.array(colthresh[1:])*heightscale+self.adjust )
labels = [str(x) for x in colthresh[1:]]
labels[-1] = '>'+labels[-1]
ax.set_yticklabels( labels )
ax.set_ylabel('Norm. React.', position=(0,0), ha='left', size=6)
ax.set_frame_on(True)
for l in ('right','top','bottom'):
ax.spines[l].set_visible(False)
ax.spines['left'].set_bounds(self.adjust, colthresh[3]*heightscale+self.adjust)
def highlightLowReactivity(self, profile, cutoff=0.0001, window=1):
"""Profile is a np array (0-indexed) of values"""
for i,r in enumerate(profile):
if r<cutoff:
patch = patches.Rectangle((i+0.5,0),window,4,linewidth=0,fill=True,alpha=0.2)
self.topPatches.append(patch)
patch = patches.Rectangle((i+0.5,-4),window,4,linewidth=0,fill=True,alpha=0.2)
self.botPatches.append(patch)
def writePlot(self, outPath="arcs.pdf", bounds=None, write=True,
msg=None, msg_pos=(0,1), msg_kwargs={}, **args):
cutbounds = True
if bounds is None:
bounds = (0,len(self.seq))
cutbounds = False
else:
bounds = [bounds[0]-0.5, bounds[1]+0.5] # make new copy
doubleplot = len(self.botPatches)>0
scaleFactor = 0.05
figWidth = (bounds[1]-bounds[0])*scaleFactor
figHeight = 2*max(self.height)*scaleFactor
fig = plot.figure( figsize=(figWidth, figHeight)) # 500*scaleFactor
fig.subplots_adjust(hspace=0.0)
axT = fig.add_subplot(211)
axB = None
for pat in self.topPatches:
axT.add_patch(pat)
pat.set_clip_on(cutbounds)
axT.set_xlim(bounds)
axT.set_ylim(0, max(self.height))
axT.set_frame_on(False)
axT.axes.get_yaxis().set_visible(False)
if self.toplegend:
self.toplegend.drawLegend(axT, bounds[0], max(20, self.height[1]*.5))
if doubleplot:
axB = fig.add_subplot(212, sharex=axT)
for pat in self.botPatches:
axB.add_patch(pat)
pat.set_clip_on(cutbounds)
axB.set_xlim(bounds)
axB.set_ylim(-max(self.height), 0)
axB.set_frame_on(False)
axB.axes.get_yaxis().set_visible(False)
axB.tick_params(axis='both', which='both', top=False, bottom=False, labelbottom=False)
if self.botlegend:
self.botlegend.drawLegend(axB, bounds[0], -self.height[0]*.5)
# format sequence ticks
axT.get_xaxis().tick_bottom()
majorLocator = MultipleLocator(100)
minorLocator = MultipleLocator(20)
tickinterval = 5
axT.xaxis.set_major_locator(majorLocator)
axT.xaxis.set_major_formatter( FormatStrFormatter('%i') )
axT.xaxis.set_minor_locator(minorLocator)
axT.xaxis.set_minor_formatter( FormatStrFormatter('%i') )
majlabels = axT.axes.get_xaxis().get_majorticklabels()
minlabels = axT.axes.get_xaxis().get_minorticklabels()
majticks = axT.axes.get_xaxis().get_major_ticks()
minticks = axT.axes.get_xaxis().get_minor_ticks()
for label in majlabels:
label.set_size(10)
if bounds[0] == 0:
majlabels[1].set_visible(False)
minlabels[1].set_visible(False)
majticks[1].set_visible(False)
minticks[1].set_visible(False)
beginint, r = divmod(bounds[0], 20)
if r == 0:
beginint+=1
for i, label in enumerate(minlabels):
label.set_size(7)
if i % tickinterval == beginint:
label.set_visible(False)
# plot gridlines
if self.grid:
axT.grid(b=True, which="minor", color='black',linestyle='--', alpha=0.5)
axT.grid(b=True, which="major", color='black',linestyle='-', lw=2, alpha=0.8)
if doubleplot:
axB.grid(b=True, which="minor", color='black',linestyle='--', alpha=0.5)
axB.grid(b=True, which="major", color='black',linestyle='-', lw=2, alpha=0.8)
# write title (structure names)
if self.title:
axT.text(0.0, self.height[1]-2, self.title, horizontalalignment='left',
size="24",weight="bold", color="blue")
# put nuc sequence on axis
if self.drawseq:
fontProp = matplotlib.font_manager.FontProperties(family = "sans-serif",
style="normal",
weight="extra bold",
size="4")
for i, nuc in enumerate(self.seq):
if i<bounds[0]-1:
continue
elif i>bounds[1]-1:
break
if nuc == "T":
nuc = "U"
try:
col = self.seqcolors[i]
except IndexError:
col = "black"
axT.annotate(nuc, xy=(i+0.5, 0),fontproperties=fontProp,color=col,
annotation_clip=False,verticalalignment="baseline")
#if self.intdistance is not None:
# xvals = np.arange(bounds[0]+1, bounds[1]+1)
# yvals = self.intdistance[bounds[0]:bounds[1]+1]
# if np.mean(yvals) > 0:
# axT.plot( xvals, yvals, color="black", lw=2)
# else:
# axB.plot( xvals, yvals, color="black", lw=2)
if self.reactprofile is not None:
self.plotProfile(axT, bounds, **args)
if msg is not None:
axT.text(msg_pos[0], msg_pos[1], msg, transform=axT.transAxes, **msg_kwargs)
# save the figure
if write and outPath != 'show':
fig.savefig(outPath, dpi=100, bbox_inches="tight", transparent=True)
plot.close(fig)
elif write and outPath == 'show':
plot.show()
else:
return fig, axT, axB
def addCT(self, ctObj, color='black', alpha=0.7, panel=1):
seqlen = len(ctObj.ct)
if self.seq == '' or self.seq[0] == ' ':
self.seq = ctObj.seq
elif len(self.seq) != seqlen:
print("Warning:: CT length = {0}; expecting length = {1}".format(seqlen, len(self.seq)))
i = 0
while i < seqlen:
if ctObj.ct[i] > i:
outerPair = [ i+1, ctObj.ct[i] ]
# find the right side of helix
lastPairedNuc = ctObj.ct[i]
i += 1
while i<seqlen and (lastPairedNuc-ctObj.ct[i]) == 1:
lastPairedNuc = ctObj.ct[i]
i += 1
i -= 1
innerPair = [ i+1, ctObj.ct[i] ]
self.addArcPath(outerPair, innerPair, panel=panel, color=color, alpha=alpha)
i += 1
def addRings(self, ringfile, metric='z', panel=1, bins=None, contactfilter=(None,None),
filterneg=False):
"""Add arcs from ringmapper file
metric = z or sig
"""
if contactfilter[0]:
print("Performing contact filtering with distance={}".format(contactfilter[0]))
if filterneg:
print("Filtering out negative correlations")
colors = [(44,123,182), (44,123,182), (171,217,233), (255,255,255), (253,174,97), (215,25,28), (215,25,28)]
#colors = [(176,70,147), (176,70,147), (229,203,228), (255,255,255), (253,174,97), (215,25,28), (215,25,28)]
colors = [tuple([y/255.0 for y in x]) for x in colors]
alpha = [1.0, 1.0, 0.0, 0.0, 1.0, 1.0]
gradiant = [False, True, False, False, True, False]
if metric=='z':
if bins is None:
bins = [-50, -5, -1, 0, 1, 5, 50]
else:
bins = [-1e10, -bins[1], -bins[0], 0, bins[0], bins[1], 1e10]
else:
if bins is None:
bins = [-1e10, -100, -20, 0, 20, 100, 1e10]
else:
bins = [-1e-10, -bins[1], -bins[0], 0, bins[0], bins[1], 1e10]
allcorrs = []
with open(ringfile) as inp:
header = inp.readline().split()
window = int(header[1].split('=')[1])
mname = header[2].split('=')[1]
inp.readline()
# define molecule length if not set from something else
if self.seq == '':
self.seq = ' '*int(header[0])
for line in inp:
spl = line.split()
i = int(spl[0])
j = int(spl[1])
if contactfilter[0] and contactfilter[1].contactDistance(i,j) <= contactfilter[0]:
continue
if filterneg and int(spl[3])<0:
continue
if metric == 'z':
val = float(spl[4])
else:
val = float(spl[2])
if val > bins[3]:
allcorrs.append( ( int(spl[0]), int(spl[1]), float(spl[3])*val ) )
if len(allcorrs)==0:
print('WARNING: No RINGs passing filter in {}'.format(ringfile))
for i in range(len(bins)-1):
corrs = [c for c in allcorrs if bins[i]<c[2]<=bins[i+1]]
corrs.sort(key=lambda x:x[2])
for c in corrs:
if gradiant[i]:
col = self._colorGrad(c[2], colors[i], colors[i+1], bins[i], bins[i+1])
else:
col = colors[i]
self.addArcPath( c[:2], panel=panel, color=col, alpha=alpha[i], window=window)
# Add the legend
t = 'RING {0} win={1} {2}'.format(mname, window, metric.upper())
if filterneg:
c = (colors[4], colors[5])
l = ('>{}'.format(bins[4]), '>={}'.format(bins[5]))
else:
c = (colors[1], colors[2], colors[4], colors[5])
l = ('<={}'.format(bins[1]), '<{}'.format(bins[2]),
'>{}'.format(bins[4]), '>={}'.format(bins[5]))
if panel>0:
if self.toplegend is not None:
self.toplegend.append(t, c, l)
else:
self.toplegend = ArcLegend(title=t, colors=c, labels=l)
else:
if self.botlegend is not None:
self.botlegend.append(t, c, l)
else:
self.botlegend = ArcLegend(title=t, colors=c, labels=l)
def addPairProb(self, dpObj, panel=1, bins=None):
""" add pairing probability arcs from a dotplot object"""
if self.seq == '':
self.seq = ' '*dpObj.length
elif len(self.seq) != dpObj.length:
print("Warning:: dp file sequence length = {0}; CT/FASTA length = {1}".format(dpObj.length, len(self.seq)))
refcolors = [ (150,150,150), (255,204,0), (72,143,205) ,(81, 184, 72) ]
refalpha = [0.55, 0.65, 0.75, 0.85]
gradiant = [False, False, False, False]
if bins is None:
#bins = [0.01, 0.1, 0.5, 0.9, 1.0]
bins = [0.03, 0.1, 0.3, 0.8, 1.0]
colors = refcolors
alpha = refalpha
else:
if len(bins) > 5:
raise IndexError('{0} PairProb levels specified -- the maximum allowed is 4'.format(len(bins)-1))
colors = refcolors[-(len(bins)-1):]
alpha = refalpha[-(len(bins)-1):]
# convert colors to percents
colors = [tuple([y/255.0 for y in x]) for x in colors]
for i in range(len(bins)-1):
cutdp = dpObj.requireProb(bins[i], bins[i+1])
cutpairs = cutdp.pairList()
if len(cutpairs) == 0:
continue
# sort each of the pairs by its strength
strength = []
for p in cutpairs:
elem = cutdp.partfun[p[0]-1]
pos = ( elem['pair'] == p[1]-1) # make mask
strength.append(elem['log10'][pos][0]) # get value
strengthzip = list(zip(cutpairs, strength))
strengthzip.sort(key=lambda x: x[1], reverse=True)
cutpairs, strength = list(zip(*strengthzip))
# iterate through sorted pairs and draw arcs
for pindex, pair in enumerate(cutpairs):
if gradiant[i]:
col = self._colorGrad(strength[pindex], colors[i], colors[i+1],
bins[i], bins[i+1], log=True)
else:
col = colors[i]
self.addArcPath(pair, panel=panel, color=col, alpha=alpha[i])
# Add the legend
t = 'Pairing Prob.'
c = colors
l = ['>{}'.format(x) for x in bins[:-1]]
if panel>0:
self.toplegend = ArcLegend(title=t, colors=c, labels=l)
else:
self.botlegend = ArcLegend(title=t, colors=c, labels=l)
def addPairMap(self, pmobj, panel=1, plotall=False):
"""plot pairs output by pairmapper
plotall = True will plot all complementary correlations (not just 1&2)
"""
if len(pmobj.primary)==0 and len(pmobj.secondary)==0:
print('WARNING: No PAIR-MaP correlations in {}'.format(pmobj.sourcename))
def getZ(corrlist):
return [(x[0], x[1], x[3]) for x in corrlist]
colors = [(100, 100, 100), (30,194,255), (0,0,243)]
colors = [tuple([x/255.0 for x in c]) for c in colors]
if len(self.seq)==0:
self.seq = ' '*pmobj.molsize
if plotall:
self.plotAlphaGradient( getZ(pmobj.remainder), colors[0], (0.0,0.8),
1, 6, window=pmobj.window, panel=panel)
self.plotAlphaGradient( getZ(pmobj.secondary), colors[1], (0.2,0.6),
2, 6, window=pmobj.window, panel=panel)
self.plotAlphaGradient( getZ(pmobj.primary), colors[2], (0.5,0.9),
2, 6, window=pmobj.window, panel=panel)
# make legend
c = colors[::-1] # reverse colors so primary on top
l = ['Principal','Minor','Not passing']
if not plotall:
c = c[:-1]
l = l[:-1]
if panel>0:
if self.toplegend is not None:
self.toplegend.append('PairMap', c, l)
else:
self.toplegend = ArcLegend(title='PairMap', colors=c, labels=l)
else:
if self.botlegend is not None:
self.botlegend.append('PairMap', c, l)
else:
self.botlegend = ArcLegend(title='PairMap', colors=c, labels=l)
def _colorGrad(self, value, colorMin, colorMax, minValue, maxValue, log=False):
""" return an interpolated rgb color value """
if log:
value = 10**-value
minValue = 10**-minValue
maxValue = 10**-maxValue
if value > maxValue:
return colorMax
elif value < minValue:
return colorMin
else:
v = value - min(maxValue, minValue)
v /= abs(maxValue-minValue)
col = []
for i in range(3):
col.append( v*(colorMax[i] - colorMin[i]) + colorMin[i] )
return col
def plotAlphaGradient(self, pairlist, color, alpha_range, lb, ub, window=1, panel=1):
"""plot the list of pairs with the same color but different alpha"""
if max(color) > 1:
color = [x/255. for x in color]
dynamicrange = ub-lb
for i,j,val in sorted(pairlist, key=lambda x:x[2]):
if val<lb:
continue
elif val>ub:
scale = 1
else:
scale = (val-lb)/dynamicrange
a = (alpha_range[1]-alpha_range[0])*scale+alpha_range[0]
self.addArcPath( (i,j), window=window, color=color, panel=panel, alpha=a)
def compareCTs(self, refCT, compCT, panel=1):
if len(refCT.ct) != len(compCT.ct):
raise IndexError('CT objects are different sizes')
share = refCT.copy()
refonly = refCT.copy()
componly = refCT.copy()
# ct files and set to blank (ie 0)
for c in (share, refonly, componly):
for i in range(len(c.ct)):
c.ct[i] = 0
for i in range(len(refCT.ct)):
if refCT.ct[i] == compCT.ct[i]:
share.ct[i] = refCT.ct[i]
else:
refonly.ct[i] = refCT.ct[i]
componly.ct[i] = compCT.ct[i]
sharedcolor = (150/255., 150/255., 150/255.)
refcolor = (38/255., 202/255., 145/255.)
compcolor = (153/255., 0.0, 1.0)
self.addCT(share, color=sharedcolor, panel=panel)
self.addCT(refonly, color=refcolor, panel=panel)
self.addCT(componly, color=compcolor, panel=panel)
sens,ppv,nums = refCT.computePPVSens(compCT, False)
msg = 'Sens={0:.2f} PPV={1:.2f}'.format(sens, ppv)
print(msg)
if panel>0:
self.toplegend = ArcLegend(colors=[sharedcolor,refcolor,compcolor],
labels=['Shared', refCT.name, compCT.name],
msg=msg)
else:
self.botlegend = ArcLegend(colors=[sharedcolor,refcolor,compcolor],
labels=['Shared', refCT.name, compCT.name],
msg=msg)
return sens,ppv
def assignSeqColors(self, shapearr):
if len(shapearr) != len(self.seq):
raise IndexError("Shape Array does not match length of sequence")
col = []
for x in shapearr:
if x < -4:
col.append( (160,160,160 ) ) # grey
elif x > 0.85:
col.append( (255,0,0) ) # red
elif 0.85 >= x >0.4:
col.append( (255,164,26) ) # orange
else:
col.append( (0,0,0) ) # black
self.seqcolors = [tuple([y/255.0 for y in x]) for x in col]
def colorSeqByMAP(self, mapfile):
shape, seq = RNAtools.readSHAPE(mapfile)
if self.seq == '' or self.seq.count(' ')==len(self.seq):
self.seq = seq
elif len(shape) != len(self.seq):
raise IndexError("Mapfile does not match length of sequence!")
self.assignSeqColors(shape)
def readSHAPE(self, mapfile):
shape, seq = RNAtools.readSHAPE(mapfile)
if self.seq == '' or self.seq.count(' ') == len(self.seq):
self.seq = seq
elif len(shape) != len(self.seq):
raise IndexError("Mapfile does not match length of sequence!")
self.reactprofile = shape
# need to give the plot some height if no other things added
if max(self.height)==0:
self.height[1] = max(5, min(10, len(self.reactprofile)/50.))
def readProfile(self, profilefile, dms=False):
with open(profilefile) as inp:
line = inp.readline().split()
if len(line) == 2 or len(line)==4:
ftype=1
else:
ftype=2
if ftype==1:
self.readSHAPE(profilefile)
else:
import ReactivityProfile
profile = ReactivityProfile.ReactivityProfile(profilefile)
self.reactprofile = profile.normprofile
if self.seq == '' or self.seq.count(' ') == len(self.seq):
self.seq = profile.sequence
if dms:
self.reactprofileType = 'DMS'
# need to give the plot some height if no other things added
if max(self.height)==0:
self.height[1] = max(5, min(10, len(self.reactprofile)/50.))
def old_addInteractionDistance(self, readMatFile, thresh, panel=1):
height = []
readMat = np.loadtxt(readMatFile)
for i in range(len(self.seq)):
for j in range(i,len(self.seq)):
if readMat[i][j] < thresh:
break
n = float(j-i)
for j in range(i, -1, -1):
if readMat[i][j] < thresh:
break
m = float(i-j)
try:
z = n*math.sin(math.atan(m/n))
except: