forked from MustoeLab/StructureAnalysisTools
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRNAStructureObjects.py
More file actions
1597 lines (1168 loc) · 50.2 KB
/
RNAStructureObjects.py
File metadata and controls
1597 lines (1168 loc) · 50.2 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
##################################################################################
# GPL statement:
# This file is part of SuperFold.
#
# SuperFold is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# SuperFold is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with SuperFold. If not, see <http://www.gnu.org/licenses/>.
#
# 17 Nov 2014
# Copywrite 2014
# Greggory M Rice
# all rights reserved
#
# V2 version of RNAtools modified by Anthony Mustoe
# 2016
##################################################################################
########################################################
# #
# RNAtools2.py CT and dotplot data structures #
# v 2.0 2016 #
# #
# author: Gregg Rice #
# Anthony Mustoe #
########################################################
# CHANGE-LOG
# Feb 2020 Added separate filterNC, filter single functionality
# -CT masking functionality,
# -bp consistency checking
# -writeRNAstructureSeq
# -addPairs
#
# 12/6/18 Full merging of Tony's RNAtools
#
# v0.8.1 contact distance fixed
# Tom Christy: Contact Distance Fixed Again, now uses a breadth first search algorithm
#
# v0.8 numpy dotplot functions added
import sys
import numpy as np
class CT(object):
def __init__(self,fIN=None, **kwargs):
"""
if givin an input file .ct construct the ct object automatically
"""
if fIN:
#self.name = fIN
#self.num,self.seq,self.ct = self.readCT(fIN)
self.readCT(fIN, **kwargs)
def __str__(self):
"""
overide the default print statement for the object
"""
a = '{ Name= %s, len(CT)= %s }' % (self.name, str(len(self.ct)))
return a
def readFasta(self, fastapath):
"""Assign sequence from fastafile"""
with open(fastapath) as inp:
seq = ''
inp.readline() # pop off the header
for line in inp:
if line[0] == '>':
print("WARNING: Multiple sequences in {}. Using the first sequence.".format(fastapath))
break
seq += line.strip()
if 'T' in seq or 't' in seq:
print("WARNING: replacing 'T' with 'U' from {}".format(fastapath))
seq = seq.replace('T','U')
seq = seq.replace('t','u')
self.seq = list(seq)
def readCT(self, fIN, structNum = 0, filterNC = False, filterSingle=False):
"""
reads a ct file, !requires header!
structNum allows selection of a given SS if multiple are stored in the same file
filterNC will check the bps and filter out any between NC
filterSingle will filter out any singleton bps
"""
num,seq,bp,mask = [],[],[],[]
try:
with open(fIN) as f:
# process the first line (pops off the first element)
spl = f.readline().split()
numnucs = int(spl[0])
header = ' '.join(spl[1:])
curstruct = 0
for i,line in enumerate(f):
spl = line.split()
if (i+1) % (numnucs+1) == 0:
# catch the next header
curstruct+=1
if curstruct>structNum:
break
header = ' '.join(spl[1:])
continue
if curstruct == structNum:
num.append( int(spl[0]) )
seq.append( str(spl[1]) )
bp.append( int(spl[4]) )
# check if there is masking info
if len(spl)== 7 and spl[6]=='1':
mask.append(1)
else:
mask.append(0)
except Exception as e:
raise IOError("{0} has invalid format or does not exist".format(fIN))
if len(num)==0:
sys.exit("Structure %d was not found in the ct file" % structNum)
if 'T' in seq:
print("Note: T nucleotides have been recoded as U")
seq = ['U' if x=='T' else x for x in seq]
# check consistency!
for i in range(len(bp)):
if bp[i] != 0:
p1 = (i+1, bp[i])
p2 = (bp[bp[i]-1], bp[i])
if p1 != p2:
print("WARNING: Inconsistent pair {0[0]}-{0[1]} vs. {1[0]}-{1[1]}".format(p1,p2))
self.name= fIN
self.header = header
self.num = num
self.seq = seq
self.ct = bp
self.mask = mask
if filterNC:
self.filterNC()
if filterSingle:
self.filterSingleton()
def filterNC(self):
"""
Filter out non-canonical basepairs from the ct datastructure
"""
for i, nt in enumerate(self.ct):
if nt == 0:
continue
pi = self.num.index(nt)
bp = self.seq[pi] + self.seq[i]
if bp not in ('AU','UA','GC','CG','GU','UG',' '):
self.ct[i] = 0
self.ct[pi] = 0
#print 'Deleted %d %s' % (self.num[i], self.seq[i])
continue
def filterSingleton(self):
"""
Filter out singleton basepairs from the ct datastructure
"""
for i, nt in enumerate(self.ct):
if nt == 0:
continue
pi = self.num.index(nt)
neigh = False
for j in (-1, 1):
try:
neigh = (neigh or (nt-self.ct[i+j] == j))
except IndexError:
pass
if not neigh:
self.ct[i] = 0
self.ct[pi] = 0
#print 'Deleted %d %s *' % (self.num[i], self.seq[i])
def writeCT(self, fOUT, writemask=False):
"""
writes a ct file from the ct object
writemask = True will write out any masking info
"""
try:
mask = writemask and len(self.mask) == len(self.ct)
except:
mask = False
#handle empty ct object case
if not self.ct:
print("empty ct object. Nothing to write")
return
w = open(fOUT,'w')
w.write('{0:6d} {1}\n'.format(len(self.num),self.name))
for i in range(len(self.num)-1):
if mask and self.mask[i]:
line = '{0:5d} {1} {2:5d} {3:5d} {4:5d} {0:5d} 1\n'.format(self.num[i],self.seq[i],self.num[i]-1,self.num[i]+1,self.ct[i])
else:
line = '{0:5d} {1} {2:5d} {3:5d} {4:5d} {0:5d}\n'.format(self.num[i],self.seq[i],self.num[i]-1,self.num[i]+1,self.ct[i])
w.write(line)
#last line is different
i = len(self.num)-1
if mask and self.mask[i]:
line = '{0:5d} {1} {2:5d} {3:5d} {4:5d} {0:5d} 1\n'.format(self.num[i],self.seq[i],self.num[i]-1,0,self.ct[i])
else:
line = '{0:5d} {1} {2:5d} {3:5d} {4:5d} {0:5d}\n'.format(self.num[i],self.seq[i],self.num[i]-1,0,self.ct[i])
w.write(line)
w.close()
def copy(self):
"""
returns a deep copy of the ct object
"""
out = CT()
out.name = self.name[:]
out.num = self.num[:]
out.seq = self.seq[:]
out.ct = self.ct[:]
return out
def pairList(self):
"""
#returns a list of base pairs i<j as a array of tuples:
[(19,50),(20,49)....]
"""
out = []
for nt in range(len(self.ct)):
if self.ct[nt] != 0 and self.ct[nt] > self.num[nt]:
out.append((self.num[nt],self.ct[nt]))
return out
def pairedResidueList(self, paired = True):
""" return a list of residues that are paired (or single-stranded, if paired=False)"""
out = []
for i,nt in enumerate(self.ct):
if ( nt != 0 ) == paired:
out.append(self.num[i])
return out
def junctionResidues(self, incGU = False):
""" return a list of residues at junctions. Write in functionality to include opiton of GU pairs"""
jun = []
for i,nt in enumerate(self.ct):
if nt == 0: # if its not paired
continue
pi = self.num.index(nt)
try:
if self.ct[i-1]==0 or self.ct[i+1]==0 or \
self.ct[pi-1]==0 or self.ct[pi+1]==0:
jun.append(self.num[i])
except IndexError:
# this means we're at the beginning or end of the chain, hence must be junction
jun.append(self.num[i])
return jun
def addPairs(self, pairs):
"""Add base pairs to current ct file
pairs should be a list of pairs (1-indexed)
"""
for i,j in pairs:
if self.ct[i-1] != 0:
print('Warning: nt {} is already paired!!!'.format(i))
if self.ct[j-1] != 0:
print('Warning: nt {} is already paired!!!'.format(j))
self.ct[i-1] = j
self.ct[j-1] = i
def pair2CT(self, pairs, seq=None, name=None, skipConflicting=True,
filterNC=False, filterSingle=False):
"""
constructs a ct object from a list of base pairs and a sequence
pairs are an array of bp tuples ( i < j )
i.e. [(4,26),(5,25),...]
length is implied from the given sequence
"""
# Admittedly messy logic to see if self.seq has been defined, and if so,
# use self.seq as sequence. Otherwise, seq variable needs to be defined
try:
if self.seq is None:
raise AttributeError('Sequence is not defined')
except:
if seq is not None:
self.seq = seq
else:
raise AttributeError('Sequence is not defined')
length = len(self.seq)
self.num = list(range(1,length+1))
#give it a name if it has one
if name:
self.name=name
else:
self.name='RNA_'+str(length)
self.ct = []
for i in range(length):
self.ct.append(0)
for i,j in pairs:
if self.ct[i-1]!=0:
print('Warning: conflicting pairs, (%s - %s) : (%s - %s)' % (str(i),str(j),str(self.ct[i-1]),str(i)))
if skipConflicting: continue
if self.ct[j-1]!=0:
print('Warning: conflicting pairs, (%s - %s) : (%s - %s)' % (str(i),str(j),str(j),str(self.ct[j-1])))
if skipConflicting: continue
self.ct[i-1]=j
self.ct[j-1]=i
if filterNC:
self.filterNC()
if filterSingle:
self.filterSingleton()
def getNTslice(self, start=None, end=None):
offset = self.num[0]
try:
start = start - offset
except TypeError:
assert start is None
try:
end = end+1-offset
except TypeError:
assert end is None
sel = slice(start, end)
return sel
def maskCT(self, start, end, nocross=True, inverse=False):
"""return a copy of the original CT file, but with the specified region
masked out (ie base pairs set to 0)
if inverse = True, do the inverse -- ie return a CT with base pairs only
involving the specified region"""
# in case numbering differs from indexing, go by indexes
out = self.copy()
out.name += '_mask_'+str(start)+'_'+str(end)
sele = self.getNTslice(start, end)
offset = self.num[0]
if inverse:
out.ct[:] = [0]*len(out.ct)
out.ct[sele] = self.ct[sele]
for nt in self.ct[sele]:
out.ct[nt-offset] = self.ct[nt-offset]
return out
# below code will only execute if not inverse
# zero out the masked region
out.ct[sele] = [0]*len(out.ct[sele])
for nt in self.ct[sele]:
if nt !=0:
out.ct[nt-offset] = 0
if nocross:
for i in range(sele.start):
nt = out.ct[i]-offset
if nt >= sele.stop:
out.ct[i] = 0
out.ct[nt] = 0
return out
def cutCT(self, start,end):
"""
returns a new ct file containing only base pairs within the specified region
"""
sel = self.getNTslice(start, end)
offset = self.num[0]
numnts = end-start+1
out = CT()
out.seq = self.seq[sel]
out.num = list(range(1,numnts+1))
out.name = self.name + '_cut_'+str(start)+'_'+str(end)
out.ct = []
temp = self.ct[sel]
# renumber from 1
for nt in temp:
nt_out = nt-(start-offset)
# cut out pairings that lie outside the window
if nt_out <= 0 or nt_out > numnts:
nt_out = 0
out.ct.append(nt_out)
return out
def stripCT(self):
"""
returns an array the length of the ct object
in a non-redundant form - e.g. only gives pairs i<j
"""
pairs = self.pairList()
halfPlexCT = np.zeros_like(self.ct)
for i,j in pairs:
halfPlexCT[i-1] = j
return halfPlexCT
def ctToArcList(self):
"""
returns a 2D array containing arc list elements
"""
pairs = self.stripCT()
outarr = []
for i,v in enumerate(pairs):
if v!=0:
temp = np.zeros_like(pairs)
temp[i] = v
outarr.append(temp)
return outarr
def contactDistance(self,i,j):
"""
Caclulates the contact distance between pairs i,j in
the RNA using the RNAtools CT Object. This is different
than the old contact distance function because it utilizes a breadth
first search to determine the distance. While BFS may take longer
than contact distance, it will always find the shortest distance.
Added by Tom Christy
"""
#this method will be used later to make sure a nucleotide hasn't
#been visited and is within the bounds of the RNA
def viable(nt, rna):
addMe = True
#don't add if nt is the pair of an unpaired nt (0 in the ct)
if(nt == 0):
addMe = False
#don't add if nt is smaller than the lowest nt in the ct
elif(nt < rna.num[0]):
addMe = False
#don't add if nt is larger than the highest nt in the ct
elif(nt > rna.num[-1]):
addMe = False
#don't add if this nt has already been visited
elif(level[nt] >= 0):
addMe = False
return addMe
#create an array to keep track of how far each nt is from i
#The default value of -1 also means that an nt hasn't been visited.
level = np.zeros(len(self.num) + 1)
level = level - 1
#each index matches to the nt number, so index 0 is just an empty place holder
#create the queue and add nt i, set its level as 0
queue = list()
queue.append(i)
level[i] = 0
#while the queue has members, keep popping and searching until the NT is found
notFound = True
contactDistance = 0
while len(queue) > 0 and notFound:
currentNT = queue.pop(0)
#if the current nucleotide is the one we're searching for, record it's level as the contact distance
#and break out of the search
if(currentNT == j):
contactDistance = level[currentNT]
notFound = False
break
#grab all the neighbors of the current NT and determine if they are inbounds and unvisited
#If so, add them to the queue and set their levels.
NTBack = currentNT -1
NTUp = currentNT + 1
#get the pair of NT -1 b/c of the weird way coded the ct file, it's off by 1
NTPair = self.ct[currentNT-1]
#check all the neighbors to see if they should be added to the search, and if so, record their level(ie their Contact Distance)
if viable(NTBack, self):
queue.append(NTBack)
level[NTBack] = level[currentNT] + 1
if viable(NTUp, self):
queue.append(NTUp)
level[NTUp] = level[currentNT] + 1
if viable(NTPair, self):
queue.append(NTPair)
level[NTPair] = level[currentNT] + 1
#return the contactDistance from the search
return contactDistance
def GreggContactDistance(self,i,j):
"""
calculates the contact distance between pairs i,j in
in the RNA using the RNAtools CT object. Method for
calculating the contact is described in Hajdin et al
(2013).
THIS FUNCTION IS BROKEN. It doesn't handle multi helix
junctions correctly and will often return a longer distance
than the real answer.
"""
print("WARNING: GreggContactDistance is broken and should not be used!!!")
#correct for indexing offset
i, j = i-1, j-1
#error out if nucleotide out of range
if max(i,j) > len(self.ct):
print('Error!, nucleotide {0} out of range!'.format(max(i,j)+1))
return
#i must always be less than j, correct for this
if j < i:
i, j = j, i
count = 0.0
tempBack = 10000.0
k = int(i)
def backTrace(rna,j,k):
bcount = 2
k -= 1
if k-1 == j:
return bcount
bcount += 1
while k > j:
if rna.ct[k] == 0:
k -= 1
bcount += 1
# if not single stranded, exit the backtrace
else:
return None
return bcount
# search forward through sequence
while k < j:
#debuging stuff, prevent infinite loop
#if count > 200:
# print i,j
# break
#nonpaired nucleotides are single beads
if self.ct[k] == 0:
k += 1
#count += 6.5
count += 1
#branches through helices can't be skipped
#treated as single beads
elif self.ct[k] > j + 1:
# try backtracing a few if it is close (within 10)
if self.ct[k] - 10 < j:
back = backTrace(self, j,self.ct[k])
# if the backtracing is able to reach
# your nt, add its length to the count
# and break
if back:
#print 'backitup'
# store the backtracing count for later
# if it ends up being lower than the final
# we will use it instead
if count + back < tempBack:
tempBack = count + back
k += 1
#count += 6.5
count += 1
# simple stepping
elif self.ct[k] < i + 1:
k += 1
#count += 6.5
count += 1
elif self.ct[k] < k+1:
k += 1
count += 1
#print "Backtracking prevented, going forward to "+str(k+1)
#handle branching, jumping the base of a helix is only 1
else:
# one count for the step to the next
count += 1
k = self.ct[k] - 1
# if by jumping you land on your nt
# stop counting
if k - 1 == j:
break
# one count for jumping the helix
#count += 15.0
#count += 1
#print i,k,j
finalCount = min(count, tempBack)
return finalCount
def extractHelices(self,fillPairs=True,splitHelixByBulge=True):
"""
returns a list of helices in a given CT file and the nucleotides
making up the list as a dict object. e.g. {0:[(1,50),(2,49),(3,48)}
defaults to filling 1,1 and 2,2 mismatches
Since April 20, 2018 an option has been added to no longer split helices by single
nucleotide bulges. Prior to this option bulges on the 5' of the helix split the helix
but those on the 3' end did not.
"""
# first step is to find all the helices
rna = self.copy()
if fillPairs:
rna = rna.fillPairs()
helices = {}
nt = 0
heNum = 0
while nt < len(rna.ct):
if rna.ct[nt] == 0:
nt += 1
continue
else:
# skip dups
if nt > rna.ct[nt]:
nt += 1
continue
tempPairs = []
stillHelix = True
previous = rna.ct[nt]
#this is the default behavior which splits helices that are separated by a single nucleotide bulge
if splitHelixByBulge:
while stillHelix:
# see if the helix juts up against another one
if abs(rna.ct[nt] - previous ) > 1:
break
#add the pairs
elif rna.ct[nt] != 0:
tempPairs.append((nt+1,rna.ct[nt]))
previous = rna.ct[nt]
nt+=1
else:
break
else:
while stillHelix:
if rna.ct[nt] != 0 and not(abs(rna.ct[nt] - previous ) > 2):
tempPairs.append((nt+1,rna.ct[nt]))
previous = rna.ct[nt]
nt+=1
#This if statement handles bulges on the 5' end of the helix by reading through them
#The prior if statement handles them on the 3' end of the helix
elif rna.ct[nt+1] == rna.ct[nt-1]-1:
nt+=1
else:
break
# remove single bp helices
if len(tempPairs) <= 1:
continue
helices[heNum] = tempPairs
heNum += 1
return helices
def fillPairs(self, mismatch=1):
"""
fills 1,1 and/or 2,2 mismatches in an RNA structure
mismatch = 1 will fill only 1,1 mismatches
mismatch = 2 will fill both
"""
rna = self.copy()
# fill in 1,1 mismatch, 2,2 mismatch
for i in range(len(rna.ct)-3):
if rna.ct[i+1] == 0:
if rna.ct[i] - rna.ct[i+2] == 2:
rna.ct[i+1] = rna.ct[i] - 1
if mismatch==2 and rna.ct[i+1] + rna.ct[i+2] == 0:
if rna.ct[i] - rna.ct[i+3] == 3:
rna.ct[i+1] = rna.ct[i] - 1
rna.ct[i+2] = rna.ct[i] - 2
return rna
def extractPK(self,fillPairs=True):
"""
returns the pk1 and pk2 pairs from a CT file. Ignores single base
pairs. PK1 is defined as the helix crossing the most other bps.
if there is a tie, the most 5' helix is called pk1
Code from original RNAtools was updated to more robustly assign pk1/pk2
returns pk1 and pk2 as a list of base pairs e.g [(1,10),(2,9)...
"""
def checkOverlap(h1,h2):
# only need to check one set of pairs from each
# of the helices. Test is to see if they form
# a cross hatching pattern
if max(h1[0]) > min(h2[0]) > min(h1[0]) and max(h2[0]) > max(h1[0]):
return True
if max(h2[0]) > min(h1[0]) > min(h2[0]) and max(h1[0]) > max(h2[0]):
return True
return False
# make a copy so we don't destroy the original object
rna = self.copy()
# get the helices by calling the extract helix function
helices = rna.extractHelices(fillPairs=fillPairs)
heNum = len(helices)
# do the helices overlap? Check for a crosshatching pattern
# append them to a list if they have it.
overlaps = [] # stores the helix number
for i in range(heNum):
for j in range(i+1,heNum):
if checkOverlap(helices[i],helices[j]):
overlaps.append((i,j))
# if there are no overlapping bps, return none
if len(overlaps) == 0:
return None, None
# iterate through all pairs of overlapping helices and count
# the number of pairs in each to determine helix crossing most bps
crossbps = {}
for i,j in overlaps:
if i not in crossbps:
crossbps[i] = 0
if j not in crossbps:
crossbps[j] = 0
crossbps[i] += len(helices[j])
crossbps[j] += len(helices[i])
# convert to list and sort
crossbps = list(crossbps.items())
# first sort list by helix number -- i.e. 5' to 3'
crossbps.sort(key = lambda x: x[0])
# now sort by which helix crosses the most BPs. This two-step procedure
# ensures that in the case of ties, we always choose 5'-most helix
crossbps.sort(key = lambda x: x[1], reverse=True)
pk1 = helices[crossbps[0][0]]
pk2 = []
for k,v in crossbps[1:]:
pk2.extend(helices[k])
return pk1, pk2
def padCT(self, referenceCT, giveAlignment=False):
"""
utilizes the global padCT method on this object
"""
return padCT(self, referenceCT, giveAlignment)
def readSHAPE(self, fIN):
"""
utilizes the global readSHAPE method and appends a the data to the object as .shape
"""
self.shape, seq = readSHAPE(fIN)
if len(self.shape)< len(self.ct):
print("warning! shape array is smaller than the CT range")
def writeSHAPE(self, fOUT):
"""
utilizes the global writeSHAPE method, and writes the .shape array attached to the object to a file
"""
try:
writeSHAPE(self.shape, fOUT)
except:
print("No SHAPE data present")
return
def computePPVSens(self, compCT, exact=True, mask=False):
"""
compute the ppv and sensitivity between the current CT and the passed CT
exact = True will require BPs to be exactly correct.
False allows +/-1 bp slippage (RNAstructure convention)
mask = True will exclude masked regions from calculation
"""
# check mask is properly set up if using
if mask:
try:
if len(self.mask) != len(self.ct):
raise AttributeError()
except:
raise AttributeError('Mask is not properly initialized')
if len(self.ct) != len(compCT.ct):
raise IndexError('CT objects are different sizes')
# compute totals
totr, totc = 0, 0
for i,v in enumerate(self.ct):
if mask and self.mask[i]:
continue
if v!=0:
totr+=1
if compCT.ct[i] !=0:
totc+=1
totr /= 2
totc /= 2
sharedpairs = 0
for i,v in enumerate(self.ct):
if v==0 or v<i or (mask and self.mask[i]):
continue
try:
if v == compCT.ct[i]:
sharedpairs+=1
elif not exact and (v==compCT.ct[i]-1 or v==compCT.ct[i]+1):
sharedpairs+=1
elif not exact and (v==compCT.ct[i-1] or v==compCT.ct[i+1]):
sharedpairs+=1
except IndexError:
pass
try:
ppv = sharedpairs/float(totc)
sens = sharedpairs/float(totr)
except ZeroDivisionError:
ppv, sens = 0.0, 0.0
return sens, ppv, (sharedpairs, totc, totr)
def writeSTO(self, outfile, name='seq'):
""""write structure file out into Stockholm (STO) file format
for use for infernal searches"""
with open(outfile, 'w') as out:
out.write('# STOCKHOLM 1.0\n\n')
namelen = max(len(name), 12)
out.write('{0} '.format(name.ljust(namelen)))
for nt in self.seq:
out.write(nt)
out.write('\n')
out.write('{0} '.format('#=GC SS_cons'.ljust(namelen)))
for nt, pair in enumerate(self.ct):
if pair==0:
out.write('.')
elif pair>nt:
out.write('(')
else:
out.write(')')
out.write('\n//\n')
def writeRNAstructureSeq(self, writename):
with open(writename,'w') as out:
out.write(';\nSequence from {0}\n'.format(self.name))
out.write('{0}1'.format(''.join(self.seq)))
#################################################################################
# end of CT class
#################################################################################
def padCT(targetCT, referenceCT,giveAlignment=False):
"""Aligns the target CT to the reference CT and pads the referece
CT file with 000s in order to input into CircleCompare"""
out = CT()
out.seq = referenceCT.seq
out.num = referenceCT.num
#align target to reference
seed = 200
if len(targetCT.seq) <= seed: